code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from z3 import * def main(): x, y = Reals('x y') soft_constraints = [x > 2, x < 1, x < 0, Or(x + y > 0, y < 0), Or(y >= 0, x >= 0), Or(y < 0, x < 0), Or(y > 0, x < 0)] hard_constraints = BoolVal(True) solver = MSSSolver(hard_constraints, soft_constraints) for lits in enumerate_sets(solver): print("%s" % lits) def enumerate_sets(solver): while True: if sat == solver.s.check(): MSS = solver.grow() yield MSS else: break class MSSSolver: s = Solver() varcache = {} idcache = {} def __init__(self, hard, soft): self.n = len(soft) self.soft = soft self.s.add(hard) self.soft_vars = set([self.c_var(i) for i in range(self.n)]) self.orig_soft_vars = set([self.c_var(i) for i in range(self.n)]) self.s.add([(self.c_var(i) == soft[i]) for i in range(self.n)]) def c_var(self, i): if i not in self.varcache: v = Bool(str(self.soft[abs(i)])) self.idcache[v] = abs(i) if i >= 0: self.varcache[i] = v else: self.varcache[i] = Not(v) return self.varcache[i] # Retrieve the latest model # Add formulas that are true in the model to # the current mss def update_unknown(self): self.model = self.s.model() new_unknown = set([]) for x in self.unknown: if is_true(self.model[x]): self.mss.append(x) else: new_unknown.add(x) self.unknown = new_unknown # Create a name, propositional atom, # for formula 'fml' and return the name. def add_def(self, fml): name = Bool("%s" % fml) self.s.add(name == fml) return name # replace Fs := f0, f1, f2, .. by # Or(f1, f0), Or(f2, And(f1, f0)), Or(f3, And(f2, And(f1, f0))), ... def relax_core(self, Fs): assert(Fs <= self.soft_vars) prefix = BoolVal(True) self.soft_vars -= Fs Fs = [ f for f in Fs ] for i in range(len(Fs)-1): prefix = self.add_def(And(Fs[i], prefix)) self.soft_vars.add(self.add_def(Or(prefix, Fs[i+1]))) # Resolve literals from the core that # are 'explained', e.g., implied by # other literals. def resolve_core(self, core): new_core = set([]) for x in core: if x in self.mcs_explain: new_core |= self.mcs_explain[x] else: new_core.add(x) return new_core # Given a current satisfiable state # Extract an MSS, and ensure that currently # encountered cores are avoided in next iterations # by weakening the set of literals that are # examined in next iterations. # Strengthen the solver state by enforcing that # an element from the MCS is encountered. def grow(self): self.mss = [] self.mcs = [] self.nmcs = [] self.mcs_explain = {} self.unknown = self.soft_vars self.update_unknown() cores = [] while len(self.unknown) > 0: x = self.unknown.pop() is_sat = self.s.check(self.mss + [x] + self.nmcs) if is_sat == sat: self.mss.append(x) self.update_unknown() elif is_sat == unsat: core = self.s.unsat_core() core = self.resolve_core(core) self.mcs_explain[Not(x)] = {y for y in core if not eq(x,y)} self.mcs.append(x) self.nmcs.append(Not(x)) cores += [core] else: print("solver returned %s" % is_sat) exit() mss = [x for x in self.orig_soft_vars if is_true(self.model[x])] mcs = [x for x in self.orig_soft_vars if not is_true(self.model[x])] self.s.add(Or(mcs)) core_literals = set([]) cores.sort(key=lambda element: len(element)) for core in cores: if len(core & core_literals) == 0: self.relax_core(core) core_literals |= core return mss main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/mus/mss.py
mss.py
from __future__ import print_function import sys if sys.version_info.major >= 3: from functools import reduce from z3 import * def _to_complex(a): if isinstance(a, ComplexExpr): return a else: return ComplexExpr(a, RealVal(0)) def _is_zero(a): return (isinstance(a, int) and a == 0) or (is_rational_value(a) and a.numerator_as_long() == 0) class ComplexExpr: def __init__(self, r, i): self.r = r self.i = i def __add__(self, other): other = _to_complex(other) return ComplexExpr(self.r + other.r, self.i + other.i) def __radd__(self, other): other = _to_complex(other) return ComplexExpr(other.r + self.r, other.i + self.i) def __sub__(self, other): other = _to_complex(other) return ComplexExpr(self.r - other.r, self.i - other.i) def __rsub__(self, other): other = _to_complex(other) return ComplexExpr(other.r - self.r, other.i - self.i) def __mul__(self, other): other = _to_complex(other) return ComplexExpr(self.r*other.r - self.i*other.i, self.r*other.i + self.i*other.r) def __rmul__(self, other): other = _to_complex(other) return ComplexExpr(other.r*self.r - other.i*self.i, other.i*self.r + other.r*self.i) def __pow__(self, k): if k == 0: return ComplexExpr(1, 0) if k == 1: return self if k < 0: return (self ** (-k)).inv() return reduce(lambda x, y: x * y, [self for _ in range(k)], ComplexExpr(1, 0)) def inv(self): den = self.r*self.r + self.i*self.i return ComplexExpr(self.r/den, -self.i/den) def __div__(self, other): inv_other = _to_complex(other).inv() return self.__mul__(inv_other) if sys.version_info.major >= 3: # In python 3 the meaning of the '/' operator # was changed. def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): other = _to_complex(other) return self.inv().__mul__(other) def __eq__(self, other): other = _to_complex(other) return And(self.r == other.r, self.i == other.i) def __neq__(self, other): return Not(self.__eq__(other)) def simplify(self): return ComplexExpr(simplify(self.r), simplify(self.i)) def repr_i(self): if is_rational_value(self.i): return "%s*I" % self.i else: return "(%s)*I" % str(self.i) def __repr__(self): if _is_zero(self.i): return str(self.r) elif _is_zero(self.r): return self.repr_i() else: return "%s + %s" % (self.r, self.repr_i()) def Complex(a): return ComplexExpr(Real('%s.r' % a), Real('%s.i' % a)) I = ComplexExpr(RealVal(0), RealVal(1)) def evaluate_cexpr(m, e): return ComplexExpr(m[e.r], m[e.i]) x = Complex("x") s = Tactic('qfnra-nlsat').solver() s.add(x*x == -2) print(s) print(s.check()) m = s.model() print('x = %s' % evaluate_cexpr(m, x)) print((evaluate_cexpr(m,x)*evaluate_cexpr(m,x)).simplify()) s.add(x.i != -1) print(s) print(s.check()) print(s.model()) s.add(x.i != 1) print(s.check()) # print(s.model()) print(((3 + I) ** 2)/(5 - I)) print(((3 + I) ** -3)/(5 - I))
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/complex/complex.py
complex.py
from z3 import * def gencon(gr): """ Input a graph as an adjacency list, e.g. {0:[1,2], 1:[2], 2:[1,0]}. Produces solver to check if the given graph has a Hamiltonian cycle. Query the solver using s.check() and if sat, then s.model() spells out the cycle. Two example graphs from http://en.wikipedia.org/wiki/Hamiltonian_path are tested. ======================================================= Explanation: Generate a list of Int vars. Constrain the first Int var ("Node 0") to be 0. Pick a node i, and attempt to number all nodes reachable from i to have a number one higher (mod L) than assigned to node i (use an Or constraint). ======================================================= """ L = len(gr) cv = [Int('cv%s'%i) for i in range(L)] s = Solver() s.add(cv[0]==0) for i in range(L): s.add(Or([cv[j]==(cv[i]+1)%L for j in gr[i]])) return s def examples(): # Example Graphs: The Dodecahedral graph from http://en.wikipedia.org/wiki/Hamiltonian_path grdodec = { 0: [1, 4, 5], 1: [0, 7, 2], 2: [1, 9, 3], 3: [2, 11, 4], 4: [3, 13, 0], 5: [0, 14, 6], 6: [5, 16, 7], 7: [6, 8, 1], 8: [7, 17, 9], 9: [8, 10, 2], 10: [9, 18, 11], 11: [10, 3, 12], 12: [11, 19, 13], 13: [12, 14, 4], 14: [13, 15, 5], 15: [14, 16, 19], 16: [6, 17, 15], 17: [16, 8, 18], 18: [10, 19, 17], 19: [18, 12, 15] } import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint(grdodec) sdodec=gencon(grdodec) print(sdodec.check()) print(sdodec.model()) # ======================================================= # See http://en.wikipedia.org/wiki/Hamiltonian_path for the Herschel graph # being the smallest possible polyhedral graph that does not have a Hamiltonian # cycle. # grherschel = { 0: [1, 9, 10, 7], 1: [0, 8, 2], 2: [1, 9, 3], 3: [2, 8, 4], 4: [3, 9, 10, 5], 5: [4, 8, 6], 6: [5, 10, 7], 7: [6, 8, 0], 8: [1, 3, 5, 7], 9: [2, 0, 4], 10: [6, 4, 0] } pp.pprint(grherschel) sherschel=gencon(grherschel) print(sherschel.check()) # ======================================================= if __name__ == "__main__": examples()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/hamiltonian/hamiltonian.py
hamiltonian.py
import mk_genfile_common import argparse import logging import os import sys def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("api_files", nargs="+") parser.add_argument("--z3py-output-dir", dest="z3py_output_dir", default=None) parser.add_argument("--dotnet-output-dir", dest="dotnet_output_dir", default=None) parser.add_argument("--java-output-dir", dest="java_output_dir", default=None) parser.add_argument("--java-package-name", dest="java_package_name", default=None, help="Name to give the Java package (e.g. ``com.microsoft.z3``).") parser.add_argument("--ml-output-dir", dest="ml_output_dir", default=None) pargs = parser.parse_args(args) if not mk_genfile_common.check_files_exist(pargs.api_files): logging.error('One or more API files do not exist') return 1 count = 0 if pargs.z3py_output_dir: if not mk_genfile_common.check_dir_exists(pargs.z3py_output_dir): return 1 output = mk_genfile_common.mk_z3consts_py_internal(pargs.api_files, pargs.z3py_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if pargs.dotnet_output_dir: if not mk_genfile_common.check_dir_exists(pargs.dotnet_output_dir): return 1 output = mk_genfile_common.mk_z3consts_dotnet_internal( pargs.api_files, pargs.dotnet_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if pargs.java_output_dir: if pargs.java_package_name == None: logging.error('Java package name must be specified') return 1 if not mk_genfile_common.check_dir_exists(pargs.java_output_dir): return 1 outputs = mk_genfile_common.mk_z3consts_java_internal( pargs.api_files, pargs.java_package_name, pargs.java_output_dir) for generated_file in outputs: logging.info('Generated "{}"'.format(generated_file)) count += 1 if pargs.ml_output_dir: if not mk_genfile_common.check_dir_exists(pargs.ml_output_dir): return 1 output = mk_genfile_common.mk_z3consts_ml_internal( pargs.api_files, pargs.ml_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if count == 0: logging.info('No files generated. You need to specific an output directory' ' for the relevant language bindings') # TODO: Add support for other bindings return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_consts_files.py
mk_consts_files.py
import io import os import pprint import logging import re import sys # Logger for this module _logger = logging.getLogger(__name__) ############################################################################### # Utility functions ############################################################################### def check_dir_exists(output_dir): """ Returns ``True`` if ``output_dir`` exists, otherwise returns ``False``. """ if not os.path.isdir(output_dir): _logger.error('"{}" is not an existing directory'.format(output_dir)) return False return True def check_files_exist(files): assert isinstance(files, list) for f in files: if not os.path.exists(f): _logger.error('"{}" does not exist'.format(f)) return False return True def sorted_headers_by_component(l): """ Take a list of header files and sort them by the path after ``src/``. E.g. for ``src/ast/fpa/fpa2bv_converter.h`` the sorting key is ``ast/fpa/fpa2bv_converter.h``. The sort is done this way because for the CMake build there are two directories for every component (e.g. ``<src_dir>/src/ast/fpa`` and ``<build_dir>/src/ast/fpa``). We don't want to sort based on different ``<src_dir>`` and ``<build_dir>`` prefixes so that we can match the Python build system's behaviour. """ assert isinstance(l, list) def get_key(path): _logger.debug("get_key({})".format(path)) path_components = [] stripped_path = path assert 'src' in stripped_path.split(os.path.sep) or 'src' in stripped_path.split('/') # Keep stripping off directory components until we hit ``src`` while os.path.basename(stripped_path) != 'src': path_components.append(os.path.basename(stripped_path)) stripped_path = os.path.dirname(stripped_path) assert len(path_components) > 0 path_components.reverse() # For consistency across platforms use ``/`` rather than ``os.sep``. # This is a sorting key so it doesn't need to a platform suitable # path r = '/'.join(path_components) _logger.debug("return key:'{}'".format(r)) return r sorted_headers = sorted(l, key=get_key) _logger.debug('sorted headers:{}'.format(pprint.pformat(sorted_headers))) return sorted_headers ############################################################################### # Functions for generating constant declarations for language bindings ############################################################################### def mk_z3consts_py_internal(api_files, output_dir): """ Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") z3consts = open(os.path.join(output_dir, 'z3', 'z3consts.py'), 'w') z3consts_output_path = z3consts.name z3consts.write('# Automatically generated file\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] z3consts.write('# enum %s\n' % name) # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write('%s = %s\n' % (k, v)) z3consts.write('\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.close() return z3consts_output_path def mk_z3consts_dotnet_internal(api_files, output_dir): """ Generate ``Enumerations.cs`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] z3consts = open(os.path.join(output_dir, 'Enumerations.cs'), 'w') z3consts_output_path = z3consts.name z3consts.write('// Automatically generated file\n\n') z3consts.write('using System;\n\n' '#pragma warning disable 1591\n\n' 'namespace Microsoft.Z3\n' '{\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: z3consts.write(' /// <summary>%s</summary>\n' % name) z3consts.write(' public enum %s {\n' % name) z3consts.write # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write(' %s = %s,\n' % (k, v)) z3consts.write(' }\n\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.write('}\n'); z3consts.close() return z3consts_output_path def mk_z3consts_java_internal(api_files, package_name, output_dir): """ Generate "com.microsoft.z3.enumerations" package from the list of API header files in ``api_files`` and write the package directory into the ``output_dir`` directory Returns a list of the generated java source files. """ blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] gendir = os.path.join(output_dir, "enumerations") if not os.path.exists(gendir): os.mkdir(gendir) generated_enumeration_files = [] for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: efile = open('%s.java' % os.path.join(gendir, name), 'w') generated_enumeration_files.append(efile.name) efile.write('/**\n * Automatically generated file\n **/\n\n') efile.write('package %s.enumerations;\n\n' % package_name) efile.write('import java.util.HashMap;\n') efile.write('import java.util.Map;\n') efile.write('\n') efile.write('/**\n') efile.write(' * %s\n' % name) efile.write(' **/\n') efile.write('public enum %s {\n' % name) efile.write first = True # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): if first: first = False else: efile.write(',\n') efile.write(' %s (%s)' % (k, v)) efile.write(";\n") efile.write('\n private final int intValue;\n\n') efile.write(' %s(int v) {\n' % name) efile.write(' this.intValue = v;\n') efile.write(' }\n\n') efile.write(' // Cannot initialize map in constructor, so need to do it lazily.\n') efile.write(' // Easiest thread-safe way is the initialization-on-demand holder pattern.\n') efile.write(' private static class %s_MappingHolder {\n' % name) efile.write(' private static final Map<Integer, %s> intMapping = new HashMap<>();\n' % name) efile.write(' static {\n') efile.write(' for (%s k : %s.values())\n' % (name, name)) efile.write(' intMapping.put(k.toInt(), k);\n') efile.write(' }\n') efile.write(' }\n\n') efile.write(' public static final %s fromInt(int v) {\n' % name) efile.write(' %s k = %s_MappingHolder.intMapping.get(v);\n' % (name, name)) efile.write(' if (k != null) return k;\n') efile.write(' throw new IllegalArgumentException("Illegal value " + v + " for %s");\n' % name) efile.write(' }\n\n') efile.write(' public final int toInt() { return this.intValue; }\n') # efile.write(';\n %s(int v) {}\n' % name) efile.write('}\n\n') efile.close() mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() return generated_enumeration_files # Extract enumeration types from z3_api.h, and add ML definitions def mk_z3consts_ml_internal(api_files, output_dir): """ Generate ``z3enums.ml`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] if not os.path.exists(output_dir): os.mkdir(output_dir) efile = open('%s.ml' % os.path.join(output_dir, "z3enums"), 'w') z3consts_output_path = efile.name efile.write('(* Automatically generated file *)\n\n') efile.write('(** The enumeration types of Z3. *)\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: sorted_decls = sorted(decls.items(), key=lambda pair: pair[1]) efile.write('(** %s *)\n' % name[3:]) efile.write('type %s =\n' % name[3:]) # strip Z3_ for k, i in sorted_decls: efile.write(' | %s \n' % k[3:]) # strip Z3_ efile.write('\n') efile.write('(** Convert %s to int*)\n' % name[3:]) efile.write('let int_of_%s x : int =\n' % (name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %s -> %d\n' % (k[3:], i)) efile.write('\n') efile.write('(** Convert int to %s*)\n' % name[3:]) efile.write('let %s_of_int x : %s =\n' % (name[3:],name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %d -> %s\n' % (i, k[3:])) # use Z3.Exception? efile.write(' | _ -> raise (Failure "undefined enum value")\n\n') mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() efile.close() return z3consts_output_path # efile = open('%s.mli' % os.path.join(gendir, "z3enums"), 'w') # efile.write('(* Automatically generated file *)\n\n') # efile.write('(** The enumeration types of Z3. *)\n\n') # for api_file in api_files: # api_file_c = ml.find_file(api_file, ml.name) # api_file = os.path.join(api_file_c.src_dir, api_file) # api = open(api_file, 'r') # SEARCHING = 0 # FOUND_ENUM = 1 # IN_ENUM = 2 # mode = SEARCHING # decls = {} # idx = 0 # linenum = 1 # for line in api: # m1 = blank_pat.match(line) # m2 = comment_pat.match(line) # if m1 or m2: # # skip blank lines and comments # linenum = linenum + 1 # elif mode == SEARCHING: # m = typedef_pat.match(line) # if m: # mode = FOUND_ENUM # m = typedef2_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # elif mode == FOUND_ENUM: # m = openbrace_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # else: # assert False, "Invalid %s, line: %s" % (api_file, linenum) # else: # assert mode == IN_ENUM # words = re.split('[^\-a-zA-Z0-9_]+', line) # m = closebrace_pat.match(line) # if m: # name = words[1] # if name not in DeprecatedEnums: # efile.write('(** %s *)\n' % name[3:]) # efile.write('type %s =\n' % name[3:]) # strip Z3_ # for k, i in sorted(decls.items(), key=lambda pair: pair[1]): # efile.write(' | %s \n' % k[3:]) # strip Z3_ # efile.write('\n') # efile.write('(** Convert %s to int*)\n' % name[3:]) # efile.write('val int_of_%s : %s -> int\n' % (name[3:], name[3:])) # strip Z3_ # efile.write('(** Convert int to %s*)\n' % name[3:]) # efile.write('val %s_of_int : int -> %s\n' % (name[3:],name[3:])) # strip Z3_ # efile.write('\n') # mode = SEARCHING # else: # if words[2] != '': # if len(words[2]) > 1 and words[2][1] == 'x': # idx = int(words[2], 16) # else: # idx = int(words[2]) # decls[words[1]] = idx # idx = idx + 1 # linenum = linenum + 1 # api.close() # efile.close() # if VERBOSE: # print ('Generated "%s/z3enums.mli"' % ('%s' % gendir)) ############################################################################### # Functions for generating a "module definition file" for MSVC ############################################################################### def mk_def_file_internal(defname, dll_name, export_header_files): """ Writes to a module definition file to a file named ``defname``. ``dll_name`` is the name of the dll (without the ``.dll`` suffix). ``export_header_file`` is a list of header files to scan for symbols to include in the module definition file. """ assert isinstance(export_header_files, list) pat1 = re.compile(".*Z3_API.*") fout = open(defname, 'w') fout.write('LIBRARY "%s"\nEXPORTS\n' % dll_name) num = 1 for export_header_file in export_header_files: api = open(export_header_file, 'r') for line in api: m = pat1.match(line) if m: words = re.split('\W+', line) i = 0 for w in words: if w == 'Z3_API': f = words[i+1] fout.write('\t%s @%s\n' % (f, num)) i = i + 1 num = num + 1 api.close() fout.close() ############################################################################### # Functions for generating ``gparams_register_modules.cpp`` ############################################################################### def path_after_src(h_file): h_file = h_file.replace("\\","/") idx = h_file.rfind("src/") if idx == -1: return h_file return h_file[idx + 4:] def mk_gparams_register_modules_internal(h_files_full_path, path): """ Generate a ``gparams_register_modules.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedure ``` void gparams_register_modules() ``` This procedure is invoked by gparams::init() """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) cmds = [] mod_cmds = [] mod_descrs = [] fullname = os.path.join(path, 'gparams_register_modules.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "util/gparams.h"\n') reg_pat = re.compile('[ \t]*REG_PARAMS\(\'([^\']*)\'\)') reg_mod_pat = re.compile('[ \t]*REG_MODULE_PARAMS\(\'([^\']*)\', *\'([^\']*)\'\)') reg_mod_descr_pat = re.compile('[ \t]*REG_MODULE_DESCRIPTION\(\'([^\']*)\', *\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = reg_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) cmds.append((m.group(1))) m = reg_mod_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) mod_cmds.append((m.group(1), m.group(2))) m = reg_mod_descr_pat.match(line) if m: mod_descrs.append((m.group(1), m.group(2))) fout.write('void gparams_register_modules() {\n') for code in cmds: fout.write('{ param_descrs d; %s(d); gparams::register_global(d); }\n' % code) for (mod, code) in mod_cmds: fout.write('{ std::function<param_descrs *(void)> f = []() { auto* d = alloc(param_descrs); %s(*d); return d; }; gparams::register_module("%s", f); }\n' % (code, mod)) for (mod, descr) in mod_descrs: fout.write('gparams::register_module_descr("%s", "%s");\n' % (mod, descr)) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions/data structures for generating ``install_tactics.cpp`` ############################################################################### def mk_install_tactic_cpp_internal(h_files_full_path, path): """ Generate a ``install_tactics.cpp`` file in the directory ``path``. Returns the path the generated file. This file implements the procedure ``` void install_tactics(tactic_manager & ctx) ``` It installs all tactics declared in the given header files ``h_files_full_path`` The procedure looks for ``ADD_TACTIC`` and ``ADD_PROBE``commands in the ``.h`` and ``.hpp`` files of these components. """ ADD_TACTIC_DATA = [] ADD_PROBE_DATA = [] def ADD_TACTIC(name, descr, cmd): ADD_TACTIC_DATA.append((name, descr, cmd)) def ADD_PROBE(name, descr, cmd): ADD_PROBE_DATA.append((name, descr, cmd)) eval_globals = { 'ADD_TACTIC': ADD_TACTIC, 'ADD_PROBE': ADD_PROBE, } assert isinstance(h_files_full_path, list) assert check_dir_exists(path) fullname = os.path.join(path, 'install_tactic.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "tactic/tactic.h"\n') fout.write('#include "cmd_context/tactic_cmds.h"\n') fout.write('#include "cmd_context/cmd_context.h"\n') tactic_pat = re.compile('[ \t]*ADD_TACTIC\(.*\)') probe_pat = re.compile('[ \t]*ADD_PROBE\(.*\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False try: with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: if tactic_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_TACTIC command at '{}'\n{}".format( fullname, line)) raise e if probe_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_PROBE command at '{}'\n{}".format( fullname, line)) raise e except Exception as e: _logger.error("Failed to read file {}\n".format(h_file)) raise e # First pass will just generate the tactic factories fout.write('#define ADD_TACTIC_CMD(NAME, DESCR, CODE) ctx.insert(alloc(tactic_cmd, symbol(NAME), DESCR, [](ast_manager &m, const params_ref &p) { return CODE; }))\n') fout.write('#define ADD_PROBE(NAME, DESCR, PROBE) ctx.insert(alloc(probe_info, symbol(NAME), DESCR, PROBE))\n') fout.write('void install_tactics(tactic_manager & ctx) {\n') for data in ADD_TACTIC_DATA: fout.write(' ADD_TACTIC_CMD("%s", "%s", %s);\n' % data) for data in ADD_PROBE_DATA: fout.write(' ADD_PROBE("%s", "%s", %s);\n' % data) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``mem_initializer.cpp`` ############################################################################### def mk_mem_initializer_cpp_internal(h_files_full_path, path): """ Generate a ``mem_initializer.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedures ``` void mem_initialize() void mem_finalize() ``` These procedures are invoked by the Z3 memory_manager """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) initializer_cmds = [] finalizer_cmds = [] fullname = os.path.join(path, 'mem_initializer.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') initializer_pat = re.compile('[ \t]*ADD_INITIALIZER\(\'([^\']*)\'\)') # ADD_INITIALIZER with priority initializer_prio_pat = re.compile('[ \t]*ADD_INITIALIZER\(\'([^\']*)\',[ \t]*(-?[0-9]*)\)') finalizer_pat = re.compile('[ \t]*ADD_FINALIZER\(\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = initializer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), 0)) m = initializer_prio_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), int(m.group(2)))) m = finalizer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) finalizer_cmds.append(m.group(1)) initializer_cmds.sort(key=lambda tup: tup[1]) fout.write('void mem_initialize() {\n') for (cmd, prio) in initializer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.write('void mem_finalize() {\n') for cmd in finalizer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``database.h`` ############################################################################### def mk_pat_db_internal(inputFilePath, outputFilePath): """ Generate ``g_pattern_database[]`` declaration header file. """ with open(inputFilePath, 'r') as fin: with open(outputFilePath, 'w') as fout: fout.write('static char const g_pattern_database[] =\n') for line in fin: fout.write('"%s\\n"\n' % line.strip('\n')) fout.write(';\n') ############################################################################### # Functions and data structures for generating ``*_params.hpp`` files from # ``*.pyg`` files ############################################################################### UINT = 0 BOOL = 1 DOUBLE = 2 STRING = 3 SYMBOL = 4 UINT_MAX = 4294967295 TYPE2CPK = { UINT : 'CPK_UINT', BOOL : 'CPK_BOOL', DOUBLE : 'CPK_DOUBLE', STRING : 'CPK_STRING', SYMBOL : 'CPK_SYMBOL' } TYPE2CTYPE = { UINT : 'unsigned', BOOL : 'bool', DOUBLE : 'double', STRING : 'char const *', SYMBOL : 'symbol' } TYPE2GETTER = { UINT : 'get_uint', BOOL : 'get_bool', DOUBLE : 'get_double', STRING : 'get_str', SYMBOL : 'get_sym' } def pyg_default(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" return p[2] def pyg_default_as_c_literal(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" elif p[1] == STRING: return '"%s"' % p[2] elif p[1] == SYMBOL: return 'symbol("%s")' % p[2] elif p[1] == UINT: return '%su' % p[2] else: return p[2] def to_c_method(s): return s.replace('.', '_') def max_memory_param(): return ('max_memory', UINT, UINT_MAX, 'maximum amount of memory in megabytes') def max_steps_param(): return ('max_steps', UINT, UINT_MAX, 'maximum number of steps') def mk_hpp_from_pyg(pyg_file, output_dir): """ Generates the corresponding header file for the input pyg file at the path ``pyg_file``. The file is emitted into the directory ``output_dir``. Returns the path to the generated file """ CURRENT_PYG_HPP_DEST_DIR = output_dir # Note OUTPUT_HPP_FILE cannot be a string as we need a mutable variable # for the nested function to modify OUTPUT_HPP_FILE = [ ] # The function below has been nested so that it can use closure to capture # the above variables that aren't global but instead local to this # function. This avoids use of global state which makes this function safer. def def_module_params(module_name, export, params, class_name=None, description=None): dirname = CURRENT_PYG_HPP_DEST_DIR assert(os.path.exists(dirname)) if class_name is None: class_name = '%s_params' % module_name hpp = os.path.join(dirname, '%s.hpp' % class_name) out = open(hpp, 'w') out.write('// Automatically generated file\n') out.write('#ifndef __%s_HPP_\n' % class_name.upper()) out.write('#define __%s_HPP_\n' % class_name.upper()) out.write('#include "util/params.h"\n') if export: out.write('#include "util/gparams.h"\n') out.write('struct %s {\n' % class_name) out.write(' params_ref const & p;\n') if export: out.write(' params_ref g;\n') out.write(' %s(params_ref const & _p = params_ref::get_empty()):\n' % class_name) out.write(' p(_p)') if export: out.write(', g(gparams::get_module("%s"))' % module_name) out.write(' {}\n') out.write(' static void collect_param_descrs(param_descrs & d) {\n') for param in params: out.write(' d.insert("%s", %s, "%s", "%s","%s");\n' % (param[0], TYPE2CPK[param[1]], param[3], pyg_default(param), module_name)) out.write(' }\n') if export: out.write(' /*\n') out.write(" REG_MODULE_PARAMS('%s', '%s::collect_param_descrs')\n" % (module_name, class_name)) if description is not None: out.write(" REG_MODULE_DESCRIPTION('%s', '%s')\n" % (module_name, description)) out.write(' */\n') # Generated accessors for param in params: if export: out.write(' %s %s() const { return p.%s("%s", g, %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) else: out.write(' %s %s() const { return p.%s("%s", %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) out.write('};\n') out.write('#endif\n') out.close() OUTPUT_HPP_FILE.append(hpp) # Globals to use when executing the ``.pyg`` file. pyg_globals = { 'UINT' : UINT, 'BOOL' : BOOL, 'DOUBLE' : DOUBLE, 'STRING' : STRING, 'SYMBOL' : SYMBOL, 'UINT_MAX' : UINT_MAX, 'max_memory_param' : max_memory_param, 'max_steps_param' : max_steps_param, # Note that once this function is enterred that function # executes with respect to the globals of this module and # not the globals defined here 'def_module_params' : def_module_params, } with open(pyg_file, 'r') as fh: eval(fh.read() + "\n", pyg_globals, None) assert len(OUTPUT_HPP_FILE) == 1 return OUTPUT_HPP_FILE[0]
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_genfile_common.py
mk_genfile_common.py
from mk_util import * def init_version(): set_version(4, 8, 8, 0) # Z3 Project definition def init_project_def(): init_version() add_lib('util', [], includes2install = ['z3_version.h']) add_lib('polynomial', ['util'], 'math/polynomial') add_lib('interval', ['util'], 'math/interval') add_lib('dd', ['util', 'interval'], 'math/dd') add_lib('simplex', ['util'], 'math/simplex') add_lib('hilbert', ['util'], 'math/hilbert') add_lib('automata', ['util'], 'math/automata') add_lib('realclosure', ['interval'], 'math/realclosure') add_lib('subpaving', ['interval'], 'math/subpaving') add_lib('ast', ['util', 'polynomial']) add_lib('grobner', ['ast', 'dd', 'simplex'], 'math/grobner') add_lib('sat', ['util','dd', 'grobner']) add_lib('nlsat', ['polynomial', 'sat']) add_lib('lp', ['util','nlsat','grobner', 'interval'], 'math/lp') add_lib('rewriter', ['ast', 'polynomial', 'automata'], 'ast/rewriter') add_lib('macros', ['rewriter'], 'ast/macros') add_lib('normal_forms', ['rewriter'], 'ast/normal_forms') add_lib('model', ['rewriter']) add_lib('tactic', ['ast', 'model']) add_lib('substitution', ['ast', 'rewriter'], 'ast/substitution') add_lib('parser_util', ['ast'], 'parsers/util') add_lib('proofs', ['rewriter', 'util'], 'ast/proofs') add_lib('solver', ['model', 'tactic', 'proofs']) add_lib('cmd_context', ['solver', 'rewriter']) add_lib('sat_tactic', ['tactic', 'sat', 'solver'], 'sat/tactic') add_lib('smt2parser', ['cmd_context', 'parser_util'], 'parsers/smt2') add_lib('pattern', ['normal_forms', 'smt2parser', 'rewriter'], 'ast/pattern') add_lib('core_tactics', ['tactic', 'macros', 'normal_forms', 'rewriter', 'pattern'], 'tactic/core') add_lib('arith_tactics', ['core_tactics', 'sat'], 'tactic/arith') add_lib('nlsat_tactic', ['nlsat', 'sat_tactic', 'arith_tactics'], 'nlsat/tactic') add_lib('subpaving_tactic', ['core_tactics', 'subpaving'], 'math/subpaving/tactic') add_lib('aig_tactic', ['tactic'], 'tactic/aig') add_lib('ackermannization', ['model', 'rewriter', 'ast', 'solver', 'tactic'], 'ackermannization') add_lib('fpa', ['ast', 'util', 'rewriter', 'model'], 'ast/fpa') add_lib('bit_blaster', ['rewriter', 'rewriter'], 'ast/rewriter/bit_blaster') add_lib('smt_params', ['ast', 'rewriter', 'pattern', 'bit_blaster'], 'smt/params') add_lib('proto_model', ['model', 'rewriter', 'smt_params'], 'smt/proto_model') add_lib('smt', ['bit_blaster', 'macros', 'normal_forms', 'cmd_context', 'proto_model', 'substitution', 'grobner', 'simplex', 'proofs', 'pattern', 'parser_util', 'fpa', 'lp']) add_lib('bv_tactics', ['tactic', 'bit_blaster', 'core_tactics'], 'tactic/bv') add_lib('fuzzing', ['ast'], 'test/fuzzing') add_lib('smt_tactic', ['smt'], 'smt/tactic') add_lib('sls_tactic', ['tactic', 'normal_forms', 'core_tactics', 'bv_tactics'], 'tactic/sls') add_lib('qe', ['smt','sat','nlsat','tactic','nlsat_tactic'], 'qe') add_lib('sat_solver', ['solver', 'core_tactics', 'aig_tactic', 'bv_tactics', 'arith_tactics', 'sat_tactic'], 'sat/sat_solver') add_lib('fd_solver', ['core_tactics', 'arith_tactics', 'sat_solver', 'smt'], 'tactic/fd_solver') add_lib('muz', ['smt', 'sat', 'smt2parser', 'aig_tactic', 'qe'], 'muz/base') add_lib('dataflow', ['muz'], 'muz/dataflow') add_lib('transforms', ['muz', 'hilbert', 'dataflow'], 'muz/transforms') add_lib('rel', ['muz', 'transforms'], 'muz/rel') add_lib('spacer', ['muz', 'transforms', 'arith_tactics', 'smt_tactic'], 'muz/spacer') add_lib('clp', ['muz', 'transforms'], 'muz/clp') add_lib('tab', ['muz', 'transforms'], 'muz/tab') add_lib('ddnf', ['muz', 'transforms', 'rel'], 'muz/ddnf') add_lib('bmc', ['muz', 'transforms', 'fd_solver'], 'muz/bmc') add_lib('fp', ['muz', 'clp', 'tab', 'rel', 'bmc', 'ddnf', 'spacer'], 'muz/fp') add_lib('ufbv_tactic', ['normal_forms', 'core_tactics', 'macros', 'smt_tactic', 'rewriter'], 'tactic/ufbv') add_lib('smtlogic_tactics', ['ackermannization', 'sat_solver', 'arith_tactics', 'bv_tactics', 'nlsat_tactic', 'smt_tactic', 'aig_tactic', 'fp', 'muz','qe'], 'tactic/smtlogics') add_lib('fpa_tactics', ['fpa', 'core_tactics', 'bv_tactics', 'sat_tactic', 'smt_tactic', 'arith_tactics', 'smtlogic_tactics'], 'tactic/fpa') add_lib('portfolio', ['smtlogic_tactics', 'sat_solver', 'ufbv_tactic', 'fpa_tactics', 'aig_tactic', 'fp', 'fd_solver', 'qe','sls_tactic', 'subpaving_tactic'], 'tactic/portfolio') add_lib('opt', ['smt', 'smtlogic_tactics', 'sls_tactic', 'sat_solver'], 'opt') API_files = ['z3_api.h', 'z3_ast_containers.h', 'z3_algebraic.h', 'z3_polynomial.h', 'z3_rcf.h', 'z3_fixedpoint.h', 'z3_optimization.h', 'z3_fpa.h', 'z3_spacer.h'] add_lib('api', ['portfolio', 'realclosure', 'opt'], includes2install=['z3.h', 'z3_v1.h', 'z3_macros.h'] + API_files) add_lib('extra_cmds', ['cmd_context', 'subpaving_tactic', 'qe', 'arith_tactics'], 'cmd_context/extra_cmds') add_exe('shell', ['api', 'sat', 'extra_cmds','opt'], exe_name='z3') add_exe('test', ['api', 'fuzzing', 'simplex'], exe_name='test-z3', install=False) _libz3Component = add_dll('api_dll', ['api', 'sat', 'extra_cmds'], 'api/dll', reexports=['api'], dll_name='libz3', static=build_static_lib(), export_files=API_files, staging_link='python') add_dot_net_core_dll('dotnet', ['api_dll'], 'api/dotnet', dll_name='Microsoft.Z3', default_key_file='src/api/dotnet/Microsoft.Z3.snk') add_java_dll('java', ['api_dll'], 'api/java', dll_name='libz3java', package_name="com.microsoft.z3", manifest_file='manifest') add_ml_lib('ml', ['api_dll'], 'api/ml', lib_name='libz3ml') add_hlib('cpp', 'api/c++', includes2install=['z3++.h']) set_z3py_dir('api/python') add_python(_libz3Component) add_python_install(_libz3Component) add_js() # Examples add_cpp_example('cpp_example', 'c++') add_cpp_example('z3_tptp', 'tptp') add_c_example('c_example', 'c') add_c_example('maxsat') add_dotnet_example('dotnet_example', 'dotnet') add_java_example('java_example', 'java') add_ml_example('ml_example', 'ml') add_z3py_example('py_example', 'python') return API_files
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_project.py
mk_project.py
import os import glob import re import getopt import sys import shutil import subprocess import zipfile from mk_exception import * from mk_project import * import mk_util BUILD_DIR='build-dist' BUILD_X64_DIR=os.path.join('build-dist', 'x64') BUILD_X86_DIR=os.path.join('build-dist', 'x86') VERBOSE=True DIST_DIR='dist' FORCE_MK=False DOTNET_CORE_ENABLED=True DOTNET_KEY_FILE=None JAVA_ENABLED=True ZIP_BUILD_OUTPUTS=False GIT_HASH=False PYTHON_ENABLED=True X86ONLY=False X64ONLY=False MAKEJOBS=getenv("MAKEJOBS", "24") def set_verbose(flag): global VERBOSE VERBOSE = flag def is_verbose(): return VERBOSE def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(path): global BUILD_DIR, BUILD_X86_DIR, BUILD_X64_DIR BUILD_DIR = mk_util.norm_path(path) BUILD_X86_DIR = os.path.join(path, 'x86') BUILD_X64_DIR = os.path.join(path, 'x64') mk_dir(BUILD_X86_DIR) mk_dir(BUILD_X64_DIR) def display_help(): print("mk_win_dist.py: Z3 Windows distribution generator\n") print("This script generates the zip files containing executables, dlls, header files for Windows.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") print(" -b <sudir>, --build=<subdir> subdirectory where x86 and x64 Z3 versions will be built (default: build-dist).") print(" -f, --force force script to regenerate Makefiles.") print(" --nodotnet do not include .NET bindings in the binary distribution files.") print(" --dotnet-key=<file> strongname sign the .NET assembly with the private key in <file>.") print(" --nojava do not include Java bindings in the binary distribution files.") print(" --nopython do not include Python bindings in the binary distribution files.") print(" --zip package build outputs in zip file.") print(" --githash include git hash in the Zip file.") print(" --x86-only x86 dist only.") print(" --x64-only x64 dist only.") exit(0) # Parse configuration option for mk_make script def parse_options(): global FORCE_MK, JAVA_ENABLED, ZIP_BUILD_OUTPUTS, GIT_HASH, DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, PYTHON_ENABLED, X86ONLY, X64ONLY path = BUILD_DIR options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:hsf', ['build=', 'help', 'silent', 'force', 'nojava', 'nodotnet', 'dotnet-key=', 'zip', 'githash', 'nopython', 'x86-only', 'x64-only' ]) print(options) for opt, arg in options: if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') path = arg elif opt in ('-s', '--silent'): set_verbose(False) elif opt in ('-h', '--help'): display_help() elif opt in ('-f', '--force'): FORCE_MK = True elif opt == '--nodotnet': DOTNET_CORE_ENABLED = False elif opt == '--nopython': PYTHON_ENABLED = False elif opt == '--dotnet-key': DOTNET_KEY_FILE = arg elif opt == '--nojava': JAVA_ENABLED = False elif opt == '--zip': ZIP_BUILD_OUTPUTS = True elif opt == '--githash': GIT_HASH = True elif opt == '--x86-only' and not X64ONLY: X86ONLY = True elif opt == '--x64-only' and not X86ONLY: X64ONLY = True else: raise MKException("Invalid command line option '%s'" % opt) set_build_dir(path) # Check whether build directory already exists or not def check_build_dir(path): return os.path.exists(path) and os.path.exists(os.path.join(path, 'Makefile')) # Create a build directory using mk_make.py def mk_build_dir(path, x64): if not check_build_dir(path) or FORCE_MK: parallel = '--parallel=' + MAKEJOBS opts = ["python", os.path.join('scripts', 'mk_make.py'), parallel, "-b", path] if DOTNET_CORE_ENABLED: opts.append('--dotnet') if not DOTNET_KEY_FILE is None: opts.append('--dotnet-key=' + DOTNET_KEY_FILE) if JAVA_ENABLED: opts.append('--java') if x64: opts.append('-x') if GIT_HASH: opts.append('--githash=%s' % mk_util.git_hash()) opts.append('--git-describe') if PYTHON_ENABLED: opts.append('--python') if subprocess.call(opts) != 0: raise MKException("Failed to generate build directory at '%s'" % path) # Create build directories def mk_build_dirs(): mk_build_dir(BUILD_X86_DIR, False) mk_build_dir(BUILD_X64_DIR, True) # Check if on Visual Studio command prompt def check_vc_cmd_prompt(): try: DEVNULL = open(os.devnull, 'wb') subprocess.call(['cl'], stdout=DEVNULL, stderr=DEVNULL) except: raise MKException("You must execute the mk_win_dist.py script on a Visual Studio Command Prompt") def exec_cmds(cmds): cmd_file = 'z3_tmp.cmd' f = open(cmd_file, 'w') for cmd in cmds: f.write(cmd) f.write('\n') f.close() res = 0 try: res = subprocess.call(cmd_file, shell=True) except: res = 1 try: os.erase(cmd_file) except: pass return res # Compile Z3 (if x64 == True, then it builds it in x64 mode). def mk_z3(x64): cmds = [] if x64: cmds.append('call "%VCINSTALLDIR%vcvarsall.bat" amd64') cmds.append('cd %s' % BUILD_X64_DIR) else: cmds.append('call "%VCINSTALLDIR%vcvarsall.bat" x86') cmds.append('cd %s' % BUILD_X86_DIR) cmds.append('nmake') if exec_cmds(cmds) != 0: raise MKException("Failed to make z3, x64: %s" % x64) def mk_z3s(): mk_z3(False) mk_z3(True) def get_z3_name(x64): major, minor, build, revision = get_version() if x64: platform = "x64" else: platform = "x86" if GIT_HASH: return 'z3-%s.%s.%s.%s-%s-win' % (major, minor, build, mk_util.git_hash(), platform) else: return 'z3-%s.%s.%s-%s-win' % (major, minor, build, platform) def mk_dist_dir(x64): if x64: platform = "x64" build_path = BUILD_X64_DIR else: platform = "x86" build_path = BUILD_X86_DIR dist_path = os.path.join(DIST_DIR, get_z3_name(x64)) mk_dir(dist_path) mk_util.DOTNET_CORE_ENABLED = True mk_util.DOTNET_KEY_FILE = DOTNET_KEY_FILE mk_util.JAVA_ENABLED = JAVA_ENABLED mk_util.PYTHON_ENABLED = PYTHON_ENABLED mk_win_dist(build_path, dist_path) if is_verbose(): print("Generated %s distribution folder at '%s'" % (platform, dist_path)) def mk_dist_dirs(): mk_dist_dir(False) mk_dist_dir(True) def get_dist_path(x64): return get_z3_name(x64) def mk_zip(x64): dist_path = get_dist_path(x64) old = os.getcwd() try: os.chdir(DIST_DIR) zfname = '%s.zip' % dist_path zipout = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dist_path): for f in files: zipout.write(os.path.join(root, f)) if is_verbose(): print("Generated '%s'" % zfname) except: pass os.chdir(old) # Create a zip file for each platform def mk_zips(): mk_zip(False) mk_zip(True) VS_RUNTIME_PATS = [re.compile('vcomp.*\.dll'), re.compile('msvcp.*\.dll'), re.compile('msvcr.*\.dll')] # Copy Visual Studio Runtime libraries def cp_vs_runtime(x64): if x64: platform = "x64" else: platform = "x86" vcdir = os.environ['VCINSTALLDIR'] path = '%sredist' % vcdir vs_runtime_files = [] print("Walking %s" % path) # Everything changes with every release of VS # Prior versions of VS had DLLs under "redist\x64" # There are now several variants of redistributables # The naming convention defies my understanding so # we use a "check_root" filter to find some hopefully suitable # redistributable. def check_root(root): return platform in root and ("CRT" in root or "MP" in root) and "onecore" not in root and "debug" not in root for root, dirs, files in os.walk(path): for filename in files: if fnmatch(filename, '*.dll') and check_root(root): print("Checking %s %s" % (root, filename)) for pat in VS_RUNTIME_PATS: if pat.match(filename): fname = os.path.join(root, filename) if not os.path.isdir(fname): vs_runtime_files.append(fname) if not vs_runtime_files: raise MKException("Did not find any runtime files to include") bin_dist_path = os.path.join(DIST_DIR, get_dist_path(x64), 'bin') for f in vs_runtime_files: shutil.copy(f, bin_dist_path) if is_verbose(): print("Copied '%s' to '%s'" % (f, bin_dist_path)) def cp_vs_runtimes(): cp_vs_runtime(True) cp_vs_runtime(False) def cp_license(x64): shutil.copy("LICENSE.txt", os.path.join(DIST_DIR, get_dist_path(x64))) def cp_licenses(): cp_license(True) cp_license(False) # Entry point def main(): if os.name != 'nt': raise MKException("This script is for Windows only") parse_options() check_vc_cmd_prompt() if X86ONLY: mk_build_dir(BUILD_X86_DIR, False) mk_z3(False) init_project_def() mk_dist_dir(False) cp_license(False) cp_vs_runtime(False) if ZIP_BUILD_OUTPUTS: mk_zip(False) elif X64ONLY: mk_build_dir(BUILD_X64_DIR, True) mk_z3(True) init_project_def() mk_dist_dir(True) cp_license(True) cp_vs_runtime(True) if ZIP_BUILD_OUTPUTS: mk_zip(True) else: mk_build_dirs() mk_z3s() init_project_def() mk_dist_dirs() cp_licenses() cp_vs_runtimes() if ZIP_BUILD_OUTPUTS: mk_zips() main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_win_dist.py
mk_win_dist.py
import io import sys import os import re import getopt import shutil from mk_exception import * import mk_genfile_common from fnmatch import fnmatch import distutils.sysconfig import compileall import subprocess def getenv(name, default): try: return os.environ[name].strip(' "\'') except: return default CXX=getenv("CXX", None) CC=getenv("CC", None) CPPFLAGS=getenv("CPPFLAGS", "") CXXFLAGS=getenv("CXXFLAGS", "") AR=getenv("AR", "ar") EXAMP_DEBUG_FLAG='' LDFLAGS=getenv("LDFLAGS", "") JNI_HOME=getenv("JNI_HOME", None) OCAMLC=getenv("OCAMLC", "ocamlc") OCAMLOPT=getenv("OCAMLOPT", "ocamlopt") OCAML_LIB=getenv("OCAML_LIB", None) OCAMLFIND=getenv("OCAMLFIND", "ocamlfind") CSC=getenv("CSC", None) DOTNET="dotnet" GACUTIL=getenv("GACUTIL", 'gacutil') # Standard install directories relative to PREFIX INSTALL_BIN_DIR=getenv("Z3_INSTALL_BIN_DIR", "bin") INSTALL_LIB_DIR=getenv("Z3_INSTALL_LIB_DIR", "lib") INSTALL_INCLUDE_DIR=getenv("Z3_INSTALL_INCLUDE_DIR", "include") INSTALL_PKGCONFIG_DIR=getenv("Z3_INSTALL_PKGCONFIG_DIR", os.path.join(INSTALL_LIB_DIR, 'pkgconfig')) CXX_COMPILERS=['g++', 'clang++'] C_COMPILERS=['gcc', 'clang'] CSC_COMPILERS=['csc', 'mcs'] JAVAC=None JAR=None PYTHON_PACKAGE_DIR=distutils.sysconfig.get_python_lib(prefix=getenv("PREFIX", None)) BUILD_DIR='build' REV_BUILD_DIR='..' SRC_DIR='src' EXAMPLE_DIR='examples' # Required Components Z3_DLL_COMPONENT='api_dll' PATTERN_COMPONENT='pattern' UTIL_COMPONENT='util' API_COMPONENT='api' DOTNET_COMPONENT='dotnet' DOTNET_CORE_COMPONENT='dotnet' JAVA_COMPONENT='java' ML_COMPONENT='ml' CPP_COMPONENT='cpp' PYTHON_COMPONENT='python' ##################### IS_WINDOWS=False IS_LINUX=False IS_HURD=False IS_OSX=False IS_FREEBSD=False IS_NETBSD=False IS_OPENBSD=False IS_CYGWIN=False IS_CYGWIN_MINGW=False IS_MSYS2=False VERBOSE=True DEBUG_MODE=False SHOW_CPPS = True VS_X64 = False VS_ARM = False LINUX_X64 = True ONLY_MAKEFILES = False Z3PY_SRC_DIR=None Z3JS_SRC_DIR=None VS_PROJ = False TRACE = False PYTHON_ENABLED=False DOTNET_CORE_ENABLED=False DOTNET_KEY_FILE=getenv("Z3_DOTNET_KEY_FILE", None) JAVA_ENABLED=False ML_ENABLED=False JS_ENABLED=False PYTHON_INSTALL_ENABLED=False STATIC_LIB=False STATIC_BIN=False VER_MAJOR=None VER_MINOR=None VER_BUILD=None VER_TWEAK=None PREFIX=sys.prefix GMP=False VS_PAR=False VS_PAR_NUM=8 GPROF=False GIT_HASH=False GIT_DESCRIBE=False SLOW_OPTIMIZE=False LOG_SYNC=False SINGLE_THREADED=False GUARD_CF=False ALWAYS_DYNAMIC_BASE=False FPMATH="Default" FPMATH_FLAGS="-mfpmath=sse -msse -msse2" def check_output(cmd): out = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] if out != None: enc = sys.stdout.encoding if enc != None: return out.decode(enc).rstrip('\r\n') else: return out.rstrip('\r\n') else: return "" def git_hash(): try: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) r = check_output(['git', 'show-ref', '--abbrev=12', 'refs/heads/%s' % branch]) except: raise MKException("Failed to retrieve git hash") ls = r.split(' ') if len(ls) != 2: raise MKException("Unexpected git output " + r) return ls[0] def is_windows(): return IS_WINDOWS def is_linux(): return IS_LINUX def is_hurd(): return IS_HURD def is_freebsd(): return IS_FREEBSD def is_netbsd(): return IS_NETBSD def is_openbsd(): return IS_OPENBSD def is_osx(): return IS_OSX def is_cygwin(): return IS_CYGWIN def is_cygwin_mingw(): return IS_CYGWIN_MINGW def is_msys2(): return IS_MSYS2 def norm_path(p): return os.path.expanduser(os.path.normpath(p)) def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in getenv("PATH", "").split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None class TempFile: def __init__(self, name): try: self.name = name self.fname = open(name, 'w') except: raise MKException("Failed to create temporary file '%s'" % self.name) def add(self, s): self.fname.write(s) def commit(self): self.fname.close() def __del__(self): self.fname.close() try: os.remove(self.name) except: pass def exec_cmd(cmd): if isinstance(cmd, str): cmd = cmd.split(' ') new_cmd = [] first = True for e in cmd: if first: first = False new_cmd.append(e) else: if e != "": se = e.split(' ') if len(se) > 1: for e2 in se: if e2 != "": new_cmd.append(e2) else: new_cmd.append(e) cmd = new_cmd null = open(os.devnull, 'wb') try: return subprocess.call(cmd, stdout=null, stderr=null) except: # Failed to create process return 1 finally: null.close() # rm -f fname def rmf(fname): if os.path.exists(fname): os.remove(fname) def exec_compiler_cmd(cmd): r = exec_cmd(cmd) if is_windows() or is_cygwin_mingw() or is_cygwin() or is_msys2(): rmf('a.exe') else: rmf('a.out') return r def test_cxx_compiler(cc): if is_verbose(): print("Testing %s..." % cc) t = TempFile('tst.cpp') t.add('#include<iostream>\nint main() { return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, CXXFLAGS, 'tst.cpp', LDFLAGS]) == 0 def test_c_compiler(cc): if is_verbose(): print("Testing %s..." % cc) t = TempFile('tst.c') t.add('#include<stdio.h>\nint main() { return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, 'tst.c', LDFLAGS]) == 0 def test_gmp(cc): if is_verbose(): print("Testing GMP...") t = TempFile('tstgmp.cpp') t.add('#include<gmp.h>\nint main() { mpz_t t; mpz_init(t); mpz_clear(t); return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, 'tstgmp.cpp', LDFLAGS, '-lgmp']) == 0 def test_fpmath(cc): global FPMATH_FLAGS if is_verbose(): print("Testing floating point support...") t = TempFile('tstsse.cpp') t.add('int main() { return 42; }\n') t.commit() # -Werror is needed because some versions of clang warn about unrecognized # -m flags. if exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpmath=sse -msse -msse2']) == 0: FPMATH_FLAGS="-mfpmath=sse -msse -msse2" return "SSE2-GCC" elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-msse -msse2']) == 0: FPMATH_FLAGS="-msse -msse2" return "SSE2-CLANG" elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpu=vfp -mfloat-abi=hard']) == 0: FPMATH_FLAGS="-mfpu=vfp -mfloat-abi=hard" return "ARM-VFP" else: FPMATH_FLAGS="" return "UNKNOWN" def find_jni_h(path): for root, dirs, files in os.walk(path): for f in files: if f == 'jni.h': return root return False def check_java(): global JNI_HOME global JAVAC global JAR JDK_HOME = getenv('JDK_HOME', None) # we only need to check this locally. if is_verbose(): print("Finding javac ...") if JDK_HOME is not None: if IS_WINDOWS: JAVAC = os.path.join(JDK_HOME, 'bin', 'javac.exe') else: JAVAC = os.path.join(JDK_HOME, 'bin', 'javac') if not os.path.exists(JAVAC): raise MKException("Failed to detect javac at '%s/bin'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME)) else: # Search for javac in the path. ind = 'javac' if IS_WINDOWS: ind = ind + '.exe' paths = os.getenv('PATH', None) if paths: spaths = paths.split(os.pathsep) for i in range(0, len(spaths)): cmb = os.path.join(spaths[i], ind) if os.path.exists(cmb): JAVAC = cmb break if JAVAC is None: raise MKException('No java compiler in the path, please adjust your PATH or set JDK_HOME to the location of the JDK.') if is_verbose(): print("Finding jar ...") if IS_WINDOWS: JAR = os.path.join(os.path.dirname(JAVAC), 'jar.exe') else: JAR = os.path.join(os.path.dirname(JAVAC), 'jar') if not os.path.exists(JAR): raise MKException("Failed to detect jar at '%s'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME)) if is_verbose(): print("Testing %s..." % JAVAC) t = TempFile('Hello.java') t.add('public class Hello { public static void main(String[] args) { System.out.println("Hello, World"); }}\n') t.commit() oo = TempFile('output') eo = TempFile('errout') try: subprocess.call([JAVAC, 'Hello.java', '-verbose'], stdout=oo.fname, stderr=eo.fname) oo.commit() eo.commit() except: raise MKException('Found, but failed to run Java compiler at %s' % (JAVAC)) os.remove('Hello.class') if is_verbose(): print("Finding jni.h...") if JNI_HOME is not None: if not os.path.exists(os.path.join(JNI_HOME, 'jni.h')): raise MKException("Failed to detect jni.h '%s'; the environment variable JNI_HOME is probably set to the wrong path." % os.path.join(JNI_HOME)) else: # Search for jni.h in the library directories... t = open('errout', 'r') open_pat = re.compile("\[search path for class files: (.*)\]") cdirs = [] for line in t: m = open_pat.match(line) if m: libdirs = m.group(1).split(',') for libdir in libdirs: q = os.path.dirname(libdir) if cdirs.count(q) == 0 and len(q) > 0: cdirs.append(q) t.close() # ... plus some heuristic ones. extra_dirs = [] # For the libraries, even the JDK usually uses a JRE that comes with it. To find the # headers we have to go a little bit higher up. for dir in cdirs: extra_dirs.append(os.path.abspath(os.path.join(dir, '..'))) if IS_OSX: # Apparently Apple knows best where to put stuff... extra_dirs.append('/System/Library/Frameworks/JavaVM.framework/Headers/') cdirs[len(cdirs):] = extra_dirs for dir in cdirs: q = find_jni_h(dir) if q is not False: JNI_HOME = q if JNI_HOME is None: raise MKException("Failed to detect jni.h. Possible solution: set JNI_HOME with the path to JDK.") def test_csc_compiler(c): t = TempFile('hello.cs') t.add('public class hello { public static void Main() {} }') t.commit() if is_verbose(): print ('Testing %s...' % c) r = exec_cmd([c, 'hello.cs']) try: rmf('hello.cs') rmf('hello.exe') except: pass return r == 0 def check_dotnet_core(): if not IS_WINDOWS: return r = exec_cmd([DOTNET, '--help']) if r != 0: raise MKException('Failed testing dotnet. Make sure to install and configure dotnet core utilities') def check_ml(): t = TempFile('hello.ml') t.add('print_string "Hello world!\n";;') t.commit() if is_verbose(): print ('Testing %s...' % OCAMLC) r = exec_cmd([OCAMLC, '-o', 'a.out', 'hello.ml']) if r != 0: raise MKException('Failed testing ocamlc compiler. Set environment variable OCAMLC with the path to the Ocaml compiler') if is_verbose(): print ('Testing %s...' % OCAMLOPT) r = exec_cmd([OCAMLOPT, '-o', 'a.out', 'hello.ml']) if r != 0: raise MKException('Failed testing ocamlopt compiler. Set environment variable OCAMLOPT with the path to the Ocaml native compiler. Note that ocamlopt may require flexlink to be in your path.') try: rmf('hello.cmi') rmf('hello.cmo') rmf('hello.cmx') rmf('a.out') rmf('hello.o') except: pass find_ml_lib() find_ocaml_find() def find_ocaml_find(): global OCAMLFIND if is_verbose(): print ("Testing %s..." % OCAMLFIND) r = exec_cmd([OCAMLFIND, 'printconf']) if r != 0: OCAMLFIND = '' def find_ml_lib(): global OCAML_LIB if is_verbose(): print ('Finding OCAML_LIB...') t = TempFile('output') null = open(os.devnull, 'wb') try: subprocess.call([OCAMLC, '-where'], stdout=t.fname, stderr=null) t.commit() except: raise MKException('Failed to find Ocaml library; please set OCAML_LIB') finally: null.close() t = open('output', 'r') for line in t: OCAML_LIB = line[:-1] if is_verbose(): print ('OCAML_LIB=%s' % OCAML_LIB) t.close() rmf('output') return def is64(): global LINUX_X64 return LINUX_X64 and sys.maxsize >= 2**32 def check_ar(): if is_verbose(): print("Testing ar...") if which(AR) is None: raise MKException('%s (archive tool) was not found' % AR) def find_cxx_compiler(): global CXX, CXX_COMPILERS if CXX is not None: if test_cxx_compiler(CXX): return CXX for cxx in CXX_COMPILERS: if test_cxx_compiler(cxx): CXX = cxx return CXX raise MKException('C++ compiler was not found. Try to set the environment variable CXX with the C++ compiler available in your system.') def find_c_compiler(): global CC, C_COMPILERS if CC is not None: if test_c_compiler(CC): return CC for c in C_COMPILERS: if test_c_compiler(c): CC = c return CC raise MKException('C compiler was not found. Try to set the environment variable CC with the C compiler available in your system.') def set_version(major, minor, build, revision): global VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK, GIT_DESCRIBE VER_MAJOR = major VER_MINOR = minor VER_BUILD = build VER_TWEAK = revision if GIT_DESCRIBE: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) VER_TWEAK = int(check_output(['git', 'rev-list', '--count', 'HEAD'])) def get_version(): return (VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) def get_version_string(n): if n == 3: return "{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD) return "{}.{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD,VER_TWEAK) def build_static_lib(): return STATIC_LIB def build_static_bin(): return STATIC_BIN def is_cr_lf(fname): # Check whether text files use cr/lf f = open(fname, 'r') line = f.readline() f.close() sz = len(line) return sz >= 2 and line[sz-2] == '\r' and line[sz-1] == '\n' # dos2unix in python # cr/lf --> lf def dos2unix(fname): if is_cr_lf(fname): fin = open(fname, 'r') fname_new = '%s.new' % fname fout = open(fname_new, 'w') for line in fin: line = line.rstrip('\r\n') fout.write(line) fout.write('\n') fin.close() fout.close() shutil.move(fname_new, fname) if is_verbose(): print("dos2unix '%s'" % fname) def dos2unix_tree(): for root, dirs, files in os.walk('src'): for f in files: dos2unix(os.path.join(root, f)) def check_eol(): if not IS_WINDOWS: # Linux/OSX/BSD check if the end-of-line is cr/lf if is_cr_lf('LICENSE.txt'): if is_verbose(): print("Fixing end of line...") dos2unix_tree() if os.name == 'nt': IS_WINDOWS=True # Visual Studio already displays the files being compiled SHOW_CPPS=False elif os.name == 'posix': if os.uname()[0] == 'Darwin': IS_OSX=True elif os.uname()[0] == 'Linux': IS_LINUX=True elif os.uname()[0] == 'GNU': IS_HURD=True elif os.uname()[0] == 'FreeBSD': IS_FREEBSD=True elif os.uname()[0] == 'NetBSD': IS_NETBSD=True elif os.uname()[0] == 'OpenBSD': IS_OPENBSD=True elif os.uname()[0][:6] == 'CYGWIN': IS_CYGWIN=True if (CC != None and "mingw" in CC): IS_CYGWIN_MINGW=True elif os.uname()[0].startswith('MSYS_NT') or os.uname()[0].startswith('MINGW'): IS_MSYS2=True if os.uname()[4] == 'x86_64': LINUX_X64=True else: LINUX_X64=False def display_help(exit_code): print("mk_make.py: Z3 Makefile generator\n") print("This script generates the Makefile for the Z3 theorem prover.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") if not IS_WINDOWS: print(" -p <dir>, --prefix=<dir> installation prefix (default: %s)." % PREFIX) else: print(" --parallel=num use cl option /MP with 'num' parallel processes") print(" --pypkgdir=<dir> Force a particular Python package directory (default %s)" % PYTHON_PACKAGE_DIR) print(" -b <subdir>, --build=<subdir> subdirectory where Z3 will be built (default: %s)." % BUILD_DIR) print(" --githash=hash include the given hash in the binaries.") print(" --git-describe include the output of 'git describe' in the version information.") print(" -d, --debug compile Z3 in debug mode.") print(" -t, --trace enable tracing in release mode.") if IS_WINDOWS: print(" --guardcf enable Control Flow Guard runtime checks.") print(" -x, --x64 create 64 binary when using Visual Studio.") else: print(" --x86 force 32-bit x86 build on x64 systems.") print(" -m, --makefiles generate only makefiles.") if IS_WINDOWS: print(" -v, --vsproj generate Visual Studio Project Files.") print(" --optimize generate optimized code during linking.") print(" --dotnet generate .NET platform bindings.") print(" --dotnet-key=<file> sign the .NET assembly using the private key in <file>.") print(" --java generate Java bindings.") print(" --ml generate OCaml bindings.") print(" --js generate JScript bindings.") print(" --python generate Python bindings.") print(" --staticlib build Z3 static library.") print(" --staticbin build a statically linked Z3 binary.") if not IS_WINDOWS: print(" -g, --gmp use GMP.") print(" --gprof enable gprof") print(" --log-sync synchronize access to API log files to enable multi-thread API logging.") print(" --single-threaded non-thread-safe build") print("") print("Some influential environment variables:") if not IS_WINDOWS: print(" CXX C++ compiler") print(" CC C compiler") print(" LDFLAGS Linker flags, e.g., -L<lib dir> if you have libraries in a non-standard directory") print(" CPPFLAGS Preprocessor flags, e.g., -I<include dir> if you have header files in a non-standard directory") print(" CXXFLAGS C++ compiler flags") print(" JDK_HOME JDK installation directory (only relevant if -j or --java option is provided)") print(" JNI_HOME JNI bindings directory (only relevant if -j or --java option is provided)") print(" OCAMLC Ocaml byte-code compiler (only relevant with --ml)") print(" OCAMLFIND Ocaml find tool (only relevant with --ml)") print(" OCAMLOPT Ocaml native compiler (only relevant with --ml)") print(" OCAML_LIB Ocaml library directory (only relevant with --ml)") print(" CSC C# Compiler (only relevant if .NET bindings are enabled)") print(" GACUTIL GAC Utility (only relevant if .NET bindings are enabled)") print(" Z3_INSTALL_BIN_DIR Install directory for binaries relative to install prefix") print(" Z3_INSTALL_LIB_DIR Install directory for libraries relative to install prefix") print(" Z3_INSTALL_INCLUDE_DIR Install directory for header files relative to install prefix") print(" Z3_INSTALL_PKGCONFIG_DIR Install directory for pkgconfig files relative to install prefix") exit(exit_code) # Parse configuration option for mk_make script def parse_options(): global VERBOSE, DEBUG_MODE, IS_WINDOWS, VS_X64, ONLY_MAKEFILES, SHOW_CPPS, VS_PROJ, TRACE, VS_PAR, VS_PAR_NUM global DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, JAVA_ENABLED, ML_ENABLED, JS_ENABLED, STATIC_LIB, STATIC_BIN, PREFIX, GMP, PYTHON_PACKAGE_DIR, GPROF, GIT_HASH, GIT_DESCRIBE, PYTHON_INSTALL_ENABLED, PYTHON_ENABLED global LINUX_X64, SLOW_OPTIMIZE, LOG_SYNC, SINGLE_THREADED global GUARD_CF, ALWAYS_DYNAMIC_BASE try: options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:df:sxhmcvtnp:gj', ['build=', 'debug', 'silent', 'x64', 'help', 'makefiles', 'showcpp', 'vsproj', 'guardcf', 'trace', 'dotnet', 'dotnet-key=', 'staticlib', 'prefix=', 'gmp', 'java', 'parallel=', 'gprof', 'js', 'githash=', 'git-describe', 'x86', 'ml', 'optimize', 'pypkgdir=', 'python', 'staticbin', 'log-sync', 'single-threaded']) except: print("ERROR: Invalid command line option") display_help(1) for opt, arg in options: print('opt = %s, arg = %s' % (opt, arg)) if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') set_build_dir(arg) elif opt in ('-s', '--silent'): VERBOSE = False elif opt in ('-d', '--debug'): DEBUG_MODE = True elif opt in ('-x', '--x64'): if not IS_WINDOWS: raise MKException('x64 compilation mode can only be specified when using Visual Studio') VS_X64 = True elif opt in ('--x86'): LINUX_X64=False elif opt in ('-h', '--help'): display_help(0) elif opt in ('-m', '--makefiles'): ONLY_MAKEFILES = True elif opt in ('-c', '--showcpp'): SHOW_CPPS = True elif opt in ('-v', '--vsproj'): VS_PROJ = True elif opt in ('-t', '--trace'): TRACE = True elif opt in ('--dotnet',): DOTNET_CORE_ENABLED = True elif opt in ('--dotnet-key'): DOTNET_KEY_FILE = arg elif opt in ('--staticlib'): STATIC_LIB = True elif opt in ('--staticbin'): STATIC_BIN = True elif opt in ('--optimize'): SLOW_OPTIMIZE = True elif not IS_WINDOWS and opt in ('-p', '--prefix'): PREFIX = arg elif opt in ('--pypkgdir'): PYTHON_PACKAGE_DIR = arg elif IS_WINDOWS and opt == '--parallel': VS_PAR = True VS_PAR_NUM = int(arg) elif opt in ('-g', '--gmp'): GMP = True elif opt in ('-j', '--java'): JAVA_ENABLED = True elif opt == '--gprof': GPROF = True elif opt == '--githash': GIT_HASH=arg elif opt == '--git-describe': GIT_DESCRIBE = True elif opt in ('', '--ml'): ML_ENABLED = True elif opt == "--js": JS_ENABLED = True elif opt in ('', '--log-sync'): LOG_SYNC = True elif opt == '--single-threaded': SINGLE_THREADED = True elif opt in ('--python'): PYTHON_ENABLED = True PYTHON_INSTALL_ENABLED = True elif opt == '--guardcf': GUARD_CF = True ALWAYS_DYNAMIC_BASE = True # /GUARD:CF requires /DYNAMICBASE else: print("ERROR: Invalid command line option '%s'" % opt) display_help(1) # Return a list containing a file names included using '#include' in # the given C/C++ file named fname. def extract_c_includes(fname): result = [] # We look for well behaved #include directives std_inc_pat = re.compile("[ \t]*#include[ \t]*\"(.*)\"[ \t]*") system_inc_pat = re.compile("[ \t]*#include[ \t]*\<.*\>[ \t]*") # We should generate and error for any occurrence of #include that does not match the previous pattern. non_std_inc_pat = re.compile(".*#include.*") f = io.open(fname, encoding='utf-8', mode='r') linenum = 1 for line in f: m1 = std_inc_pat.match(line) if m1: root_file_name = m1.group(1) slash_pos = root_file_name.rfind('/') if slash_pos >= 0 and root_file_name.find("..") < 0 : #it is a hack for lp include files that behave as continued from "src" # print(root_file_name) root_file_name = root_file_name[slash_pos+1:] result.append(root_file_name) elif not system_inc_pat.match(line) and non_std_inc_pat.match(line): raise MKException("Invalid #include directive at '%s':%s" % (fname, line)) linenum = linenum + 1 f.close() return result # Given a path dir1/subdir2/subdir3 returns ../../.. def reverse_path(p): # Filter out empty components (e.g. will have one if path ends in a slash) l = list(filter(lambda x: len(x) > 0, p.split(os.sep))) n = len(l) r = '..' for i in range(1, n): r = os.path.join(r, '..') return r def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(d): global BUILD_DIR, REV_BUILD_DIR BUILD_DIR = norm_path(d) REV_BUILD_DIR = reverse_path(d) def set_z3js_dir(p): global SRC_DIR, Z3JS_SRC_DIR p = norm_path(p) full = os.path.join(SRC_DIR, p) if not os.path.exists(full): raise MKException("Python bindings directory '%s' does not exist" % full) Z3JS_SRC_DIR = full if VERBOSE: print("Js bindings directory was detected.") def set_z3py_dir(p): global SRC_DIR, Z3PY_SRC_DIR p = norm_path(p) full = os.path.join(SRC_DIR, p) if not os.path.exists(full): raise MKException("Python bindings directory '%s' does not exist" % full) Z3PY_SRC_DIR = full if VERBOSE: print("Python bindings directory was detected.") _UNIQ_ID = 0 def mk_fresh_name(prefix): global _UNIQ_ID r = '%s_%s' % (prefix, _UNIQ_ID) _UNIQ_ID = _UNIQ_ID + 1 return r _Id = 0 _Components = [] _ComponentNames = set() _Name2Component = {} _Processed_Headers = set() # Return the Component object named name def get_component(name): return _Name2Component[name] def get_components(): return _Components # Return the directory where the python bindings are located. def get_z3py_dir(): return Z3PY_SRC_DIR # Return directory where the js bindings are located def get_z3js_dir(): return Z3JS_SRC_DIR # Return true if in verbose mode def is_verbose(): return VERBOSE def is_java_enabled(): return JAVA_ENABLED def is_ml_enabled(): return ML_ENABLED def is_js_enabled(): return JS_ENABLED def is_dotnet_core_enabled(): return DOTNET_CORE_ENABLED def is_python_enabled(): return PYTHON_ENABLED def is_python_install_enabled(): return PYTHON_INSTALL_ENABLED def is_compiler(given, expected): """ Return True if the 'given' compiler is the expected one. >>> is_compiler('g++', 'g++') True >>> is_compiler('/home/g++', 'g++') True >>> is_compiler(os.path.join('home', 'g++'), 'g++') True >>> is_compiler('clang++', 'g++') False >>> is_compiler(os.path.join('home', 'clang++'), 'clang++') True """ if given == expected: return True if len(expected) < len(given): return given[len(given) - len(expected) - 1] == os.sep and given[len(given) - len(expected):] == expected return False def is_CXX_gpp(): return is_compiler(CXX, 'g++') def is_clang_in_gpp_form(cc): str = check_output([cc, '--version']) try: version_string = str.encode('utf-8') except: version_string = str clang = 'clang'.encode('utf-8') return version_string.find(clang) != -1 def is_CXX_clangpp(): if is_compiler(CXX, 'g++'): return is_clang_in_gpp_form(CXX) return is_compiler(CXX, 'clang++') def get_cpp_files(path): return filter(lambda f: f.endswith('.cpp'), os.listdir(path)) def get_c_files(path): return filter(lambda f: f.endswith('.c'), os.listdir(path)) def get_cs_files(path): return filter(lambda f: f.endswith('.cs'), os.listdir(path)) def get_java_files(path): return filter(lambda f: f.endswith('.java'), os.listdir(path)) def get_ml_files(path): return filter(lambda f: f.endswith('.ml'), os.listdir(path)) def find_all_deps(name, deps): new_deps = [] for dep in deps: if dep in _ComponentNames: if not (dep in new_deps): new_deps.append(dep) for dep_dep in get_component(dep).deps: if not (dep_dep in new_deps): new_deps.append(dep_dep) else: raise MKException("Unknown component '%s' at '%s'." % (dep, name)) return new_deps class Component: def __init__(self, name, path, deps): global BUILD_DIR, SRC_DIR, REV_BUILD_DIR if name in _ComponentNames: raise MKException("Component '%s' was already defined." % name) if path is None: path = name self.name = name path = norm_path(path) self.path = path self.deps = find_all_deps(name, deps) self.build_dir = path self.src_dir = os.path.join(SRC_DIR, path) self.to_src_dir = os.path.join(REV_BUILD_DIR, self.src_dir) def get_link_name(self): return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)' # Find fname in the include paths for the given component. # ownerfile is only used for creating error messages. # That is, we were looking for fname when processing ownerfile def find_file(self, fname, ownerfile): full_fname = os.path.join(self.src_dir, fname) if os.path.exists(full_fname): return self for dep in self.deps: c_dep = get_component(dep) full_fname = os.path.join(c_dep.src_dir, fname) if os.path.exists(full_fname): return c_dep raise MKException("Failed to find include file '%s' for '%s' when processing '%s'." % (fname, ownerfile, self.name)) # Display all dependencies of file basename located in the given component directory. # The result is displayed at out def add_cpp_h_deps(self, out, basename): includes = extract_c_includes(os.path.join(self.src_dir, basename)) out.write(os.path.join(self.to_src_dir, basename)) for include in includes: owner = self.find_file(include, basename) out.write(' %s.node' % os.path.join(owner.build_dir, include)) # Add a rule for each #include directive in the file basename located at the current component. def add_rule_for_each_include(self, out, basename): fullname = os.path.join(self.src_dir, basename) includes = extract_c_includes(fullname) for include in includes: owner = self.find_file(include, fullname) owner.add_h_rule(out, include) # Display a Makefile rule for an include file located in the given component directory. # 'include' is something of the form: ast.h, polynomial.h # The rule displayed at out is of the form # ast/ast_pp.h.node : ../src/util/ast_pp.h util/util.h.node ast/ast.h.node # @echo "done" > ast/ast_pp.h.node def add_h_rule(self, out, include): include_src_path = os.path.join(self.to_src_dir, include) if include_src_path in _Processed_Headers: return _Processed_Headers.add(include_src_path) self.add_rule_for_each_include(out, include) include_node = '%s.node' % os.path.join(self.build_dir, include) out.write('%s: ' % include_node) self.add_cpp_h_deps(out, include) out.write('\n') out.write('\t@echo done > %s\n' % include_node) def add_cpp_rules(self, out, include_defs, cppfile): self.add_rule_for_each_include(out, cppfile) objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) srcfile = os.path.join(self.to_src_dir, cppfile) out.write('%s: ' % objfile) self.add_cpp_h_deps(out, cppfile) out.write('\n') if SHOW_CPPS: out.write('\t@echo %s\n' % os.path.join(self.src_dir, cppfile)) out.write('\t@$(CXX) $(CXXFLAGS) $(%s) $(CXX_OUT_FLAG)%s %s\n' % (include_defs, objfile, srcfile)) def mk_makefile(self, out): include_defs = mk_fresh_name('includes') out.write('%s =' % include_defs) for dep in self.deps: out.write(' -I%s' % get_component(dep).to_src_dir) out.write(' -I%s' % os.path.join(REV_BUILD_DIR,"src")) out.write('\n') mk_dir(os.path.join(BUILD_DIR, self.build_dir)) if VS_PAR and IS_WINDOWS: cppfiles = list(get_cpp_files(self.src_dir)) dependencies = set() for cppfile in cppfiles: dependencies.add(os.path.join(self.to_src_dir, cppfile)) self.add_rule_for_each_include(out, cppfile) includes = extract_c_includes(os.path.join(self.src_dir, cppfile)) for include in includes: owner = self.find_file(include, cppfile) dependencies.add('%s.node' % os.path.join(owner.build_dir, include)) for cppfile in cppfiles: out.write('%s$(OBJ_EXT) ' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])) out.write(': ') for dep in dependencies: out.write(dep) out.write(' ') out.write('\n') out.write('\t@$(CXX) $(CXXFLAGS) /MP%s $(%s)' % (VS_PAR_NUM, include_defs)) for cppfile in cppfiles: out.write(' ') out.write(os.path.join(self.to_src_dir, cppfile)) out.write('\n') out.write('\tmove *.obj %s\n' % self.build_dir) else: for cppfile in get_cpp_files(self.src_dir): self.add_cpp_rules(out, include_defs, cppfile) # Return true if the component should be included in the all: rule def main_component(self): return False # Return true if the component contains an AssemblyInfo.cs file that needs to be updated. def has_assembly_info(self): return False # Return true if the component needs builder to generate an install_tactics.cpp file def require_install_tactics(self): return False # Return true if the component needs a def file def require_def_file(self): return False # Return true if the component needs builder to generate a mem_initializer.cpp file with mem_initialize() and mem_finalize() functions. def require_mem_initializer(self): return False def mk_install_deps(self, out): return def mk_install(self, out): return def mk_uninstall(self, out): return def is_example(self): return False # Invoked when creating a (windows) distribution package using components at build_path, and # storing them at dist_path def mk_win_dist(self, build_path, dist_path): return def mk_unix_dist(self, build_path, dist_path): return # Used to print warnings or errors after mk_make.py is done, so that they # are not quite as easy to miss. def final_info(self): pass class LibComponent(Component): def __init__(self, name, path, deps, includes2install): Component.__init__(self, name, path, deps) self.includes2install = includes2install def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for lib objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) libfile = '%s$(LIB_EXT)' % os.path.join(self.build_dir, self.name) out.write('%s:' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('%s: %s\n\n' % (self.name, libfile)) def mk_install_deps(self, out): return def mk_install(self, out): for include in self.includes2install: MakeRuleCmd.install_files( out, os.path.join(self.to_src_dir, include), os.path.join(INSTALL_INCLUDE_DIR, include) ) def mk_uninstall(self, out): for include in self.includes2install: MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_INCLUDE_DIR, include)) def mk_win_dist(self, build_path, dist_path): mk_dir(os.path.join(dist_path, INSTALL_INCLUDE_DIR)) for include in self.includes2install: shutil.copy(os.path.join(self.src_dir, include), os.path.join(dist_path, INSTALL_INCLUDE_DIR, include)) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) # "Library" containing only .h files. This is just a placeholder for includes files to be installed. class HLibComponent(LibComponent): def __init__(self, name, path, includes2install): LibComponent.__init__(self, name, path, [], includes2install) def mk_makefile(self, out): return # Auxiliary function for sort_components def comp_components(c1, c2): id1 = get_component(c1).id id2 = get_component(c2).id return id2 - id1 # Sort components based on (reverse) definition time def sort_components(cnames): return sorted(cnames, key=lambda c: get_component(c).id, reverse=True) class ExeComponent(Component): def __init__(self, name, exe_name, path, deps, install): Component.__init__(self, name, path, deps) if exe_name is None: exe_name = name self.exe_name = exe_name self.install = install def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for exe exefile = '%s$(EXE_EXT)' % self.exe_name out.write('%s:' % exefile) deps = sort_components(self.deps) objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) for obj in objs: out.write(' ') out.write(obj) for dep in deps: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write('\n') extra_opt = '-static' if not IS_WINDOWS and STATIC_BIN else '' out.write('\t$(LINK) %s $(LINK_OUT_FLAG)%s $(LINK_FLAGS)' % (extra_opt, exefile)) for obj in objs: out.write(' ') out.write(obj) for dep in deps: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('%s: %s\n\n' % (self.name, exefile)) def require_install_tactics(self): return ('tactic' in self.deps) and ('cmd_context' in self.deps) def require_mem_initializer(self): return True # All executables (to be installed) are included in the all: rule def main_component(self): return self.install def mk_install_deps(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name out.write('%s' % exefile) def mk_install(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name MakeRuleCmd.install_files(out, exefile, os.path.join(INSTALL_BIN_DIR, exefile)) def mk_uninstall(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_BIN_DIR, exefile)) def mk_win_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.exe' % os.path.join(build_path, self.exe_name), '%s.exe' % os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name)) def mk_unix_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy(os.path.join(build_path, self.exe_name), os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name)) class ExtraExeComponent(ExeComponent): def __init__(self, name, exe_name, path, deps, install): ExeComponent.__init__(self, name, exe_name, path, deps, install) def main_component(self): return False def require_mem_initializer(self): return False def get_so_ext(): sysname = os.uname()[0] if sysname == 'Darwin': return 'dylib' elif sysname == 'Linux' or sysname == 'GNU' or sysname == 'FreeBSD' or sysname == 'NetBSD' or sysname == 'OpenBSD': return 'so' elif sysname == 'CYGWIN' or sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'): return 'dll' else: assert(False) return 'dll' class DLLComponent(Component): def __init__(self, name, dll_name, path, deps, export_files, reexports, install, static, staging_link=None): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name self.dll_name = dll_name self.export_files = export_files self.reexports = reexports self.install = install self.static = static self.staging_link = staging_link # link a copy of the shared object into this directory on build def get_link_name(self): if self.static: return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)' else: return self.name + '$(SO_EXT)' def dll_file(self): """ Return file name of component suitable for use in a Makefile """ return '%s$(SO_EXT)' % self.dll_name def install_path(self): """ Return install location of component (relative to prefix) suitable for use in a Makefile """ return os.path.join(INSTALL_LIB_DIR, self.dll_file()) def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for (SO_EXT) out.write('%s:' % self.dll_file()) deps = sort_components(self.deps) objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) # Explicitly include obj files of reexport. This fixes problems with exported symbols on Linux and OSX. for reexport in self.reexports: reexport = get_component(reexport) for cppfile in get_cpp_files(reexport.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(reexport.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) for obj in objs: out.write(' ') out.write(obj) for dep in deps: if dep not in self.reexports: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write('\n') out.write('\t$(LINK) $(SLINK_OUT_FLAG)%s $(SLINK_FLAGS)' % self.dll_file()) for obj in objs: out.write(' ') out.write(obj) for dep in deps: if dep not in self.reexports: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write(' $(SLINK_EXTRA_FLAGS)') if IS_WINDOWS: out.write(' /DEF:%s.def' % os.path.join(self.to_src_dir, self.name)) if self.staging_link: if IS_WINDOWS: out.write('\n\tcopy %s %s' % (self.dll_file(), self.staging_link)) elif IS_OSX: out.write('\n\tcp %s %s' % (self.dll_file(), self.staging_link)) else: out.write('\n\tln -f -s %s %s' % (os.path.join(reverse_path(self.staging_link), self.dll_file()), self.staging_link)) out.write('\n') if self.static: if IS_WINDOWS: libfile = '%s-static$(LIB_EXT)' % self.dll_name else: libfile = '%s$(LIB_EXT)' % self.dll_name self.mk_static(out, libfile) out.write('%s: %s %s\n\n' % (self.name, self.dll_file(), libfile)) else: out.write('%s: %s\n\n' % (self.name, self.dll_file())) def mk_static(self, out, libfile): # generate rule for lib objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) # we have to "reexport" all object files for dep in self.deps: dep = get_component(dep) for cppfile in get_cpp_files(dep.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(dep.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) out.write('%s:' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') def main_component(self): return self.install def require_install_tactics(self): return ('tactic' in self.deps) and ('cmd_context' in self.deps) def require_mem_initializer(self): return True def require_def_file(self): return IS_WINDOWS and self.export_files def mk_install_deps(self, out): out.write('%s$(SO_EXT)' % self.dll_name) if self.static: out.write(' %s$(LIB_EXT)' % self.dll_name) def mk_install(self, out): if self.install: MakeRuleCmd.install_files(out, self.dll_file(), self.install_path()) if self.static: libfile = '%s$(LIB_EXT)' % self.dll_name MakeRuleCmd.install_files(out, libfile, os.path.join(INSTALL_LIB_DIR, libfile)) def mk_uninstall(self, out): MakeRuleCmd.remove_installed_files(out, self.install_path()) libfile = '%s$(LIB_EXT)' % self.dll_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, libfile)) def mk_win_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.lib' % os.path.join(build_path, self.dll_name), '%s.lib' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_unix_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) so = get_so_ext() shutil.copy('%s.%s' % (os.path.join(build_path, self.dll_name), so), '%s.%s' % (os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name), so)) shutil.copy('%s.a' % os.path.join(build_path, self.dll_name), '%s.a' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) class JsComponent(Component): def __init__(self): Component.__init__(self, "js", None, []) def main_component(self): return False def mk_win_dist(self, build_path, dist_path): return def mk_unix_dist(self, build_path, dist_path): return def mk_makefile(self, out): return class PythonComponent(Component): def __init__(self, name, libz3Component): assert isinstance(libz3Component, DLLComponent) global PYTHON_ENABLED Component.__init__(self, name, None, []) self.libz3Component = libz3Component def main_component(self): return False def mk_win_dist(self, build_path, dist_path): if not is_python_enabled(): return src = os.path.join(build_path, 'python', 'z3') dst = os.path.join(dist_path, INSTALL_BIN_DIR, 'python', 'z3') if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) def mk_makefile(self, out): return class PythonInstallComponent(Component): def __init__(self, name, libz3Component): assert isinstance(libz3Component, DLLComponent) global PYTHON_INSTALL_ENABLED Component.__init__(self, name, None, []) self.pythonPkgDir = None self.in_prefix_install = True self.libz3Component = libz3Component if not PYTHON_INSTALL_ENABLED: return if IS_WINDOWS: # Installing under Windows doesn't make sense as the install prefix is used # but that doesn't make sense under Windows # CMW: It makes perfectly good sense; the prefix is Python's sys.prefix, # i.e., something along the lines of C:\Python\... At the moment we are not # sure whether we would want to install libz3.dll into that directory though. PYTHON_INSTALL_ENABLED = False return else: PYTHON_INSTALL_ENABLED = True if IS_WINDOWS or IS_OSX: # Use full path that is possibly outside of install prefix self.in_prefix_install = PYTHON_PACKAGE_DIR.startswith(PREFIX) self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX) else: # Use path inside the prefix (should be the normal case on Linux) # CMW: Also normal on *BSD? if not PYTHON_PACKAGE_DIR.startswith(PREFIX): raise MKException(('The python package directory ({}) must live ' + 'under the install prefix ({}) to install the python bindings.' + 'Use --pypkgdir and --prefix to set the python package directory ' + 'and install prefix respectively. Note that the python package ' + 'directory does not need to exist and will be created if ' + 'necessary during install.').format( PYTHON_PACKAGE_DIR, PREFIX)) self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX) self.in_prefix_install = True if self.in_prefix_install: assert not os.path.isabs(self.pythonPkgDir) def final_info(self): if not PYTHON_PACKAGE_DIR.startswith(PREFIX) and PYTHON_INSTALL_ENABLED: print("Warning: The detected Python package directory (%s) is not " "in the installation prefix (%s). This can lead to a broken " "Python API installation. Use --pypkgdir= to change the " "Python package directory." % (PYTHON_PACKAGE_DIR, PREFIX)) def main_component(self): return False def mk_install(self, out): if not is_python_install_enabled(): return MakeRuleCmd.make_install_directory(out, os.path.join(self.pythonPkgDir, 'z3'), in_prefix=self.in_prefix_install) MakeRuleCmd.make_install_directory(out, os.path.join(self.pythonPkgDir, 'z3', 'lib'), in_prefix=self.in_prefix_install) # Sym-link or copy libz3 into python package directory if IS_WINDOWS or IS_OSX: MakeRuleCmd.install_files(out, self.libz3Component.dll_file(), os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file()), in_prefix=self.in_prefix_install ) else: # Create symbolic link to save space. # It's important that this symbolic link be relative (rather # than absolute) so that the install is relocatable (needed for # staged installs that use DESTDIR). MakeRuleCmd.create_relative_symbolic_link(out, self.libz3Component.install_path(), os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file() ), ) MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '*.py'), os.path.join(self.pythonPkgDir, 'z3'), in_prefix=self.in_prefix_install) if sys.version >= "3": pythonPycacheDir = os.path.join(self.pythonPkgDir, 'z3', '__pycache__') MakeRuleCmd.make_install_directory(out, pythonPycacheDir, in_prefix=self.in_prefix_install) MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '__pycache__', '*.pyc'), pythonPycacheDir, in_prefix=self.in_prefix_install) else: MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '*.pyc'), os.path.join(self.pythonPkgDir,'z3'), in_prefix=self.in_prefix_install) if PYTHON_PACKAGE_DIR != distutils.sysconfig.get_python_lib(): out.write('\t@echo Z3Py was installed at \'%s\', make sure this directory is in your PYTHONPATH environment variable.' % PYTHON_PACKAGE_DIR) def mk_uninstall(self, out): if not is_python_install_enabled(): return MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, self.libz3Component.dll_file()), in_prefix=self.in_prefix_install ) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '*.py'), in_prefix=self.in_prefix_install) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '*.pyc'), in_prefix=self.in_prefix_install) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '__pycache__', '*.pyc'), in_prefix=self.in_prefix_install ) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file())) def mk_makefile(self, out): return def set_key_file(self): global DOTNET_KEY_FILE # We need to give the assembly a strong name so that it # can be installed into the GAC with ``make install`` if not DOTNET_KEY_FILE is None: self.key_file = DOTNET_KEY_FILE if not self.key_file is None: if os.path.isfile(self.key_file): self.key_file = os.path.abspath(self.key_file) elif os.path.isfile(os.path.join(self.src_dir, self.key_file)): self.key_file = os.path.abspath(os.path.join(self.src_dir, self.key_file)) else: print("Keyfile '%s' could not be found; %s.dll will be unsigned." % (self.key_file, self.dll_name)) self.key_file = None # build for dotnet core class DotNetDLLComponent(Component): def __init__(self, name, dll_name, path, deps, assembly_info_dir, default_key_file): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name if assembly_info_dir is None: assembly_info_dir = "." self.dll_name = dll_name self.assembly_info_dir = assembly_info_dir self.key_file = default_key_file def mk_makefile(self, out): if not is_dotnet_core_enabled(): return cs_fp_files = [] for cs_file in get_cs_files(self.src_dir): cs_fp_files.append(os.path.join(self.to_src_dir, cs_file)) if self.assembly_info_dir != '.': for cs_file in get_cs_files(os.path.join(self.src_dir, self.assembly_info_dir)): cs_fp_files.append(os.path.join(self.to_src_dir, self.assembly_info_dir, cs_file)) dllfile = '%s.dll' % self.dll_name out.write('%s: %s$(SO_EXT)' % (dllfile, get_component(Z3_DLL_COMPONENT).dll_name)) for cs_file in cs_fp_files: out.write(' ') out.write(cs_file) out.write('\n') set_key_file(self) key = "" if not self.key_file is None: key = "<AssemblyOriginatorKeyFile>%s</AssemblyOriginatorKeyFile>" % self.key_file key += "\n<SignAssembly>true</SignAssembly>" version = get_version_string(3) core_csproj_str = """<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.4</TargetFramework> <DefineConstants>$(DefineConstants);DOTNET_CORE</DefineConstants> <DebugType>portable</DebugType> <AssemblyName>Microsoft.Z3</AssemblyName> <OutputType>Library</OutputType> <PackageId>Microsoft.Z3</PackageId> <RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion> <Version>%s</Version> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <Authors>Microsoft</Authors> <Company>Microsoft</Company> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <Description>Z3 is a satisfiability modulo theories solver from Microsoft Research.</Description> <Copyright>Copyright Microsoft Corporation. All rights reserved.</Copyright> <PackageTags>smt constraint solver theorem prover</PackageTags> %s </PropertyGroup> <ItemGroup> <Compile Include="..\%s\*.cs;*.cs" Exclude="bin\**;obj\**;**\*.xproj;packages\**" /> </ItemGroup> </Project>""" % (version, key, self.to_src_dir) mk_dir(os.path.join(BUILD_DIR, 'dotnet')) csproj = os.path.join('dotnet', 'z3.csproj') with open(os.path.join(BUILD_DIR, csproj), 'w') as ous: ous.write(core_csproj_str) dotnetCmdLine = [DOTNET, "build", csproj] dotnetCmdLine.extend(['-c']) if DEBUG_MODE: dotnetCmdLine.extend(['Debug']) else: dotnetCmdLine.extend(['Release']) path = os.path.join(os.path.abspath(BUILD_DIR), ".") dotnetCmdLine.extend(['-o', path]) MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine)) out.write('\n') out.write('%s: %s\n\n' % (self.name, dllfile)) def main_component(self): return is_dotnet_core_enabled() def has_assembly_info(self): # TBD: is this required for dotnet core given that version numbers are in z3.csproj file? return False def mk_win_dist(self, build_path, dist_path): if is_dotnet_core_enabled(): mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name), '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) if DEBUG_MODE: shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_unix_dist(self, build_path, dist_path): if is_dotnet_core_enabled(): mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name), '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_install_deps(self, out): pass def mk_install(self, out): pass def mk_uninstall(self, out): pass class JavaDLLComponent(Component): def __init__(self, name, dll_name, package_name, manifest_file, path, deps): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name self.dll_name = dll_name self.package_name = package_name self.manifest_file = manifest_file self.install = not is_windows() def mk_makefile(self, out): global JAVAC global JAR if is_java_enabled(): mk_dir(os.path.join(BUILD_DIR, 'api', 'java', 'classes')) dllfile = '%s$(SO_EXT)' % self.dll_name out.write('libz3java$(SO_EXT): libz3$(SO_EXT) %s\n' % os.path.join(self.to_src_dir, 'Native.cpp')) t = '\t$(CXX) $(CXXFLAGS) $(CXX_OUT_FLAG)api/java/Native$(OBJ_EXT) -I"%s" -I"%s/PLATFORM" -I%s %s/Native.cpp\n' % (JNI_HOME, JNI_HOME, get_component('api').to_src_dir, self.to_src_dir) if IS_OSX: t = t.replace('PLATFORM', 'darwin') elif is_linux(): t = t.replace('PLATFORM', 'linux') elif is_hurd(): t = t.replace('PLATFORM', 'hurd') elif IS_FREEBSD: t = t.replace('PLATFORM', 'freebsd') elif IS_NETBSD: t = t.replace('PLATFORM', 'netbsd') elif IS_OPENBSD: t = t.replace('PLATFORM', 'openbsd') elif IS_CYGWIN: t = t.replace('PLATFORM', 'cygwin') elif IS_MSYS2: t = t.replace('PLATFORM', 'win32') else: t = t.replace('PLATFORM', 'win32') out.write(t) if IS_WINDOWS: # On Windows, CL creates a .lib file to link against. out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(LIB_EXT)\n' % os.path.join('api', 'java', 'Native')) else: out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(SO_EXT)\n' % os.path.join('api', 'java', 'Native')) out.write('%s.jar: libz3java$(SO_EXT) ' % self.package_name) deps = '' for jfile in get_java_files(self.src_dir): deps += ('%s ' % os.path.join(self.to_src_dir, jfile)) for jfile in get_java_files(os.path.join(self.src_dir, "enumerations")): deps += '%s ' % os.path.join(self.to_src_dir, 'enumerations', jfile) out.write(deps) out.write('\n') #if IS_WINDOWS: JAVAC = '"%s"' % JAVAC JAR = '"%s"' % JAR t = ('\t%s %s.java -d %s\n' % (JAVAC, os.path.join(self.to_src_dir, 'enumerations', '*'), os.path.join('api', 'java', 'classes'))) out.write(t) t = ('\t%s -cp %s %s.java -d %s\n' % (JAVAC, os.path.join('api', 'java', 'classes'), os.path.join(self.to_src_dir, '*'), os.path.join('api', 'java', 'classes'))) out.write(t) out.write('\t%s cfm %s.jar %s -C %s .\n' % (JAR, self.package_name, os.path.join(self.to_src_dir, 'manifest'), os.path.join('api', 'java', 'classes'))) out.write('java: %s.jar\n\n' % self.package_name) def main_component(self): return is_java_enabled() def mk_win_dist(self, build_path, dist_path): if JAVA_ENABLED: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.jar' % os.path.join(build_path, self.package_name), '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name)) shutil.copy(os.path.join(build_path, 'libz3java.dll'), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.dll')) shutil.copy(os.path.join(build_path, 'libz3java.lib'), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.lib')) def mk_unix_dist(self, build_path, dist_path): if JAVA_ENABLED: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.jar' % os.path.join(build_path, self.package_name), '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name)) so = get_so_ext() shutil.copy(os.path.join(build_path, 'libz3java.%s' % so), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.%s' % so)) def mk_install(self, out): if is_java_enabled() and self.install: dllfile = '%s$(SO_EXT)' % self.dll_name MakeRuleCmd.install_files(out, dllfile, os.path.join(INSTALL_LIB_DIR, dllfile)) jarfile = '{}.jar'.format(self.package_name) MakeRuleCmd.install_files(out, jarfile, os.path.join(INSTALL_LIB_DIR, jarfile)) def mk_uninstall(self, out): if is_java_enabled() and self.install: dllfile = '%s$(SO_EXT)' % self.dll_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, dllfile)) jarfile = '{}.jar'.format(self.package_name) MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, jarfile)) class MLComponent(Component): def __init__(self, name, lib_name, path, deps): Component.__init__(self, name, path, deps) if lib_name is None: lib_name = name self.lib_name = lib_name self.modules = ["z3enums", "z3native", "z3"] # dependencies in this order! self.stubs = "z3native_stubs" self.sub_dir = os.path.join('api', 'ml') self.destdir = "" self.ldconf = "" # Calling _init_ocamlfind_paths() is postponed to later because # OCAMLFIND hasn't been checked yet. def _install_bindings(self): # FIXME: Depending on global state is gross. We can't pre-compute this # in the constructor because we haven't tested for ocamlfind yet return OCAMLFIND != '' def _init_ocamlfind_paths(self): """ Initialises self.destdir and self.ldconf Do not call this from the MLComponent constructor because OCAMLFIND has not been checked at that point """ if self.destdir != "" and self.ldconf != "": # Initialisation already done return # Use Ocamlfind to get the default destdir and ldconf path self.destdir = check_output([OCAMLFIND, 'printconf', 'destdir']) if self.destdir == "": raise MKException('Failed to get OCaml destdir') if not os.path.isdir(self.destdir): raise MKException('The destdir reported by {ocamlfind} ({destdir}) does not exist'.format(ocamlfind=OCAMLFIND, destdir=self.destdir)) self.ldconf = check_output([OCAMLFIND, 'printconf', 'ldconf']) if self.ldconf == "": raise MKException('Failed to get OCaml ldconf path') def final_info(self): if not self._install_bindings(): print("WARNING: Could not find ocamlfind utility. OCaml bindings will not be installed") def mk_makefile(self, out): if is_ml_enabled(): CP_CMD = 'cp' if IS_WINDOWS: CP_CMD='copy' OCAML_FLAGS = '' if DEBUG_MODE: OCAML_FLAGS += '-g' if OCAMLFIND: OCAMLCF = OCAMLFIND + ' ' + 'ocamlc -package zarith' + ' ' + OCAML_FLAGS OCAMLOPTF = OCAMLFIND + ' ' + 'ocamlopt -package zarith' + ' ' + OCAML_FLAGS else: OCAMLCF = OCAMLC + ' ' + OCAML_FLAGS OCAMLOPTF = OCAMLOPT + ' ' + OCAML_FLAGS src_dir = self.to_src_dir mk_dir(os.path.join(BUILD_DIR, self.sub_dir)) api_src = get_component(API_COMPONENT).to_src_dir # remove /GL and -std=c++11; the ocaml tools don't like them. if IS_WINDOWS: out.write('CXXFLAGS_OCAML=$(CXXFLAGS:/GL=)\n') else: out.write('CXXFLAGS_OCAML=$(subst -std=c++11,,$(CXXFLAGS))\n') substitutions = { 'VERSION': "{}.{}.{}.{}".format(VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) } configure_file(os.path.join(self.src_dir, 'META.in'), os.path.join(BUILD_DIR, self.sub_dir, 'META'), substitutions) stubsc = os.path.join(src_dir, self.stubs + '.c') stubso = os.path.join(self.sub_dir, self.stubs) + '$(OBJ_EXT)' base_dll_name = get_component(Z3_DLL_COMPONENT).dll_name if STATIC_LIB: z3link = 'z3-static' z3linkdep = base_dll_name + '-static$(LIB_EXT)' out.write('%s: %s\n' % (z3linkdep, base_dll_name + '$(LIB_EXT)')) out.write('\tcp $< $@\n') else: z3link = 'z3' z3linkdep = base_dll_name + '$(SO_EXT)' out.write('%s: %s %s\n' % (stubso, stubsc, z3linkdep)) out.write('\t%s -ccopt "$(CXXFLAGS_OCAML) -I %s -I %s -I %s $(CXX_OUT_FLAG)%s" -c %s\n' % (OCAMLCF, OCAML_LIB, api_src, src_dir, stubso, stubsc)) cmos = '' for m in self.modules: ml = os.path.join(src_dir, m + '.ml') cmo = os.path.join(self.sub_dir, m + '.cmo') existing_mli = os.path.join(src_dir, m + '.mli') mli = os.path.join(self.sub_dir, m + '.mli') cmi = os.path.join(self.sub_dir, m + '.cmi') out.write('%s: %s %s\n' % (cmo, ml, cmos)) if (os.path.exists(existing_mli[3:])): out.write('\t%s %s %s\n' % (CP_CMD, existing_mli, mli)) else: out.write('\t%s -i -I %s -c %s > %s\n' % (OCAMLCF, self.sub_dir, ml, mli)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmi, mli)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmo, ml)) cmos = cmos + cmo + ' ' cmxs = '' for m in self.modules: ff = os.path.join(src_dir, m + '.ml') ft = os.path.join(self.sub_dir, m + '.cmx') out.write('%s: %s %s %s\n' % (ft, ff, cmos, cmxs)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLOPTF, self.sub_dir, ft, ff)) cmxs = cmxs + ' ' + ft OCAMLMKLIB = 'ocamlmklib' LIBZ3 = '-cclib -l' + z3link if is_cygwin() and not(is_cygwin_mingw()): LIBZ3 = z3linkdep LIBZ3 = LIBZ3 + ' ' + ' '.join(map(lambda x: '-cclib ' + x, LDFLAGS.split())) if DEBUG_MODE and not(is_cygwin()): # Some ocamlmklib's don't like -g; observed on cygwin, but may be others as well. OCAMLMKLIB += ' -g' z3mls = os.path.join(self.sub_dir, 'z3ml') out.write('%s.cma: %s %s %s\n' % (z3mls, cmos, stubso, z3linkdep)) out.write('\t%s -o %s -I %s %s %s %s\n' % (OCAMLMKLIB, z3mls, self.sub_dir, stubso, cmos, LIBZ3)) out.write('%s.cmxa: %s %s %s %s.cma\n' % (z3mls, cmxs, stubso, z3linkdep, z3mls)) out.write('\t%s -o %s -I %s %s %s %s\n' % (OCAMLMKLIB, z3mls, self.sub_dir, stubso, cmxs, LIBZ3)) out.write('%s.cmxs: %s.cmxa\n' % (z3mls, z3mls)) out.write('\t%s -linkall -shared -o %s.cmxs -I . -I %s %s.cmxa\n' % (OCAMLOPTF, z3mls, self.sub_dir, z3mls)) out.write('\n') out.write('ml: %s.cma %s.cmxa %s.cmxs\n' % (z3mls, z3mls, z3mls)) out.write('\n') if IS_WINDOWS: out.write('ocamlfind_install: ') self.mk_install_deps(out) out.write('\n') self.mk_install(out) out.write('\n') out.write('ocamlfind_uninstall:\n') self.mk_uninstall(out) out.write('\n') def mk_install_deps(self, out): if is_ml_enabled() and self._install_bindings(): out.write(get_component(Z3_DLL_COMPONENT).dll_name + '$(SO_EXT) ') out.write(os.path.join(self.sub_dir, 'META ')) out.write(os.path.join(self.sub_dir, 'z3ml.cma ')) out.write(os.path.join(self.sub_dir, 'z3ml.cmxa ')) out.write(os.path.join(self.sub_dir, 'z3ml.cmxs ')) def mk_install(self, out): if is_ml_enabled() and self._install_bindings(): self._init_ocamlfind_paths() in_prefix = self.destdir.startswith(PREFIX) maybe_stripped_destdir = strip_path_prefix(self.destdir, PREFIX) # Note that when doing a staged install with DESTDIR that modifying # OCaml's ``ld.conf`` may fail. Therefore packagers will need to # make their packages modify it manually at package install time # as opposed to ``make install`` time. MakeRuleCmd.make_install_directory(out, maybe_stripped_destdir, in_prefix=in_prefix) out.write('\t@{ocamlfind} install -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3 {metafile}'.format( ldconf=self.ldconf, ocamlfind=OCAMLFIND, ocaml_destdir=self.destdir, metafile=os.path.join(self.sub_dir, 'META'))) for m in self.modules: mli = os.path.join(self.src_dir, m) + '.mli' if os.path.exists(mli): out.write(' ' + os.path.join(self.to_src_dir, m) + '.mli') else: out.write(' ' + os.path.join(self.sub_dir, m) + '.mli') out.write(' ' + os.path.join(self.sub_dir, m) + '.cmi') out.write(' ' + os.path.join(self.sub_dir, m) + '.cmx') out.write(' %s' % ((os.path.join(self.sub_dir, 'libz3ml$(LIB_EXT)')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml$(LIB_EXT)')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cma')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxa')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxs')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'dllz3ml')))) if is_windows() or is_cygwin_mingw(): out.write('.dll') else: out.write('.so') # .so also on OSX! out.write('\n') def mk_uninstall(self, out): if is_ml_enabled() and self._install_bindings(): self._init_ocamlfind_paths() out.write('\t@{ocamlfind} remove -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3\n'.format( ldconf=self.ldconf, ocamlfind=OCAMLFIND, ocaml_destdir=self.destdir)) def main_component(self): return is_ml_enabled() class ExampleComponent(Component): def __init__(self, name, path): Component.__init__(self, name, path, []) self.ex_dir = os.path.join(EXAMPLE_DIR, self.path) self.to_ex_dir = os.path.join(REV_BUILD_DIR, self.ex_dir) def is_example(self): return True class CppExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def compiler(self): return "$(CXX)" def src_files(self): return get_cpp_files(self.ex_dir) def mk_makefile(self, out): dll_name = get_component(Z3_DLL_COMPONENT).dll_name dll = '%s$(SO_EXT)' % dll_name objfiles = '' for cppfile in self.src_files(): objfile = '%s$(OBJ_EXT)' % (cppfile[:cppfile.rfind('.')]) objfiles = objfiles + ('%s ' % objfile) out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cppfile))); out.write('\t%s $(CXXFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(CXX_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile)) # Add include dir components out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir) out.write(' -I%s' % get_component(CPP_COMPONENT).to_src_dir) out.write(' %s' % os.path.join(self.to_ex_dir, cppfile)) out.write('\n') exefile = '%s$(EXE_EXT)' % self.name out.write('%s: %s %s\n' % (exefile, dll, objfiles)) out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles)) if IS_WINDOWS: out.write('%s.lib' % dll_name) else: out.write(dll) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('_ex_%s: %s\n\n' % (self.name, exefile)) class CExampleComponent(CppExampleComponent): def __init__(self, name, path): CppExampleComponent.__init__(self, name, path) def compiler(self): return "$(CC)" def src_files(self): return get_c_files(self.ex_dir) def mk_makefile(self, out): dll_name = get_component(Z3_DLL_COMPONENT).dll_name dll = '%s$(SO_EXT)' % dll_name objfiles = '' for cfile in self.src_files(): objfile = '%s$(OBJ_EXT)' % (cfile[:cfile.rfind('.')]) objfiles = objfiles + ('%s ' % objfile) out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cfile))); out.write('\t%s $(CFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(C_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile)) out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir) out.write(' %s' % os.path.join(self.to_ex_dir, cfile)) out.write('\n') exefile = '%s$(EXE_EXT)' % self.name out.write('%s: %s %s\n' % (exefile, dll, objfiles)) out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles)) if IS_WINDOWS: out.write('%s.lib' % dll_name) else: out.write(dll) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('_ex_%s: %s\n\n' % (self.name, exefile)) class DotNetExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return is_dotnet_core_enabled() def mk_makefile(self, out): if is_dotnet_core_enabled(): proj_name = 'dotnet_example.csproj' out.write('_ex_%s:' % self.name) for csfile in get_cs_files(self.ex_dir): out.write(' ') out.write(os.path.join(self.to_ex_dir, csfile)) mk_dir(os.path.join(BUILD_DIR, 'dotnet_example')) csproj = os.path.join('dotnet_example', proj_name) if VS_X64: platform = 'x64' elif VS_ARM: platform = 'ARM' else: platform = 'x86' dotnet_proj_str = """<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <PlatformTarget>%s</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="..\%s/*.cs" /> <Reference Include="Microsoft.Z3"> <HintPath>..\Microsoft.Z3.dll</HintPath> </Reference> </ItemGroup> </Project>""" % (platform, self.to_ex_dir) with open(os.path.join(BUILD_DIR, csproj), 'w') as ous: ous.write(dotnet_proj_str) out.write('\n') dotnetCmdLine = [DOTNET, "build", csproj] dotnetCmdLine.extend(['-c']) if DEBUG_MODE: dotnetCmdLine.extend(['Debug']) else: dotnetCmdLine.extend(['Release']) MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine)) out.write('\n') class JavaExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return JAVA_ENABLED def mk_makefile(self, out): if JAVA_ENABLED: pkg = get_component(JAVA_COMPONENT).package_name + '.jar' out.write('JavaExample.class: %s' % (pkg)) deps = '' for jfile in get_java_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, jfile)) if IS_WINDOWS: deps = deps.replace('/', '\\') out.write('%s\n' % deps) out.write('\t%s -cp %s ' % (JAVAC, pkg)) win_ex_dir = self.to_ex_dir for javafile in get_java_files(self.ex_dir): out.write(' ') out.write(os.path.join(win_ex_dir, javafile)) out.write(' -d .\n') out.write('_ex_%s: JavaExample.class\n\n' % (self.name)) class MLExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return ML_ENABLED def mk_makefile(self, out): if ML_ENABLED: out.write('ml_example.byte: api/ml/z3ml.cma') for mlfile in get_ml_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, mlfile)) out.write('\n') out.write('\tocamlfind %s ' % OCAMLC) if DEBUG_MODE: out.write('-g ') out.write('-custom -o ml_example.byte -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cma') for mlfile in get_ml_files(self.ex_dir): out.write(' %s/%s' % (self.to_ex_dir, mlfile)) out.write('\n') out.write('ml_example$(EXE_EXT): api/ml/z3ml.cmxa') for mlfile in get_ml_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, mlfile)) out.write('\n') out.write('\tocamlfind %s ' % OCAMLOPT) if DEBUG_MODE: out.write('-g ') out.write('-o ml_example$(EXE_EXT) -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cmxa') for mlfile in get_ml_files(self.ex_dir): out.write(' %s/%s' % (self.to_ex_dir, mlfile)) out.write('\n') out.write('_ex_%s: ml_example.byte ml_example$(EXE_EXT)\n\n' % self.name) class PythonExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) # Python examples are just placeholders, we just copy the *.py files when mk_makefile is invoked. # We don't need to include them in the :examples rule def mk_makefile(self, out): full = os.path.join(EXAMPLE_DIR, self.path) for py in filter(lambda f: f.endswith('.py'), os.listdir(full)): shutil.copyfile(os.path.join(full, py), os.path.join(BUILD_DIR, 'python', py)) if is_verbose(): print("Copied Z3Py example '%s' to '%s'" % (py, os.path.join(BUILD_DIR, 'python'))) out.write('_ex_%s: \n\n' % self.name) def mk_win_dist(self, build_path, dist_path): full = os.path.join(EXAMPLE_DIR, self.path) py = 'example.py' shutil.copyfile(os.path.join(full, py), os.path.join(dist_path, INSTALL_BIN_DIR, 'python', py)) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) def reg_component(name, c): global _Id, _Components, _ComponentNames, _Name2Component c.id = _Id _Id = _Id + 1 _Components.append(c) _ComponentNames.add(name) _Name2Component[name] = c if VERBOSE: print("New component: '%s'" % name) def add_lib(name, deps=[], path=None, includes2install=[]): c = LibComponent(name, path, deps, includes2install) reg_component(name, c) def add_hlib(name, path=None, includes2install=[]): c = HLibComponent(name, path, includes2install) reg_component(name, c) def add_exe(name, deps=[], path=None, exe_name=None, install=True): c = ExeComponent(name, exe_name, path, deps, install) reg_component(name, c) def add_extra_exe(name, deps=[], path=None, exe_name=None, install=True): c = ExtraExeComponent(name, exe_name, path, deps, install) reg_component(name, c) def add_dll(name, deps=[], path=None, dll_name=None, export_files=[], reexports=[], install=True, static=False, staging_link=None): c = DLLComponent(name, dll_name, path, deps, export_files, reexports, install, static, staging_link) reg_component(name, c) return c def add_dot_net_core_dll(name, deps=[], path=None, dll_name=None, assembly_info_dir=None, default_key_file=None): c = DotNetDLLComponent(name, dll_name, path, deps, assembly_info_dir, default_key_file) reg_component(name, c) def add_java_dll(name, deps=[], path=None, dll_name=None, package_name=None, manifest_file=None): c = JavaDLLComponent(name, dll_name, package_name, manifest_file, path, deps) reg_component(name, c) def add_python(libz3Component): name = 'python' reg_component(name, PythonComponent(name, libz3Component)) def add_js(): reg_component('js', JsComponent()) def add_python_install(libz3Component): name = 'python_install' reg_component(name, PythonInstallComponent(name, libz3Component)) def add_ml_lib(name, deps=[], path=None, lib_name=None): c = MLComponent(name, lib_name, path, deps) reg_component(name, c) def add_cpp_example(name, path=None): c = CppExampleComponent(name, path) reg_component(name, c) def add_c_example(name, path=None): c = CExampleComponent(name, path) reg_component(name, c) def add_dotnet_example(name, path=None): c = DotNetExampleComponent(name, path) reg_component(name, c) def add_java_example(name, path=None): c = JavaExampleComponent(name, path) reg_component(name, c) def add_ml_example(name, path=None): c = MLExampleComponent(name, path) reg_component(name, c) def add_z3py_example(name, path=None): c = PythonExampleComponent(name, path) reg_component(name, c) def mk_config(): if ONLY_MAKEFILES: return config = open(os.path.join(BUILD_DIR, 'config.mk'), 'w') global CXX, CC, GMP, CPPFLAGS, CXXFLAGS, LDFLAGS, EXAMP_DEBUG_FLAG, FPMATH_FLAGS, LOG_SYNC, SINGLE_THREADED if IS_WINDOWS: config.write( 'CC=cl\n' 'CXX=cl\n' 'CXX_OUT_FLAG=/Fo\n' 'C_OUT_FLAG=/Fo\n' 'OBJ_EXT=.obj\n' 'LIB_EXT=.lib\n' 'AR=lib\n' 'AR_OUTFLAG=/OUT:\n' 'EXE_EXT=.exe\n' 'LINK=cl\n' 'LINK_OUT_FLAG=/Fe\n' 'SO_EXT=.dll\n' 'SLINK=cl\n' 'SLINK_OUT_FLAG=/Fe\n' 'OS_DEFINES=/D _WINDOWS\n') extra_opt = '' link_extra_opt = '' if LOG_SYNC: extra_opt = '%s /DZ3_LOG_SYNC' % extra_opt if SINGLE_THREADED: extra_opt = '%s /DSINGLE_THREAD' % extra_opt if GIT_HASH: extra_opt = ' %s /D Z3GITHASH=%s' % (extra_opt, GIT_HASH) if GUARD_CF: extra_opt = ' %s /guard:cf' % extra_opt link_extra_opt = ' %s /GUARD:CF' % link_extra_opt if STATIC_BIN: static_opt = '/MT' else: static_opt = '/MD' maybe_disable_dynamic_base = '/DYNAMICBASE' if ALWAYS_DYNAMIC_BASE else '/DYNAMICBASE:NO' if DEBUG_MODE: static_opt = static_opt + 'd' config.write( 'AR_FLAGS=/nologo\n' 'LINK_FLAGS=/nologo %s\n' 'SLINK_FLAGS=/nologo /LDd\n' % static_opt) if VS_X64: config.write( 'CXXFLAGS=/c /Zi /nologo /W3 /WX- /Od /Oy- /D WIN32 /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /D _WINDOWS /Gm- /EHsc /RTC1 /GS /Gd %s %s\n' % (extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X64 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X64 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt)) elif VS_ARM: print("ARM on VS is unsupported") exit(1) else: config.write( 'CXXFLAGS=/c /Zi /nologo /W3 /WX- /Od /Oy- /D WIN32 /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /D _WINDOWS /Gm- /EHsc /RTC1 /GS /Gd /arch:SSE2 %s %s\n' % (extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt)) else: # Windows Release mode LTCG=' /LTCG' if SLOW_OPTIMIZE else '' GL = ' /GL' if SLOW_OPTIMIZE else '' config.write( 'AR_FLAGS=/nologo %s\n' 'LINK_FLAGS=/nologo %s\n' 'SLINK_FLAGS=/nologo /LD\n' % (LTCG, static_opt)) if TRACE: extra_opt = '%s /D _TRACE ' % extra_opt if VS_X64: config.write( 'CXXFLAGS=/c%s /Zi /nologo /W3 /WX- /O2 /D _EXTERNAL_RELEASE /D WIN32 /D NDEBUG /D _LIB /D _WINDOWS /D _UNICODE /D UNICODE /Gm- /EHsc /GS /Gd /GF /Gy /TP %s %s\n' % (GL, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link%s /profile /MACHINE:X64 /SUBSYSTEM:CONSOLE /STACK:8388608 %s\n' 'SLINK_EXTRA_FLAGS=/link%s /profile /MACHINE:X64 /SUBSYSTEM:WINDOWS /STACK:8388608 %s\n' % (LTCG, link_extra_opt, LTCG, link_extra_opt)) elif VS_ARM: print("ARM on VS is unsupported") exit(1) else: config.write( 'CXXFLAGS=/nologo /c%s /Zi /W3 /WX- /O2 /Oy- /D _EXTERNAL_RELEASE /D WIN32 /D NDEBUG /D _CONSOLE /D _WINDOWS /D ASYNC_COMMANDS /Gm- /EHsc /GS /Gd /arch:SSE2 %s %s\n' % (GL, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link%s /DEBUG /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link%s /DEBUG /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (LTCG, link_extra_opt, LTCG, maybe_disable_dynamic_base, link_extra_opt)) config.write('CFLAGS=$(CXXFLAGS)\n') # End of Windows VS config.mk if is_verbose(): print('64-bit: %s' % is64()) if is_java_enabled(): print('JNI Bindings: %s' % JNI_HOME) print('Java Compiler: %s' % JAVAC) if is_ml_enabled(): print('OCaml Compiler: %s' % OCAMLC) print('OCaml Find tool: %s' % OCAMLFIND) print('OCaml Native: %s' % OCAMLOPT) print('OCaml Library: %s' % OCAML_LIB) else: OS_DEFINES = "" ARITH = "internal" check_ar() CXX = find_cxx_compiler() CC = find_c_compiler() SLIBEXTRAFLAGS = '' # SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so.0' % LDFLAGS EXE_EXT = '' LIB_EXT = '.a' if GPROF: CXXFLAGS = '%s -pg' % CXXFLAGS LDFLAGS = '%s -pg' % LDFLAGS if GMP: test_gmp(CXX) ARITH = "gmp" CPPFLAGS = '%s -D_MP_GMP' % CPPFLAGS LDFLAGS = '%s -lgmp' % LDFLAGS SLIBEXTRAFLAGS = '%s -lgmp' % SLIBEXTRAFLAGS else: CPPFLAGS = '%s -D_MP_INTERNAL' % CPPFLAGS if GIT_HASH: CPPFLAGS = '%s -DZ3GITHASH=%s' % (CPPFLAGS, GIT_HASH) CXXFLAGS = '%s -std=c++11' % CXXFLAGS CXXFLAGS = '%s -fvisibility=hidden -c' % CXXFLAGS FPMATH = test_fpmath(CXX) CXXFLAGS = '%s %s' % (CXXFLAGS, FPMATH_FLAGS) if LOG_SYNC: CXXFLAGS = '%s -DZ3_LOG_SYNC' % CXXFLAGS if SINGLE_THREADED: CXXFLAGS = '%s -DSINGLE_THREAD' % CXXFLAGS if DEBUG_MODE: CXXFLAGS = '%s -g -Wall' % CXXFLAGS EXAMP_DEBUG_FLAG = '-g' CPPFLAGS = '%s -DZ3DEBUG -D_DEBUG' % CPPFLAGS else: CXXFLAGS = '%s -O3' % CXXFLAGS if GPROF: CXXFLAGS += '-fomit-frame-pointer' CPPFLAGS = '%s -DNDEBUG -D_EXTERNAL_RELEASE' % CPPFLAGS if is_CXX_clangpp(): CXXFLAGS = '%s -Wno-unknown-pragmas -Wno-overloaded-virtual -Wno-unused-value' % CXXFLAGS sysname, _, _, _, machine = os.uname() if sysname == 'Darwin': SO_EXT = '.dylib' SLIBFLAGS = '-dynamiclib' elif sysname == 'Linux': CXXFLAGS = '%s -D_LINUX_' % CXXFLAGS OS_DEFINES = '-D_LINUX_' SO_EXT = '.so' SLIBFLAGS = '-shared' SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so' % SLIBEXTRAFLAGS elif sysname == 'GNU': CXXFLAGS = '%s -D_HURD_' % CXXFLAGS OS_DEFINES = '-D_HURD_' SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'FreeBSD': CXXFLAGS = '%s -D_FREEBSD_' % CXXFLAGS OS_DEFINES = '-D_FREEBSD_' SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'NetBSD': CXXFLAGS = '%s -D_NETBSD_' % CXXFLAGS OS_DEFINES = '-D_NETBSD_' SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'OpenBSD': CXXFLAGS = '%s -D_OPENBSD_' % CXXFLAGS OS_DEFINES = '-D_OPENBSD_' SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname.startswith('CYGWIN'): CXXFLAGS = '%s -D_CYGWIN' % CXXFLAGS OS_DEFINES = '-D_CYGWIN' SO_EXT = '.dll' SLIBFLAGS = '-shared' elif sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'): CXXFLAGS = '%s -D_MINGW' % CXXFLAGS OS_DEFINES = '-D_MINGW' SO_EXT = '.dll' SLIBFLAGS = '-shared' EXE_EXT = '.exe' LIB_EXT = '.lib' else: raise MKException('Unsupported platform: %s' % sysname) if is64(): if not sysname.startswith('CYGWIN') and not sysname.startswith('MSYS') and not sysname.startswith('MINGW'): CXXFLAGS = '%s -fPIC' % CXXFLAGS if sysname == 'Linux': CPPFLAGS = '%s -D_USE_THREAD_LOCAL' % CPPFLAGS elif not LINUX_X64: CXXFLAGS = '%s -m32' % CXXFLAGS LDFLAGS = '%s -m32' % LDFLAGS SLIBFLAGS = '%s -m32' % SLIBFLAGS if TRACE or DEBUG_MODE: CPPFLAGS = '%s -D_TRACE' % CPPFLAGS if is_cygwin_mingw(): # when cross-compiling with MinGW, we need to statically link its standard libraries # and to make it create an import library. SLIBEXTRAFLAGS = '%s -static-libgcc -static-libstdc++ -Wl,--out-implib,libz3.dll.a' % SLIBEXTRAFLAGS LDFLAGS = '%s -static-libgcc -static-libstdc++' % LDFLAGS if sysname == 'Linux' and machine.startswith('armv7') or machine.startswith('armv8'): CXXFLAGS = '%s -fpic' % CXXFLAGS config.write('PREFIX=%s\n' % PREFIX) config.write('CC=%s\n' % CC) config.write('CXX=%s\n' % CXX) config.write('CXXFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS)) config.write('CFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS.replace('-std=c++11', ''))) config.write('EXAMP_DEBUG_FLAG=%s\n' % EXAMP_DEBUG_FLAG) config.write('CXX_OUT_FLAG=-o \n') config.write('C_OUT_FLAG=-o \n') config.write('OBJ_EXT=.o\n') config.write('LIB_EXT=%s\n' % LIB_EXT) config.write('AR=%s\n' % AR) config.write('AR_FLAGS=rcs\n') config.write('AR_OUTFLAG=\n') config.write('EXE_EXT=%s\n' % EXE_EXT) config.write('LINK=%s\n' % CXX) config.write('LINK_FLAGS=\n') config.write('LINK_OUT_FLAG=-o \n') if is_linux() and (build_static_lib() or build_static_bin()): config.write('LINK_EXTRA_FLAGS=-Wl,--whole-archive -lrt -lpthread -Wl,--no-whole-archive %s\n' % LDFLAGS) else: config.write('LINK_EXTRA_FLAGS=-lpthread %s\n' % LDFLAGS) config.write('SO_EXT=%s\n' % SO_EXT) config.write('SLINK=%s\n' % CXX) config.write('SLINK_FLAGS=%s\n' % SLIBFLAGS) config.write('SLINK_EXTRA_FLAGS=-lpthread %s\n' % SLIBEXTRAFLAGS) config.write('SLINK_OUT_FLAG=-o \n') config.write('OS_DEFINES=%s\n' % OS_DEFINES) if is_verbose(): print('Host platform: %s' % sysname) print('C++ Compiler: %s' % CXX) print('C Compiler : %s' % CC) if is_cygwin_mingw(): print('MinGW32 cross: %s' % (is_cygwin_mingw())) print('Archive Tool: %s' % AR) print('Arithmetic: %s' % ARITH) print('Prefix: %s' % PREFIX) print('64-bit: %s' % is64()) print('FP math: %s' % FPMATH) print("Python pkg dir: %s" % PYTHON_PACKAGE_DIR) if GPROF: print('gprof: enabled') print('Python version: %s' % distutils.sysconfig.get_python_version()) if is_java_enabled(): print('JNI Bindings: %s' % JNI_HOME) print('Java Compiler: %s' % JAVAC) if is_ml_enabled(): print('OCaml Compiler: %s' % OCAMLC) print('OCaml Find tool: %s' % OCAMLFIND) print('OCaml Native: %s' % OCAMLOPT) print('OCaml Library: %s' % OCAML_LIB) if is_dotnet_core_enabled(): print('C# Compiler: %s' % DOTNET) config.close() def mk_install(out): out.write('install: ') for c in get_components(): c.mk_install_deps(out) out.write(' ') out.write('\n') MakeRuleCmd.make_install_directory(out, INSTALL_BIN_DIR) MakeRuleCmd.make_install_directory(out, INSTALL_INCLUDE_DIR) MakeRuleCmd.make_install_directory(out, INSTALL_LIB_DIR) for c in get_components(): c.mk_install(out) out.write('\t@echo Z3 was successfully installed.\n') out.write('\n') def mk_uninstall(out): out.write('uninstall:\n') for c in get_components(): c.mk_uninstall(out) out.write('\t@echo Z3 was successfully uninstalled.\n') out.write('\n') # Generate the Z3 makefile def mk_makefile(): mk_dir(BUILD_DIR) mk_config() if VERBOSE: print("Writing %s" % os.path.join(BUILD_DIR, 'Makefile')) out = open(os.path.join(BUILD_DIR, 'Makefile'), 'w') out.write('# Automatically generated file.\n') out.write('include config.mk\n') # Generate :all rule out.write('all:') for c in get_components(): if c.main_component(): out.write(' %s' % c.name) out.write('\n\t@echo Z3 was successfully built.\n') out.write("\t@echo \"Z3Py scripts can already be executed in the \'%s\' directory.\"\n" % os.path.join(BUILD_DIR, 'python')) pathvar = "DYLD_LIBRARY_PATH" if IS_OSX else "PATH" if IS_WINDOWS else "LD_LIBRARY_PATH" out.write("\t@echo \"Z3Py scripts stored in arbitrary directories can be executed if the \'%s\' directory is added to the PYTHONPATH environment variable and the \'%s\' directory is added to the %s environment variable.\"\n" % (os.path.join(BUILD_DIR, 'python'), BUILD_DIR, pathvar)) if not IS_WINDOWS: out.write("\t@echo Use the following command to install Z3 at prefix $(PREFIX).\n") out.write('\t@echo " sudo make install"\n\n') # out.write("\t@echo If you are doing a staged install you can use DESTDIR.\n") # out.write('\t@echo " make DESTDIR=/some/temp/directory install"\n') # Generate :examples rule out.write('examples:') for c in get_components(): if c.is_example(): out.write(' _ex_%s' % c.name) out.write('\n\t@echo Z3 examples were successfully built.\n') # Generate components for c in get_components(): c.mk_makefile(out) # Generate install/uninstall rules if not WINDOWS if not IS_WINDOWS: mk_install(out) mk_uninstall(out) for c in get_components(): c.final_info() out.close() # Finalize if VERBOSE: print("Makefile was successfully generated.") if DEBUG_MODE: print(" compilation mode: Debug") else: print(" compilation mode: Release") if IS_WINDOWS: if VS_X64: print(" platform: x64\n") print("To build Z3, open a [Visual Studio x64 Command Prompt], then") elif VS_ARM: print(" platform: ARM\n") print("To build Z3, open a [Visual Studio ARM Command Prompt], then") else: print(" platform: x86") print("To build Z3, open a [Visual Studio Command Prompt], then") print("type 'cd %s && nmake'\n" % os.path.join(os.getcwd(), BUILD_DIR)) print('Remark: to open a Visual Studio Command Prompt, go to: "Start > All Programs > Visual Studio > Visual Studio Tools"') else: print("Type 'cd %s; make' to build Z3" % BUILD_DIR) # Generate automatically generated source code def mk_auto_src(): if not ONLY_MAKEFILES: exec_pyg_scripts() mk_pat_db() mk_all_install_tactic_cpps() mk_all_mem_initializer_cpps() mk_all_gparams_register_modules() def _execfile(file, globals=globals(), locals=locals()): if sys.version < "2.7": execfile(file, globals, locals) else: with open(file, "r") as fh: exec(fh.read()+"\n", globals, locals) # Execute python auxiliary scripts that generate extra code for Z3. def exec_pyg_scripts(): for root, dirs, files in os.walk('src'): for f in files: if f.endswith('.pyg'): script = os.path.join(root, f) generated_file = mk_genfile_common.mk_hpp_from_pyg(script, root) if is_verbose(): print("Generated '{}'".format(generated_file)) # TODO: delete after src/ast/pattern/expr_pattern_match # database.smt ==> database.h def mk_pat_db(): c = get_component(PATTERN_COMPONENT) fin = os.path.join(c.src_dir, 'database.smt2') fout = os.path.join(c.src_dir, 'database.h') mk_genfile_common.mk_pat_db_internal(fin, fout) if VERBOSE: print("Generated '{}'".format(fout)) # Update version numbers def update_version(): major = VER_MAJOR minor = VER_MINOR build = VER_BUILD revision = VER_TWEAK if major is None or minor is None or build is None or revision is None: raise MKException("set_version(major, minor, build, revision) must be used before invoking update_version()") if not ONLY_MAKEFILES: mk_version_dot_h(major, minor, build, revision) mk_all_assembly_infos(major, minor, build, revision) mk_def_files() def get_full_version_string(major, minor, build, revision): global GIT_HASH, GIT_DESCRIBE res = "Z3 %s.%s.%s.%s" % (major, minor, build, revision) if GIT_HASH: res += " " + GIT_HASH if GIT_DESCRIBE: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) res += " " + branch + " " + check_output(['git', 'describe']) return '"' + res + '"' # Update files with the version number def mk_version_dot_h(major, minor, build, revision): c = get_component(UTIL_COMPONENT) version_template = os.path.join(c.src_dir, 'z3_version.h.in') version_header_output = os.path.join(c.src_dir, 'z3_version.h') # Note the substitution names are what is used by the CMake # builds system. If you change these you should change them # in the CMake build too configure_file(version_template, version_header_output, { 'Z3_VERSION_MAJOR': str(major), 'Z3_VERSION_MINOR': str(minor), 'Z3_VERSION_PATCH': str(build), 'Z3_VERSION_TWEAK': str(revision), 'Z3_FULL_VERSION': get_full_version_string(major, minor, build, revision) } ) if VERBOSE: print("Generated '%s'" % version_header_output) # Generate AssemblyInfo.cs files with the right version numbers by using ``AssemblyInfo.cs.in`` files as a template def mk_all_assembly_infos(major, minor, build, revision): for c in get_components(): if c.has_assembly_info(): c.make_assembly_info(major, minor, build, revision) def get_header_files_for_components(component_src_dirs): assert isinstance(component_src_dirs, list) h_files_full_path = [] for component_src_dir in sorted(component_src_dirs): h_files = filter(lambda f: f.endswith('.h') or f.endswith('.hpp'), os.listdir(component_src_dir)) h_files = list(map(lambda p: os.path.join(component_src_dir, p), h_files)) h_files_full_path.extend(h_files) return h_files_full_path def mk_install_tactic_cpp(cnames, path): component_src_dirs = [] for cname in cnames: print("Component %s" % cname) c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_install_tactic_cpp_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_install_tactic_cpps(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_install_tactics(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_install_tactic_cpp(cnames, c.src_dir) def mk_mem_initializer_cpp(cnames, path): component_src_dirs = [] for cname in cnames: c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_mem_initializer_cpp_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_mem_initializer_cpps(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_mem_initializer(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_mem_initializer_cpp(cnames, c.src_dir) def mk_gparams_register_modules(cnames, path): component_src_dirs = [] for cname in cnames: c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_gparams_register_modules_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_gparams_register_modules(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_mem_initializer(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_gparams_register_modules(cnames, c.src_dir) # Generate a .def based on the files at c.export_files slot. def mk_def_file(c): defname = '%s.def' % os.path.join(c.src_dir, c.name) dll_name = c.dll_name export_header_files = [] for dot_h in c.export_files: dot_h_c = c.find_file(dot_h, c.name) api = os.path.join(dot_h_c.src_dir, dot_h) export_header_files.append(api) mk_genfile_common.mk_def_file_internal(defname, dll_name, export_header_files) if VERBOSE: print("Generated '%s'" % defname) def mk_def_files(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_def_file(): mk_def_file(c) def cp_z3py_to_build(): mk_dir(BUILD_DIR) mk_dir(os.path.join(BUILD_DIR, 'python')) z3py_dest = os.path.join(BUILD_DIR, 'python', 'z3') z3py_src = os.path.join(Z3PY_SRC_DIR, 'z3') # Erase existing .pyc files for root, dirs, files in os.walk(Z3PY_SRC_DIR): for f in files: if f.endswith('.pyc'): rmf(os.path.join(root, f)) # Compile Z3Py files if compileall.compile_dir(z3py_src, force=1) != 1: raise MKException("failed to compile Z3Py sources") if is_verbose: print("Generated python bytecode") # Copy sources to build mk_dir(z3py_dest) for py in filter(lambda f: f.endswith('.py'), os.listdir(z3py_src)): shutil.copyfile(os.path.join(z3py_src, py), os.path.join(z3py_dest, py)) if is_verbose(): print("Copied '%s'" % py) # Python 2.x support for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(z3py_src)): shutil.copyfile(os.path.join(z3py_src, pyc), os.path.join(z3py_dest, pyc)) if is_verbose(): print("Copied '%s'" % pyc) # Python 3.x support src_pycache = os.path.join(z3py_src, '__pycache__') target_pycache = os.path.join(z3py_dest, '__pycache__') if os.path.exists(src_pycache): for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(src_pycache)): mk_dir(target_pycache) shutil.copyfile(os.path.join(src_pycache, pyc), os.path.join(target_pycache, pyc)) if is_verbose(): print("Copied '%s'" % pyc) # Copy z3test.py shutil.copyfile(os.path.join(Z3PY_SRC_DIR, 'z3test.py'), os.path.join(BUILD_DIR, 'python', 'z3test.py')) def mk_bindings(api_files): if not ONLY_MAKEFILES: mk_z3consts_py(api_files) new_api_files = [] api = get_component(API_COMPONENT) for api_file in api_files: api_file_path = api.find_file(api_file, api.name) new_api_files.append(os.path.join(api_file_path.src_dir, api_file)) g = globals() g["API_FILES"] = new_api_files if is_java_enabled(): check_java() mk_z3consts_java(api_files) # Generate some of the bindings and "api" module files import update_api dotnet_output_dir = None if is_dotnet_core_enabled(): dotnet_output_dir = os.path.join(BUILD_DIR, 'dotnet') mk_dir(dotnet_output_dir) java_output_dir = None java_package_name = None if is_java_enabled(): java_output_dir = get_component('java').src_dir java_package_name = get_component('java').package_name ml_output_dir = None if is_ml_enabled(): ml_output_dir = get_component('ml').src_dir if is_js_enabled(): set_z3js_dir("api/js") js_output_dir = get_component('js').src_dir # Get the update_api module to do the work for us update_api.generate_files(api_files=new_api_files, api_output_dir=get_component('api').src_dir, z3py_output_dir=get_z3py_dir(), dotnet_output_dir=dotnet_output_dir, java_output_dir=java_output_dir, java_package_name=java_package_name, js_output_dir=get_z3js_dir(), ml_output_dir=ml_output_dir, ml_src_dir=ml_output_dir ) cp_z3py_to_build() if is_ml_enabled(): check_ml() mk_z3consts_ml(api_files) if is_dotnet_core_enabled(): check_dotnet_core() mk_z3consts_dotnet(api_files, dotnet_output_dir) # Extract enumeration types from API files, and add python definitions. def mk_z3consts_py(api_files): if Z3PY_SRC_DIR is None: raise MKException("You must invoke set_z3py_dir(path):") full_path_api_files = [] api_dll = get_component(Z3_DLL_COMPONENT) for api_file in api_files: api_file_c = api_dll.find_file(api_file, api_dll.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_py_internal(full_path_api_files, Z3PY_SRC_DIR) if VERBOSE: print("Generated '{}".format(generated_file)) # Extract enumeration types from z3_api.h, and add .Net definitions def mk_z3consts_dotnet(api_files, output_dir): dotnet = get_component(DOTNET_COMPONENT) if not dotnet: dotnet = get_component(DOTNET_CORE_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = dotnet.find_file(api_file, dotnet.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_dotnet_internal(full_path_api_files, output_dir) if VERBOSE: print("Generated '{}".format(generated_file)) # Extract enumeration types from z3_api.h, and add Java definitions def mk_z3consts_java(api_files): java = get_component(JAVA_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = java.find_file(api_file, java.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_files = mk_genfile_common.mk_z3consts_java_internal( full_path_api_files, java.package_name, java.src_dir) if VERBOSE: for generated_file in generated_files: print("Generated '{}'".format(generated_file)) # Extract enumeration types from z3_api.h, and add ML definitions def mk_z3consts_ml(api_files): ml = get_component(ML_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = ml.find_file(api_file, ml.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_ml_internal( full_path_api_files, ml.src_dir) if VERBOSE: print ('Generated "%s"' % generated_file) def mk_gui_str(id): return '4D2F40D8-E5F9-473B-B548-%012d' % id def get_platform_toolset_str(): default = 'v110'; vstr = check_output(['msbuild', '/ver']) lines = vstr.split('\n') lline = lines[-1] tokens = lline.split('.') if len(tokens) < 2: return default else: if tokens[0] == "15": # Visual Studio 2017 reports 15.* but the PlatformToolsetVersion is 141 return "v141" else: return 'v' + tokens[0] + tokens[1] def mk_vs_proj_property_groups(f, name, target_ext, type): f.write(' <ItemGroup Label="ProjectConfigurations">\n') f.write(' <ProjectConfiguration Include="Debug|Win32">\n') f.write(' <Configuration>Debug</Configuration>\n') f.write(' <Platform>Win32</Platform>\n') f.write(' </ProjectConfiguration>\n') f.write(' <ProjectConfiguration Include="Release|Win32">\n') f.write(' <Configuration>Release</Configuration>\n') f.write(' <Platform>Win32</Platform>\n') f.write(' </ProjectConfiguration>\n') f.write(' </ItemGroup>\n') f.write(' <PropertyGroup Label="Globals">\n') f.write(' <ProjectGuid>{%s}</ProjectGuid>\n' % mk_gui_str(0)) f.write(' <ProjectName>%s</ProjectName>\n' % name) f.write(' <Keyword>Win32Proj</Keyword>\n') f.write(' <PlatformToolset>%s</PlatformToolset>\n' % get_platform_toolset_str()) f.write(' </PropertyGroup>\n') f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'" Label="Configuration">\n') f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type) f.write(' <CharacterSet>Unicode</CharacterSet>\n') f.write(' <UseOfMfc>false</UseOfMfc>\n') f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'" Label="Configuration">\n') f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type) f.write(' <CharacterSet>Unicode</CharacterSet>\n') f.write(' <UseOfMfc>false</UseOfMfc>\n') f.write(' </PropertyGroup>\n') f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\n') f.write(' <ImportGroup Label="ExtensionSettings" />\n') f.write(' <ImportGroup Label="PropertySheets">\n') f.write(' <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists(\'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props\')" Label="LocalAppDataPlatform" /> </ImportGroup>\n') f.write(' <PropertyGroup Label="UserMacros" />\n') f.write(' <PropertyGroup>\n') f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">$(SolutionDir)\$(ProjectName)\$(Configuration)\</OutDir>\n') f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">%s</TargetName>\n' % name) f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">.%s</TargetExt>\n' % target_ext) f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">$(SolutionDir)\$(ProjectName)\$(Configuration)\</OutDir>\n') f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">%s</TargetName>\n' % name) f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">.%s</TargetExt>\n' % target_ext) f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') f.write(' <IntDir>$(ProjectName)\$(Configuration)\</IntDir>\n') f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') f.write(' <IntDir>$(ProjectName)\$(Configuration)\</IntDir>\n') f.write(' </PropertyGroup>\n') def mk_vs_proj_cl_compile(f, name, components, debug): f.write(' <ClCompile>\n') f.write(' <Optimization>Disabled</Optimization>\n') if debug: f.write(' <PreprocessorDefinitions>WIN32;_DEBUG;Z3DEBUG;_TRACE;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n') else: f.write(' <PreprocessorDefinitions>WIN32;NDEBUG;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n') if VS_PAR: f.write(' <MinimalRebuild>false</MinimalRebuild>\n') f.write(' <MultiProcessorCompilation>true</MultiProcessorCompilation>\n') else: f.write(' <MinimalRebuild>true</MinimalRebuild>\n') f.write(' <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\n') f.write(' <WarningLevel>Level3</WarningLevel>\n') if debug: f.write(' <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\n') else: f.write(' <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\n') f.write(' <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\n') f.write(' <AdditionalIncludeDirectories>') deps = find_all_deps(name, components) first = True for dep in deps: if first: first = False else: f.write(';') f.write(get_component(dep).to_src_dir) f.write(';%s\n' % os.path.join(REV_BUILD_DIR, SRC_DIR)) f.write('</AdditionalIncludeDirectories>\n') f.write(' </ClCompile>\n') def mk_vs_proj_dep_groups(f, name, components): f.write(' <ItemGroup>\n') deps = find_all_deps(name, components) for dep in deps: dep = get_component(dep) for cpp in filter(lambda f: f.endswith('.cpp'), os.listdir(dep.src_dir)): f.write(' <ClCompile Include="%s" />\n' % os.path.join(dep.to_src_dir, cpp)) f.write(' </ItemGroup>\n') def mk_vs_proj_link_exe(f, name, debug): f.write(' <Link>\n') f.write(' <OutputFile>$(OutDir)%s.exe</OutputFile>\n' % name) f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n') f.write(' <SubSystem>Console</SubSystem>\n') f.write(' <StackReserveSize>8388608</StackReserveSize>\n') f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n') f.write(' <DataExecutionPrevention/>\n') f.write(' <TargetMachine>MachineX86</TargetMachine>\n') f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n') f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n') f.write(' </Link>\n') def mk_vs_proj(name, components): if not VS_PROJ: return proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name) modes=['Debug', 'Release'] PLATFORMS=['Win32'] f = open(proj_name, 'w') f.write('<?xml version="1.0" encoding="utf-8"?>\n') f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n') mk_vs_proj_property_groups(f, name, 'exe', 'Application') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=True) mk_vs_proj_link_exe(f, name, debug=True) f.write(' </ItemDefinitionGroup>\n') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=False) mk_vs_proj_link_exe(f, name, debug=False) f.write(' </ItemDefinitionGroup>\n') mk_vs_proj_dep_groups(f, name, components) f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n') f.write(' <ImportGroup Label="ExtensionTargets">\n') f.write(' </ImportGroup>\n') f.write('</Project>\n') f.close() if is_verbose(): print("Generated '%s'" % proj_name) def mk_vs_proj_link_dll(f, name, debug): f.write(' <Link>\n') f.write(' <OutputFile>$(OutDir)%s.dll</OutputFile>\n' % name) f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n') f.write(' <SubSystem>Console</SubSystem>\n') f.write(' <StackReserveSize>8388608</StackReserveSize>\n') f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n') f.write(' <DataExecutionPrevention/>\n') f.write(' <TargetMachine>MachineX86</TargetMachine>\n') f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n') f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n') f.write(' <ModuleDefinitionFile>%s</ModuleDefinitionFile>' % os.path.join(get_component('api_dll').to_src_dir, 'api_dll.def')) f.write(' </Link>\n') def mk_vs_proj_dll(name, components): if not VS_PROJ: return proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name) modes=['Debug', 'Release'] PLATFORMS=['Win32'] f = open(proj_name, 'w') f.write('<?xml version="1.0" encoding="utf-8"?>\n') f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n') mk_vs_proj_property_groups(f, name, 'dll', 'DynamicLibrary') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=True) mk_vs_proj_link_dll(f, name, debug=True) f.write(' </ItemDefinitionGroup>\n') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=False) mk_vs_proj_link_dll(f, name, debug=False) f.write(' </ItemDefinitionGroup>\n') mk_vs_proj_dep_groups(f, name, components) f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n') f.write(' <ImportGroup Label="ExtensionTargets">\n') f.write(' </ImportGroup>\n') f.write('</Project>\n') f.close() if is_verbose(): print("Generated '%s'" % proj_name) def mk_win_dist(build_path, dist_path): for c in get_components(): c.mk_win_dist(build_path, dist_path) def mk_unix_dist(build_path, dist_path): for c in get_components(): c.mk_unix_dist(build_path, dist_path) # Add Z3Py to bin directory for pyc in filter(lambda f: f.endswith('.pyc') or f.endswith('.py'), os.listdir(build_path)): shutil.copy(os.path.join(build_path, pyc), os.path.join(dist_path, INSTALL_BIN_DIR, pyc)) class MakeRuleCmd(object): """ These class methods provide a convenient way to emit frequently needed commands used in Makefile rules Note that several of the method are meant for use during ``make install`` and ``make uninstall``. These methods correctly use ``$(PREFIX)`` and ``$(DESTDIR)`` and therefore are preferable to writing commands manually which can be error prone. """ @classmethod def install_root(cls): """ Returns a string that will expand to the install location when used in a makefile rule. """ # Note: DESTDIR is to support staged installs return "$(DESTDIR)$(PREFIX)/" @classmethod def _is_str(cls, obj): if sys.version_info.major > 2: # Python 3 or newer. Strings are always unicode and of type str return isinstance(obj, str) else: # Python 2. Has byte-string and unicode representation, allow both return isinstance(obj, str) or isinstance(obj, unicode) @classmethod def _install_root(cls, path, in_prefix, out, is_install=True): if not in_prefix: # The Python bindings on OSX are sometimes not installed inside the prefix. install_root = "$(DESTDIR)" action_string = 'install' if is_install else 'uninstall' cls.write_cmd(out, 'echo "WARNING: {}ing files/directories ({}) that are not in the install prefix ($(PREFIX))."'.format( action_string, path)) #print("WARNING: Generating makefile rule that {}s {} '{}' which is outside the installation prefix '{}'.".format( # action_string, 'to' if is_install else 'from', path, PREFIX)) else: # assert not os.path.isabs(path) install_root = cls.install_root() return install_root @classmethod def install_files(cls, out, src_pattern, dest, in_prefix=True): assert len(dest) > 0 assert cls._is_str(src_pattern) assert not ' ' in src_pattern assert cls._is_str(dest) assert not ' ' in dest assert not os.path.isabs(src_pattern) install_root = cls._install_root(dest, in_prefix, out) cls.write_cmd(out, "cp {src_pattern} {install_root}{dest}".format( src_pattern=src_pattern, install_root=install_root, dest=dest)) @classmethod def remove_installed_files(cls, out, pattern, in_prefix=True): assert len(pattern) > 0 assert cls._is_str(pattern) assert not ' ' in pattern install_root = cls._install_root(pattern, in_prefix, out, is_install=False) cls.write_cmd(out, "rm -f {install_root}{pattern}".format( install_root=install_root, pattern=pattern)) @classmethod def make_install_directory(cls, out, dir, in_prefix=True): assert len(dir) > 0 assert cls._is_str(dir) assert not ' ' in dir install_root = cls._install_root(dir, in_prefix, out) if is_windows(): cls.write_cmd(out, "IF NOT EXIST {dir} (mkdir {dir})".format( install_root=install_root, dir=dir)) else: cls.write_cmd(out, "mkdir -p {install_root}{dir}".format( install_root=install_root, dir=dir)) @classmethod def _is_path_prefix_of(cls, temp_path, target_as_abs): """ Returns True iff ``temp_path`` is a path prefix of ``target_as_abs`` """ assert cls._is_str(temp_path) assert cls._is_str(target_as_abs) assert len(temp_path) > 0 assert len(target_as_abs) > 0 assert os.path.isabs(temp_path) assert os.path.isabs(target_as_abs) # Need to stick extra slash in front otherwise we might think that # ``/lib`` is a prefix of ``/lib64``. Of course if ``temp_path == # '/'`` then we shouldn't else we would check if ``//`` (rather than # ``/``) is a prefix of ``/lib64``, which would fail. if len(temp_path) > 1: temp_path += os.sep return target_as_abs.startswith(temp_path) @classmethod def create_relative_symbolic_link(cls, out, target, link_name): assert cls._is_str(target) assert cls._is_str(link_name) assert len(target) > 0 assert len(link_name) > 0 assert not os.path.isabs(target) assert not os.path.isabs(link_name) # We can't test to see if link_name is a file or directory # because it may not exist yet. Instead follow the convention # that if there is a leading slash target is a directory otherwise # it's a file if link_name[-1] != '/': # link_name is a file temp_path = os.path.dirname(link_name) else: # link_name is a directory temp_path = link_name[:-1] temp_path = '/' + temp_path relative_path = "" targetAsAbs = '/' + target assert os.path.isabs(targetAsAbs) assert os.path.isabs(temp_path) # Keep walking up the directory tree until temp_path # is a prefix of targetAsAbs while not cls._is_path_prefix_of(temp_path, targetAsAbs): assert temp_path != '/' temp_path = os.path.dirname(temp_path) relative_path += '../' # Now get the path from the common prefix directory to the target target_from_prefix = targetAsAbs[len(temp_path):] relative_path += target_from_prefix # Remove any double slashes relative_path = relative_path.replace('//','/') cls.create_symbolic_link(out, relative_path, link_name) @classmethod def create_symbolic_link(cls, out, target, link_name): assert cls._is_str(target) assert cls._is_str(link_name) assert not os.path.isabs(target) cls.write_cmd(out, 'ln -s {target} {install_root}{link_name}'.format( target=target, install_root=cls.install_root(), link_name=link_name)) # TODO: Refactor all of the build system to emit commands using this # helper to simplify code. This will also let us replace ``@`` with # ``$(Verb)`` and have it set to ``@`` or empty at build time depending on # a variable (e.g. ``VERBOSE``) passed to the ``make`` invocation. This # would be very helpful for debugging. @classmethod def write_cmd(cls, out, line): out.write("\t@{}\n".format(line)) def strip_path_prefix(path, prefix): if path.startswith(prefix): stripped_path = path[len(prefix):] stripped_path.replace('//','/') if stripped_path[0] == '/': stripped_path = stripped_path[1:] assert not os.path.isabs(stripped_path) return stripped_path else: return path def configure_file(template_file_path, output_file_path, substitutions): """ Read a template file ``template_file_path``, perform substitutions found in the ``substitutions`` dictionary and write the result to the output file ``output_file_path``. The template file should contain zero or more template strings of the form ``@NAME@``. The substitutions dictionary maps old strings (without the ``@`` symbols) to their replacements. """ assert isinstance(template_file_path, str) assert isinstance(output_file_path, str) assert isinstance(substitutions, dict) assert len(template_file_path) > 0 assert len(output_file_path) > 0 print("Generating {} from {}".format(output_file_path, template_file_path)) if not os.path.exists(template_file_path): raise MKException('Could not find template file "{}"'.format(template_file_path)) # Read whole template file into string template_string = None with open(template_file_path, 'r') as f: template_string = f.read() # Do replacements for (old_string, replacement) in substitutions.items(): template_string = template_string.replace('@{}@'.format(old_string), replacement) # Write the string to the file with open(output_file_path, 'w') as f: f.write(template_string) if __name__ == '__main__': import doctest doctest.testmod()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_util.py
mk_util.py
# 1. download releases from github # 2. copy over libz3.dll for the different architectures # 3. copy over Microsoft.Z3.dll from suitable distribution # 4. copy nuspec file from packages # 5. call nuget pack # 6. sign package import json import os import urllib.request import zipfile import sys import os.path import shutil import subprocess import mk_util import mk_project release_data = json.loads(urllib.request.urlopen("https://api.github.com/repos/Z3Prover/z3/releases/latest").read().decode()) release_tag_name = release_data['tag_name'] release_tag_ref_data = json.loads(urllib.request.urlopen("https://api.github.com/repos/Z3Prover/z3/git/refs/tags/%s" % release_tag_name).read().decode()) release_tag_sha = release_tag_ref_data['object']['sha'] #release_tag_data = json.loads(urllib.request.urlopen("https://api.github.com/repos/Z3Prover/z3/commits/%s" % release_tag_sha).read().decode()) release_version = release_tag_name[3:] release_commit = release_tag_sha # release_tag_data['object']['sha'] print(release_version) def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def download_installs(): for asset in release_data['assets']: url = asset['browser_download_url'] name = asset['name'] print("Downloading ", url) sys.stdout.flush() urllib.request.urlretrieve(url, "packages/%s" % name) os_info = {"z64-ubuntu-14" : ('so', 'ubuntu.14.04-x64'), 'ubuntu-16' : ('so', 'ubuntu-x64'), 'x64-win' : ('dll', 'win-x64'), # Skip x86 as I can't get dotnet build to produce AnyCPU TargetPlatform # 'x86-win' : ('dll', 'win-x86'), 'osx' : ('dylib', 'macos'), 'debian' : ('so', 'debian.8-x64') } def classify_package(f): for os_name in os_info: if os_name in f: ext, dst = os_info[os_name] return os_name, f[:-4], ext, dst return None def unpack(): shutil.rmtree("out", ignore_errors=True) # unzip files in packages # out # +- runtimes # +- win-x64 # +- win-x86 # +- ubuntu.16.04-x64 # +- ubuntu.14.04-x64 # +- debian.8-x64 # +- macos # + for f in os.listdir("packages"): print(f) if f.endswith(".zip") and classify_package(f): os_name, package_dir, ext, dst = classify_package(f) path = os.path.abspath(os.path.join("packages", f)) zip_ref = zipfile.ZipFile(path, 'r') zip_ref.extract("%s/bin/libz3.%s" % (package_dir, ext), "tmp") mk_dir("out/runtimes/%s/native" % dst) shutil.move("tmp/%s/bin/libz3.%s" % (package_dir, ext), "out/runtimes/%s/native/." % dst, "/y") if "x64-win" in f: mk_dir("out/lib/netstandard1.4/") for b in ["Microsoft.Z3.dll"]: zip_ref.extract("%s/bin/%s" % (package_dir, b), "tmp") shutil.move("tmp/%s/bin/%s" % (package_dir, b), "out/lib/netstandard1.4/%s" % b) def mk_targets(): mk_dir("out/build") shutil.copy("../src/api/dotnet/Microsoft.Z3.targets.in", "out/build/Microsoft.Z3.targets") def create_nuget_spec(): contents = """<?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata> <id>Microsoft.Z3.x64</id> <version>{0}</version> <authors>Microsoft</authors> <description> Z3 is a satisfiability modulo theories solver from Microsoft Research. Linux Dependencies: libgomp.so.1 installed </description> <copyright>&#169; Microsoft Corporation. All rights reserved.</copyright> <tags>smt constraint solver theorem prover</tags> <iconUrl>https://raw.githubusercontent.com/Z3Prover/z3/{1}/resources/icon.jpg</iconUrl> <projectUrl>https://github.com/Z3Prover/z3</projectUrl> <licenseUrl>https://raw.githubusercontent.com/Z3Prover/z3/{1}/LICENSE.txt</licenseUrl> <repository type="git" url="https://github.com/Z3Prover/z3.git" branch="master" commit="{1}" /> <requireLicenseAcceptance>true</requireLicenseAcceptance> <language>en</language> </metadata> </package>""".format(release_version, release_commit) with open("out/Microsoft.Z3.x64.nuspec", 'w') as f: f.write(contents) def create_nuget_package(): subprocess.call(["nuget", "pack"], cwd="out") def main(): mk_dir("packages") download_installs() unpack() mk_targets() create_nuget_spec() create_nuget_package() main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_nuget_release.py
mk_nuget_release.py
import mk_util import mk_exception import argparse import logging import re import os import sys ########################################################## # TODO: rewrite this file without using global variables. # This file is a big HACK. # It started as small simple script. # Now, it is too big, and is invoked from mk_make.py # ########################################################## IN = 0 OUT = 1 INOUT = 2 IN_ARRAY = 3 OUT_ARRAY = 4 INOUT_ARRAY = 5 OUT_MANAGED_ARRAY = 6 # Primitive Types VOID = 0 VOID_PTR = 1 INT = 2 UINT = 3 INT64 = 4 UINT64 = 5 STRING = 6 STRING_PTR = 7 BOOL = 8 SYMBOL = 9 PRINT_MODE = 10 ERROR_CODE = 11 DOUBLE = 12 FLOAT = 13 CHAR = 14 CHAR_PTR = 15 FIRST_OBJ_ID = 100 def is_obj(ty): return ty >= FIRST_OBJ_ID Type2Str = { VOID : 'void', VOID_PTR : 'void*', INT : 'int', UINT : 'unsigned', INT64 : 'int64_t', UINT64 : 'uint64_t', DOUBLE : 'double', FLOAT : 'float', STRING : 'Z3_string', STRING_PTR : 'Z3_string_ptr', BOOL : 'bool', SYMBOL : 'Z3_symbol', PRINT_MODE : 'Z3_ast_print_mode', ERROR_CODE : 'Z3_error_code', CHAR: 'char', CHAR_PTR: 'Z3_char_ptr' } Type2PyStr = { VOID_PTR : 'ctypes.c_void_p', INT : 'ctypes.c_int', UINT : 'ctypes.c_uint', INT64 : 'ctypes.c_longlong', UINT64 : 'ctypes.c_ulonglong', DOUBLE : 'ctypes.c_double', FLOAT : 'ctypes.c_float', STRING : 'ctypes.c_char_p', STRING_PTR : 'ctypes.POINTER(ctypes.c_char_p)', BOOL : 'ctypes.c_bool', SYMBOL : 'Symbol', PRINT_MODE : 'ctypes.c_uint', ERROR_CODE : 'ctypes.c_uint', CHAR : 'ctypes.c_char', CHAR_PTR: 'ctypes.POINTER(ctypes.c_char)' } # Mapping to .NET types Type2Dotnet = { VOID : 'void', VOID_PTR : 'IntPtr', INT : 'int', UINT : 'uint', INT64 : 'Int64', UINT64 : 'UInt64', DOUBLE : 'double', FLOAT : 'float', STRING : 'string', STRING_PTR : 'byte**', BOOL : 'byte', SYMBOL : 'IntPtr', PRINT_MODE : 'uint', ERROR_CODE : 'uint', CHAR : 'char', CHAR_PTR : 'IntPtr' } # Mapping to Java types Type2Java = { VOID : 'void', VOID_PTR : 'long', INT : 'int', UINT : 'int', INT64 : 'long', UINT64 : 'long', DOUBLE : 'double', FLOAT : 'float', STRING : 'String', STRING_PTR : 'StringPtr', BOOL : 'boolean', SYMBOL : 'long', PRINT_MODE : 'int', ERROR_CODE : 'int', CHAR : 'char', CHAR_PTR : 'long' } Type2JavaW = { VOID : 'void', VOID_PTR : 'jlong', INT : 'jint', UINT : 'jint', INT64 : 'jlong', UINT64 : 'jlong', DOUBLE : 'jdouble', FLOAT : 'jfloat', STRING : 'jstring', STRING_PTR : 'jobject', BOOL : 'jboolean', SYMBOL : 'jlong', PRINT_MODE : 'jint', ERROR_CODE : 'jint', CHAR : 'jchar', CHAR_PTR : 'jlong'} # Mapping to ML types Type2ML = { VOID : 'unit', VOID_PTR : 'VOIDP', INT : 'int', UINT : 'int', INT64 : 'int', UINT64 : 'int', DOUBLE : 'float', FLOAT : 'float', STRING : 'string', STRING_PTR : 'char**', BOOL : 'bool', SYMBOL : 'z3_symbol', PRINT_MODE : 'int', ERROR_CODE : 'int', CHAR : 'char', CHAR_PTR : 'string' } next_type_id = FIRST_OBJ_ID def def_Type(var, c_type, py_type): global next_type_id exec('%s = %s' % (var, next_type_id), globals()) Type2Str[next_type_id] = c_type Type2PyStr[next_type_id] = py_type next_type_id = next_type_id + 1 def def_Types(api_files): pat1 = re.compile(" *def_Type\(\'(.*)\',[^\']*\'(.*)\',[^\']*\'(.*)\'\)[ \t]*") for api_file in api_files: api = open(api_file, 'r') for line in api: m = pat1.match(line) if m: def_Type(m.group(1), m.group(2), m.group(3)) for k in Type2Str: v = Type2Str[k] if is_obj(k): Type2Dotnet[k] = v Type2ML[k] = v.lower() def type2str(ty): global Type2Str return Type2Str[ty] def type2pystr(ty): global Type2PyStr return Type2PyStr[ty] def type2dotnet(ty): global Type2Dotnet return Type2Dotnet[ty] def type2java(ty): global Type2Java if (ty >= FIRST_OBJ_ID): return 'long' else: return Type2Java[ty] def type2javaw(ty): global Type2JavaW if (ty >= FIRST_OBJ_ID): return 'jlong' else: return Type2JavaW[ty] def type2ml(ty): global Type2ML q = Type2ML[ty] if q[0:3] == 'z3_': return q[3:] else: return q; def _in(ty): return (IN, ty) def _in_array(sz, ty): return (IN_ARRAY, ty, sz) def _out(ty): return (OUT, ty) def _out_array(sz, ty): return (OUT_ARRAY, ty, sz, sz) # cap contains the position of the argument that stores the capacity of the array # sz contains the position of the output argument that stores the (real) size of the array def _out_array2(cap, sz, ty): return (OUT_ARRAY, ty, cap, sz) def _inout_array(sz, ty): return (INOUT_ARRAY, ty, sz, sz) def _out_managed_array(sz,ty): return (OUT_MANAGED_ARRAY, ty, 0, sz) def param_kind(p): return p[0] def param_type(p): return p[1] def param_array_capacity_pos(p): return p[2] def param_array_size_pos(p): return p[3] def param2str(p): if param_kind(p) == IN_ARRAY: return "%s const *" % type2str(param_type(p)) elif param_kind(p) == OUT_ARRAY or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY: return "%s*" % type2str(param_type(p)) elif param_kind(p) == OUT: return "%s*" % type2str(param_type(p)) else: return type2str(param_type(p)) def param2dotnet(p): k = param_kind(p) if k == OUT: if param_type(p) == STRING: return "out IntPtr" else: return "[In, Out] ref %s" % type2dotnet(param_type(p)) elif k == IN_ARRAY: return "[In] %s[]" % type2dotnet(param_type(p)) elif k == INOUT_ARRAY: return "[In, Out] %s[]" % type2dotnet(param_type(p)) elif k == OUT_ARRAY: return "[Out] %s[]" % type2dotnet(param_type(p)) elif k == OUT_MANAGED_ARRAY: return "[Out] out %s[]" % type2dotnet(param_type(p)) else: return type2dotnet(param_type(p)) def param2java(p): k = param_kind(p) if k == OUT: if param_type(p) == INT or param_type(p) == UINT: return "IntPtr" elif param_type(p) == INT64 or param_type(p) == UINT64 or param_type(p) == VOID_PTR or param_type(p) >= FIRST_OBJ_ID: return "LongPtr" elif param_type(p) == STRING: return "StringPtr" else: print("ERROR: unreachable code") assert(False) exit(1) elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: return "%s[]" % type2java(param_type(p)) elif k == OUT_MANAGED_ARRAY: if param_type(p) == UINT: return "UIntArrayPtr" else: return "ObjArrayPtr" else: return type2java(param_type(p)) def param2javaw(p): k = param_kind(p) if k == OUT: return "jobject" elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL: return "jintArray" else: return "jlongArray" elif k == OUT_MANAGED_ARRAY: return "jlong" else: return type2javaw(param_type(p)) def param2pystr(p): if param_kind(p) == IN_ARRAY or param_kind(p) == OUT_ARRAY or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT: return "ctypes.POINTER(%s)" % type2pystr(param_type(p)) else: return type2pystr(param_type(p)) def param2ml(p): k = param_kind(p) if k == OUT: if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL or param_type(p) == INT64 or param_type(p) == UINT64: return "int" elif param_type(p) == STRING: return "string" else: return "ptr" elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: return "%s list" % type2ml(param_type(p)) elif k == OUT_MANAGED_ARRAY: return "%s list" % type2ml(param_type(p)) else: return type2ml(param_type(p)) # Save name, result, params to generate wrapper _API2PY = [] def mk_py_binding(name, result, params): global core_py global _API2PY _API2PY.append((name, result, params)) if result != VOID: core_py.write("_lib.%s.restype = %s\n" % (name, type2pystr(result))) core_py.write("_lib.%s.argtypes = [" % name) first = True for p in params: if first: first = False else: core_py.write(", ") core_py.write(param2pystr(p)) core_py.write("]\n") def extra_API(name, result, params): mk_py_binding(name, result, params) reg_dotnet(name, result, params) def display_args(num): for i in range(num): if i > 0: core_py.write(", ") core_py.write("a%s" % i) def display_args_to_z3(params): i = 0 for p in params: if i > 0: core_py.write(", ") if param_type(p) == STRING: core_py.write("_str_to_bytes(a%s)" % i) else: core_py.write("a%s" % i) i = i + 1 NULLWrapped = [ 'Z3_mk_context', 'Z3_mk_context_rc' ] Unwrapped = [ 'Z3_del_context', 'Z3_get_error_code' ] def mk_py_wrappers(): core_py.write(""" class Elementaries: def __init__(self, f): self.f = f self.get_error_code = _lib.Z3_get_error_code self.get_error_message = _lib.Z3_get_error_msg self.OK = Z3_OK self.Exception = Z3Exception def Check(self, ctx): err = self.get_error_code(ctx) if err != self.OK: raise self.Exception(self.get_error_message(ctx, err)) def Z3_set_error_handler(ctx, hndlr, _elems=Elementaries(_lib.Z3_set_error_handler)): ceh = _error_handler_type(hndlr) _elems.f(ctx, ceh) _elems.Check(ctx) return ceh """) for sig in _API2PY: mk_py_wrapper_single(sig) if sig[1] == STRING: mk_py_wrapper_single(sig, decode_string=False) def mk_py_wrapper_single(sig, decode_string=True): name = sig[0] result = sig[1] params = sig[2] num = len(params) def_name = name if not decode_string: def_name += '_bytes' core_py.write("def %s(" % def_name) display_args(num) comma = ", " if num != 0 else "" core_py.write("%s_elems=Elementaries(_lib.%s)):\n" % (comma, name)) lval = "r = " if result != VOID else "" core_py.write(" %s_elems.f(" % lval) display_args_to_z3(params) core_py.write(")\n") if len(params) > 0 and param_type(params[0]) == CONTEXT and not name in Unwrapped: core_py.write(" _elems.Check(a0)\n") if result == STRING and decode_string: core_py.write(" return _to_pystr(r)\n") elif result != VOID: core_py.write(" return r\n") core_py.write("\n") ## .NET API native interface _dotnet_decls = [] def reg_dotnet(name, result, params): global _dotnet_decls _dotnet_decls.append((name, result, params)) def mk_dotnet(dotnet): global Type2Str dotnet.write('// Automatically generated file\n') dotnet.write('using System;\n') dotnet.write('using System.Collections.Generic;\n') dotnet.write('using System.Text;\n') dotnet.write('using System.Runtime.InteropServices;\n\n') dotnet.write('#pragma warning disable 1591\n\n') dotnet.write('namespace Microsoft.Z3\n') dotnet.write('{\n') for k in Type2Str: v = Type2Str[k] if is_obj(k): dotnet.write(' using %s = System.IntPtr;\n' % v) dotnet.write('\n') dotnet.write(' public class Native\n') dotnet.write(' {\n\n') dotnet.write(' [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n') dotnet.write(' public delegate void Z3_error_handler(Z3_context c, Z3_error_code e);\n\n') dotnet.write(' public class LIB\n') dotnet.write(' {\n') dotnet.write(' const string Z3_DLL_NAME = \"libz3\";\n' ' \n') dotnet.write(' [DllImport(Z3_DLL_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n') dotnet.write(' public extern static void Z3_set_error_handler(Z3_context a0, Z3_error_handler a1);\n\n') for name, result, params in _dotnet_decls: dotnet.write(' [DllImport(Z3_DLL_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n') dotnet.write(' ') if result == STRING: dotnet.write('public extern static IntPtr %s(' % (name)) else: dotnet.write('public extern static %s %s(' % (type2dotnet(result), name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') dotnet.write('%s a%d' % (param2dotnet(param), i)) i = i + 1 dotnet.write(');\n\n') dotnet.write(' }\n') def mk_dotnet_wrappers(dotnet): global Type2Str dotnet.write("\n") dotnet.write(" public static void Z3_set_error_handler(Z3_context a0, Z3_error_handler a1) {\n") dotnet.write(" LIB.Z3_set_error_handler(a0, a1);\n") dotnet.write(" Z3_error_code err = (Z3_error_code)LIB.Z3_get_error_code(a0);\n") dotnet.write(" if (err != Z3_error_code.Z3_OK)\n") dotnet.write(" throw new Z3Exception(Marshal.PtrToStringAnsi(LIB.Z3_get_error_msg(a0, (uint)err)));\n") dotnet.write(" }\n\n") for name, result, params in _dotnet_decls: if result == STRING: dotnet.write(' public static string %s(' % (name)) else: dotnet.write(' public static %s %s(' % (type2dotnet(result), name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') dotnet.write('%s a%d' % (param2dotnet(param), i)) i = i + 1 dotnet.write(') {\n') dotnet.write(' ') if result == STRING: dotnet.write('IntPtr r = ') elif result != VOID: dotnet.write('%s r = ' % type2dotnet(result)) dotnet.write('LIB.%s(' % (name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') if param_kind(param) == OUT: if param_type(param) == STRING: dotnet.write('out ') else: dotnet.write('ref ') elif param_kind(param) == OUT_MANAGED_ARRAY: dotnet.write('out ') dotnet.write('a%d' % i) i = i + 1 dotnet.write(');\n') if name not in Unwrapped: if name in NULLWrapped: dotnet.write(" if (r == IntPtr.Zero)\n") dotnet.write(" throw new Z3Exception(\"Object allocation failed.\");\n") else: if len(params) > 0 and param_type(params[0]) == CONTEXT: dotnet.write(" Z3_error_code err = (Z3_error_code)LIB.Z3_get_error_code(a0);\n") dotnet.write(" if (err != Z3_error_code.Z3_OK)\n") dotnet.write(" throw new Z3Exception(Marshal.PtrToStringAnsi(LIB.Z3_get_error_msg(a0, (uint)err)));\n") if result == STRING: dotnet.write(" return Marshal.PtrToStringAnsi(r);\n") elif result != VOID: dotnet.write(" return r;\n") dotnet.write(" }\n\n") dotnet.write(" }\n\n") dotnet.write("}\n\n") def java_method_name(name): result = '' name = name[3:] # Remove Z3_ n = len(name) i = 0 while i < n: if name[i] == '_': i = i + 1 if i < n: result += name[i].upper() else: result += name[i] i = i + 1 return result # Return the type of the java array elements def java_array_element_type(p): if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL: return 'jint' else: return 'jlong' def mk_java(java_dir, package_name): java_nativef = os.path.join(java_dir, 'Native.java') java_wrapperf = os.path.join(java_dir, 'Native.cpp') java_native = open(java_nativef, 'w') java_native.write('// Automatically generated file\n') java_native.write('package %s;\n' % package_name) java_native.write('import %s.enumerations.*;\n' % package_name) java_native.write('public final class Native {\n') java_native.write(' public static class IntPtr { public int value; }\n') java_native.write(' public static class LongPtr { public long value; }\n') java_native.write(' public static class StringPtr { public String value; }\n') java_native.write(' public static class ObjArrayPtr { public long[] value; }\n') java_native.write(' public static class UIntArrayPtr { public int[] value; }\n') java_native.write(' public static native void setInternalErrorHandler(long ctx);\n\n') java_native.write(' static {\n') java_native.write(' try { System.loadLibrary("z3java"); }\n') java_native.write(' catch (UnsatisfiedLinkError ex) { System.loadLibrary("libz3java"); }\n') java_native.write(' }\n') java_native.write('\n') for name, result, params in _dotnet_decls: java_native.write(' protected static native %s INTERNAL%s(' % (type2java(result), java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('%s a%d' % (param2java(param), i)) i = i + 1 java_native.write(');\n') java_native.write('\n\n') # Exception wrappers for name, result, params in _dotnet_decls: java_native.write(' public static %s %s(' % (type2java(result), java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('%s a%d' % (param2java(param), i)) i = i + 1 java_native.write(')') if (len(params) > 0 and param_type(params[0]) == CONTEXT) or name in NULLWrapped: java_native.write(' throws Z3Exception') java_native.write('\n') java_native.write(' {\n') java_native.write(' ') if result != VOID: java_native.write('%s res = ' % type2java(result)) java_native.write('INTERNAL%s(' % (java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('a%d' % i) i = i + 1 java_native.write(');\n') if name not in Unwrapped: if name in NULLWrapped: java_native.write(" if (res == 0)\n") java_native.write(" throw new Z3Exception(\"Object allocation failed.\");\n") else: if len(params) > 0 and param_type(params[0]) == CONTEXT: java_native.write(' Z3_error_code err = Z3_error_code.fromInt(INTERNALgetErrorCode(a0));\n') java_native.write(' if (err != Z3_error_code.Z3_OK)\n') java_native.write(' throw new Z3Exception(INTERNALgetErrorMsg(a0, err.toInt()));\n') if result != VOID: java_native.write(' return res;\n') java_native.write(' }\n\n') java_native.write('}\n') java_wrapper = open(java_wrapperf, 'w') pkg_str = package_name.replace('.', '_') java_wrapper.write('// Automatically generated file\n') java_wrapper.write('#include<jni.h>\n') java_wrapper.write('#include<stdlib.h>\n') java_wrapper.write('#include"z3.h"\n') java_wrapper.write('#ifdef __cplusplus\n') java_wrapper.write('extern "C" {\n') java_wrapper.write('#endif\n\n') java_wrapper.write('#ifdef __GNUC__\n#if __GNUC__ >= 4\n#define DLL_VIS __attribute__ ((visibility ("default")))\n#else\n#define DLL_VIS\n#endif\n#else\n#define DLL_VIS\n#endif\n\n') java_wrapper.write('#if defined(__LP64__) || defined(_WIN64)\n\n') java_wrapper.write('#define GETLONGAELEMS(T,OLD,NEW) \\\n') java_wrapper.write(' T * NEW = (OLD == 0) ? 0 : (T*) jenv->GetLongArrayElements(OLD, NULL);\n') java_wrapper.write('#define RELEASELONGAELEMS(OLD,NEW) \\\n') java_wrapper.write(' if (OLD != 0) jenv->ReleaseLongArrayElements(OLD, (jlong *) NEW, JNI_ABORT); \n\n') java_wrapper.write('#define GETLONGAREGION(T,OLD,Z,SZ,NEW) \\\n') java_wrapper.write(' jenv->GetLongArrayRegion(OLD,Z,(jsize)SZ,(jlong*)NEW); \n') java_wrapper.write('#define SETLONGAREGION(OLD,Z,SZ,NEW) \\\n') java_wrapper.write(' jenv->SetLongArrayRegion(OLD,Z,(jsize)SZ,(jlong*)NEW) \n\n') java_wrapper.write('#else\n\n') java_wrapper.write('#define GETLONGAELEMS(T,OLD,NEW) \\\n') java_wrapper.write(' T * NEW = 0; { \\\n') java_wrapper.write(' jlong * temp = (OLD == 0) ? 0 : jenv->GetLongArrayElements(OLD, NULL); \\\n') java_wrapper.write(' unsigned int size = (OLD == 0) ? 0 :jenv->GetArrayLength(OLD); \\\n') java_wrapper.write(' if (OLD != 0) { \\\n') java_wrapper.write(' NEW = (T*) (new int[size]); \\\n') java_wrapper.write(' for (unsigned i=0; i < size; i++) \\\n') java_wrapper.write(' NEW[i] = reinterpret_cast<T>(temp[i]); \\\n') java_wrapper.write(' jenv->ReleaseLongArrayElements(OLD, temp, JNI_ABORT); \\\n') java_wrapper.write(' } \\\n') java_wrapper.write(' } \n\n') java_wrapper.write('#define RELEASELONGAELEMS(OLD,NEW) \\\n') java_wrapper.write(' delete [] NEW; \n\n') java_wrapper.write('#define GETLONGAREGION(T,OLD,Z,SZ,NEW) \\\n') java_wrapper.write(' { \\\n') java_wrapper.write(' jlong * temp = new jlong[SZ]; \\\n') java_wrapper.write(' jenv->GetLongArrayRegion(OLD,Z,(jsize)SZ,(jlong*)temp); \\\n') java_wrapper.write(' for (int i = 0; i < (SZ); i++) \\\n') java_wrapper.write(' NEW[i] = reinterpret_cast<T>(temp[i]); \\\n') java_wrapper.write(' delete [] temp; \\\n') java_wrapper.write(' }\n\n') java_wrapper.write('#define SETLONGAREGION(OLD,Z,SZ,NEW) \\\n') java_wrapper.write(' { \\\n') java_wrapper.write(' jlong * temp = new jlong[SZ]; \\\n') java_wrapper.write(' for (int i = 0; i < (SZ); i++) \\\n') java_wrapper.write(' temp[i] = reinterpret_cast<jlong>(NEW[i]); \\\n') java_wrapper.write(' jenv->SetLongArrayRegion(OLD,Z,(jsize)SZ,temp); \\\n') java_wrapper.write(' delete [] temp; \\\n') java_wrapper.write(' }\n\n') java_wrapper.write('#endif\n\n') java_wrapper.write('void Z3JavaErrorHandler(Z3_context c, Z3_error_code e)\n') java_wrapper.write('{\n') java_wrapper.write(' // Internal do-nothing error handler. This is required to avoid that Z3 calls exit()\n') java_wrapper.write(' // upon errors, but the actual error handling is done by throwing exceptions in the\n') java_wrapper.write(' // wrappers below.\n') java_wrapper.write('}\n\n') java_wrapper.write('DLL_VIS JNIEXPORT void JNICALL Java_%s_Native_setInternalErrorHandler(JNIEnv * jenv, jclass cls, jlong a0)\n' % pkg_str) java_wrapper.write('{\n') java_wrapper.write(' Z3_set_error_handler((Z3_context)a0, Z3JavaErrorHandler);\n') java_wrapper.write('}\n\n') java_wrapper.write('') for name, result, params in _dotnet_decls: java_wrapper.write('DLL_VIS JNIEXPORT %s JNICALL Java_%s_Native_INTERNAL%s(JNIEnv * jenv, jclass cls' % (type2javaw(result), pkg_str, java_method_name(name))) i = 0 for param in params: java_wrapper.write(', ') java_wrapper.write('%s a%d' % (param2javaw(param), i)) i = i + 1 java_wrapper.write(') {\n') # preprocess arrays, strings, in/out arguments i = 0 for param in params: k = param_kind(param) if k == OUT or k == INOUT: java_wrapper.write(' %s _a%s;\n' % (type2str(param_type(param)), i)) elif k == IN_ARRAY or k == INOUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' %s * _a%s = (%s*) jenv->GetIntArrayElements(a%s, NULL);\n' % (type2str(param_type(param)), i, type2str(param_type(param)), i)) else: java_wrapper.write(' GETLONGAELEMS(%s, a%s, _a%s);\n' % (type2str(param_type(param)), i, i)) elif k == OUT_ARRAY: java_wrapper.write(' %s * _a%s = (%s *) malloc(((unsigned)a%s) * sizeof(%s));\n' % (type2str(param_type(param)), i, type2str(param_type(param)), param_array_capacity_pos(param), type2str(param_type(param)))) if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->GetIntArrayRegion(a%s, 0, (jsize)a%s, (jint*)_a%s);\n' % (i, param_array_capacity_pos(param), i)) else: java_wrapper.write(' GETLONGAREGION(%s, a%s, 0, a%s, _a%s);\n' % (type2str(param_type(param)), i, param_array_capacity_pos(param), i)) elif k == IN and param_type(param) == STRING: java_wrapper.write(' Z3_string _a%s = (Z3_string) jenv->GetStringUTFChars(a%s, NULL);\n' % (i, i)) elif k == OUT_MANAGED_ARRAY: java_wrapper.write(' %s * _a%s = 0;\n' % (type2str(param_type(param)), i)) i = i + 1 # invoke procedure java_wrapper.write(' ') if result != VOID: java_wrapper.write('%s result = ' % type2str(result)) java_wrapper.write('%s(' % name) i = 0 first = True for param in params: if first: first = False else: java_wrapper.write(', ') k = param_kind(param) if k == OUT or k == INOUT: java_wrapper.write('&_a%s' % i) elif k == OUT_ARRAY or k == IN_ARRAY or k == INOUT_ARRAY: java_wrapper.write('_a%s' % i) elif k == OUT_MANAGED_ARRAY: java_wrapper.write('&_a%s' % i) elif k == IN and param_type(param) == STRING: java_wrapper.write('_a%s' % i) else: java_wrapper.write('(%s)a%i' % (param2str(param), i)) i = i + 1 java_wrapper.write(');\n') # cleanup i = 0 for param in params: k = param_kind(param) if k == OUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->SetIntArrayRegion(a%s, 0, (jsize)a%s, (jint*)_a%s);\n' % (i, param_array_capacity_pos(param), i)) else: java_wrapper.write(' SETLONGAREGION(a%s, 0, a%s, _a%s);\n' % (i, param_array_capacity_pos(param), i)) java_wrapper.write(' free(_a%s);\n' % i) elif k == IN_ARRAY or k == OUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->ReleaseIntArrayElements(a%s, (jint*)_a%s, JNI_ABORT);\n' % (i, i)) else: java_wrapper.write(' RELEASELONGAELEMS(a%s, _a%s);\n' % (i, i)) elif k == OUT or k == INOUT: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' {\n') java_wrapper.write(' jclass mc = jenv->GetObjectClass(a%s);\n' % i) java_wrapper.write(' jfieldID fid = jenv->GetFieldID(mc, "value", "I");\n') java_wrapper.write(' jenv->SetIntField(a%s, fid, (jint) _a%s);\n' % (i, i)) java_wrapper.write(' }\n') else: java_wrapper.write(' {\n') java_wrapper.write(' jclass mc = jenv->GetObjectClass(a%s);\n' % i) java_wrapper.write(' jfieldID fid = jenv->GetFieldID(mc, "value", "J");\n') java_wrapper.write(' jenv->SetLongField(a%s, fid, (jlong) _a%s);\n' % (i, i)) java_wrapper.write(' }\n') elif k == OUT_MANAGED_ARRAY: java_wrapper.write(' *(jlong**)a%s = (jlong*)_a%s;\n' % (i, i)) elif k == IN and param_type(param) == STRING: java_wrapper.write(' jenv->ReleaseStringUTFChars(a%s, _a%s);\n' % (i, i)); i = i + 1 # return if result == STRING: java_wrapper.write(' return jenv->NewStringUTF(result);\n') elif result != VOID: java_wrapper.write(' return (%s) result;\n' % type2javaw(result)) java_wrapper.write('}\n') java_wrapper.write('#ifdef __cplusplus\n') java_wrapper.write('}\n') java_wrapper.write('#endif\n') if mk_util.is_verbose(): print("Generated '%s'" % java_nativef) Type2Napi = { VOID : '', VOID_PTR : '', INT : 'number', UINT : 'number', INT64 : 'number', UINT64 : 'number', DOUBLE : 'number', FLOAT : 'number', STRING : 'string', STRING_PTR : 'array', BOOL : 'number', SYMBOL : 'external', PRINT_MODE : 'number', ERROR_CODE : 'number', CHAR : 'number' } def type2napi(t): try: return Type2Napi[t] except: return "external" Type2NapiBuilder = { VOID : '', VOID_PTR : '', INT : 'int32', UINT : 'uint32', INT64 : 'int64', UINT64 : 'uint64', DOUBLE : 'double', FLOAT : 'float', STRING : 'string', STRING_PTR : 'array', BOOL : 'bool', SYMBOL : 'external', PRINT_MODE : 'int32', ERROR_CODE : 'int32', CHAR : 'char' } def type2napibuilder(t): try: return Type2NapiBuilder[t] except: return "external" def mk_js(js_output_dir): with open(os.path.join(js_output_dir, "z3.json"), 'w') as ous: ous.write("{\n") ous.write(" \"api\": [\n") for name, result, params in _dotnet_decls: ous.write(" {\n") ous.write(" \"name\": \"%s\",\n" % name) ous.write(" \"c_type\": \"%s\",\n" % Type2Str[result]) ous.write(" \"napi_type\": \"%s\",\n" % type2napi(result)) ous.write(" \"arg_list\": [") first = True for p in params: if first: first = False ous.write("\n {\n") else: ous.write(",\n {\n") t = param_type(p) k = t ous.write(" \"name\": \"%s\",\n" % "") # TBD ous.write(" \"c_type\": \"%s\",\n" % type2str(t)) ous.write(" \"napi_type\": \"%s\",\n" % type2napi(t)) ous.write(" \"napi_builder\": \"%s\"\n" % type2napibuilder(t)) ous.write( " }") ous.write("],\n") ous.write(" \"napi_builder\": \"%s\"\n" % type2napibuilder(result)) ous.write(" },\n") ous.write(" ]\n") ous.write("}\n") def mk_log_header(file, name, params): file.write("void log_%s(" % name) i = 0 for p in params: if i > 0: file.write(", ") file.write("%s a%s" % (param2str(p), i)) i = i + 1 file.write(")") def log_param(p): kind = param_kind(p) ty = param_type(p) return is_obj(ty) and (kind == OUT or kind == INOUT or kind == OUT_ARRAY or kind == INOUT_ARRAY) def log_result(result, params): for p in params: if log_param(p): return True return False def mk_log_macro(file, name, params): file.write("#define LOG_%s(" % name) i = 0 for p in params: if i > 0: file.write(", ") file.write("_ARG%s" % i) i = i + 1 file.write(") z3_log_ctx _LOG_CTX; ") auxs = set() i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) if cap not in auxs: auxs.add(cap) file.write("unsigned _Z3_UNUSED Z3ARG%s = 0; " % cap) sz = param_array_size_pos(p) if sz not in auxs: auxs.add(sz) file.write("unsigned * _Z3_UNUSED Z3ARG%s = 0; " % sz) file.write("%s _Z3_UNUSED Z3ARG%s = 0; " % (param2str(p), i)) i = i + 1 file.write("if (_LOG_CTX.enabled()) { log_%s(" % name) i = 0 for p in params: if (i > 0): file.write(', ') file.write("_ARG%s" %i) i = i + 1 file.write("); ") auxs = set() i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) if cap not in auxs: auxs.add(cap) file.write("Z3ARG%s = _ARG%s; " % (cap, cap)) sz = param_array_size_pos(p) if sz not in auxs: auxs.add(sz) file.write("Z3ARG%s = _ARG%s; " % (sz, sz)) file.write("Z3ARG%s = _ARG%s; " % (i, i)) i = i + 1 file.write("}\n") def mk_log_result_macro(file, name, result, params): file.write("#define RETURN_%s" % name) if is_obj(result): file.write("(Z3RES)") file.write(" ") file.write("if (_LOG_CTX.enabled()) { ") if is_obj(result): file.write("SetR(Z3RES); ") i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) sz = param_array_size_pos(p) if cap == sz: file.write("for (unsigned i = 0; i < Z3ARG%s; i++) { SetAO(Z3ARG%s[i], %s, i); } " % (sz, i, i)) else: file.write("for (unsigned i = 0; Z3ARG%s && i < *Z3ARG%s; i++) { SetAO(Z3ARG%s[i], %s, i); } " % (sz, sz, i, i)) if kind == OUT or kind == INOUT: file.write("SetO((Z3ARG%s == 0 ? 0 : *Z3ARG%s), %s); " % (i, i, i)) i = i + 1 file.write("} ") if is_obj(result): file.write("return Z3RES\n") else: file.write("return\n") def mk_exec_header(file, name): file.write("void exec_%s(z3_replayer & in)" % name) def error(msg): sys.stderr.write(msg) exit(-1) next_id = 0 API2Id = {} def def_API(name, result, params): global API2Id, next_id global log_h, log_c mk_py_binding(name, result, params) reg_dotnet(name, result, params) API2Id[next_id] = name mk_log_header(log_h, name, params) log_h.write(';\n') mk_log_header(log_c, name, params) log_c.write(' {\n R();\n') mk_exec_header(exe_c, name) exe_c.write(' {\n') # Create Log function & Function call i = 0 exe_c.write(" ") if is_obj(result): exe_c.write("%s result = " % type2str(result)) exe_c.write("%s(\n " % name) for p in params: kind = param_kind(p) ty = param_type(p) if (i > 0): exe_c.write(",\n ") if kind == IN: if is_obj(ty): log_c.write(" P(a%s);\n" % i) exe_c.write("reinterpret_cast<%s>(in.get_obj(%s))" % (param2str(p), i)) elif ty == STRING: log_c.write(" S(a%s);\n" % i) exe_c.write("in.get_str(%s)" % i) elif ty == SYMBOL: log_c.write(" Sy(a%s);\n" % i) exe_c.write("in.get_symbol(%s)" % i) elif ty == UINT: log_c.write(" U(a%s);\n" % i) exe_c.write("in.get_uint(%s)" % i) elif ty == UINT64: log_c.write(" U(a%s);\n" % i) exe_c.write("in.get_uint64(%s)" % i) elif ty == INT: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_int(%s)" % i) elif ty == INT64: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_int64(%s)" % i) elif ty == DOUBLE: log_c.write(" D(a%s);\n" % i) exe_c.write("in.get_double(%s)" % i) elif ty == FLOAT: log_c.write(" D(a%s);\n" % i) exe_c.write("in.get_float(%s)" % i) elif ty == BOOL: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_bool(%s)" % i) elif ty == PRINT_MODE or ty == ERROR_CODE: log_c.write(" U(static_cast<unsigned>(a%s));\n" % i) exe_c.write("static_cast<%s>(in.get_uint(%s))" % (type2str(ty), i)) else: error("unsupported parameter for %s, %s" % (name, p)) elif kind == INOUT: error("unsupported parameter for %s, %s" % (name, p)) elif kind == OUT: if is_obj(ty): log_c.write(" P(0);\n") exe_c.write("reinterpret_cast<%s>(in.get_obj_addr(%s))" % (param2str(p), i)) elif ty == STRING: log_c.write(" S(\"\");\n") exe_c.write("in.get_str_addr(%s)" % i) elif ty == UINT: log_c.write(" U(0);\n") exe_c.write("in.get_uint_addr(%s)" % i) elif ty == UINT64: log_c.write(" U(0);\n") exe_c.write("in.get_uint64_addr(%s)" % i) elif ty == INT: log_c.write(" I(0);\n") exe_c.write("in.get_int_addr(%s)" % i) elif ty == INT64: log_c.write(" I(0);\n") exe_c.write("in.get_int64_addr(%s)" % i) elif ty == VOID_PTR: log_c.write(" P(0);\n") exe_c.write("in.get_obj_addr(%s)" % i) else: error("unsupported parameter for %s, %s" % (name, p)) elif kind == IN_ARRAY or kind == INOUT_ARRAY: sz = param_array_capacity_pos(p) log_c.write(" for (unsigned i = 0; i < a%s; i++) { " % sz) if is_obj(ty): log_c.write("P(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Ap(a%s);\n" % sz) exe_c.write("reinterpret_cast<%s*>(in.get_obj_array(%s))" % (type2str(ty), i)) elif ty == SYMBOL: log_c.write("Sy(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Asy(a%s);\n" % sz) exe_c.write("in.get_symbol_array(%s)" % i) elif ty == UINT: log_c.write("U(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Au(a%s);\n" % sz) exe_c.write("in.get_uint_array(%s)" % i) elif ty == INT: log_c.write("I(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Ai(a%s);\n" % sz) exe_c.write("in.get_int_array(%s)" % i) elif ty == BOOL: log_c.write("U(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Au(a%s);\n" % sz) exe_c.write("in.get_bool_array(%s)" % i) else: error ("unsupported parameter for %s, %s, %s" % (ty, name, p)) elif kind == OUT_ARRAY: sz = param_array_capacity_pos(p) sz_p = params[sz] sz_p_k = param_kind(sz_p) tstr = type2str(ty) if sz_p_k == OUT or sz_p_k == INOUT: sz_e = ("(*a%s)" % sz) else: sz_e = ("a%s" % sz) log_c.write(" for (unsigned i = 0; i < %s; i++) { " % sz_e) if is_obj(ty): log_c.write("P(0);") log_c.write(" }\n") log_c.write(" Ap(%s);\n" % sz_e) exe_c.write("reinterpret_cast<%s*>(in.get_obj_array(%s))" % (tstr, i)) elif ty == UINT: log_c.write("U(0);") log_c.write(" }\n") log_c.write(" Au(%s);\n" % sz_e) exe_c.write("in.get_uint_array(%s)" % i) else: error ("unsupported parameter for %s, %s" % (name, p)) elif kind == OUT_MANAGED_ARRAY: sz = param_array_size_pos(p) sz_p = params[sz] sz_p_k = param_kind(sz_p) tstr = type2str(ty) if sz_p_k == OUT or sz_p_k == INOUT: sz_e = ("(*a%s)" % sz) else: sz_e = ("a%s" % sz) log_c.write(" for (unsigned i = 0; i < %s; i++) { " % sz_e) log_c.write("P(0);") log_c.write(" }\n") log_c.write(" Ap(%s);\n" % sz_e) exe_c.write("reinterpret_cast<%s**>(in.get_obj_array(%s))" % (tstr, i)) else: error ("unsupported parameter for %s, %s" % (name, p)) i = i + 1 log_c.write(" C(%s);\n" % next_id) exe_c.write(");\n") if is_obj(result): exe_c.write(" in.store_result(result);\n") if name == 'Z3_mk_context' or name == 'Z3_mk_context_rc': exe_c.write(" Z3_set_error_handler(result, Z3_replayer_error_handler);") log_c.write('}\n') exe_c.write('}\n') mk_log_macro(log_h, name, params) if log_result(result, params): mk_log_result_macro(log_h, name, result, params) next_id = next_id + 1 def mk_bindings(exe_c): exe_c.write("void register_z3_replayer_cmds(z3_replayer & in) {\n") for key, val in API2Id.items(): exe_c.write(" in.register_cmd(%s, exec_%s, \"%s\");\n" % (key, val, val)) exe_c.write("}\n") def ml_method_name(name): return name[3:] # Remove Z3_ def is_out_param(p): if param_kind(p) == OUT or param_kind(p) == INOUT or param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT_MANAGED_ARRAY: return True else: return False def outparams(params): op = [] for param in params: if is_out_param(param): op.append(param) return op def is_in_param(p): if param_kind(p) == IN or param_kind(p) == INOUT or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY: return True else: return False def inparams(params): ip = [] for param in params: if is_in_param(param): ip.append(param) return ip def is_array_param(p): if param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT_ARRAY: return True else: return False def arrayparams(params): op = [] for param in params: if is_array_param(param): op.append(param) return op def ml_plus_type(ts): if ts == 'Z3_context': return 'Z3_context_plus' elif ts == 'Z3_ast' or ts == 'Z3_sort' or ts == 'Z3_func_decl' or ts == 'Z3_app' or ts == 'Z3_pattern': return 'Z3_ast_plus' elif ts == 'Z3_symbol': return 'Z3_symbol_plus' elif ts == 'Z3_constructor': return 'Z3_constructor_plus' elif ts == 'Z3_constructor_list': return 'Z3_constructor_list_plus' elif ts == 'Z3_rcf_num': return 'Z3_rcf_num_plus' elif ts == 'Z3_params': return 'Z3_params_plus' elif ts == 'Z3_param_descrs': return 'Z3_param_descrs_plus' elif ts == 'Z3_model': return 'Z3_model_plus' elif ts == 'Z3_func_interp': return 'Z3_func_interp_plus' elif ts == 'Z3_func_entry': return 'Z3_func_entry_plus' elif ts == 'Z3_goal': return 'Z3_goal_plus' elif ts == 'Z3_tactic': return 'Z3_tactic_plus' elif ts == 'Z3_probe': return 'Z3_probe_plus' elif ts == 'Z3_apply_result': return 'Z3_apply_result_plus' elif ts == 'Z3_solver': return 'Z3_solver_plus' elif ts == 'Z3_stats': return 'Z3_stats_plus' elif ts == 'Z3_ast_vector': return 'Z3_ast_vector_plus' elif ts == 'Z3_ast_map': return 'Z3_ast_map_plus' elif ts == 'Z3_fixedpoint': return 'Z3_fixedpoint_plus' elif ts == 'Z3_optimize': return 'Z3_optimize_plus' else: return ts def ml_minus_type(ts): if ts == 'Z3_ast' or ts == 'Z3_sort' or ts == 'Z3_func_decl' or ts == 'Z3_app' or ts == 'Z3_pattern': return 'Z3_ast' if ts == 'Z3_ast_plus' or ts == 'Z3_sort_plus' or ts == 'Z3_func_decl_plus' or ts == 'Z3_app_plus' or ts == 'Z3_pattern_plus': return 'Z3_ast' elif ts == 'Z3_constructor_plus': return 'Z3_constructor' elif ts == 'Z3_constructor_list_plus': return 'Z3_constructor_list' elif ts == 'Z3_rcf_num_plus': return 'Z3_rcf_num' elif ts == 'Z3_params_plus': return 'Z3_params' elif ts == 'Z3_param_descrs_plus': return 'Z3_param_descrs' elif ts == 'Z3_model_plus': return 'Z3_model' elif ts == 'Z3_func_interp_plus': return 'Z3_func_interp' elif ts == 'Z3_func_entry_plus': return 'Z3_func_entry' elif ts == 'Z3_goal_plus': return 'Z3_goal' elif ts == 'Z3_tactic_plus': return 'Z3_tactic' elif ts == 'Z3_probe_plus': return 'Z3_probe' elif ts == 'Z3_apply_result_plus': return 'Z3_apply_result' elif ts == 'Z3_solver_plus': return 'Z3_solver' elif ts == 'Z3_stats_plus': return 'Z3_stats' elif ts == 'Z3_ast_vector_plus': return 'Z3_ast_vector' elif ts == 'Z3_ast_map_plus': return 'Z3_ast_map' elif ts == 'Z3_fixedpoint_plus': return 'Z3_fixedpoint' elif ts == 'Z3_optimize_plus': return 'Z3_optimize' else: return ts def ml_plus_type_raw(ts): if ml_has_plus_type(ts): return ml_plus_type(ts) + '_raw'; else: return ts def ml_plus_ops_type(ts): if ml_has_plus_type(ts): return ml_plus_type(ts) + '_custom_ops' else: return 'default_custom_ops' def ml_has_plus_type(ts): return ts != ml_plus_type(ts) def ml_unwrap(t, ts, s): if t == STRING: return '(' + ts + ') String_val(' + s + ')' elif t == BOOL or (type2str(t) == 'bool'): return '(' + ts + ') Bool_val(' + s + ')' elif t == INT or t == PRINT_MODE or t == ERROR_CODE: return '(' + ts + ') Int_val(' + s + ')' elif t == UINT: return '(' + ts + ') Unsigned_int_val(' + s + ')' elif t == INT64: return '(' + ts + ') Long_val(' + s + ')' elif t == UINT64: return '(' + ts + ') Unsigned_long_val(' + s + ')' elif t == DOUBLE: return '(' + ts + ') Double_val(' + s + ')' elif ml_has_plus_type(ts): pts = ml_plus_type(ts) return '(' + ts + ') ' + ml_plus_type_raw(ts) + '((' + pts + '*) Data_custom_val(' + s + '))' else: return '* ((' + ts + '*) Data_custom_val(' + s + '))' def ml_set_wrap(t, d, n): if t == VOID: return d + ' = Val_unit;' elif t == BOOL or (type2str(t) == 'bool'): return d + ' = Val_bool(' + n + ');' elif t == INT or t == UINT or t == PRINT_MODE or t == ERROR_CODE: return d + ' = Val_int(' + n + ');' elif t == INT64 or t == UINT64: return d + ' = Val_long(' + n + ');' elif t == DOUBLE: return d + '= caml_copy_double(' + n + ');' elif t == STRING: return d + ' = caml_copy_string((const char*) ' + n + ');' else: pts = ml_plus_type(type2str(t)) return '*(' + pts + '*)Data_custom_val(' + d + ') = ' + n + ';' def ml_alloc_and_store(t, lhs, rhs): if t == VOID or t == BOOL or t == INT or t == UINT or t == PRINT_MODE or t == ERROR_CODE or t == INT64 or t == UINT64 or t == DOUBLE or t == STRING or (type2str(t) == 'bool'): return ml_set_wrap(t, lhs, rhs) else: pts = ml_plus_type(type2str(t)) pops = ml_plus_ops_type(type2str(t)) alloc_str = '%s = caml_alloc_custom(&%s, sizeof(%s), 0, 1); ' % (lhs, pops, pts) return alloc_str + ml_set_wrap(t, lhs, rhs) def mk_ml(ml_src_dir, ml_output_dir): global Type2Str ml_nativef = os.path.join(ml_output_dir, 'z3native.ml') ml_native = open(ml_nativef, 'w') ml_native.write('(* Automatically generated file *)\n\n') ml_pref = open(os.path.join(ml_src_dir, 'z3native.ml.pre'), 'r') for s in ml_pref: ml_native.write(s); ml_pref.close() ml_native.write('\n') for name, result, params in _dotnet_decls: ml_native.write('external %s : ' % ml_method_name(name)) ip = inparams(params) op = outparams(params) if len(ip) == 0: ml_native.write(' unit -> ') for p in ip: ml_native.write('%s -> ' % param2ml(p)) if len(op) > 0: ml_native.write('(') first = True if result != VOID or len(op) == 0: ml_native.write('%s' % type2ml(result)) first = False for p in op: if first: first = False else: ml_native.write(' * ') ml_native.write('%s' % param2ml(p)) if len(op) > 0: ml_native.write(')') if len(ip) > 5: ml_native.write(' = "n_%s_bytecode" "n_%s"\n' % (ml_method_name(name), ml_method_name(name))) else: ml_native.write(' = "n_%s"\n' % ml_method_name(name)) ml_native.write('\n') # null pointer helpers for type_id in Type2Str: type_name = Type2Str[type_id] if ml_has_plus_type(type_name) and not type_name in ['Z3_context', 'Z3_sort', 'Z3_func_decl', 'Z3_app', 'Z3_pattern']: ml_name = type2ml(type_id) ml_native.write('external context_of_%s : %s -> context = "n_context_of_%s"\n' % (ml_name, ml_name, ml_name)) ml_native.write('external is_null_%s : %s -> bool = "n_is_null_%s"\n' % (ml_name, ml_name, ml_name)) ml_native.write('external mk_null_%s : context -> %s = "n_mk_null_%s"\n\n' % (ml_name, ml_name, ml_name)) ml_native.write('(**/**)\n') ml_native.close() if mk_util.is_verbose(): print ('Generated "%s"' % ml_nativef) mk_z3native_stubs_c(ml_src_dir, ml_output_dir) z3_long_funs = frozenset([ 'Z3_solver_check', 'Z3_solver_check_assumptions', 'Z3_simplify', 'Z3_simplify_ex', ]) z3_ml_overrides = frozenset([ 'Z3_mk_config' ]) def mk_z3native_stubs_c(ml_src_dir, ml_output_dir): # C interface ml_wrapperf = os.path.join(ml_output_dir, 'z3native_stubs.c') ml_wrapper = open(ml_wrapperf, 'w') ml_wrapper.write('// Automatically generated file\n\n') ml_pref = open(os.path.join(ml_src_dir, 'z3native_stubs.c.pre'), 'r') for s in ml_pref: ml_wrapper.write(s); ml_pref.close() for name, result, params in _dotnet_decls: if name in z3_ml_overrides: continue ip = inparams(params) op = outparams(params) ap = arrayparams(params) ret_size = len(op) if result != VOID: ret_size = ret_size + 1 # Setup frame ml_wrapper.write('CAMLprim DLL_PUBLIC value n_%s(' % ml_method_name(name)) first = True i = 0 for p in params: if is_in_param(p): if first: first = False else: ml_wrapper.write(', ') ml_wrapper.write('value a%d' % i) i = i + 1 ml_wrapper.write(') {\n') ml_wrapper.write(' CAMLparam%d(' % len(ip)) i = 0 first = True for p in params: if is_in_param(p): if first: first = False else: ml_wrapper.write(', ') ml_wrapper.write('a%d' % i) i = i + 1 ml_wrapper.write(');\n') i = 0 if len(op) + len(ap) == 0: ml_wrapper.write(' CAMLlocal1(result);\n') else: c = 0 needs_tmp_value = False for p in params: if is_out_param(p) or is_array_param(p): c = c + 1 needs_tmp_value = needs_tmp_value or param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY if needs_tmp_value: c = c + 1 if len(ap) > 0: c = c + 1 ml_wrapper.write(' CAMLlocal%s(result, z3rv_val' % (c+2)) for p in params: if is_out_param(p) or is_array_param(p): ml_wrapper.write(', _a%s_val' % i) i = i + 1 if needs_tmp_value: ml_wrapper.write(', tmp_val') if len(ap) != 0: ml_wrapper.write(', _iter'); ml_wrapper.write(');\n') if len(ap) > 0: ml_wrapper.write(' unsigned _i;\n') # determine if the function has a context as parameter. have_context = (len(params) > 0) and (param_type(params[0]) == CONTEXT) if have_context and name not in Unwrapped: ml_wrapper.write(' Z3_error_code ec;\n') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' %s z3rv_m;\n' % ts) ml_wrapper.write(' %s z3rv;\n' % pts) else: ml_wrapper.write(' %s z3rv;\n' % ts) # declare all required local variables # To comply with C89, we need to first declare the variables and initialize them # only afterwards. i = 0 for param in params: if param_type(param) == CONTEXT and i == 0: ml_wrapper.write(' Z3_context_plus ctx_p;\n') ml_wrapper.write(' Z3_context _a0;\n') else: k = param_kind(param) if k == OUT_ARRAY: ml_wrapper.write(' %s * _a%s;\n' % (type2str(param_type(param)), i)) elif k == OUT_MANAGED_ARRAY: ml_wrapper.write(' %s * _a%s;\n' % (type2str(param_type(param)), i)) elif k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' %s * _a%s;\n' % (ts, i)) elif k == IN: t = param_type(param) ml_wrapper.write(' %s _a%s;\n' % (type2str(t), i)) elif k == OUT or k == INOUT: t = param_type(param) ml_wrapper.write(' %s _a%s;\n' % (type2str(t), i)) ts = type2str(t) if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' %s _a%dp;\n' % (pts, i)) i = i + 1 # End of variable declarations in outermost block: # To comply with C89, no variable declarations may occur in the outermost block # from that point onwards (breaks builds with at least VC 2012 and prior) ml_wrapper.write('\n') # Declare locals, preprocess arrays, strings, in/out arguments i = 0 for param in params: if param_type(param) == CONTEXT and i == 0: ml_wrapper.write(' ctx_p = *(Z3_context_plus*) Data_custom_val(a' + str(i) + ');\n') ml_wrapper.write(' _a0 = ctx_p->ctx;\n') else: k = param_kind(param) if k == OUT_ARRAY: ml_wrapper.write(' _a%s = (%s*) malloc(sizeof(%s) * (_a%s));\n' % ( i, type2str(param_type(param)), type2str(param_type(param)), param_array_capacity_pos(param))) elif k == OUT_MANAGED_ARRAY: ml_wrapper.write(' _a%s = 0;\n' % i) elif k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' _a%s = (%s*) malloc(sizeof(%s) * _a%s);\n' % (i, ts, ts, param_array_capacity_pos(param))) elif k == IN: t = param_type(param) ml_wrapper.write(' _a%s = %s;\n' % (i, ml_unwrap(t, type2str(t), 'a' + str(i)))) i = i + 1 i = 0 for param in params: k = param_kind(param) if k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' _iter = a' + str(i) + ';\n') ml_wrapper.write(' for (_i = 0; _i < _a%s; _i++) {\n' % param_array_capacity_pos(param)) ml_wrapper.write(' assert(_iter != Val_emptylist);\n') ml_wrapper.write(' _a%s[_i] = %s;\n' % (i, ml_unwrap(t, ts, 'Field(_iter, 0)'))) ml_wrapper.write(' _iter = Field(_iter, 1);\n') ml_wrapper.write(' }\n') ml_wrapper.write(' assert(_iter == Val_emptylist);\n\n') i = i + 1 release_caml_gc= name in z3_long_funs if release_caml_gc: ml_wrapper.write('\n caml_release_runtime_system();\n') ml_wrapper.write('\n /* invoke Z3 function */\n ') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): ml_wrapper.write('z3rv_m = ') else: ml_wrapper.write('z3rv = ') # invoke procedure ml_wrapper.write('%s(' % name) i = 0 first = True for param in params: if first: first = False else: ml_wrapper.write(', ') k = param_kind(param) if k == OUT or k == INOUT or k == OUT_MANAGED_ARRAY: ml_wrapper.write('&_a%s' % i) else: ml_wrapper.write('_a%i' % i) i = i + 1 ml_wrapper.write(');\n') if name in NULLWrapped: ml_wrapper.write(' if (z3rv_m == NULL) {\n') ml_wrapper.write(' caml_raise_with_string(*caml_named_value("Z3EXCEPTION"), "Object allocation failed");\n') ml_wrapper.write(' }\n') if release_caml_gc: ml_wrapper.write('\n caml_acquire_runtime_system();\n') if have_context and name not in Unwrapped: ml_wrapper.write(' ec = Z3_get_error_code(ctx_p->ctx);\n') ml_wrapper.write(' if (ec != Z3_OK) {\n') ml_wrapper.write(' const char * msg = Z3_get_error_msg(ctx_p->ctx, ec);\n') ml_wrapper.write(' caml_raise_with_string(*caml_named_value("Z3EXCEPTION"), msg);\n') ml_wrapper.write(' }\n') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): pts = ml_plus_type(ts) if name in NULLWrapped: ml_wrapper.write(' z3rv = %s_mk(z3rv_m);\n' % pts) else: ml_wrapper.write(' z3rv = %s_mk(ctx_p, (%s) z3rv_m);\n' % (pts, ml_minus_type(ts))) # convert output params if len(op) > 0: # we have output parameters (i.e. call-by-reference arguments to the Z3 native # code function). Hence, the value returned by the OCaml native wrapper is a tuple # which contains the Z3 native function's return value (if it is non-void) in its # first and the output parameters in the following components. ml_wrapper.write('\n /* construct return tuple */\n') ml_wrapper.write(' result = caml_alloc(%s, 0);\n' % ret_size) i = 0 for p in params: pt = param_type(p) ts = type2str(pt) if param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY: # convert a C-array into an OCaml list and return it ml_wrapper.write('\n _a%s_val = Val_emptylist;\n' % i) ml_wrapper.write(' for (_i = _a%s; _i > 0; _i--) {\n' % param_array_capacity_pos(p)) pts = ml_plus_type(ts) pops = ml_plus_ops_type(ts) if ml_has_plus_type(ts): ml_wrapper.write(' %s _a%dp = %s_mk(ctx_p, (%s) _a%d[_i - 1]);\n' % (pts, i, pts, ml_minus_type(ts), i)) ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, 'tmp_val', '_a%dp' % i)) else: ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, 'tmp_val', '_a%d[_i - 1]' % i)) ml_wrapper.write(' _iter = caml_alloc(2,0);\n') ml_wrapper.write(' Store_field(_iter, 0, tmp_val);\n') ml_wrapper.write(' Store_field(_iter, 1, _a%s_val);\n' % i) ml_wrapper.write(' _a%s_val = _iter;\n' % i) ml_wrapper.write(' }\n\n') elif param_kind(p) == OUT_MANAGED_ARRAY: wrp = ml_set_wrap(pt, '_a%d_val' % i, '_a%d' % i) wrp = wrp.replace('*)', '**)') wrp = wrp.replace('_plus', '') ml_wrapper.write(' %s\n' % wrp) elif is_out_param(p): if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' _a%dp = %s_mk(ctx_p, (%s) _a%d);\n' % (i, pts, ml_minus_type(ts), i)) ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, '_a%d_val' % i, '_a%dp' % i)) else: ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, '_a%d_val' % i, '_a%d' % i)) i = i + 1 # return tuples i = j = 0 if result != VOID: ml_wrapper.write(' %s' % ml_alloc_and_store(result, 'z3rv_val', 'z3rv')) ml_wrapper.write(' Store_field(result, 0, z3rv_val);\n') j = j + 1 for p in params: if is_out_param(p): ml_wrapper.write(' Store_field(result, %s, _a%s_val);\n' % (j, i)) j = j + 1 i = i + 1 else: # As we have no output parameters, we simply return the result ml_wrapper.write('\n /* construct simple return value */\n') ml_wrapper.write(' %s' % ml_alloc_and_store(result, "result", "z3rv")) # local array cleanup ml_wrapper.write('\n /* cleanup and return */\n') i = 0 for p in params: k = param_kind(p) if k == OUT_ARRAY or k == IN_ARRAY or k == INOUT_ARRAY: ml_wrapper.write(' free(_a%s);\n' % i) i = i + 1 # return ml_wrapper.write(' CAMLreturn(result);\n') ml_wrapper.write('}\n\n') if len(ip) > 5: ml_wrapper.write('CAMLprim DLL_PUBLIC value n_%s_bytecode(value * argv, int argn) {\n' % ml_method_name(name)) ml_wrapper.write(' return n_%s(' % ml_method_name(name)) i = 0 while i < len(ip): if i == 0: ml_wrapper.write('argv[0]') else: ml_wrapper.write(', argv[%s]' % i) i = i + 1 ml_wrapper.write(');\n}\n') ml_wrapper.write('\n\n') ml_wrapper.write('#ifdef __cplusplus\n') ml_wrapper.write('}\n') ml_wrapper.write('#endif\n') if mk_util.is_verbose(): print ('Generated "%s"' % ml_wrapperf) # Collect API(...) commands from def def_APIs(api_files): pat1 = re.compile(" *def_API.*") pat2 = re.compile(" *extra_API.*") for api_file in api_files: api = open(api_file, 'r') for line in api: line = line.strip('\r\n\t ') try: m = pat1.match(line) if m: eval(line) m = pat2.match(line) if m: eval(line) except Exception: raise mk_exec_header.MKException("Failed to process API definition: %s" % line) def write_log_h_preamble(log_h): log_h.write('// Automatically generated file\n') log_h.write('#include\"api/z3.h\"\n') log_h.write('#ifdef __GNUC__\n') log_h.write('#define _Z3_UNUSED __attribute__((unused))\n') log_h.write('#else\n') log_h.write('#define _Z3_UNUSED\n') log_h.write('#endif\n') # log_h.write('#include<iostream>\n') log_h.write('#include<atomic>\n') log_h.write('extern std::ostream * g_z3_log;\n') log_h.write('extern std::atomic<bool> g_z3_log_enabled;\n') log_h.write('class z3_log_ctx { bool m_prev; public: z3_log_ctx() { m_prev = g_z3_log && g_z3_log_enabled.exchange(false); } ~z3_log_ctx() { if (g_z3_log) g_z3_log_enabled = m_prev; } bool enabled() const { return m_prev; } };\n') log_h.write('inline void SetR(void * obj) { *g_z3_log << "= " << obj << "\\n"; }\ninline void SetO(void * obj, unsigned pos) { *g_z3_log << "* " << obj << " " << pos << "\\n"; } \ninline void SetAO(void * obj, unsigned pos, unsigned idx) { *g_z3_log << "@ " << obj << " " << pos << " " << idx << "\\n"; }\n') log_h.write('#define RETURN_Z3(Z3RES) if (_LOG_CTX.enabled()) { SetR(Z3RES); } return Z3RES\n') log_h.write('void _Z3_append_log(char const * msg);\n') def write_log_c_preamble(log_c): log_c.write('// Automatically generated file\n') log_c.write('#include<iostream>\n') log_c.write('#include\"api/z3.h\"\n') log_c.write('#include\"api/api_log_macros.h\"\n') log_c.write('#include\"api/z3_logger.h\"\n') def write_exe_c_preamble(exe_c): exe_c.write('// Automatically generated file\n') exe_c.write('#include\"api/z3.h\"\n') exe_c.write('#include\"api/z3_replayer.h\"\n') # exe_c.write('void Z3_replayer_error_handler(Z3_context ctx, Z3_error_code c) { printf("[REPLAYER ERROR HANDLER]: %s\\n", Z3_get_error_msg(ctx, c)); }\n') def write_core_py_post(core_py): core_py.write(""" # Clean up del _lib del _default_dirs del _all_dirs del _ext """) def write_core_py_preamble(core_py): core_py.write( """ # Automatically generated file import sys, os import ctypes import pkg_resources from .z3types import * from .z3consts import * _ext = 'dll' if sys.platform in ('win32', 'cygwin') else 'dylib' if sys.platform == 'darwin' else 'so' _lib = None _default_dirs = ['.', os.path.dirname(os.path.abspath(__file__)), pkg_resources.resource_filename('z3', 'lib'), os.path.join(sys.prefix, 'lib'), None] _all_dirs = [] # search the default dirs first _all_dirs.extend(_default_dirs) if sys.version < '3': import __builtin__ if hasattr(__builtin__, "Z3_LIB_DIRS"): _all_dirs = __builtin__.Z3_LIB_DIRS else: import builtins if hasattr(builtins, "Z3_LIB_DIRS"): _all_dirs = builtins.Z3_LIB_DIRS for v in ('Z3_LIBRARY_PATH', 'PATH', 'PYTHONPATH'): if v in os.environ: lp = os.environ[v]; lds = lp.split(';') if sys.platform in ('win32') else lp.split(':') _all_dirs.extend(lds) _failures = [] for d in _all_dirs: try: d = os.path.realpath(d) if os.path.isdir(d): d = os.path.join(d, 'libz3.%s' % _ext) if os.path.isfile(d): _lib = ctypes.CDLL(d) break except Exception as e: _failures += [e] pass if _lib is None: # If all else failed, ask the system to find it. try: _lib = ctypes.CDLL('libz3.%s' % _ext) except Exception as e: _failures += [e] pass if _lib is None: print("Could not find libz3.%s; consider adding the directory containing it to" % _ext) print(" - your system's PATH environment variable,") print(" - the Z3_LIBRARY_PATH environment variable, or ") print(" - to the custom Z3_LIBRARY_DIRS Python-builtin before importing the z3 module, e.g. via") if sys.version < '3': print(" import __builtin__") print(" __builtin__.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) else: print(" import builtins") print(" builtins.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) raise Z3Exception("libz3.%s not found." % _ext) def _str_to_bytes(s): if isinstance(s, str): try: return s.encode('latin-1') except: # kick the bucket down the road. :-J return s else: return s if sys.version < '3': def _to_pystr(s): return s else: def _to_pystr(s): if s != None: enc = sys.stdout.encoding if enc != None: return s.decode(enc) else: return s.decode('latin-1') else: return "" _error_handler_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint) _lib.Z3_set_error_handler.restype = None _lib.Z3_set_error_handler.argtypes = [ContextObj, _error_handler_type] """ ) log_h = None log_c = None exe_c = None core_py = None # FIXME: This can only be called once from this module # due to its use of global state! def generate_files(api_files, api_output_dir=None, z3py_output_dir=None, dotnet_output_dir=None, java_output_dir=None, java_package_name=None, js_output_dir=None, ml_output_dir=None, ml_src_dir=None): """ Scan the api files in ``api_files`` and emit the relevant API files into the output directories specified. If an output directory is set to ``None`` then the files for that language binding or module are not emitted. The reason for this function interface is: * The CMake build system needs to control where files are emitted. * The CMake build system needs to be able to choose which API files are emitted. * This function should be as decoupled from the Python build system as much as possible but it must be possible for the Python build system code to use this function. Therefore we: * Do not use the ``mk_util.is_*_enabled()`` functions to determine if certain files should be or should not be emitted. * Do not use the components declared in the Python build system to determine the output directory paths. """ # FIXME: These should not be global global log_h, log_c, exe_c, core_py assert isinstance(api_files, list) # Hack: Avoid emitting files when we don't want them # by writing to temporary files that get deleted when # closed. This allows us to work around the fact that # existing code is designed to always emit these files. def mk_file_or_temp(output_dir, file_name, mode='w'): if output_dir != None: assert os.path.exists(output_dir) and os.path.isdir(output_dir) return open(os.path.join(output_dir, file_name), mode) else: # Return a file that we can write to without caring print("Faking emission of '{}'".format(file_name)) import tempfile return tempfile.TemporaryFile(mode=mode) with mk_file_or_temp(api_output_dir, 'api_log_macros.h') as log_h: with mk_file_or_temp(api_output_dir, 'api_log_macros.cpp') as log_c: with mk_file_or_temp(api_output_dir, 'api_commands.cpp') as exe_c: with mk_file_or_temp(z3py_output_dir, os.path.join('z3', 'z3core.py')) as core_py: # Write preambles write_log_h_preamble(log_h) write_log_c_preamble(log_c) write_exe_c_preamble(exe_c) write_core_py_preamble(core_py) # FIXME: these functions are awful def_Types(api_files) def_APIs(api_files) mk_bindings(exe_c) mk_py_wrappers() write_core_py_post(core_py) if mk_util.is_verbose(): print("Generated '{}'".format(log_h.name)) print("Generated '{}'".format(log_c.name)) print("Generated '{}'".format(exe_c.name)) print("Generated '{}'".format(core_py.name)) if dotnet_output_dir: with open(os.path.join(dotnet_output_dir, 'Native.cs'), 'w') as dotnet_file: mk_dotnet(dotnet_file) mk_dotnet_wrappers(dotnet_file) if mk_util.is_verbose(): print("Generated '{}'".format(dotnet_file.name)) if java_output_dir: mk_java(java_output_dir, java_package_name) if ml_output_dir: assert not ml_src_dir is None mk_ml(ml_src_dir, ml_output_dir) if js_output_dir: mk_js(js_output_dir) def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("api_files", nargs="+", help="API header files to generate files from") parser.add_argument("--api_output_dir", default=None, help="Directory to emit files for api module. If not specified no files are emitted.") parser.add_argument("--z3py-output-dir", dest="z3py_output_dir", default=None, help="Directory to emit z3py files. If not specified no files are emitted.") parser.add_argument("--dotnet-output-dir", dest="dotnet_output_dir", default=None, help="Directory to emit dotnet files. If not specified no files are emitted.") parser.add_argument("--java-output-dir", dest="java_output_dir", default=None, help="Directory to emit Java files. If not specified no files are emitted.") parser.add_argument("--java-package-name", dest="java_package_name", default=None, help="Name to give the Java package (e.g. ``com.microsoft.z3``).") parser.add_argument("--ml-src-dir", dest="ml_src_dir", default=None, help="Directory containing OCaml source files. If not specified no files are emitted") parser.add_argument("--ml-output-dir", dest="ml_output_dir", default=None, help="Directory to emit OCaml files. If not specified no files are emitted.") parser.add_argument("--js_output_dir", dest="js_output_dir", default=None, help="Directory to emit js bindings. If not specified no files are emitted.") pargs = parser.parse_args(args) if pargs.java_output_dir: if pargs.java_package_name == None: logging.error('--java-package-name must be specified') return 1 if pargs.ml_output_dir: if pargs.ml_src_dir is None: logging.error('--ml-src-dir must be specified') return 1 for api_file in pargs.api_files: if not os.path.exists(api_file): logging.error('"{}" does not exist'.format(api_file)) return 1 generate_files(api_files=pargs.api_files, api_output_dir=pargs.api_output_dir, z3py_output_dir=pargs.z3py_output_dir, dotnet_output_dir=pargs.dotnet_output_dir, java_output_dir=pargs.java_output_dir, java_package_name=pargs.java_package_name, js_output_dir=pargs.js_output_dir, ml_output_dir=pargs.ml_output_dir, ml_src_dir=pargs.ml_src_dir) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/update_api.py
update_api.py
import os import glob import re import getopt import sys import shutil import subprocess import zipfile from mk_exception import * from mk_project import * import mk_util BUILD_DIR='build-dist' VERBOSE=True DIST_DIR='dist' FORCE_MK=False DOTNET_CORE_ENABLED=True DOTNET_KEY_FILE=None JAVA_ENABLED=True GIT_HASH=False PYTHON_ENABLED=True MAKEJOBS=getenv("MAKEJOBS", '8') def set_verbose(flag): global VERBOSE VERBOSE = flag def is_verbose(): return VERBOSE def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(path): global BUILD_DIR BUILD_DIR = mk_util.norm_path(path) mk_dir(BUILD_DIR) def display_help(): print("mk_unix_dist.py: Z3 Linux/OSX/BSD distribution generator\n") print("This script generates the zip files containing executables, shared objects, header files for Linux/OSX/BSD.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") print(" -b <sudir>, --build=<subdir> subdirectory where x86 and x64 Z3 versions will be built (default: build-dist).") print(" -f, --force force script to regenerate Makefiles.") print(" --nodotnet do not include .NET bindings in the binary distribution files.") print(" --dotnet-key=<file> sign the .NET assembly with the private key in <file>.") print(" --nojava do not include Java bindings in the binary distribution files.") print(" --nopython do not include Python bindings in the binary distribution files.") print(" --githash include git hash in the Zip file.") exit(0) # Parse configuration option for mk_make script def parse_options(): global FORCE_MK, JAVA_ENABLED, GIT_HASH, DOTNET_CORE_ENABLED, DOTNET_KEY_FILE path = BUILD_DIR options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:hsf', ['build=', 'help', 'silent', 'force', 'nojava', 'nodotnet', 'dotnet-key=', 'githash', 'nopython' ]) for opt, arg in options: if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') path = arg elif opt in ('-s', '--silent'): set_verbose(False) elif opt in ('-h', '--help'): display_help() elif opt in ('-f', '--force'): FORCE_MK = True elif opt == '--nodotnet': DOTNET_CORE_ENABLED = False elif opt == '--nopython': PYTHON_ENABLED = False elif opt == '--dotnet-key': DOTNET_KEY_FILE = arg elif opt == '--nojava': JAVA_ENABLED = False elif opt == '--githash': GIT_HASH = True else: raise MKException("Invalid command line option '%s'" % opt) set_build_dir(path) # Check whether build directory already exists or not def check_build_dir(path): return os.path.exists(path) and os.path.exists(os.path.join(path, 'Makefile')) # Create a build directory using mk_make.py def mk_build_dir(path): if not check_build_dir(path) or FORCE_MK: opts = [sys.executable, os.path.join('scripts', 'mk_make.py'), "-b", path, "--staticlib"] if DOTNET_CORE_ENABLED: opts.append('--dotnet') if not DOTNET_KEY_FILE is None: opts.append('--dotnet-key=' + DOTNET_KEY_FILE) if JAVA_ENABLED: opts.append('--java') if GIT_HASH: opts.append('--githash=%s' % mk_util.git_hash()) opts.append('--git-describe') if PYTHON_ENABLED: opts.append('--python') if subprocess.call(opts) != 0: raise MKException("Failed to generate build directory at '%s'" % path) # Create build directories def mk_build_dirs(): mk_build_dir(BUILD_DIR) class cd: def __init__(self, newPath): self.newPath = newPath def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) def mk_z3(): with cd(BUILD_DIR): try: return subprocess.call(['make', '-j', MAKEJOBS]) except: return 1 def get_os_name(): import platform basic = os.uname()[0].lower() if basic == 'linux': dist = platform.linux_distribution() if len(dist) == 3 and len(dist[0]) > 0 and len(dist[1]) > 0: return '%s-%s' % (dist[0].lower(), dist[1].lower()) else: return basic elif basic == 'darwin': ver = platform.mac_ver() if len(ver) == 3 and len(ver[0]) > 0: return 'osx-%s' % ver[0] else: return 'osx' elif basic == 'freebsd': ver = platform.version() idx1 = ver.find(' ') idx2 = ver.find('-') if idx1 < 0 or idx2 < 0 or idx1 >= idx2: return basic else: return 'freebsd-%s' % ver[(idx1+1):idx2] else: return basic def get_z3_name(): major, minor, build, revision = get_version() if sys.maxsize >= 2**32: platform = "x64" else: platform = "x86" osname = get_os_name() if GIT_HASH: return 'z3-%s.%s.%s.%s-%s-%s' % (major, minor, build, mk_util.git_hash(), platform, osname) else: return 'z3-%s.%s.%s-%s-%s' % (major, minor, build, platform, osname) def mk_dist_dir(): build_path = BUILD_DIR dist_path = os.path.join(DIST_DIR, get_z3_name()) mk_dir(dist_path) mk_util.DOTNET_CORE_ENABLED = DOTNET_CORE_ENABLED mk_util.DOTNET_ENABLED = False mk_util.DOTNET_KEY_FILE = DOTNET_KEY_FILE mk_util.JAVA_ENABLED = JAVA_ENABLED mk_util.PYTHON_ENABLED = PYTHON_ENABLED mk_unix_dist(build_path, dist_path) if is_verbose(): print("Generated distribution folder at '%s'" % dist_path) def get_dist_path(): return get_z3_name() def mk_zip(): dist_path = get_dist_path() old = os.getcwd() try: os.chdir(DIST_DIR) zfname = '%s.zip' % dist_path zipout = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dist_path): for f in files: zipout.write(os.path.join(root, f)) if is_verbose(): print("Generated '%s'" % zfname) except: pass os.chdir(old) def cp_license(): shutil.copy("LICENSE.txt", os.path.join(DIST_DIR, get_dist_path())) # Entry point def main(): parse_options() mk_build_dirs() mk_z3() init_project_def() mk_dist_dir() cp_license() mk_zip() main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_unix_dist.py
mk_unix_dist.py
# 1. copy over dlls # 2. copy over libz3.dll for the different architectures # 3. copy over Microsoft.Z3.dll from suitable distribution # 4. copy nuspec file from packages # 5. call nuget pack # 6. sign package import json import os import zipfile import sys import os.path import shutil import subprocess def mk_dir(d): if not os.path.exists(d): os.makedirs(d) os_info = {"z64-ubuntu-14" : ('so', 'ubuntu.14.04-x64'), 'ubuntu-16' : ('so', 'ubuntu-x64'), 'x64-win' : ('dll', 'win-x64'), # Skip x86 as I can't get dotnet build to produce AnyCPU TargetPlatform # 'x86-win' : ('dll', 'win-x86'), 'osx' : ('dylib', 'macos'), 'debian' : ('so', 'debian.8-x64') } def classify_package(f): for os_name in os_info: if os_name in f: ext, dst = os_info[os_name] return os_name, f[:-4], ext, dst return None def unpack(packages): # unzip files in packages # out # +- runtimes # +- win-x64 # +- win-x86 # +- ubuntu.16.04-x64 # +- ubuntu.14.04-x64 # +- debian.8-x64 # +- macos # + for f in os.listdir(packages): print(f) if f.endswith(".zip") and classify_package(f): os_name, package_dir, ext, dst = classify_package(f) path = os.path.abspath(os.path.join(packages, f)) zip_ref = zipfile.ZipFile(path, 'r') zip_ref.extract("%s/bin/libz3.%s" % (package_dir, ext), "tmp") mk_dir("out/runtimes/%s/native" % dst) shutil.move("tmp/%s/bin/libz3.%s" % (package_dir, ext), "out/runtimes/%s/native/." % dst) if "x64-win" in f: mk_dir("out/lib/netstandard1.4/") for b in ["Microsoft.Z3.dll"]: zip_ref.extract("%s/bin/%s" % (package_dir, b), "tmp") shutil.move("tmp/%s/bin/%s" % (package_dir, b), "out/lib/netstandard1.4/%s" % b) def mk_targets(source_root): mk_dir("out/build") shutil.copy("{}/src/api/dotnet/Microsoft.Z3.targets.in".format(source_root), "out/build/Microsoft.Z3.x64.targets") def mk_icon(source_root): mk_dir("out/content") shutil.copy("{}/resources/icon.jpg".format(source_root), "out/content/icon.jpg") def mk_license(source_root): mk_dir("out/content") shutil.copy("{}/LICENSE.txt".format(source_root), "out/content/LICENSE.txt") def create_nuget_spec(version, repo, branch, commit): contents = """<?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata> <id>Microsoft.Z3.x64</id> <version>{0}</version> <authors>Microsoft</authors> <description> Z3 is a satisfiability modulo theories solver from Microsoft Research. Linux Dependencies: libgomp.so.1 installed </description> <copyright>&#169; Microsoft Corporation. All rights reserved.</copyright> <tags>smt constraint solver theorem prover</tags> <icon>content/icon.jpg</icon> <projectUrl>https://github.com/Z3Prover/z3</projectUrl> <license type="file">content/LICENSE.txt</license> <repository type="git" url="{1}" branch="{2}" commit="{3}" /> <requireLicenseAcceptance>true</requireLicenseAcceptance> <language>en</language> <dependencies> <group targetFramework=".NETStandard1.4" /> </dependencies> </metadata> </package>""".format(version, repo, branch, commit) print(contents) with open("out/Microsoft.Z3.x64.nuspec", 'w') as f: f.write(contents) def main(): packages = sys.argv[1] version = sys.argv[2] repo = sys.argv[3] branch = sys.argv[4] commit = sys.argv[5] source_root = sys.argv[6] print(packages) mk_dir(packages) unpack(packages) mk_targets(source_root) mk_icon(source_root) mk_license(source_root) create_nuget_spec(version, repo, branch, commit) main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/scripts/mk_nuget_task.py
mk_nuget_task.py
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction def _to_rcfnum(num, ctx=None): if isinstance(num, RCFNum): return num else: return RCFNum(num, ctx) def Pi(ctx=None): ctx = z3._get_ctx(ctx) return RCFNum(Z3_rcf_mk_pi(ctx.ref()), ctx) def E(ctx=None): ctx = z3._get_ctx(ctx) return RCFNum(Z3_rcf_mk_e(ctx.ref()), ctx) def MkInfinitesimal(name="eps", ctx=None): # Todo: remove parameter name. # For now, we keep it for backward compatibility. ctx = z3._get_ctx(ctx) return RCFNum(Z3_rcf_mk_infinitesimal(ctx.ref()), ctx) def MkRoots(p, ctx=None): ctx = z3._get_ctx(ctx) num = len(p) _tmp = [] _as = (RCFNumObj * num)() _rs = (RCFNumObj * num)() for i in range(num): _a = _to_rcfnum(p[i], ctx) _tmp.append(_a) # prevent GC _as[i] = _a.num nr = Z3_rcf_mk_roots(ctx.ref(), num, _as, _rs) r = [] for i in range(nr): r.append(RCFNum(_rs[i], ctx)) return r class RCFNum: def __init__(self, num, ctx=None): # TODO: add support for converting AST numeral values into RCFNum if isinstance(num, RCFNumObj): self.num = num self.ctx = z3._get_ctx(ctx) else: self.ctx = z3._get_ctx(ctx) self.num = Z3_rcf_mk_rational(self.ctx_ref(), str(num)) def __del__(self): Z3_rcf_del(self.ctx_ref(), self.num) def ctx_ref(self): return self.ctx.ref() def __repr__(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, False, in_html_mode()) def compact_str(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, True, in_html_mode()) def __add__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), self.num, v.num), self.ctx) def __radd__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), v.num, self.num), self.ctx) def __mul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), self.num, v.num), self.ctx) def __rmul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), v.num, self.num), self.ctx) def __sub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), self.num, v.num), self.ctx) def __rsub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), v.num, self.num), self.ctx) def __div__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), self.num, v.num), self.ctx) def __rdiv__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), v.num, self.num), self.ctx) def __neg__(self): return self.__rsub__(0) def power(self, k): return RCFNum(Z3_rcf_power(self.ctx_ref(), self.num, k), self.ctx) def __pow__(self, k): return self.power(k) def decimal(self, prec=5): return Z3_rcf_num_to_decimal_string(self.ctx_ref(), self.num, prec) def __lt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), self.num, v.num) def __rlt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), v.num, self.num) def __gt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), self.num, v.num) def __rgt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), v.num, self.num) def __le__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), self.num, v.num) def __rle__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), v.num, self.num) def __ge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), self.num, v.num) def __rge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), v.num, self.num) def __eq__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_eq(self.ctx_ref(), self.num, v.num) def __ne__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_neq(self.ctx_ref(), self.num, v.num) def split(self): n = (RCFNumObj * 1)() d = (RCFNumObj * 1)() Z3_rcf_get_numerator_denominator(self.ctx_ref(), self.num, n, d) return (RCFNum(n[0], self.ctx), RCFNum(d[0], self.ctx))
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3rcf.py
z3rcf.py
# enum Z3_lbool Z3_L_FALSE = -1 Z3_L_UNDEF = 0 Z3_L_TRUE = 1 # enum Z3_symbol_kind Z3_INT_SYMBOL = 0 Z3_STRING_SYMBOL = 1 # enum Z3_parameter_kind Z3_PARAMETER_INT = 0 Z3_PARAMETER_DOUBLE = 1 Z3_PARAMETER_RATIONAL = 2 Z3_PARAMETER_SYMBOL = 3 Z3_PARAMETER_SORT = 4 Z3_PARAMETER_AST = 5 Z3_PARAMETER_FUNC_DECL = 6 # enum Z3_sort_kind Z3_UNINTERPRETED_SORT = 0 Z3_BOOL_SORT = 1 Z3_INT_SORT = 2 Z3_REAL_SORT = 3 Z3_BV_SORT = 4 Z3_ARRAY_SORT = 5 Z3_DATATYPE_SORT = 6 Z3_RELATION_SORT = 7 Z3_FINITE_DOMAIN_SORT = 8 Z3_FLOATING_POINT_SORT = 9 Z3_ROUNDING_MODE_SORT = 10 Z3_SEQ_SORT = 11 Z3_RE_SORT = 12 Z3_UNKNOWN_SORT = 1000 # enum Z3_ast_kind Z3_NUMERAL_AST = 0 Z3_APP_AST = 1 Z3_VAR_AST = 2 Z3_QUANTIFIER_AST = 3 Z3_SORT_AST = 4 Z3_FUNC_DECL_AST = 5 Z3_UNKNOWN_AST = 1000 # enum Z3_decl_kind Z3_OP_TRUE = 256 Z3_OP_FALSE = 257 Z3_OP_EQ = 258 Z3_OP_DISTINCT = 259 Z3_OP_ITE = 260 Z3_OP_AND = 261 Z3_OP_OR = 262 Z3_OP_IFF = 263 Z3_OP_XOR = 264 Z3_OP_NOT = 265 Z3_OP_IMPLIES = 266 Z3_OP_OEQ = 267 Z3_OP_ANUM = 512 Z3_OP_AGNUM = 513 Z3_OP_LE = 514 Z3_OP_GE = 515 Z3_OP_LT = 516 Z3_OP_GT = 517 Z3_OP_ADD = 518 Z3_OP_SUB = 519 Z3_OP_UMINUS = 520 Z3_OP_MUL = 521 Z3_OP_DIV = 522 Z3_OP_IDIV = 523 Z3_OP_REM = 524 Z3_OP_MOD = 525 Z3_OP_TO_REAL = 526 Z3_OP_TO_INT = 527 Z3_OP_IS_INT = 528 Z3_OP_POWER = 529 Z3_OP_STORE = 768 Z3_OP_SELECT = 769 Z3_OP_CONST_ARRAY = 770 Z3_OP_ARRAY_MAP = 771 Z3_OP_ARRAY_DEFAULT = 772 Z3_OP_SET_UNION = 773 Z3_OP_SET_INTERSECT = 774 Z3_OP_SET_DIFFERENCE = 775 Z3_OP_SET_COMPLEMENT = 776 Z3_OP_SET_SUBSET = 777 Z3_OP_AS_ARRAY = 778 Z3_OP_ARRAY_EXT = 779 Z3_OP_BNUM = 1024 Z3_OP_BIT1 = 1025 Z3_OP_BIT0 = 1026 Z3_OP_BNEG = 1027 Z3_OP_BADD = 1028 Z3_OP_BSUB = 1029 Z3_OP_BMUL = 1030 Z3_OP_BSDIV = 1031 Z3_OP_BUDIV = 1032 Z3_OP_BSREM = 1033 Z3_OP_BUREM = 1034 Z3_OP_BSMOD = 1035 Z3_OP_BSDIV0 = 1036 Z3_OP_BUDIV0 = 1037 Z3_OP_BSREM0 = 1038 Z3_OP_BUREM0 = 1039 Z3_OP_BSMOD0 = 1040 Z3_OP_ULEQ = 1041 Z3_OP_SLEQ = 1042 Z3_OP_UGEQ = 1043 Z3_OP_SGEQ = 1044 Z3_OP_ULT = 1045 Z3_OP_SLT = 1046 Z3_OP_UGT = 1047 Z3_OP_SGT = 1048 Z3_OP_BAND = 1049 Z3_OP_BOR = 1050 Z3_OP_BNOT = 1051 Z3_OP_BXOR = 1052 Z3_OP_BNAND = 1053 Z3_OP_BNOR = 1054 Z3_OP_BXNOR = 1055 Z3_OP_CONCAT = 1056 Z3_OP_SIGN_EXT = 1057 Z3_OP_ZERO_EXT = 1058 Z3_OP_EXTRACT = 1059 Z3_OP_REPEAT = 1060 Z3_OP_BREDOR = 1061 Z3_OP_BREDAND = 1062 Z3_OP_BCOMP = 1063 Z3_OP_BSHL = 1064 Z3_OP_BLSHR = 1065 Z3_OP_BASHR = 1066 Z3_OP_ROTATE_LEFT = 1067 Z3_OP_ROTATE_RIGHT = 1068 Z3_OP_EXT_ROTATE_LEFT = 1069 Z3_OP_EXT_ROTATE_RIGHT = 1070 Z3_OP_BIT2BOOL = 1071 Z3_OP_INT2BV = 1072 Z3_OP_BV2INT = 1073 Z3_OP_CARRY = 1074 Z3_OP_XOR3 = 1075 Z3_OP_BSMUL_NO_OVFL = 1076 Z3_OP_BUMUL_NO_OVFL = 1077 Z3_OP_BSMUL_NO_UDFL = 1078 Z3_OP_BSDIV_I = 1079 Z3_OP_BUDIV_I = 1080 Z3_OP_BSREM_I = 1081 Z3_OP_BUREM_I = 1082 Z3_OP_BSMOD_I = 1083 Z3_OP_PR_UNDEF = 1280 Z3_OP_PR_TRUE = 1281 Z3_OP_PR_ASSERTED = 1282 Z3_OP_PR_GOAL = 1283 Z3_OP_PR_MODUS_PONENS = 1284 Z3_OP_PR_REFLEXIVITY = 1285 Z3_OP_PR_SYMMETRY = 1286 Z3_OP_PR_TRANSITIVITY = 1287 Z3_OP_PR_TRANSITIVITY_STAR = 1288 Z3_OP_PR_MONOTONICITY = 1289 Z3_OP_PR_QUANT_INTRO = 1290 Z3_OP_PR_BIND = 1291 Z3_OP_PR_DISTRIBUTIVITY = 1292 Z3_OP_PR_AND_ELIM = 1293 Z3_OP_PR_NOT_OR_ELIM = 1294 Z3_OP_PR_REWRITE = 1295 Z3_OP_PR_REWRITE_STAR = 1296 Z3_OP_PR_PULL_QUANT = 1297 Z3_OP_PR_PUSH_QUANT = 1298 Z3_OP_PR_ELIM_UNUSED_VARS = 1299 Z3_OP_PR_DER = 1300 Z3_OP_PR_QUANT_INST = 1301 Z3_OP_PR_HYPOTHESIS = 1302 Z3_OP_PR_LEMMA = 1303 Z3_OP_PR_UNIT_RESOLUTION = 1304 Z3_OP_PR_IFF_TRUE = 1305 Z3_OP_PR_IFF_FALSE = 1306 Z3_OP_PR_COMMUTATIVITY = 1307 Z3_OP_PR_DEF_AXIOM = 1308 Z3_OP_PR_DEF_INTRO = 1309 Z3_OP_PR_APPLY_DEF = 1310 Z3_OP_PR_IFF_OEQ = 1311 Z3_OP_PR_NNF_POS = 1312 Z3_OP_PR_NNF_NEG = 1313 Z3_OP_PR_SKOLEMIZE = 1314 Z3_OP_PR_MODUS_PONENS_OEQ = 1315 Z3_OP_PR_TH_LEMMA = 1316 Z3_OP_PR_HYPER_RESOLVE = 1317 Z3_OP_RA_STORE = 1536 Z3_OP_RA_EMPTY = 1537 Z3_OP_RA_IS_EMPTY = 1538 Z3_OP_RA_JOIN = 1539 Z3_OP_RA_UNION = 1540 Z3_OP_RA_WIDEN = 1541 Z3_OP_RA_PROJECT = 1542 Z3_OP_RA_FILTER = 1543 Z3_OP_RA_NEGATION_FILTER = 1544 Z3_OP_RA_RENAME = 1545 Z3_OP_RA_COMPLEMENT = 1546 Z3_OP_RA_SELECT = 1547 Z3_OP_RA_CLONE = 1548 Z3_OP_FD_CONSTANT = 1549 Z3_OP_FD_LT = 1550 Z3_OP_SEQ_UNIT = 1551 Z3_OP_SEQ_EMPTY = 1552 Z3_OP_SEQ_CONCAT = 1553 Z3_OP_SEQ_PREFIX = 1554 Z3_OP_SEQ_SUFFIX = 1555 Z3_OP_SEQ_CONTAINS = 1556 Z3_OP_SEQ_EXTRACT = 1557 Z3_OP_SEQ_REPLACE = 1558 Z3_OP_SEQ_AT = 1559 Z3_OP_SEQ_LENGTH = 1560 Z3_OP_SEQ_INDEX = 1561 Z3_OP_SEQ_TO_RE = 1562 Z3_OP_SEQ_IN_RE = 1563 Z3_OP_STR_TO_INT = 1564 Z3_OP_INT_TO_STR = 1565 Z3_OP_RE_PLUS = 1566 Z3_OP_RE_STAR = 1567 Z3_OP_RE_OPTION = 1568 Z3_OP_RE_CONCAT = 1569 Z3_OP_RE_UNION = 1570 Z3_OP_RE_RANGE = 1571 Z3_OP_RE_LOOP = 1572 Z3_OP_RE_INTERSECT = 1573 Z3_OP_RE_EMPTY_SET = 1574 Z3_OP_RE_FULL_SET = 1575 Z3_OP_RE_COMPLEMENT = 1576 Z3_OP_LABEL = 1792 Z3_OP_LABEL_LIT = 1793 Z3_OP_DT_CONSTRUCTOR = 2048 Z3_OP_DT_RECOGNISER = 2049 Z3_OP_DT_IS = 2050 Z3_OP_DT_ACCESSOR = 2051 Z3_OP_DT_UPDATE_FIELD = 2052 Z3_OP_PB_AT_MOST = 2304 Z3_OP_PB_AT_LEAST = 2305 Z3_OP_PB_LE = 2306 Z3_OP_PB_GE = 2307 Z3_OP_PB_EQ = 2308 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN = 2309 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY = 2310 Z3_OP_FPA_RM_TOWARD_POSITIVE = 2311 Z3_OP_FPA_RM_TOWARD_NEGATIVE = 2312 Z3_OP_FPA_RM_TOWARD_ZERO = 2313 Z3_OP_FPA_NUM = 2314 Z3_OP_FPA_PLUS_INF = 2315 Z3_OP_FPA_MINUS_INF = 2316 Z3_OP_FPA_NAN = 2317 Z3_OP_FPA_PLUS_ZERO = 2318 Z3_OP_FPA_MINUS_ZERO = 2319 Z3_OP_FPA_ADD = 2320 Z3_OP_FPA_SUB = 2321 Z3_OP_FPA_NEG = 2322 Z3_OP_FPA_MUL = 2323 Z3_OP_FPA_DIV = 2324 Z3_OP_FPA_REM = 2325 Z3_OP_FPA_ABS = 2326 Z3_OP_FPA_MIN = 2327 Z3_OP_FPA_MAX = 2328 Z3_OP_FPA_FMA = 2329 Z3_OP_FPA_SQRT = 2330 Z3_OP_FPA_ROUND_TO_INTEGRAL = 2331 Z3_OP_FPA_EQ = 2332 Z3_OP_FPA_LT = 2333 Z3_OP_FPA_GT = 2334 Z3_OP_FPA_LE = 2335 Z3_OP_FPA_GE = 2336 Z3_OP_FPA_IS_NAN = 2337 Z3_OP_FPA_IS_INF = 2338 Z3_OP_FPA_IS_ZERO = 2339 Z3_OP_FPA_IS_NORMAL = 2340 Z3_OP_FPA_IS_SUBNORMAL = 2341 Z3_OP_FPA_IS_NEGATIVE = 2342 Z3_OP_FPA_IS_POSITIVE = 2343 Z3_OP_FPA_FP = 2344 Z3_OP_FPA_TO_FP = 2345 Z3_OP_FPA_TO_FP_UNSIGNED = 2346 Z3_OP_FPA_TO_UBV = 2347 Z3_OP_FPA_TO_SBV = 2348 Z3_OP_FPA_TO_REAL = 2349 Z3_OP_FPA_TO_IEEE_BV = 2350 Z3_OP_FPA_BVWRAP = 2351 Z3_OP_FPA_BV2RM = 2352 Z3_OP_INTERNAL = 2353 Z3_OP_UNINTERPRETED = 2354 # enum Z3_param_kind Z3_PK_UINT = 0 Z3_PK_BOOL = 1 Z3_PK_DOUBLE = 2 Z3_PK_SYMBOL = 3 Z3_PK_STRING = 4 Z3_PK_OTHER = 5 Z3_PK_INVALID = 6 # enum Z3_ast_print_mode Z3_PRINT_SMTLIB_FULL = 0 Z3_PRINT_LOW_LEVEL = 1 Z3_PRINT_SMTLIB2_COMPLIANT = 2 # enum Z3_error_code Z3_OK = 0 Z3_SORT_ERROR = 1 Z3_IOB = 2 Z3_INVALID_ARG = 3 Z3_PARSER_ERROR = 4 Z3_NO_PARSER = 5 Z3_INVALID_PATTERN = 6 Z3_MEMOUT_FAIL = 7 Z3_FILE_ACCESS_ERROR = 8 Z3_INTERNAL_FATAL = 9 Z3_INVALID_USAGE = 10 Z3_DEC_REF_ERROR = 11 Z3_EXCEPTION = 12 # enum Z3_goal_prec Z3_GOAL_PRECISE = 0 Z3_GOAL_UNDER = 1 Z3_GOAL_OVER = 2 Z3_GOAL_UNDER_OVER = 3
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3consts.py
z3consts.py
import sys, os import ctypes import pkg_resources from .z3types import * from .z3consts import * _ext = 'dll' if sys.platform in ('win32', 'cygwin') else 'dylib' if sys.platform == 'darwin' else 'so' _lib = None _default_dirs = ['.', os.path.dirname(os.path.abspath(__file__)), pkg_resources.resource_filename('z3', 'lib'), os.path.join(sys.prefix, 'lib'), None] _all_dirs = [] if sys.version < '3': import __builtin__ if hasattr(__builtin__, "Z3_LIB_DIRS"): _all_dirs = __builtin__.Z3_LIB_DIRS else: import builtins if hasattr(builtins, "Z3_LIB_DIRS"): _all_dirs = builtins.Z3_LIB_DIRS for v in ('Z3_LIBRARY_PATH', 'PATH', 'PYTHONPATH'): if v in os.environ: lp = os.environ[v]; lds = lp.split(';') if sys.platform in ('win32') else lp.split(':') _all_dirs.extend(lds) _all_dirs.extend(_default_dirs) _failures = [] for d in _all_dirs: try: d = os.path.realpath(d) if os.path.isdir(d): d = os.path.join(d, 'libz3.%s' % _ext) if os.path.isfile(d): _lib = ctypes.CDLL(d) break except Exception as e: _failures += [e] pass if _lib is None: # If all else failed, ask the system to find it. try: _lib = ctypes.CDLL('libz3.%s' % _ext) except Exception as e: _failures += [e] pass if _lib is None: print("Could not find libz3.%s; consider adding the directory containing it to" % _ext) print(" - your system's PATH environment variable,") print(" - the Z3_LIBRARY_PATH environment variable, or ") print(" - to the custom Z3_LIBRARY_DIRS Python-builtin before importing the z3 module, e.g. via") if sys.version < '3': print(" import __builtin__") print(" __builtin__.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) else: print(" import builtins") print(" builtins.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) raise Z3Exception("libz3.%s not found." % _ext) def _to_ascii(s): if isinstance(s, str): try: return s.encode('ascii') except: # kick the bucket down the road. :-J return s else: return s if sys.version < '3': def _to_pystr(s): return s else: def _to_pystr(s): if s != None: enc = sys.stdout.encoding if enc != None: return s.decode(enc) else: return s.decode('ascii') else: return "" _error_handler_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint) _lib.Z3_set_error_handler.restype = None _lib.Z3_set_error_handler.argtypes = [ContextObj, _error_handler_type] _lib.Z3_global_param_set.argtypes = [ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_global_param_reset_all.argtypes = [] _lib.Z3_global_param_get.restype = ctypes.c_bool _lib.Z3_global_param_get.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p)] _lib.Z3_mk_config.restype = Config _lib.Z3_mk_config.argtypes = [] _lib.Z3_del_config.argtypes = [Config] _lib.Z3_set_param_value.argtypes = [Config, ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_mk_context.restype = ContextObj _lib.Z3_mk_context.argtypes = [Config] _lib.Z3_mk_context_rc.restype = ContextObj _lib.Z3_mk_context_rc.argtypes = [Config] _lib.Z3_del_context.argtypes = [ContextObj] _lib.Z3_inc_ref.argtypes = [ContextObj, Ast] _lib.Z3_dec_ref.argtypes = [ContextObj, Ast] _lib.Z3_update_param_value.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_interrupt.argtypes = [ContextObj] _lib.Z3_mk_params.restype = Params _lib.Z3_mk_params.argtypes = [ContextObj] _lib.Z3_params_inc_ref.argtypes = [ContextObj, Params] _lib.Z3_params_dec_ref.argtypes = [ContextObj, Params] _lib.Z3_params_set_bool.argtypes = [ContextObj, Params, Symbol, ctypes.c_bool] _lib.Z3_params_set_uint.argtypes = [ContextObj, Params, Symbol, ctypes.c_uint] _lib.Z3_params_set_double.argtypes = [ContextObj, Params, Symbol, ctypes.c_double] _lib.Z3_params_set_symbol.argtypes = [ContextObj, Params, Symbol, Symbol] _lib.Z3_params_to_string.restype = ctypes.c_char_p _lib.Z3_params_to_string.argtypes = [ContextObj, Params] _lib.Z3_params_validate.argtypes = [ContextObj, Params, ParamDescrs] _lib.Z3_param_descrs_inc_ref.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_dec_ref.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_get_kind.restype = ctypes.c_uint _lib.Z3_param_descrs_get_kind.argtypes = [ContextObj, ParamDescrs, Symbol] _lib.Z3_param_descrs_size.restype = ctypes.c_uint _lib.Z3_param_descrs_size.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_get_name.restype = Symbol _lib.Z3_param_descrs_get_name.argtypes = [ContextObj, ParamDescrs, ctypes.c_uint] _lib.Z3_param_descrs_get_documentation.restype = ctypes.c_char_p _lib.Z3_param_descrs_get_documentation.argtypes = [ContextObj, ParamDescrs, Symbol] _lib.Z3_param_descrs_to_string.restype = ctypes.c_char_p _lib.Z3_param_descrs_to_string.argtypes = [ContextObj, ParamDescrs] _lib.Z3_mk_int_symbol.restype = Symbol _lib.Z3_mk_int_symbol.argtypes = [ContextObj, ctypes.c_int] _lib.Z3_mk_string_symbol.restype = Symbol _lib.Z3_mk_string_symbol.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_mk_uninterpreted_sort.restype = Sort _lib.Z3_mk_uninterpreted_sort.argtypes = [ContextObj, Symbol] _lib.Z3_mk_bool_sort.restype = Sort _lib.Z3_mk_bool_sort.argtypes = [ContextObj] _lib.Z3_mk_int_sort.restype = Sort _lib.Z3_mk_int_sort.argtypes = [ContextObj] _lib.Z3_mk_real_sort.restype = Sort _lib.Z3_mk_real_sort.argtypes = [ContextObj] _lib.Z3_mk_bv_sort.restype = Sort _lib.Z3_mk_bv_sort.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_mk_finite_domain_sort.restype = Sort _lib.Z3_mk_finite_domain_sort.argtypes = [ContextObj, Symbol, ctypes.c_ulonglong] _lib.Z3_mk_array_sort.restype = Sort _lib.Z3_mk_array_sort.argtypes = [ContextObj, Sort, Sort] _lib.Z3_mk_array_sort_n.restype = Sort _lib.Z3_mk_array_sort_n.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_tuple_sort.restype = Sort _lib.Z3_mk_tuple_sort.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_enumeration_sort.restype = Sort _lib.Z3_mk_enumeration_sort.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_list_sort.restype = Sort _lib.Z3_mk_list_sort.argtypes = [ContextObj, Symbol, Sort, ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_constructor.restype = Constructor _lib.Z3_mk_constructor.argtypes = [ContextObj, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_del_constructor.argtypes = [ContextObj, Constructor] _lib.Z3_mk_datatype.restype = Sort _lib.Z3_mk_datatype.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Constructor)] _lib.Z3_mk_constructor_list.restype = ConstructorList _lib.Z3_mk_constructor_list.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Constructor)] _lib.Z3_del_constructor_list.argtypes = [ContextObj, ConstructorList] _lib.Z3_mk_datatypes.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(ConstructorList)] _lib.Z3_query_constructor.argtypes = [ContextObj, Constructor, ctypes.c_uint, ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_func_decl.restype = FuncDecl _lib.Z3_mk_func_decl.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_app.restype = Ast _lib.Z3_mk_app.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_const.restype = Ast _lib.Z3_mk_const.argtypes = [ContextObj, Symbol, Sort] _lib.Z3_mk_fresh_func_decl.restype = FuncDecl _lib.Z3_mk_fresh_func_decl.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_fresh_const.restype = Ast _lib.Z3_mk_fresh_const.argtypes = [ContextObj, ctypes.c_char_p, Sort] _lib.Z3_mk_rec_func_decl.restype = FuncDecl _lib.Z3_mk_rec_func_decl.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_add_rec_def.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_true.restype = Ast _lib.Z3_mk_true.argtypes = [ContextObj] _lib.Z3_mk_false.restype = Ast _lib.Z3_mk_false.argtypes = [ContextObj] _lib.Z3_mk_eq.restype = Ast _lib.Z3_mk_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_distinct.restype = Ast _lib.Z3_mk_distinct.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_not.restype = Ast _lib.Z3_mk_not.argtypes = [ContextObj, Ast] _lib.Z3_mk_ite.restype = Ast _lib.Z3_mk_ite.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_iff.restype = Ast _lib.Z3_mk_iff.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_implies.restype = Ast _lib.Z3_mk_implies.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_xor.restype = Ast _lib.Z3_mk_xor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_and.restype = Ast _lib.Z3_mk_and.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_or.restype = Ast _lib.Z3_mk_or.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_add.restype = Ast _lib.Z3_mk_add.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_mul.restype = Ast _lib.Z3_mk_mul.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_sub.restype = Ast _lib.Z3_mk_sub.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_unary_minus.restype = Ast _lib.Z3_mk_unary_minus.argtypes = [ContextObj, Ast] _lib.Z3_mk_div.restype = Ast _lib.Z3_mk_div.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_mod.restype = Ast _lib.Z3_mk_mod.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_rem.restype = Ast _lib.Z3_mk_rem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_power.restype = Ast _lib.Z3_mk_power.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_lt.restype = Ast _lib.Z3_mk_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_le.restype = Ast _lib.Z3_mk_le.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_gt.restype = Ast _lib.Z3_mk_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_ge.restype = Ast _lib.Z3_mk_ge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_int2real.restype = Ast _lib.Z3_mk_int2real.argtypes = [ContextObj, Ast] _lib.Z3_mk_real2int.restype = Ast _lib.Z3_mk_real2int.argtypes = [ContextObj, Ast] _lib.Z3_mk_is_int.restype = Ast _lib.Z3_mk_is_int.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvnot.restype = Ast _lib.Z3_mk_bvnot.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvredand.restype = Ast _lib.Z3_mk_bvredand.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvredor.restype = Ast _lib.Z3_mk_bvredor.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvand.restype = Ast _lib.Z3_mk_bvand.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvor.restype = Ast _lib.Z3_mk_bvor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvxor.restype = Ast _lib.Z3_mk_bvxor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvnand.restype = Ast _lib.Z3_mk_bvnand.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvnor.restype = Ast _lib.Z3_mk_bvnor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvxnor.restype = Ast _lib.Z3_mk_bvxnor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvneg.restype = Ast _lib.Z3_mk_bvneg.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvadd.restype = Ast _lib.Z3_mk_bvadd.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub.restype = Ast _lib.Z3_mk_bvsub.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvmul.restype = Ast _lib.Z3_mk_bvmul.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvudiv.restype = Ast _lib.Z3_mk_bvudiv.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsdiv.restype = Ast _lib.Z3_mk_bvsdiv.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvurem.restype = Ast _lib.Z3_mk_bvurem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsrem.restype = Ast _lib.Z3_mk_bvsrem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsmod.restype = Ast _lib.Z3_mk_bvsmod.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvult.restype = Ast _lib.Z3_mk_bvult.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvslt.restype = Ast _lib.Z3_mk_bvslt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvule.restype = Ast _lib.Z3_mk_bvule.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsle.restype = Ast _lib.Z3_mk_bvsle.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvuge.restype = Ast _lib.Z3_mk_bvuge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsge.restype = Ast _lib.Z3_mk_bvsge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvugt.restype = Ast _lib.Z3_mk_bvugt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsgt.restype = Ast _lib.Z3_mk_bvsgt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_concat.restype = Ast _lib.Z3_mk_concat.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_extract.restype = Ast _lib.Z3_mk_extract.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, Ast] _lib.Z3_mk_sign_ext.restype = Ast _lib.Z3_mk_sign_ext.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_zero_ext.restype = Ast _lib.Z3_mk_zero_ext.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_repeat.restype = Ast _lib.Z3_mk_repeat.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_bvshl.restype = Ast _lib.Z3_mk_bvshl.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvlshr.restype = Ast _lib.Z3_mk_bvlshr.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvashr.restype = Ast _lib.Z3_mk_bvashr.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_rotate_left.restype = Ast _lib.Z3_mk_rotate_left.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_rotate_right.restype = Ast _lib.Z3_mk_rotate_right.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_ext_rotate_left.restype = Ast _lib.Z3_mk_ext_rotate_left.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_ext_rotate_right.restype = Ast _lib.Z3_mk_ext_rotate_right.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_int2bv.restype = Ast _lib.Z3_mk_int2bv.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_bv2int.restype = Ast _lib.Z3_mk_bv2int.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_mk_bvadd_no_overflow.restype = Ast _lib.Z3_mk_bvadd_no_overflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvadd_no_underflow.restype = Ast _lib.Z3_mk_bvadd_no_underflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub_no_overflow.restype = Ast _lib.Z3_mk_bvsub_no_overflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub_no_underflow.restype = Ast _lib.Z3_mk_bvsub_no_underflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvsdiv_no_overflow.restype = Ast _lib.Z3_mk_bvsdiv_no_overflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvneg_no_overflow.restype = Ast _lib.Z3_mk_bvneg_no_overflow.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvmul_no_overflow.restype = Ast _lib.Z3_mk_bvmul_no_overflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvmul_no_underflow.restype = Ast _lib.Z3_mk_bvmul_no_underflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_select.restype = Ast _lib.Z3_mk_select.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_select_n.restype = Ast _lib.Z3_mk_select_n.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_store.restype = Ast _lib.Z3_mk_store.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_store_n.restype = Ast _lib.Z3_mk_store_n.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_const_array.restype = Ast _lib.Z3_mk_const_array.argtypes = [ContextObj, Sort, Ast] _lib.Z3_mk_map.restype = Ast _lib.Z3_mk_map.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_array_default.restype = Ast _lib.Z3_mk_array_default.argtypes = [ContextObj, Ast] _lib.Z3_mk_as_array.restype = Ast _lib.Z3_mk_as_array.argtypes = [ContextObj, FuncDecl] _lib.Z3_mk_set_sort.restype = Sort _lib.Z3_mk_set_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_empty_set.restype = Ast _lib.Z3_mk_empty_set.argtypes = [ContextObj, Sort] _lib.Z3_mk_full_set.restype = Ast _lib.Z3_mk_full_set.argtypes = [ContextObj, Sort] _lib.Z3_mk_set_add.restype = Ast _lib.Z3_mk_set_add.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_del.restype = Ast _lib.Z3_mk_set_del.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_union.restype = Ast _lib.Z3_mk_set_union.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_set_intersect.restype = Ast _lib.Z3_mk_set_intersect.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_set_difference.restype = Ast _lib.Z3_mk_set_difference.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_complement.restype = Ast _lib.Z3_mk_set_complement.argtypes = [ContextObj, Ast] _lib.Z3_mk_set_member.restype = Ast _lib.Z3_mk_set_member.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_subset.restype = Ast _lib.Z3_mk_set_subset.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_array_ext.restype = Ast _lib.Z3_mk_array_ext.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_numeral.restype = Ast _lib.Z3_mk_numeral.argtypes = [ContextObj, ctypes.c_char_p, Sort] _lib.Z3_mk_real.restype = Ast _lib.Z3_mk_real.argtypes = [ContextObj, ctypes.c_int, ctypes.c_int] _lib.Z3_mk_int.restype = Ast _lib.Z3_mk_int.argtypes = [ContextObj, ctypes.c_int, Sort] _lib.Z3_mk_unsigned_int.restype = Ast _lib.Z3_mk_unsigned_int.argtypes = [ContextObj, ctypes.c_uint, Sort] _lib.Z3_mk_int64.restype = Ast _lib.Z3_mk_int64.argtypes = [ContextObj, ctypes.c_longlong, Sort] _lib.Z3_mk_unsigned_int64.restype = Ast _lib.Z3_mk_unsigned_int64.argtypes = [ContextObj, ctypes.c_ulonglong, Sort] _lib.Z3_mk_bv_numeral.restype = Ast _lib.Z3_mk_bv_numeral.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(ctypes.c_bool)] _lib.Z3_mk_seq_sort.restype = Sort _lib.Z3_mk_seq_sort.argtypes = [ContextObj, Sort] _lib.Z3_is_seq_sort.restype = ctypes.c_bool _lib.Z3_is_seq_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_re_sort.restype = Sort _lib.Z3_mk_re_sort.argtypes = [ContextObj, Sort] _lib.Z3_is_re_sort.restype = ctypes.c_bool _lib.Z3_is_re_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_string_sort.restype = Sort _lib.Z3_mk_string_sort.argtypes = [ContextObj] _lib.Z3_is_string_sort.restype = ctypes.c_bool _lib.Z3_is_string_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_string.restype = Ast _lib.Z3_mk_string.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_is_string.restype = ctypes.c_bool _lib.Z3_is_string.argtypes = [ContextObj, Ast] _lib.Z3_get_string.restype = ctypes.c_char_p _lib.Z3_get_string.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_empty.restype = Ast _lib.Z3_mk_seq_empty.argtypes = [ContextObj, Sort] _lib.Z3_mk_seq_unit.restype = Ast _lib.Z3_mk_seq_unit.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_concat.restype = Ast _lib.Z3_mk_seq_concat.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_seq_prefix.restype = Ast _lib.Z3_mk_seq_prefix.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_suffix.restype = Ast _lib.Z3_mk_seq_suffix.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_contains.restype = Ast _lib.Z3_mk_seq_contains.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_extract.restype = Ast _lib.Z3_mk_seq_extract.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_seq_replace.restype = Ast _lib.Z3_mk_seq_replace.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_seq_at.restype = Ast _lib.Z3_mk_seq_at.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_length.restype = Ast _lib.Z3_mk_seq_length.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_index.restype = Ast _lib.Z3_mk_seq_index.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_str_to_int.restype = Ast _lib.Z3_mk_str_to_int.argtypes = [ContextObj, Ast] _lib.Z3_mk_int_to_str.restype = Ast _lib.Z3_mk_int_to_str.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_to_re.restype = Ast _lib.Z3_mk_seq_to_re.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_in_re.restype = Ast _lib.Z3_mk_seq_in_re.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_re_plus.restype = Ast _lib.Z3_mk_re_plus.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_star.restype = Ast _lib.Z3_mk_re_star.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_option.restype = Ast _lib.Z3_mk_re_option.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_union.restype = Ast _lib.Z3_mk_re_union.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_concat.restype = Ast _lib.Z3_mk_re_concat.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_range.restype = Ast _lib.Z3_mk_re_range.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_re_loop.restype = Ast _lib.Z3_mk_re_loop.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.c_uint] _lib.Z3_mk_re_intersect.restype = Ast _lib.Z3_mk_re_intersect.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_complement.restype = Ast _lib.Z3_mk_re_complement.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_empty.restype = Ast _lib.Z3_mk_re_empty.argtypes = [ContextObj, Sort] _lib.Z3_mk_re_full.restype = Ast _lib.Z3_mk_re_full.argtypes = [ContextObj, Sort] _lib.Z3_mk_pattern.restype = Pattern _lib.Z3_mk_pattern.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_bound.restype = Ast _lib.Z3_mk_bound.argtypes = [ContextObj, ctypes.c_uint, Sort] _lib.Z3_mk_forall.restype = Ast _lib.Z3_mk_forall.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_exists.restype = Ast _lib.Z3_mk_exists.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_quantifier.restype = Ast _lib.Z3_mk_quantifier.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_quantifier_ex.restype = Ast _lib.Z3_mk_quantifier_ex.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_forall_const.restype = Ast _lib.Z3_mk_forall_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_exists_const.restype = Ast _lib.Z3_mk_exists_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_quantifier_const.restype = Ast _lib.Z3_mk_quantifier_const.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_quantifier_const_ex.restype = Ast _lib.Z3_mk_quantifier_const_ex.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_lambda.restype = Ast _lib.Z3_mk_lambda.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_lambda_const.restype = Ast _lib.Z3_mk_lambda_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_get_symbol_kind.restype = ctypes.c_uint _lib.Z3_get_symbol_kind.argtypes = [ContextObj, Symbol] _lib.Z3_get_symbol_int.restype = ctypes.c_int _lib.Z3_get_symbol_int.argtypes = [ContextObj, Symbol] _lib.Z3_get_symbol_string.restype = ctypes.c_char_p _lib.Z3_get_symbol_string.argtypes = [ContextObj, Symbol] _lib.Z3_get_sort_name.restype = Symbol _lib.Z3_get_sort_name.argtypes = [ContextObj, Sort] _lib.Z3_get_sort_id.restype = ctypes.c_uint _lib.Z3_get_sort_id.argtypes = [ContextObj, Sort] _lib.Z3_sort_to_ast.restype = Ast _lib.Z3_sort_to_ast.argtypes = [ContextObj, Sort] _lib.Z3_is_eq_sort.restype = ctypes.c_bool _lib.Z3_is_eq_sort.argtypes = [ContextObj, Sort, Sort] _lib.Z3_get_sort_kind.restype = ctypes.c_uint _lib.Z3_get_sort_kind.argtypes = [ContextObj, Sort] _lib.Z3_get_bv_sort_size.restype = ctypes.c_uint _lib.Z3_get_bv_sort_size.argtypes = [ContextObj, Sort] _lib.Z3_get_finite_domain_sort_size.restype = ctypes.c_bool _lib.Z3_get_finite_domain_sort_size.argtypes = [ContextObj, Sort, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_get_array_sort_domain.restype = Sort _lib.Z3_get_array_sort_domain.argtypes = [ContextObj, Sort] _lib.Z3_get_array_sort_range.restype = Sort _lib.Z3_get_array_sort_range.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_mk_decl.restype = FuncDecl _lib.Z3_get_tuple_sort_mk_decl.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_num_fields.restype = ctypes.c_uint _lib.Z3_get_tuple_sort_num_fields.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_field_decl.restype = FuncDecl _lib.Z3_get_tuple_sort_field_decl.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_num_constructors.restype = ctypes.c_uint _lib.Z3_get_datatype_sort_num_constructors.argtypes = [ContextObj, Sort] _lib.Z3_get_datatype_sort_constructor.restype = FuncDecl _lib.Z3_get_datatype_sort_constructor.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_recognizer.restype = FuncDecl _lib.Z3_get_datatype_sort_recognizer.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_constructor_accessor.restype = FuncDecl _lib.Z3_get_datatype_sort_constructor_accessor.argtypes = [ContextObj, Sort, ctypes.c_uint, ctypes.c_uint] _lib.Z3_datatype_update_field.restype = Ast _lib.Z3_datatype_update_field.argtypes = [ContextObj, FuncDecl, Ast, Ast] _lib.Z3_get_relation_arity.restype = ctypes.c_uint _lib.Z3_get_relation_arity.argtypes = [ContextObj, Sort] _lib.Z3_get_relation_column.restype = Sort _lib.Z3_get_relation_column.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_atmost.restype = Ast _lib.Z3_mk_atmost.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint] _lib.Z3_mk_atleast.restype = Ast _lib.Z3_mk_atleast.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint] _lib.Z3_mk_pble.restype = Ast _lib.Z3_mk_pble.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_mk_pbge.restype = Ast _lib.Z3_mk_pbge.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_mk_pbeq.restype = Ast _lib.Z3_mk_pbeq.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_func_decl_to_ast.restype = Ast _lib.Z3_func_decl_to_ast.argtypes = [ContextObj, FuncDecl] _lib.Z3_is_eq_func_decl.restype = ctypes.c_bool _lib.Z3_is_eq_func_decl.argtypes = [ContextObj, FuncDecl, FuncDecl] _lib.Z3_get_func_decl_id.restype = ctypes.c_uint _lib.Z3_get_func_decl_id.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_name.restype = Symbol _lib.Z3_get_decl_name.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_kind.restype = ctypes.c_uint _lib.Z3_get_decl_kind.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_domain_size.restype = ctypes.c_uint _lib.Z3_get_domain_size.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_arity.restype = ctypes.c_uint _lib.Z3_get_arity.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_domain.restype = Sort _lib.Z3_get_domain.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_range.restype = Sort _lib.Z3_get_range.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_num_parameters.restype = ctypes.c_uint _lib.Z3_get_decl_num_parameters.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_parameter_kind.restype = ctypes.c_uint _lib.Z3_get_decl_parameter_kind.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_int_parameter.restype = ctypes.c_int _lib.Z3_get_decl_int_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_double_parameter.restype = ctypes.c_double _lib.Z3_get_decl_double_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_symbol_parameter.restype = Symbol _lib.Z3_get_decl_symbol_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_sort_parameter.restype = Sort _lib.Z3_get_decl_sort_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_ast_parameter.restype = Ast _lib.Z3_get_decl_ast_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_func_decl_parameter.restype = FuncDecl _lib.Z3_get_decl_func_decl_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_rational_parameter.restype = ctypes.c_char_p _lib.Z3_get_decl_rational_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_app_to_ast.restype = Ast _lib.Z3_app_to_ast.argtypes = [ContextObj, Ast] _lib.Z3_get_app_decl.restype = FuncDecl _lib.Z3_get_app_decl.argtypes = [ContextObj, Ast] _lib.Z3_get_app_num_args.restype = ctypes.c_uint _lib.Z3_get_app_num_args.argtypes = [ContextObj, Ast] _lib.Z3_get_app_arg.restype = Ast _lib.Z3_get_app_arg.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_is_eq_ast.restype = ctypes.c_bool _lib.Z3_is_eq_ast.argtypes = [ContextObj, Ast, Ast] _lib.Z3_get_ast_id.restype = ctypes.c_uint _lib.Z3_get_ast_id.argtypes = [ContextObj, Ast] _lib.Z3_get_ast_hash.restype = ctypes.c_uint _lib.Z3_get_ast_hash.argtypes = [ContextObj, Ast] _lib.Z3_get_sort.restype = Sort _lib.Z3_get_sort.argtypes = [ContextObj, Ast] _lib.Z3_is_well_sorted.restype = ctypes.c_bool _lib.Z3_is_well_sorted.argtypes = [ContextObj, Ast] _lib.Z3_get_bool_value.restype = ctypes.c_int _lib.Z3_get_bool_value.argtypes = [ContextObj, Ast] _lib.Z3_get_ast_kind.restype = ctypes.c_uint _lib.Z3_get_ast_kind.argtypes = [ContextObj, Ast] _lib.Z3_is_app.restype = ctypes.c_bool _lib.Z3_is_app.argtypes = [ContextObj, Ast] _lib.Z3_is_numeral_ast.restype = ctypes.c_bool _lib.Z3_is_numeral_ast.argtypes = [ContextObj, Ast] _lib.Z3_is_algebraic_number.restype = ctypes.c_bool _lib.Z3_is_algebraic_number.argtypes = [ContextObj, Ast] _lib.Z3_to_app.restype = Ast _lib.Z3_to_app.argtypes = [ContextObj, Ast] _lib.Z3_to_func_decl.restype = FuncDecl _lib.Z3_to_func_decl.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_string.restype = ctypes.c_char_p _lib.Z3_get_numeral_string.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_decimal_string.restype = ctypes.c_char_p _lib.Z3_get_numeral_decimal_string.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_numeral_double.restype = ctypes.c_double _lib.Z3_get_numeral_double.argtypes = [ContextObj, Ast] _lib.Z3_get_numerator.restype = Ast _lib.Z3_get_numerator.argtypes = [ContextObj, Ast] _lib.Z3_get_denominator.restype = Ast _lib.Z3_get_denominator.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_small.restype = ctypes.c_bool _lib.Z3_get_numeral_small.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_numeral_int.restype = ctypes.c_bool _lib.Z3_get_numeral_int.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_int)] _lib.Z3_get_numeral_uint.restype = ctypes.c_bool _lib.Z3_get_numeral_uint.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_get_numeral_uint64.restype = ctypes.c_bool _lib.Z3_get_numeral_uint64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_get_numeral_int64.restype = ctypes.c_bool _lib.Z3_get_numeral_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_numeral_rational_int64.restype = ctypes.c_bool _lib.Z3_get_numeral_rational_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_algebraic_number_lower.restype = Ast _lib.Z3_get_algebraic_number_lower.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_algebraic_number_upper.restype = Ast _lib.Z3_get_algebraic_number_upper.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_pattern_to_ast.restype = Ast _lib.Z3_pattern_to_ast.argtypes = [ContextObj, Pattern] _lib.Z3_get_pattern_num_terms.restype = ctypes.c_uint _lib.Z3_get_pattern_num_terms.argtypes = [ContextObj, Pattern] _lib.Z3_get_pattern.restype = Ast _lib.Z3_get_pattern.argtypes = [ContextObj, Pattern, ctypes.c_uint] _lib.Z3_get_index_value.restype = ctypes.c_uint _lib.Z3_get_index_value.argtypes = [ContextObj, Ast] _lib.Z3_is_quantifier_forall.restype = ctypes.c_bool _lib.Z3_is_quantifier_forall.argtypes = [ContextObj, Ast] _lib.Z3_is_quantifier_exists.restype = ctypes.c_bool _lib.Z3_is_quantifier_exists.argtypes = [ContextObj, Ast] _lib.Z3_is_lambda.restype = ctypes.c_bool _lib.Z3_is_lambda.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_weight.restype = ctypes.c_uint _lib.Z3_get_quantifier_weight.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_num_patterns.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_patterns.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_pattern_ast.restype = Pattern _lib.Z3_get_quantifier_pattern_ast.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_num_no_patterns.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_no_patterns.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_no_pattern_ast.restype = Ast _lib.Z3_get_quantifier_no_pattern_ast.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_num_bound.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_bound.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_bound_name.restype = Symbol _lib.Z3_get_quantifier_bound_name.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_bound_sort.restype = Sort _lib.Z3_get_quantifier_bound_sort.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_body.restype = Ast _lib.Z3_get_quantifier_body.argtypes = [ContextObj, Ast] _lib.Z3_simplify.restype = Ast _lib.Z3_simplify.argtypes = [ContextObj, Ast] _lib.Z3_simplify_ex.restype = Ast _lib.Z3_simplify_ex.argtypes = [ContextObj, Ast, Params] _lib.Z3_simplify_get_help.restype = ctypes.c_char_p _lib.Z3_simplify_get_help.argtypes = [ContextObj] _lib.Z3_simplify_get_param_descrs.restype = ParamDescrs _lib.Z3_simplify_get_param_descrs.argtypes = [ContextObj] _lib.Z3_update_term.restype = Ast _lib.Z3_update_term.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_substitute.restype = Ast _lib.Z3_substitute.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(Ast)] _lib.Z3_substitute_vars.restype = Ast _lib.Z3_substitute_vars.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_translate.restype = Ast _lib.Z3_translate.argtypes = [ContextObj, Ast, ContextObj] _lib.Z3_mk_model.restype = Model _lib.Z3_mk_model.argtypes = [ContextObj] _lib.Z3_model_inc_ref.argtypes = [ContextObj, Model] _lib.Z3_model_dec_ref.argtypes = [ContextObj, Model] _lib.Z3_model_eval.restype = ctypes.c_bool _lib.Z3_model_eval.argtypes = [ContextObj, Model, Ast, ctypes.c_bool, ctypes.POINTER(Ast)] _lib.Z3_model_get_const_interp.restype = Ast _lib.Z3_model_get_const_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_has_interp.restype = ctypes.c_bool _lib.Z3_model_has_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_get_func_interp.restype = FuncInterpObj _lib.Z3_model_get_func_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_get_num_consts.restype = ctypes.c_uint _lib.Z3_model_get_num_consts.argtypes = [ContextObj, Model] _lib.Z3_model_get_const_decl.restype = FuncDecl _lib.Z3_model_get_const_decl.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_num_funcs.restype = ctypes.c_uint _lib.Z3_model_get_num_funcs.argtypes = [ContextObj, Model] _lib.Z3_model_get_func_decl.restype = FuncDecl _lib.Z3_model_get_func_decl.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_num_sorts.restype = ctypes.c_uint _lib.Z3_model_get_num_sorts.argtypes = [ContextObj, Model] _lib.Z3_model_get_sort.restype = Sort _lib.Z3_model_get_sort.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_sort_universe.restype = AstVectorObj _lib.Z3_model_get_sort_universe.argtypes = [ContextObj, Model, Sort] _lib.Z3_model_translate.restype = Model _lib.Z3_model_translate.argtypes = [ContextObj, Model, ContextObj] _lib.Z3_is_as_array.restype = ctypes.c_bool _lib.Z3_is_as_array.argtypes = [ContextObj, Ast] _lib.Z3_get_as_array_func_decl.restype = FuncDecl _lib.Z3_get_as_array_func_decl.argtypes = [ContextObj, Ast] _lib.Z3_add_func_interp.restype = FuncInterpObj _lib.Z3_add_func_interp.argtypes = [ContextObj, Model, FuncDecl, Ast] _lib.Z3_add_const_interp.argtypes = [ContextObj, Model, FuncDecl, Ast] _lib.Z3_func_interp_inc_ref.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_dec_ref.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_get_num_entries.restype = ctypes.c_uint _lib.Z3_func_interp_get_num_entries.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_get_entry.restype = FuncEntryObj _lib.Z3_func_interp_get_entry.argtypes = [ContextObj, FuncInterpObj, ctypes.c_uint] _lib.Z3_func_interp_get_else.restype = Ast _lib.Z3_func_interp_get_else.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_set_else.argtypes = [ContextObj, FuncInterpObj, Ast] _lib.Z3_func_interp_get_arity.restype = ctypes.c_uint _lib.Z3_func_interp_get_arity.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_add_entry.argtypes = [ContextObj, FuncInterpObj, AstVectorObj, Ast] _lib.Z3_func_entry_inc_ref.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_dec_ref.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_value.restype = Ast _lib.Z3_func_entry_get_value.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_num_args.restype = ctypes.c_uint _lib.Z3_func_entry_get_num_args.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_arg.restype = Ast _lib.Z3_func_entry_get_arg.argtypes = [ContextObj, FuncEntryObj, ctypes.c_uint] _lib.Z3_open_log.restype = ctypes.c_int _lib.Z3_open_log.argtypes = [ctypes.c_char_p] _lib.Z3_append_log.argtypes = [ctypes.c_char_p] _lib.Z3_close_log.argtypes = [] _lib.Z3_toggle_warning_messages.argtypes = [ctypes.c_bool] _lib.Z3_set_ast_print_mode.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_ast_to_string.restype = ctypes.c_char_p _lib.Z3_ast_to_string.argtypes = [ContextObj, Ast] _lib.Z3_pattern_to_string.restype = ctypes.c_char_p _lib.Z3_pattern_to_string.argtypes = [ContextObj, Pattern] _lib.Z3_sort_to_string.restype = ctypes.c_char_p _lib.Z3_sort_to_string.argtypes = [ContextObj, Sort] _lib.Z3_func_decl_to_string.restype = ctypes.c_char_p _lib.Z3_func_decl_to_string.argtypes = [ContextObj, FuncDecl] _lib.Z3_model_to_string.restype = ctypes.c_char_p _lib.Z3_model_to_string.argtypes = [ContextObj, Model] _lib.Z3_benchmark_to_smtlib_string.restype = ctypes.c_char_p _lib.Z3_benchmark_to_smtlib_string.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_parse_smtlib2_string.restype = AstVectorObj _lib.Z3_parse_smtlib2_string.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl)] _lib.Z3_parse_smtlib2_file.restype = AstVectorObj _lib.Z3_parse_smtlib2_file.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl)] _lib.Z3_eval_smtlib2_string.restype = ctypes.c_char_p _lib.Z3_eval_smtlib2_string.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_get_error_code.restype = ctypes.c_uint _lib.Z3_get_error_code.argtypes = [ContextObj] _lib.Z3_set_error.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_error_msg.restype = ctypes.c_char_p _lib.Z3_get_error_msg.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_version.argtypes = [ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_get_full_version.restype = ctypes.c_char_p _lib.Z3_get_full_version.argtypes = [] _lib.Z3_enable_trace.argtypes = [ctypes.c_char_p] _lib.Z3_disable_trace.argtypes = [ctypes.c_char_p] _lib.Z3_reset_memory.argtypes = [] _lib.Z3_finalize_memory.argtypes = [] _lib.Z3_mk_goal.restype = GoalObj _lib.Z3_mk_goal.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_bool, ctypes.c_bool] _lib.Z3_goal_inc_ref.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_dec_ref.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_precision.restype = ctypes.c_uint _lib.Z3_goal_precision.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_assert.argtypes = [ContextObj, GoalObj, Ast] _lib.Z3_goal_inconsistent.restype = ctypes.c_bool _lib.Z3_goal_inconsistent.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_depth.restype = ctypes.c_uint _lib.Z3_goal_depth.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_reset.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_size.restype = ctypes.c_uint _lib.Z3_goal_size.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_formula.restype = Ast _lib.Z3_goal_formula.argtypes = [ContextObj, GoalObj, ctypes.c_uint] _lib.Z3_goal_num_exprs.restype = ctypes.c_uint _lib.Z3_goal_num_exprs.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_is_decided_sat.restype = ctypes.c_bool _lib.Z3_goal_is_decided_sat.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_is_decided_unsat.restype = ctypes.c_bool _lib.Z3_goal_is_decided_unsat.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_translate.restype = GoalObj _lib.Z3_goal_translate.argtypes = [ContextObj, GoalObj, ContextObj] _lib.Z3_goal_convert_model.restype = Model _lib.Z3_goal_convert_model.argtypes = [ContextObj, GoalObj, Model] _lib.Z3_goal_to_string.restype = ctypes.c_char_p _lib.Z3_goal_to_string.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_to_dimacs_string.restype = ctypes.c_char_p _lib.Z3_goal_to_dimacs_string.argtypes = [ContextObj, GoalObj] _lib.Z3_mk_tactic.restype = TacticObj _lib.Z3_mk_tactic.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_tactic_inc_ref.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_dec_ref.argtypes = [ContextObj, TacticObj] _lib.Z3_mk_probe.restype = ProbeObj _lib.Z3_mk_probe.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_inc_ref.argtypes = [ContextObj, ProbeObj] _lib.Z3_probe_dec_ref.argtypes = [ContextObj, ProbeObj] _lib.Z3_tactic_and_then.restype = TacticObj _lib.Z3_tactic_and_then.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_or_else.restype = TacticObj _lib.Z3_tactic_or_else.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_par_or.restype = TacticObj _lib.Z3_tactic_par_or.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(TacticObj)] _lib.Z3_tactic_par_and_then.restype = TacticObj _lib.Z3_tactic_par_and_then.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_try_for.restype = TacticObj _lib.Z3_tactic_try_for.argtypes = [ContextObj, TacticObj, ctypes.c_uint] _lib.Z3_tactic_when.restype = TacticObj _lib.Z3_tactic_when.argtypes = [ContextObj, ProbeObj, TacticObj] _lib.Z3_tactic_cond.restype = TacticObj _lib.Z3_tactic_cond.argtypes = [ContextObj, ProbeObj, TacticObj, TacticObj] _lib.Z3_tactic_repeat.restype = TacticObj _lib.Z3_tactic_repeat.argtypes = [ContextObj, TacticObj, ctypes.c_uint] _lib.Z3_tactic_skip.restype = TacticObj _lib.Z3_tactic_skip.argtypes = [ContextObj] _lib.Z3_tactic_fail.restype = TacticObj _lib.Z3_tactic_fail.argtypes = [ContextObj] _lib.Z3_tactic_fail_if.restype = TacticObj _lib.Z3_tactic_fail_if.argtypes = [ContextObj, ProbeObj] _lib.Z3_tactic_fail_if_not_decided.restype = TacticObj _lib.Z3_tactic_fail_if_not_decided.argtypes = [ContextObj] _lib.Z3_tactic_using_params.restype = TacticObj _lib.Z3_tactic_using_params.argtypes = [ContextObj, TacticObj, Params] _lib.Z3_probe_const.restype = ProbeObj _lib.Z3_probe_const.argtypes = [ContextObj, ctypes.c_double] _lib.Z3_probe_lt.restype = ProbeObj _lib.Z3_probe_lt.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_gt.restype = ProbeObj _lib.Z3_probe_gt.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_le.restype = ProbeObj _lib.Z3_probe_le.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_ge.restype = ProbeObj _lib.Z3_probe_ge.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_eq.restype = ProbeObj _lib.Z3_probe_eq.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_and.restype = ProbeObj _lib.Z3_probe_and.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_or.restype = ProbeObj _lib.Z3_probe_or.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_not.restype = ProbeObj _lib.Z3_probe_not.argtypes = [ContextObj, ProbeObj] _lib.Z3_get_num_tactics.restype = ctypes.c_uint _lib.Z3_get_num_tactics.argtypes = [ContextObj] _lib.Z3_get_tactic_name.restype = ctypes.c_char_p _lib.Z3_get_tactic_name.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_num_probes.restype = ctypes.c_uint _lib.Z3_get_num_probes.argtypes = [ContextObj] _lib.Z3_get_probe_name.restype = ctypes.c_char_p _lib.Z3_get_probe_name.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_tactic_get_help.restype = ctypes.c_char_p _lib.Z3_tactic_get_help.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_get_param_descrs.restype = ParamDescrs _lib.Z3_tactic_get_param_descrs.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_get_descr.restype = ctypes.c_char_p _lib.Z3_tactic_get_descr.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_get_descr.restype = ctypes.c_char_p _lib.Z3_probe_get_descr.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_apply.restype = ctypes.c_double _lib.Z3_probe_apply.argtypes = [ContextObj, ProbeObj, GoalObj] _lib.Z3_tactic_apply.restype = ApplyResultObj _lib.Z3_tactic_apply.argtypes = [ContextObj, TacticObj, GoalObj] _lib.Z3_tactic_apply_ex.restype = ApplyResultObj _lib.Z3_tactic_apply_ex.argtypes = [ContextObj, TacticObj, GoalObj, Params] _lib.Z3_apply_result_inc_ref.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_dec_ref.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_to_string.restype = ctypes.c_char_p _lib.Z3_apply_result_to_string.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_get_num_subgoals.restype = ctypes.c_uint _lib.Z3_apply_result_get_num_subgoals.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_get_subgoal.restype = GoalObj _lib.Z3_apply_result_get_subgoal.argtypes = [ContextObj, ApplyResultObj, ctypes.c_uint] _lib.Z3_mk_solver.restype = SolverObj _lib.Z3_mk_solver.argtypes = [ContextObj] _lib.Z3_mk_simple_solver.restype = SolverObj _lib.Z3_mk_simple_solver.argtypes = [ContextObj] _lib.Z3_mk_solver_for_logic.restype = SolverObj _lib.Z3_mk_solver_for_logic.argtypes = [ContextObj, Symbol] _lib.Z3_mk_solver_from_tactic.restype = SolverObj _lib.Z3_mk_solver_from_tactic.argtypes = [ContextObj, TacticObj] _lib.Z3_solver_translate.restype = SolverObj _lib.Z3_solver_translate.argtypes = [ContextObj, SolverObj, ContextObj] _lib.Z3_solver_import_model_converter.argtypes = [ContextObj, SolverObj, SolverObj] _lib.Z3_solver_get_help.restype = ctypes.c_char_p _lib.Z3_solver_get_help.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_param_descrs.restype = ParamDescrs _lib.Z3_solver_get_param_descrs.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_set_params.argtypes = [ContextObj, SolverObj, Params] _lib.Z3_solver_inc_ref.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_dec_ref.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_push.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_pop.argtypes = [ContextObj, SolverObj, ctypes.c_uint] _lib.Z3_solver_reset.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_num_scopes.restype = ctypes.c_uint _lib.Z3_solver_get_num_scopes.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_assert.argtypes = [ContextObj, SolverObj, Ast] _lib.Z3_solver_assert_and_track.argtypes = [ContextObj, SolverObj, Ast, Ast] _lib.Z3_solver_from_file.argtypes = [ContextObj, SolverObj, ctypes.c_char_p] _lib.Z3_solver_from_string.argtypes = [ContextObj, SolverObj, ctypes.c_char_p] _lib.Z3_solver_get_assertions.restype = AstVectorObj _lib.Z3_solver_get_assertions.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_units.restype = AstVectorObj _lib.Z3_solver_get_units.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_non_units.restype = AstVectorObj _lib.Z3_solver_get_non_units.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_check.restype = ctypes.c_int _lib.Z3_solver_check.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_check_assumptions.restype = ctypes.c_int _lib.Z3_solver_check_assumptions.argtypes = [ContextObj, SolverObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_get_implied_equalities.restype = ctypes.c_int _lib.Z3_get_implied_equalities.argtypes = [ContextObj, SolverObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_solver_get_consequences.restype = ctypes.c_int _lib.Z3_solver_get_consequences.argtypes = [ContextObj, SolverObj, AstVectorObj, AstVectorObj, AstVectorObj] _lib.Z3_solver_cube.restype = AstVectorObj _lib.Z3_solver_cube.argtypes = [ContextObj, SolverObj, AstVectorObj, ctypes.c_uint] _lib.Z3_solver_get_model.restype = Model _lib.Z3_solver_get_model.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_proof.restype = Ast _lib.Z3_solver_get_proof.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_unsat_core.restype = AstVectorObj _lib.Z3_solver_get_unsat_core.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_solver_get_reason_unknown.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_statistics.restype = StatsObj _lib.Z3_solver_get_statistics.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_to_string.restype = ctypes.c_char_p _lib.Z3_solver_to_string.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_to_dimacs_string.restype = ctypes.c_char_p _lib.Z3_solver_to_dimacs_string.argtypes = [ContextObj, SolverObj] _lib.Z3_stats_to_string.restype = ctypes.c_char_p _lib.Z3_stats_to_string.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_inc_ref.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_dec_ref.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_size.restype = ctypes.c_uint _lib.Z3_stats_size.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_get_key.restype = ctypes.c_char_p _lib.Z3_stats_get_key.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_is_uint.restype = ctypes.c_bool _lib.Z3_stats_is_uint.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_is_double.restype = ctypes.c_bool _lib.Z3_stats_is_double.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_get_uint_value.restype = ctypes.c_uint _lib.Z3_stats_get_uint_value.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_get_double_value.restype = ctypes.c_double _lib.Z3_stats_get_double_value.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_get_estimated_alloc_size.restype = ctypes.c_ulonglong _lib.Z3_get_estimated_alloc_size.argtypes = [] _lib.Z3_mk_ast_vector.restype = AstVectorObj _lib.Z3_mk_ast_vector.argtypes = [ContextObj] _lib.Z3_ast_vector_inc_ref.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_dec_ref.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_size.restype = ctypes.c_uint _lib.Z3_ast_vector_size.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_get.restype = Ast _lib.Z3_ast_vector_get.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint] _lib.Z3_ast_vector_set.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint, Ast] _lib.Z3_ast_vector_resize.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint] _lib.Z3_ast_vector_push.argtypes = [ContextObj, AstVectorObj, Ast] _lib.Z3_ast_vector_translate.restype = AstVectorObj _lib.Z3_ast_vector_translate.argtypes = [ContextObj, AstVectorObj, ContextObj] _lib.Z3_ast_vector_to_string.restype = ctypes.c_char_p _lib.Z3_ast_vector_to_string.argtypes = [ContextObj, AstVectorObj] _lib.Z3_mk_ast_map.restype = AstMapObj _lib.Z3_mk_ast_map.argtypes = [ContextObj] _lib.Z3_ast_map_inc_ref.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_dec_ref.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_contains.restype = ctypes.c_bool _lib.Z3_ast_map_contains.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_find.restype = Ast _lib.Z3_ast_map_find.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_insert.argtypes = [ContextObj, AstMapObj, Ast, Ast] _lib.Z3_ast_map_erase.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_reset.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_size.restype = ctypes.c_uint _lib.Z3_ast_map_size.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_keys.restype = AstVectorObj _lib.Z3_ast_map_keys.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_to_string.restype = ctypes.c_char_p _lib.Z3_ast_map_to_string.argtypes = [ContextObj, AstMapObj] _lib.Z3_algebraic_is_value.restype = ctypes.c_bool _lib.Z3_algebraic_is_value.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_pos.restype = ctypes.c_bool _lib.Z3_algebraic_is_pos.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_neg.restype = ctypes.c_bool _lib.Z3_algebraic_is_neg.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_zero.restype = ctypes.c_bool _lib.Z3_algebraic_is_zero.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_sign.restype = ctypes.c_int _lib.Z3_algebraic_sign.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_add.restype = Ast _lib.Z3_algebraic_add.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_sub.restype = Ast _lib.Z3_algebraic_sub.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_mul.restype = Ast _lib.Z3_algebraic_mul.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_div.restype = Ast _lib.Z3_algebraic_div.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_root.restype = Ast _lib.Z3_algebraic_root.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_algebraic_power.restype = Ast _lib.Z3_algebraic_power.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_algebraic_lt.restype = ctypes.c_bool _lib.Z3_algebraic_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_gt.restype = ctypes.c_bool _lib.Z3_algebraic_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_le.restype = ctypes.c_bool _lib.Z3_algebraic_le.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_ge.restype = ctypes.c_bool _lib.Z3_algebraic_ge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_eq.restype = ctypes.c_bool _lib.Z3_algebraic_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_neq.restype = ctypes.c_bool _lib.Z3_algebraic_neq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_roots.restype = AstVectorObj _lib.Z3_algebraic_roots.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_algebraic_eval.restype = ctypes.c_int _lib.Z3_algebraic_eval.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_polynomial_subresultants.restype = AstVectorObj _lib.Z3_polynomial_subresultants.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_rcf_del.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_mk_rational.restype = RCFNumObj _lib.Z3_rcf_mk_rational.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_rcf_mk_small_int.restype = RCFNumObj _lib.Z3_rcf_mk_small_int.argtypes = [ContextObj, ctypes.c_int] _lib.Z3_rcf_mk_pi.restype = RCFNumObj _lib.Z3_rcf_mk_pi.argtypes = [ContextObj] _lib.Z3_rcf_mk_e.restype = RCFNumObj _lib.Z3_rcf_mk_e.argtypes = [ContextObj] _lib.Z3_rcf_mk_infinitesimal.restype = RCFNumObj _lib.Z3_rcf_mk_infinitesimal.argtypes = [ContextObj] _lib.Z3_rcf_mk_roots.restype = ctypes.c_uint _lib.Z3_rcf_mk_roots.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(RCFNumObj), ctypes.POINTER(RCFNumObj)] _lib.Z3_rcf_add.restype = RCFNumObj _lib.Z3_rcf_add.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_sub.restype = RCFNumObj _lib.Z3_rcf_sub.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_mul.restype = RCFNumObj _lib.Z3_rcf_mul.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_div.restype = RCFNumObj _lib.Z3_rcf_div.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_neg.restype = RCFNumObj _lib.Z3_rcf_neg.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_inv.restype = RCFNumObj _lib.Z3_rcf_inv.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_power.restype = RCFNumObj _lib.Z3_rcf_power.argtypes = [ContextObj, RCFNumObj, ctypes.c_uint] _lib.Z3_rcf_lt.restype = ctypes.c_bool _lib.Z3_rcf_lt.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_gt.restype = ctypes.c_bool _lib.Z3_rcf_gt.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_le.restype = ctypes.c_bool _lib.Z3_rcf_le.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_ge.restype = ctypes.c_bool _lib.Z3_rcf_ge.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_eq.restype = ctypes.c_bool _lib.Z3_rcf_eq.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_neq.restype = ctypes.c_bool _lib.Z3_rcf_neq.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_num_to_string.restype = ctypes.c_char_p _lib.Z3_rcf_num_to_string.argtypes = [ContextObj, RCFNumObj, ctypes.c_bool, ctypes.c_bool] _lib.Z3_rcf_num_to_decimal_string.restype = ctypes.c_char_p _lib.Z3_rcf_num_to_decimal_string.argtypes = [ContextObj, RCFNumObj, ctypes.c_uint] _lib.Z3_rcf_get_numerator_denominator.argtypes = [ContextObj, RCFNumObj, ctypes.POINTER(RCFNumObj), ctypes.POINTER(RCFNumObj)] _lib.Z3_mk_fixedpoint.restype = FixedpointObj _lib.Z3_mk_fixedpoint.argtypes = [ContextObj] _lib.Z3_fixedpoint_inc_ref.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_dec_ref.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_add_rule.argtypes = [ContextObj, FixedpointObj, Ast, Symbol] _lib.Z3_fixedpoint_add_fact.argtypes = [ContextObj, FixedpointObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_fixedpoint_assert.argtypes = [ContextObj, FixedpointObj, Ast] _lib.Z3_fixedpoint_query.restype = ctypes.c_int _lib.Z3_fixedpoint_query.argtypes = [ContextObj, FixedpointObj, Ast] _lib.Z3_fixedpoint_query_relations.restype = ctypes.c_int _lib.Z3_fixedpoint_query_relations.argtypes = [ContextObj, FixedpointObj, ctypes.c_uint, ctypes.POINTER(FuncDecl)] _lib.Z3_fixedpoint_get_answer.restype = Ast _lib.Z3_fixedpoint_get_answer.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_fixedpoint_get_reason_unknown.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_update_rule.argtypes = [ContextObj, FixedpointObj, Ast, Symbol] _lib.Z3_fixedpoint_get_num_levels.restype = ctypes.c_uint _lib.Z3_fixedpoint_get_num_levels.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_fixedpoint_get_cover_delta.restype = Ast _lib.Z3_fixedpoint_get_cover_delta.argtypes = [ContextObj, FixedpointObj, ctypes.c_int, FuncDecl] _lib.Z3_fixedpoint_add_cover.argtypes = [ContextObj, FixedpointObj, ctypes.c_int, FuncDecl, Ast] _lib.Z3_fixedpoint_get_statistics.restype = StatsObj _lib.Z3_fixedpoint_get_statistics.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_register_relation.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_fixedpoint_set_predicate_representation.argtypes = [ContextObj, FixedpointObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Symbol)] _lib.Z3_fixedpoint_get_rules.restype = AstVectorObj _lib.Z3_fixedpoint_get_rules.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_assertions.restype = AstVectorObj _lib.Z3_fixedpoint_get_assertions.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_set_params.argtypes = [ContextObj, FixedpointObj, Params] _lib.Z3_fixedpoint_get_help.restype = ctypes.c_char_p _lib.Z3_fixedpoint_get_help.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_param_descrs.restype = ParamDescrs _lib.Z3_fixedpoint_get_param_descrs.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_to_string.restype = ctypes.c_char_p _lib.Z3_fixedpoint_to_string.argtypes = [ContextObj, FixedpointObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_fixedpoint_from_string.restype = AstVectorObj _lib.Z3_fixedpoint_from_string.argtypes = [ContextObj, FixedpointObj, ctypes.c_char_p] _lib.Z3_fixedpoint_from_file.restype = AstVectorObj _lib.Z3_fixedpoint_from_file.argtypes = [ContextObj, FixedpointObj, ctypes.c_char_p] _lib.Z3_fixedpoint_push.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_pop.argtypes = [ContextObj, FixedpointObj] _lib.Z3_mk_optimize.restype = OptimizeObj _lib.Z3_mk_optimize.argtypes = [ContextObj] _lib.Z3_optimize_inc_ref.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_dec_ref.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_assert.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_assert_soft.restype = ctypes.c_uint _lib.Z3_optimize_assert_soft.argtypes = [ContextObj, OptimizeObj, Ast, ctypes.c_char_p, Symbol] _lib.Z3_optimize_maximize.restype = ctypes.c_uint _lib.Z3_optimize_maximize.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_minimize.restype = ctypes.c_uint _lib.Z3_optimize_minimize.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_push.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_pop.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_check.restype = ctypes.c_int _lib.Z3_optimize_check.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_optimize_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_optimize_get_reason_unknown.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_model.restype = Model _lib.Z3_optimize_get_model.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_unsat_core.restype = AstVectorObj _lib.Z3_optimize_get_unsat_core.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_set_params.argtypes = [ContextObj, OptimizeObj, Params] _lib.Z3_optimize_get_param_descrs.restype = ParamDescrs _lib.Z3_optimize_get_param_descrs.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_lower.restype = Ast _lib.Z3_optimize_get_lower.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_upper.restype = Ast _lib.Z3_optimize_get_upper.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_lower_as_vector.restype = AstVectorObj _lib.Z3_optimize_get_lower_as_vector.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_upper_as_vector.restype = AstVectorObj _lib.Z3_optimize_get_upper_as_vector.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_to_string.restype = ctypes.c_char_p _lib.Z3_optimize_to_string.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_from_string.argtypes = [ContextObj, OptimizeObj, ctypes.c_char_p] _lib.Z3_optimize_from_file.argtypes = [ContextObj, OptimizeObj, ctypes.c_char_p] _lib.Z3_optimize_get_help.restype = ctypes.c_char_p _lib.Z3_optimize_get_help.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_statistics.restype = StatsObj _lib.Z3_optimize_get_statistics.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_assertions.restype = AstVectorObj _lib.Z3_optimize_get_assertions.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_objectives.restype = AstVectorObj _lib.Z3_optimize_get_objectives.argtypes = [ContextObj, OptimizeObj] _lib.Z3_mk_fpa_rounding_mode_sort.restype = Sort _lib.Z3_mk_fpa_rounding_mode_sort.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_nearest_ties_to_even.restype = Ast _lib.Z3_mk_fpa_round_nearest_ties_to_even.argtypes = [ContextObj] _lib.Z3_mk_fpa_rne.restype = Ast _lib.Z3_mk_fpa_rne.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_nearest_ties_to_away.restype = Ast _lib.Z3_mk_fpa_round_nearest_ties_to_away.argtypes = [ContextObj] _lib.Z3_mk_fpa_rna.restype = Ast _lib.Z3_mk_fpa_rna.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_positive.restype = Ast _lib.Z3_mk_fpa_round_toward_positive.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtp.restype = Ast _lib.Z3_mk_fpa_rtp.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_negative.restype = Ast _lib.Z3_mk_fpa_round_toward_negative.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtn.restype = Ast _lib.Z3_mk_fpa_rtn.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_zero.restype = Ast _lib.Z3_mk_fpa_round_toward_zero.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtz.restype = Ast _lib.Z3_mk_fpa_rtz.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort.restype = Sort _lib.Z3_mk_fpa_sort.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint] _lib.Z3_mk_fpa_sort_half.restype = Sort _lib.Z3_mk_fpa_sort_half.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_16.restype = Sort _lib.Z3_mk_fpa_sort_16.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_single.restype = Sort _lib.Z3_mk_fpa_sort_single.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_32.restype = Sort _lib.Z3_mk_fpa_sort_32.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_double.restype = Sort _lib.Z3_mk_fpa_sort_double.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_64.restype = Sort _lib.Z3_mk_fpa_sort_64.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_quadruple.restype = Sort _lib.Z3_mk_fpa_sort_quadruple.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_128.restype = Sort _lib.Z3_mk_fpa_sort_128.argtypes = [ContextObj] _lib.Z3_mk_fpa_nan.restype = Ast _lib.Z3_mk_fpa_nan.argtypes = [ContextObj, Sort] _lib.Z3_mk_fpa_inf.restype = Ast _lib.Z3_mk_fpa_inf.argtypes = [ContextObj, Sort, ctypes.c_bool] _lib.Z3_mk_fpa_zero.restype = Ast _lib.Z3_mk_fpa_zero.argtypes = [ContextObj, Sort, ctypes.c_bool] _lib.Z3_mk_fpa_fp.restype = Ast _lib.Z3_mk_fpa_fp.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_numeral_float.restype = Ast _lib.Z3_mk_fpa_numeral_float.argtypes = [ContextObj, ctypes.c_float, Sort] _lib.Z3_mk_fpa_numeral_double.restype = Ast _lib.Z3_mk_fpa_numeral_double.argtypes = [ContextObj, ctypes.c_double, Sort] _lib.Z3_mk_fpa_numeral_int.restype = Ast _lib.Z3_mk_fpa_numeral_int.argtypes = [ContextObj, ctypes.c_int, Sort] _lib.Z3_mk_fpa_numeral_int_uint.restype = Ast _lib.Z3_mk_fpa_numeral_int_uint.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_int, ctypes.c_uint, Sort] _lib.Z3_mk_fpa_numeral_int64_uint64.restype = Ast _lib.Z3_mk_fpa_numeral_int64_uint64.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_longlong, ctypes.c_ulonglong, Sort] _lib.Z3_mk_fpa_abs.restype = Ast _lib.Z3_mk_fpa_abs.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_neg.restype = Ast _lib.Z3_mk_fpa_neg.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_add.restype = Ast _lib.Z3_mk_fpa_add.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_sub.restype = Ast _lib.Z3_mk_fpa_sub.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_mul.restype = Ast _lib.Z3_mk_fpa_mul.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_div.restype = Ast _lib.Z3_mk_fpa_div.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_fma.restype = Ast _lib.Z3_mk_fpa_fma.argtypes = [ContextObj, Ast, Ast, Ast, Ast] _lib.Z3_mk_fpa_sqrt.restype = Ast _lib.Z3_mk_fpa_sqrt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_rem.restype = Ast _lib.Z3_mk_fpa_rem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_round_to_integral.restype = Ast _lib.Z3_mk_fpa_round_to_integral.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_min.restype = Ast _lib.Z3_mk_fpa_min.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_max.restype = Ast _lib.Z3_mk_fpa_max.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_leq.restype = Ast _lib.Z3_mk_fpa_leq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_lt.restype = Ast _lib.Z3_mk_fpa_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_geq.restype = Ast _lib.Z3_mk_fpa_geq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_gt.restype = Ast _lib.Z3_mk_fpa_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_eq.restype = Ast _lib.Z3_mk_fpa_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_is_normal.restype = Ast _lib.Z3_mk_fpa_is_normal.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_subnormal.restype = Ast _lib.Z3_mk_fpa_is_subnormal.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_zero.restype = Ast _lib.Z3_mk_fpa_is_zero.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_infinite.restype = Ast _lib.Z3_mk_fpa_is_infinite.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_nan.restype = Ast _lib.Z3_mk_fpa_is_nan.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_negative.restype = Ast _lib.Z3_mk_fpa_is_negative.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_positive.restype = Ast _lib.Z3_mk_fpa_is_positive.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_to_fp_bv.restype = Ast _lib.Z3_mk_fpa_to_fp_bv.argtypes = [ContextObj, Ast, Sort] _lib.Z3_mk_fpa_to_fp_float.restype = Ast _lib.Z3_mk_fpa_to_fp_float.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_real.restype = Ast _lib.Z3_mk_fpa_to_fp_real.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_signed.restype = Ast _lib.Z3_mk_fpa_to_fp_signed.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_unsigned.restype = Ast _lib.Z3_mk_fpa_to_fp_unsigned.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_ubv.restype = Ast _lib.Z3_mk_fpa_to_ubv.argtypes = [ContextObj, Ast, Ast, ctypes.c_uint] _lib.Z3_mk_fpa_to_sbv.restype = Ast _lib.Z3_mk_fpa_to_sbv.argtypes = [ContextObj, Ast, Ast, ctypes.c_uint] _lib.Z3_mk_fpa_to_real.restype = Ast _lib.Z3_mk_fpa_to_real.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_ebits.restype = ctypes.c_uint _lib.Z3_fpa_get_ebits.argtypes = [ContextObj, Sort] _lib.Z3_fpa_get_sbits.restype = ctypes.c_uint _lib.Z3_fpa_get_sbits.argtypes = [ContextObj, Sort] _lib.Z3_fpa_is_numeral_nan.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_nan.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_inf.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_inf.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_zero.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_zero.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_normal.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_normal.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_subnormal.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_subnormal.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_positive.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_positive.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_negative.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_negative.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_sign_bv.restype = Ast _lib.Z3_fpa_get_numeral_sign_bv.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_significand_bv.restype = Ast _lib.Z3_fpa_get_numeral_significand_bv.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_sign.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_sign.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_int)] _lib.Z3_fpa_get_numeral_significand_string.restype = ctypes.c_char_p _lib.Z3_fpa_get_numeral_significand_string.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_significand_uint64.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_significand_uint64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_fpa_get_numeral_exponent_string.restype = ctypes.c_char_p _lib.Z3_fpa_get_numeral_exponent_string.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_fpa_get_numeral_exponent_int64.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_exponent_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.c_bool] _lib.Z3_fpa_get_numeral_exponent_bv.restype = Ast _lib.Z3_fpa_get_numeral_exponent_bv.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_mk_fpa_to_ieee_bv.restype = Ast _lib.Z3_mk_fpa_to_ieee_bv.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_to_fp_int_real.restype = Ast _lib.Z3_mk_fpa_to_fp_int_real.argtypes = [ContextObj, Ast, Ast, Ast, Sort] _lib.Z3_fixedpoint_query_from_lvl.restype = ctypes.c_int _lib.Z3_fixedpoint_query_from_lvl.argtypes = [ContextObj, FixedpointObj, Ast, ctypes.c_uint] _lib.Z3_fixedpoint_get_ground_sat_answer.restype = Ast _lib.Z3_fixedpoint_get_ground_sat_answer.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_rules_along_trace.restype = AstVectorObj _lib.Z3_fixedpoint_get_rules_along_trace.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_rule_names_along_trace.restype = Symbol _lib.Z3_fixedpoint_get_rule_names_along_trace.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_add_invariant.argtypes = [ContextObj, FixedpointObj, FuncDecl, Ast] _lib.Z3_fixedpoint_get_reachable.restype = Ast _lib.Z3_fixedpoint_get_reachable.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_qe_model_project.restype = Ast _lib.Z3_qe_model_project.argtypes = [ContextObj, Model, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_qe_model_project_skolem.restype = Ast _lib.Z3_qe_model_project_skolem.argtypes = [ContextObj, Model, ctypes.c_uint, ctypes.POINTER(Ast), Ast, AstMapObj] _lib.Z3_model_extrapolate.restype = Ast _lib.Z3_model_extrapolate.argtypes = [ContextObj, Model, Ast] _lib.Z3_qe_lite.restype = Ast _lib.Z3_qe_lite.argtypes = [ContextObj, AstVectorObj, Ast] class Elementaries: def __init__(self, f): self.f = f self.get_error_code = _lib.Z3_get_error_code self.get_error_message = _lib.Z3_get_error_msg self.OK = Z3_OK self.Exception = Z3Exception def Check(self, ctx): err = self.get_error_code(ctx) if err != self.OK: raise self.Exception(self.get_error_message(ctx, err)) def Z3_set_error_handler(ctx, hndlr, _elems=Elementaries(_lib.Z3_set_error_handler)): ceh = _error_handler_type(hndlr) _elems.f(ctx, ceh) _elems.Check(ctx) return ceh def Z3_global_param_set(a0, a1, _elems=Elementaries(_lib.Z3_global_param_set)): _elems.f(_to_ascii(a0), _to_ascii(a1)) def Z3_global_param_reset_all(_elems=Elementaries(_lib.Z3_global_param_reset_all)): _elems.f() def Z3_global_param_get(a0, a1, _elems=Elementaries(_lib.Z3_global_param_get)): r = _elems.f(_to_ascii(a0), _to_ascii(a1)) return r def Z3_mk_config(_elems=Elementaries(_lib.Z3_mk_config)): r = _elems.f() return r def Z3_del_config(a0, _elems=Elementaries(_lib.Z3_del_config)): _elems.f(a0) def Z3_set_param_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_set_param_value)): _elems.f(a0, _to_ascii(a1), _to_ascii(a2)) def Z3_mk_context(a0, _elems=Elementaries(_lib.Z3_mk_context)): r = _elems.f(a0) return r def Z3_mk_context_rc(a0, _elems=Elementaries(_lib.Z3_mk_context_rc)): r = _elems.f(a0) return r def Z3_del_context(a0, _elems=Elementaries(_lib.Z3_del_context)): _elems.f(a0) def Z3_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_update_param_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_update_param_value)): _elems.f(a0, _to_ascii(a1), _to_ascii(a2)) _elems.Check(a0) def Z3_interrupt(a0, _elems=Elementaries(_lib.Z3_interrupt)): _elems.f(a0) _elems.Check(a0) def Z3_mk_params(a0, _elems=Elementaries(_lib.Z3_mk_params)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_params_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_params_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_params_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_params_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_params_set_bool(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_bool)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_uint(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_uint)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_double(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_double)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_symbol(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_symbol)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_to_string(a0, a1, _elems=Elementaries(_lib.Z3_params_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_params_validate(a0, a1, a2, _elems=Elementaries(_lib.Z3_params_validate)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_param_descrs_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_param_descrs_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_param_descrs_get_kind(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_kind)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_param_descrs_size(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_param_descrs_get_name(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_name)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_param_descrs_get_documentation(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_documentation)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_param_descrs_to_string(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_mk_int_symbol(a0, a1, _elems=Elementaries(_lib.Z3_mk_int_symbol)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string_symbol(a0, a1, _elems=Elementaries(_lib.Z3_mk_string_symbol)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return r def Z3_mk_uninterpreted_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_uninterpreted_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bool_sort(a0, _elems=Elementaries(_lib.Z3_mk_bool_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_int_sort(a0, _elems=Elementaries(_lib.Z3_mk_int_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_real_sort(a0, _elems=Elementaries(_lib.Z3_mk_real_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_bv_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_bv_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_finite_domain_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_finite_domain_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_array_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_sort_n(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_array_sort_n)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_tuple_sort(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_tuple_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_enumeration_sort(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_mk_enumeration_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) return r def Z3_mk_list_sort(a0, a1, a2, a3, a4, a5, a6, a7, a8, _elems=Elementaries(_lib.Z3_mk_list_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8) _elems.Check(a0) return r def Z3_mk_constructor(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_constructor)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_del_constructor(a0, a1, _elems=Elementaries(_lib.Z3_del_constructor)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_datatype(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_datatype)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_constructor_list(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_constructor_list)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_del_constructor_list(a0, a1, _elems=Elementaries(_lib.Z3_del_constructor_list)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_datatypes(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_datatypes)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_query_constructor(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_query_constructor)): _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) def Z3_mk_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_func_decl)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_app(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_app)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_const(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_const)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fresh_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fresh_func_decl)): r = _elems.f(a0, _to_ascii(a1), a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fresh_const(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fresh_const)): r = _elems.f(a0, _to_ascii(a1), a2) _elems.Check(a0) return r def Z3_mk_rec_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_rec_func_decl)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_add_rec_def(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_add_rec_def)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_mk_true(a0, _elems=Elementaries(_lib.Z3_mk_true)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_false(a0, _elems=Elementaries(_lib.Z3_mk_false)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_distinct(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_distinct)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_not(a0, a1, _elems=Elementaries(_lib.Z3_mk_not)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_ite(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_ite)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_iff(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_iff)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_implies(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_implies)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_xor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_xor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_and(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_and)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unary_minus(a0, a1, _elems=Elementaries(_lib.Z3_mk_unary_minus)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_mod(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_mod)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int2real(a0, a1, _elems=Elementaries(_lib.Z3_mk_int2real)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_real2int(a0, a1, _elems=Elementaries(_lib.Z3_mk_real2int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_is_int(a0, a1, _elems=Elementaries(_lib.Z3_mk_is_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvnot(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvnot)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvredand(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvredand)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvredor(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvredor)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvand(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvand)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvxor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvxor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvnand(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvnand)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvnor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvnor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvxnor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvxnor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvneg(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvneg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvadd(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvadd)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvmul(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvmul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvudiv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvudiv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsdiv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsdiv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvurem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvurem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsrem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsrem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsmod(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsmod)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvult(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvult)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvslt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvslt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvule(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvule)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsle(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsle)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvuge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvuge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvugt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvugt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsgt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsgt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_extract(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_extract)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_sign_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_sign_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_zero_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_zero_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_repeat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_repeat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvshl(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvshl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvlshr(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvlshr)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvashr(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvashr)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rotate_left(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rotate_left)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rotate_right(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rotate_right)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ext_rotate_left(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ext_rotate_left)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ext_rotate_right(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ext_rotate_right)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int2bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int2bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bv2int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bv2int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvadd_no_overflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvadd_no_overflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvadd_no_underflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvadd_no_underflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub_no_overflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsub_no_overflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub_no_underflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvsub_no_underflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvsdiv_no_overflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsdiv_no_overflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvneg_no_overflow(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvneg_no_overflow)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvmul_no_overflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvmul_no_overflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvmul_no_underflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvmul_no_underflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_select(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_select)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_select_n(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_select_n)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_store(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_store)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_store_n(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_store_n)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_const_array(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_const_array)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_map(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_map)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_array_default(a0, a1, _elems=Elementaries(_lib.Z3_mk_array_default)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_as_array(a0, a1, _elems=Elementaries(_lib.Z3_mk_as_array)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_set_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_empty_set(a0, a1, _elems=Elementaries(_lib.Z3_mk_empty_set)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_full_set(a0, a1, _elems=Elementaries(_lib.Z3_mk_full_set)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_del(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_del)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_union(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_union)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_intersect(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_intersect)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_difference(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_difference)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_complement(a0, a1, _elems=Elementaries(_lib.Z3_mk_set_complement)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_member(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_member)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_subset(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_subset)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_array_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_numeral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_numeral)): r = _elems.f(a0, _to_ascii(a1), a2) _elems.Check(a0) return r def Z3_mk_real(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_real)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unsigned_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_unsigned_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unsigned_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_unsigned_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bv_numeral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bv_numeral)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_seq_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_seq_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_re_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_re_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string_sort(a0, _elems=Elementaries(_lib.Z3_mk_string_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_is_string_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_string_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string(a0, a1, _elems=Elementaries(_lib.Z3_mk_string)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return r def Z3_is_string(a0, a1, _elems=Elementaries(_lib.Z3_is_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_string(a0, a1, _elems=Elementaries(_lib.Z3_get_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_mk_seq_empty(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_empty)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_unit(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_unit)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_prefix(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_prefix)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_suffix(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_suffix)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_contains(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_contains)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_extract(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_extract)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_seq_replace(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_replace)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_seq_at(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_at)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_length(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_length)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_index(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_index)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_str_to_int(a0, a1, _elems=Elementaries(_lib.Z3_mk_str_to_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_int_to_str(a0, a1, _elems=Elementaries(_lib.Z3_mk_int_to_str)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_to_re(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_to_re)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_in_re(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_in_re)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_plus(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_plus)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_star(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_star)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_option(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_option)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_union(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_union)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_range(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_range)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_loop(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_re_loop)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_re_intersect(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_intersect)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_complement(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_complement)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_empty(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_empty)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_full(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_full)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_pattern(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_pattern)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bound(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bound)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_forall(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_forall)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_exists(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_exists)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_quantifier(a0, a1, a2, a3, a4, a5, a6, a7, a8, _elems=Elementaries(_lib.Z3_mk_quantifier)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8) _elems.Check(a0) return r def Z3_mk_quantifier_ex(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, _elems=Elementaries(_lib.Z3_mk_quantifier_ex)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) _elems.Check(a0) return r def Z3_mk_forall_const(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_forall_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_exists_const(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_exists_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_quantifier_const(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_quantifier_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_quantifier_const_ex(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, _elems=Elementaries(_lib.Z3_mk_quantifier_const_ex)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) _elems.Check(a0) return r def Z3_mk_lambda(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_lambda)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_lambda_const(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_lambda_const)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_symbol_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_symbol_int(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_symbol_string(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_sort_name(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_sort_id(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_sort_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_sort_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_eq_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_sort_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_bv_sort_size(a0, a1, _elems=Elementaries(_lib.Z3_get_bv_sort_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_finite_domain_sort_size(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_finite_domain_sort_size)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_array_sort_domain(a0, a1, _elems=Elementaries(_lib.Z3_get_array_sort_domain)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_array_sort_range(a0, a1, _elems=Elementaries(_lib.Z3_get_array_sort_range)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_mk_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_tuple_sort_mk_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_num_fields(a0, a1, _elems=Elementaries(_lib.Z3_get_tuple_sort_num_fields)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_field_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_tuple_sort_field_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_num_constructors(a0, a1, _elems=Elementaries(_lib.Z3_get_datatype_sort_num_constructors)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_datatype_sort_constructor(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_datatype_sort_constructor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_recognizer(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_datatype_sort_recognizer)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_constructor_accessor(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_datatype_sort_constructor_accessor)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_datatype_update_field(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_datatype_update_field)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_relation_arity(a0, a1, _elems=Elementaries(_lib.Z3_get_relation_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_relation_column(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_relation_column)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_atmost(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_atmost)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_atleast(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_atleast)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_pble(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pble)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_pbge(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pbge)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_pbeq(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pbeq)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_func_decl_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_func_decl_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_eq_func_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_func_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_func_decl_id(a0, a1, _elems=Elementaries(_lib.Z3_get_func_decl_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_name(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_domain_size(a0, a1, _elems=Elementaries(_lib.Z3_get_domain_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_arity(a0, a1, _elems=Elementaries(_lib.Z3_get_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_domain(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_domain)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_range(a0, a1, _elems=Elementaries(_lib.Z3_get_range)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_num_parameters(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_num_parameters)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_parameter_kind(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_parameter_kind)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_int_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_int_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_double_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_double_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_symbol_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_symbol_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_sort_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_sort_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_ast_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_ast_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_func_decl_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_func_decl_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_rational_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_rational_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_app_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_app_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_app_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_num_args(a0, a1, _elems=Elementaries(_lib.Z3_get_app_num_args)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_arg(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_app_arg)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_is_eq_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_ast_id(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_ast_hash(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_hash)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_sort(a0, a1, _elems=Elementaries(_lib.Z3_get_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_well_sorted(a0, a1, _elems=Elementaries(_lib.Z3_is_well_sorted)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_bool_value(a0, a1, _elems=Elementaries(_lib.Z3_get_bool_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_ast_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_app(a0, a1, _elems=Elementaries(_lib.Z3_is_app)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_numeral_ast(a0, a1, _elems=Elementaries(_lib.Z3_is_numeral_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_algebraic_number(a0, a1, _elems=Elementaries(_lib.Z3_is_algebraic_number)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_to_app(a0, a1, _elems=Elementaries(_lib.Z3_to_app)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_to_func_decl(a0, a1, _elems=Elementaries(_lib.Z3_to_func_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numeral_string(a0, a1, _elems=Elementaries(_lib.Z3_get_numeral_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_numeral_decimal_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_get_numeral_double(a0, a1, _elems=Elementaries(_lib.Z3_get_numeral_double)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numerator(a0, a1, _elems=Elementaries(_lib.Z3_get_numerator)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_denominator(a0, a1, _elems=Elementaries(_lib.Z3_get_denominator)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numeral_small(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_numeral_small)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_numeral_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_uint(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_uint)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_uint64(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_uint64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_rational_int64(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_numeral_rational_int64)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_algebraic_number_lower(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_algebraic_number_lower)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_algebraic_number_upper(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_algebraic_number_upper)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_pattern_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_pattern_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_pattern_num_terms(a0, a1, _elems=Elementaries(_lib.Z3_get_pattern_num_terms)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_pattern(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_pattern)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_index_value(a0, a1, _elems=Elementaries(_lib.Z3_get_index_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_quantifier_forall(a0, a1, _elems=Elementaries(_lib.Z3_is_quantifier_forall)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_quantifier_exists(a0, a1, _elems=Elementaries(_lib.Z3_is_quantifier_exists)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_lambda(a0, a1, _elems=Elementaries(_lib.Z3_is_lambda)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_weight(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_weight)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_num_patterns(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_patterns)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_pattern_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_pattern_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_num_no_patterns(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_no_patterns)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_no_pattern_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_no_pattern_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_num_bound(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_bound)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_bound_name(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_bound_name)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_bound_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_bound_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_body(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_body)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_simplify(a0, a1, _elems=Elementaries(_lib.Z3_simplify)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_simplify_ex(a0, a1, a2, _elems=Elementaries(_lib.Z3_simplify_ex)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_simplify_get_help(a0, _elems=Elementaries(_lib.Z3_simplify_get_help)): r = _elems.f(a0) _elems.Check(a0) return _to_pystr(r) def Z3_simplify_get_param_descrs(a0, _elems=Elementaries(_lib.Z3_simplify_get_param_descrs)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_update_term(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_update_term)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_substitute(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_substitute)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_substitute_vars(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_substitute_vars)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_model(a0, _elems=Elementaries(_lib.Z3_mk_model)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_model_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_model_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_model_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_model_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_model_eval(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_model_eval)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_model_get_const_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_const_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_has_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_has_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_func_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_func_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_consts(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_consts)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_const_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_const_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_funcs(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_funcs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_func_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_func_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_sorts(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_sorts)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_sort_universe(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_sort_universe)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_is_as_array(a0, a1, _elems=Elementaries(_lib.Z3_is_as_array)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_as_array_func_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_as_array_func_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_add_func_interp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_add_func_interp)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_add_const_interp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_add_const_interp)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_func_interp_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_interp_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_interp_get_num_entries(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_num_entries)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_get_entry(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_interp_get_entry)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_func_interp_get_else(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_else)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_set_else(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_interp_set_else)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_func_interp_get_arity(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_add_entry(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_func_interp_add_entry)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_func_entry_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_entry_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_entry_get_value(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_get_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_entry_get_num_args(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_get_num_args)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_entry_get_arg(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_entry_get_arg)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_open_log(a0, _elems=Elementaries(_lib.Z3_open_log)): r = _elems.f(_to_ascii(a0)) return r def Z3_append_log(a0, _elems=Elementaries(_lib.Z3_append_log)): _elems.f(_to_ascii(a0)) def Z3_close_log(_elems=Elementaries(_lib.Z3_close_log)): _elems.f() def Z3_toggle_warning_messages(a0, _elems=Elementaries(_lib.Z3_toggle_warning_messages)): _elems.f(a0) def Z3_set_ast_print_mode(a0, a1, _elems=Elementaries(_lib.Z3_set_ast_print_mode)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_pattern_to_string(a0, a1, _elems=Elementaries(_lib.Z3_pattern_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_sort_to_string(a0, a1, _elems=Elementaries(_lib.Z3_sort_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_func_decl_to_string(a0, a1, _elems=Elementaries(_lib.Z3_func_decl_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_model_to_string(a0, a1, _elems=Elementaries(_lib.Z3_model_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_benchmark_to_smtlib_string(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_benchmark_to_smtlib_string)): r = _elems.f(a0, _to_ascii(a1), _to_ascii(a2), _to_ascii(a3), _to_ascii(a4), a5, a6, a7) _elems.Check(a0) return _to_pystr(r) def Z3_parse_smtlib2_string(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_parse_smtlib2_string)): r = _elems.f(a0, _to_ascii(a1), a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_parse_smtlib2_file(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_parse_smtlib2_file)): r = _elems.f(a0, _to_ascii(a1), a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_eval_smtlib2_string(a0, a1, _elems=Elementaries(_lib.Z3_eval_smtlib2_string)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_get_error_code(a0, _elems=Elementaries(_lib.Z3_get_error_code)): r = _elems.f(a0) return r def Z3_set_error(a0, a1, _elems=Elementaries(_lib.Z3_set_error)): _elems.f(a0, a1) _elems.Check(a0) def Z3_get_error_msg(a0, a1, _elems=Elementaries(_lib.Z3_get_error_msg)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_version(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_version)): _elems.f(a0, a1, a2, a3) def Z3_get_full_version(_elems=Elementaries(_lib.Z3_get_full_version)): r = _elems.f() return _to_pystr(r) def Z3_enable_trace(a0, _elems=Elementaries(_lib.Z3_enable_trace)): _elems.f(_to_ascii(a0)) def Z3_disable_trace(a0, _elems=Elementaries(_lib.Z3_disable_trace)): _elems.f(_to_ascii(a0)) def Z3_reset_memory(_elems=Elementaries(_lib.Z3_reset_memory)): _elems.f() def Z3_finalize_memory(_elems=Elementaries(_lib.Z3_finalize_memory)): _elems.f() def Z3_mk_goal(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_goal)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_goal_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_goal_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_goal_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_precision(a0, a1, _elems=Elementaries(_lib.Z3_goal_precision)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_goal_inconsistent(a0, a1, _elems=Elementaries(_lib.Z3_goal_inconsistent)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_depth(a0, a1, _elems=Elementaries(_lib.Z3_goal_depth)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_reset(a0, a1, _elems=Elementaries(_lib.Z3_goal_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_size(a0, a1, _elems=Elementaries(_lib.Z3_goal_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_formula(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_formula)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_num_exprs(a0, a1, _elems=Elementaries(_lib.Z3_goal_num_exprs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_is_decided_sat(a0, a1, _elems=Elementaries(_lib.Z3_goal_is_decided_sat)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_is_decided_unsat(a0, a1, _elems=Elementaries(_lib.Z3_goal_is_decided_unsat)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_convert_model(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_convert_model)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_to_string(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_goal_to_dimacs_string(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_dimacs_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_mk_tactic(a0, a1, _elems=Elementaries(_lib.Z3_mk_tactic)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return r def Z3_tactic_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_tactic_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_tactic_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_tactic_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_probe(a0, a1, _elems=Elementaries(_lib.Z3_mk_probe)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return r def Z3_probe_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_probe_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_probe_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_probe_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_tactic_and_then(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_and_then)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_or_else(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_or_else)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_par_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_par_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_par_and_then(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_par_and_then)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_try_for(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_try_for)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_when(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_when)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_cond(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_tactic_cond)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_tactic_repeat(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_repeat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_skip(a0, _elems=Elementaries(_lib.Z3_tactic_skip)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_fail(a0, _elems=Elementaries(_lib.Z3_tactic_fail)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_fail_if(a0, a1, _elems=Elementaries(_lib.Z3_tactic_fail_if)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_fail_if_not_decided(a0, _elems=Elementaries(_lib.Z3_tactic_fail_if_not_decided)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_using_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_using_params)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_const(a0, a1, _elems=Elementaries(_lib.Z3_probe_const)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_probe_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_and(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_and)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_not(a0, a1, _elems=Elementaries(_lib.Z3_probe_not)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_num_tactics(a0, _elems=Elementaries(_lib.Z3_get_num_tactics)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_get_tactic_name(a0, a1, _elems=Elementaries(_lib.Z3_get_tactic_name)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_num_probes(a0, _elems=Elementaries(_lib.Z3_get_num_probes)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_get_probe_name(a0, a1, _elems=Elementaries(_lib.Z3_get_probe_name)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_tactic_get_help(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_tactic_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_get_descr(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_descr)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_probe_get_descr(a0, a1, _elems=Elementaries(_lib.Z3_probe_get_descr)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_probe_apply(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_apply)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_apply(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_apply)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_apply_ex(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_tactic_apply_ex)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_apply_result_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_apply_result_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_apply_result_to_string(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_apply_result_get_num_subgoals(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_get_num_subgoals)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_apply_result_get_subgoal(a0, a1, a2, _elems=Elementaries(_lib.Z3_apply_result_get_subgoal)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_solver(a0, _elems=Elementaries(_lib.Z3_mk_solver)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_simple_solver(a0, _elems=Elementaries(_lib.Z3_mk_simple_solver)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_solver_for_logic(a0, a1, _elems=Elementaries(_lib.Z3_mk_solver_for_logic)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_solver_from_tactic(a0, a1, _elems=Elementaries(_lib.Z3_mk_solver_from_tactic)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_solver_import_model_converter(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_import_model_converter)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_get_help(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_solver_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_solver_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_push(a0, a1, _elems=Elementaries(_lib.Z3_solver_push)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_pop(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_pop)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_reset(a0, a1, _elems=Elementaries(_lib.Z3_solver_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_get_num_scopes(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_num_scopes)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_assert_and_track(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_assert_and_track)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_solver_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_from_file)): _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) def Z3_solver_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_from_string)): _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) def Z3_solver_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_units(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_units)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_non_units(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_non_units)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_check(a0, a1, _elems=Elementaries(_lib.Z3_solver_check)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_check_assumptions(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_check_assumptions)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_implied_equalities(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_get_implied_equalities)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_solver_get_consequences(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_solver_get_consequences)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_solver_cube(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_cube)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_solver_get_model(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_model)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_proof(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_proof)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_unsat_core(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_unsat_core)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_to_string(a0, a1, _elems=Elementaries(_lib.Z3_solver_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_to_dimacs_string(a0, a1, _elems=Elementaries(_lib.Z3_solver_to_dimacs_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_stats_to_string(a0, a1, _elems=Elementaries(_lib.Z3_stats_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_stats_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_stats_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_stats_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_stats_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_stats_size(a0, a1, _elems=Elementaries(_lib.Z3_stats_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_stats_get_key(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_key)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_stats_is_uint(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_is_uint)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_is_double(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_is_double)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_get_uint_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_uint_value)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_get_double_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_double_value)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_estimated_alloc_size(_elems=Elementaries(_lib.Z3_get_estimated_alloc_size)): r = _elems.f() return r def Z3_mk_ast_vector(a0, _elems=Elementaries(_lib.Z3_mk_ast_vector)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_ast_vector_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_vector_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_vector_size(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_vector_get(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_get)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_vector_set(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_ast_vector_set)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_ast_vector_resize(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_resize)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_vector_push(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_push)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_vector_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_vector_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_mk_ast_map(a0, _elems=Elementaries(_lib.Z3_mk_ast_map)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_ast_map_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_contains(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_contains)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_map_find(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_find)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_map_insert(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_ast_map_insert)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_ast_map_erase(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_erase)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_map_reset(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_size(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_map_keys(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_keys)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_map_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_algebraic_is_value(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_pos(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_pos)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_neg(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_zero(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_sign(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_sign)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_root(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_root)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_neq(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_neq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_roots(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_algebraic_roots)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_algebraic_eval(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_algebraic_eval)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_polynomial_subresultants(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_polynomial_subresultants)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_rcf_del(a0, a1, _elems=Elementaries(_lib.Z3_rcf_del)): _elems.f(a0, a1) _elems.Check(a0) def Z3_rcf_mk_rational(a0, a1, _elems=Elementaries(_lib.Z3_rcf_mk_rational)): r = _elems.f(a0, _to_ascii(a1)) _elems.Check(a0) return r def Z3_rcf_mk_small_int(a0, a1, _elems=Elementaries(_lib.Z3_rcf_mk_small_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_mk_pi(a0, _elems=Elementaries(_lib.Z3_rcf_mk_pi)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_e(a0, _elems=Elementaries(_lib.Z3_rcf_mk_e)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_infinitesimal(a0, _elems=Elementaries(_lib.Z3_rcf_mk_infinitesimal)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_roots(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_mk_roots)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_rcf_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_neg(a0, a1, _elems=Elementaries(_lib.Z3_rcf_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_inv(a0, a1, _elems=Elementaries(_lib.Z3_rcf_inv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_neq(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_neq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_num_to_string(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_num_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return _to_pystr(r) def Z3_rcf_num_to_decimal_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_num_to_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_rcf_get_numerator_denominator(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_get_numerator_denominator)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_mk_fixedpoint(a0, _elems=Elementaries(_lib.Z3_mk_fixedpoint)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_fixedpoint_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_fixedpoint_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_fixedpoint_add_rule(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_add_rule)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_add_fact(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_add_fact)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_query(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_query)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fixedpoint_query_relations(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_query_relations)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_get_answer(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_answer)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_update_rule(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_update_rule)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_get_num_levels(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_get_num_levels)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fixedpoint_get_cover_delta(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_get_cover_delta)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_add_cover(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_add_cover)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_register_relation(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_register_relation)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_set_predicate_representation(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_set_predicate_representation)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_get_rules(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rules)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_get_help(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_to_string(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_from_string)): r = _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) return r def Z3_fixedpoint_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_from_file)): r = _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) return r def Z3_fixedpoint_push(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_push)): _elems.f(a0, a1) _elems.Check(a0) def Z3_fixedpoint_pop(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_pop)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_optimize(a0, _elems=Elementaries(_lib.Z3_mk_optimize)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_optimize_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_optimize_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_optimize_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_optimize_assert_soft(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_optimize_assert_soft)): r = _elems.f(a0, a1, a2, _to_ascii(a3), a4) _elems.Check(a0) return r def Z3_optimize_maximize(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_maximize)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_minimize(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_minimize)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_push(a0, a1, _elems=Elementaries(_lib.Z3_optimize_push)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_pop(a0, a1, _elems=Elementaries(_lib.Z3_optimize_pop)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_check(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_optimize_check)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_optimize_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_get_model(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_model)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_unsat_core(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_unsat_core)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_optimize_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_lower(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_lower)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_upper(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_upper)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_lower_as_vector(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_lower_as_vector)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_upper_as_vector(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_upper_as_vector)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_to_string(a0, a1, _elems=Elementaries(_lib.Z3_optimize_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_from_string)): _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) def Z3_optimize_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_from_file)): _elems.f(a0, a1, _to_ascii(a2)) _elems.Check(a0) def Z3_optimize_get_help(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_objectives(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_objectives)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_rounding_mode_sort(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rounding_mode_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_nearest_ties_to_even(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_nearest_ties_to_even)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rne(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rne)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_nearest_ties_to_away(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_nearest_ties_to_away)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rna(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rna)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_positive(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_positive)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtp(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtp)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_negative(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_negative)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtn(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtn)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_zero(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_zero)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtz(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtz)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_sort_half(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_half)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_16(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_16)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_single(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_single)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_32(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_32)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_double(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_double)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_64(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_64)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_quadruple(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_quadruple)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_128(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_128)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_nan(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_inf(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_inf)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_zero(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_zero)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_fp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_fp)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_numeral_float(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_float)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_double(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_double)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int_uint(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int_uint)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int64_uint64(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int64_uint64)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_abs(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_abs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_neg(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_add(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_add)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_sub(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_sub)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_mul(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_mul)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_div(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_div)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_fma(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_fma)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_sqrt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_sqrt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_rem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_rem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_round_to_integral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_round_to_integral)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_min(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_min)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_max(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_max)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_leq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_leq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_geq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_geq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_is_normal(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_normal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_subnormal(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_subnormal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_zero(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_infinite(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_infinite)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_nan(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_negative(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_negative)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_positive(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_positive)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_float(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_float)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_real(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_real)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_signed(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_signed)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_unsigned(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_unsigned)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_ubv(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_ubv)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_sbv(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_sbv)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_real(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_to_real)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_ebits(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_ebits)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_sbits(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_sbits)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_nan(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_inf(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_inf)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_zero(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_normal(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_normal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_subnormal(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_subnormal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_positive(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_positive)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_negative(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_negative)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_sign_bv(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_sign_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_significand_bv(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_sign(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_sign)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fpa_get_numeral_significand_string(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fpa_get_numeral_significand_uint64(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_uint64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fpa_get_numeral_exponent_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_fpa_get_numeral_exponent_int64(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_int64)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fpa_get_numeral_exponent_bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_to_ieee_bv(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_to_ieee_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_int_real(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_int_real)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_fixedpoint_query_from_lvl(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_query_from_lvl)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_get_ground_sat_answer(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_ground_sat_answer)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_rules_along_trace(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rules_along_trace)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_rule_names_along_trace(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rule_names_along_trace)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_add_invariant(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_add_invariant)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_get_reachable(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_get_reachable)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_qe_model_project(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_qe_model_project)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_qe_model_project_skolem(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_qe_model_project_skolem)): r = _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) return r def Z3_model_extrapolate(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_extrapolate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_qe_lite(a0, a1, a2, _elems=Elementaries(_lib.Z3_qe_lite)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r # Clean up del _lib del _default_dirs del _all_dirs del _ext
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3core.py
z3core.py
from . import z3core from .z3core import * from .z3types import * from .z3consts import * from .z3printer import * from fractions import Fraction import sys import io import math import copy if sys.version < '3': def _is_int(v): return isinstance(v, (int, long)) else: def _is_int(v): return isinstance(v, int) def enable_trace(msg): Z3_enable_trace(msg) def disable_trace(msg): Z3_disable_trace(msg) def get_version_string(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return "%s.%s.%s" % (major.value, minor.value, build.value) def get_version(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return (major.value, minor.value, build.value, rev.value) def get_full_version(): return Z3_get_full_version() # We use _z3_assert instead of the assert command because we want to # produce nice error messages in Z3Py at rise4fun.com def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) def _z3_check_cint_overflow(n, name): _z3_assert(ctypes.c_int(n).value == n, name + " is too large") def open_log(fname): """Log interaction to a file. This function must be invoked immediately after init(). """ Z3_open_log(fname) def append_log(s): """Append user-defined string to interaction log. """ Z3_append_log(s) def to_symbol(s, ctx=None): """Convert an integer or string into a Z3 symbol.""" if _is_int(s): return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s) else: return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s) def _symbol2py(ctx, s): """Convert a Z3 symbol back into a Python object. """ if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL: return "k!%s" % Z3_get_symbol_int(ctx.ref(), s) else: return Z3_get_symbol_string(ctx.ref(), s) # Hack for having nary functions that can receive one argument that is the # list of arguments. # Use this when function takes a single list of arguments def _get_args(args): try: if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): return args[0] elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)): return [arg for arg in args[0]] else: return args except: # len is not necessarily defined when args is not a sequence (use reflection?) return args # Use this when function takes multiple arguments def _get_args_ast_list(args): try: if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple): return [arg for arg in args] else: return args except: return args def _to_param_value(val): if isinstance(val, bool): if val == True: return "true" else: return "false" else: return str(val) def z3_error_handler(c, e): # Do nothing error handler, just avoid exit(0) # The wrappers in z3core.py will raise a Z3Exception if an error is detected return class Context: """A Context manages all other Z3 objects, global configuration options, etc. Z3Py uses a default global context. For most applications this is sufficient. An application may use multiple Z3 contexts. Objects created in one context cannot be used in another one. However, several objects may be "translated" from one context to another. It is not safe to access Z3 objects from multiple threads. The only exception is the method `interrupt()` that can be used to interrupt() a long computation. The initialization method receives global configuration options for the new context. """ def __init__(self, *args, **kws): if __debug__: _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") conf = Z3_mk_config() for key in kws: value = kws[key] Z3_set_param_value(conf, str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_set_param_value(conf, str(prev), _to_param_value(a)) prev = None self.ctx = Z3_mk_context_rc(conf) self.eh = Z3_set_error_handler(self.ctx, z3_error_handler) Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT) Z3_del_config(conf) def __del__(self): Z3_del_context(self.ctx) self.ctx = None self.eh = None def ref(self): """Return a reference to the actual C pointer to the Z3 context.""" return self.ctx def interrupt(self): """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions. This method can be invoked from a thread different from the one executing the interruptible procedure. """ Z3_interrupt(self.ref()) # Global Z3 context _main_ctx = None def main_ctx(): """Return a reference to the global Z3 context. >>> x = Real('x') >>> x.ctx == main_ctx() True >>> c = Context() >>> c == main_ctx() False >>> x2 = Real('x', c) >>> x2.ctx == c True >>> eq(x, x2) False """ global _main_ctx if _main_ctx is None: _main_ctx = Context() return _main_ctx def _get_ctx(ctx): if ctx is None: return main_ctx() else: return ctx def set_param(*args, **kws): """Set Z3 global (or module) parameters. >>> set_param(precision=10) """ if __debug__: _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") new_kws = {} for k in kws: v = kws[k] if not set_pp_option(k, v): new_kws[k] = v for key in new_kws: value = new_kws[key] Z3_global_param_set(str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_global_param_set(str(prev), _to_param_value(a)) prev = None def reset_params(): """Reset all global (or module) parameters. """ Z3_global_param_reset_all() def set_option(*args, **kws): """Alias for 'set_param' for backward compatibility. """ return set_param(*args, **kws) def get_param(name): """Return the value of a Z3 global (or module) parameter >>> get_param('nlsat.reorder') 'true' """ ptr = (ctypes.c_char_p * 1)() if Z3_global_param_get(str(name), ptr): r = z3core._to_pystr(ptr[0]) return r raise Z3Exception("failed to retrieve value for '%s'" % name) ######################################### # # ASTs base class # ######################################### # Mark objects that use pretty printer class Z3PPObject: """Superclass for all Z3 objects that have support for pretty printing.""" def use_pp(self): return True class AstRef(Z3PPObject): """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions.""" def __init__(self, ast, ctx=None): self.ast = ast self.ctx = _get_ctx(ctx) Z3_inc_ref(self.ctx.ref(), self.as_ast()) def __del__(self): if self.ctx.ref() is not None: Z3_dec_ref(self.ctx.ref(), self.as_ast()) def __deepcopy__(self, memo={}): return _to_ast_ref(self.ast, self.ctx) def __str__(self): return obj_to_string(self) def __repr__(self): return obj_to_string(self) def __eq__(self, other): return self.eq(other) def __hash__(self): return self.hash() def __nonzero__(self): return self.__bool__() def __bool__(self): if is_true(self): return True elif is_false(self): return False elif is_eq(self) and self.num_args() == 2: return self.arg(0).eq(self.arg(1)) else: raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.") def sexpr(self): """Return a string representing the AST node in s-expression notation. >>> x = Int('x') >>> ((x + 1)*x).sexpr() '(* (+ x 1) x)' """ return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): """Return a pointer to the corresponding C Z3_ast object.""" return self.ast def get_id(self): """Return unique identifier for object. It can be used for hash-tables and maps.""" return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def ctx_ref(self): """Return a reference to the C context where this AST node is stored.""" return self.ctx.ref() def eq(self, other): """Return `True` if `self` and `other` are structurally identical. >>> x = Int('x') >>> n1 = x + 1 >>> n2 = 1 + x >>> n1.eq(n2) False >>> n1 = simplify(n1) >>> n2 = simplify(n2) >>> n1.eq(n2) True """ if __debug__: _z3_assert(is_ast(other), "Z3 AST expected") return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast()) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> x = Int('x', c1) >>> y = Int('y', c2) >>> # Nodes in different contexts can't be mixed. >>> # However, we can translate nodes from one context to another. >>> x.translate(c2) + y x + y """ if __debug__: _z3_assert(isinstance(target, Context), "argument must be a Z3 context") return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target) def __copy__(self): return self.translate(self.ctx) def hash(self): """Return a hashcode for the `self`. >>> n1 = simplify(Int('x') + 1) >>> n2 = simplify(2 + Int('x') - 1) >>> n1.hash() == n2.hash() True """ return Z3_get_ast_hash(self.ctx_ref(), self.as_ast()) def is_ast(a): """Return `True` if `a` is an AST node. >>> is_ast(10) False >>> is_ast(IntVal(10)) True >>> is_ast(Int('x')) True >>> is_ast(BoolSort()) True >>> is_ast(Function('f', IntSort(), IntSort())) True >>> is_ast("x") False >>> is_ast(Solver()) False """ return isinstance(a, AstRef) def eq(a, b): """Return `True` if `a` and `b` are structurally identical AST nodes. >>> x = Int('x') >>> y = Int('y') >>> eq(x, y) False >>> eq(x + 1, x + 1) True >>> eq(x + 1, 1 + x) False >>> eq(simplify(x + 1), simplify(1 + x)) True """ if __debug__: _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected") return a.eq(b) def _ast_kind(ctx, a): if is_ast(a): a = a.as_ast() return Z3_get_ast_kind(ctx.ref(), a) def _ctx_from_ast_arg_list(args, default_ctx=None): ctx = None for a in args: if is_ast(a) or is_probe(a): if ctx is None: ctx = a.ctx else: if __debug__: _z3_assert(ctx == a.ctx, "Context mismatch") if ctx is None: ctx = default_ctx return ctx def _ctx_from_ast_args(*args): return _ctx_from_ast_arg_list(args) def _to_func_decl_array(args): sz = len(args) _args = (FuncDecl * sz)() for i in range(sz): _args[i] = args[i].as_func_decl() return _args, sz def _to_ast_array(args): sz = len(args) _args = (Ast * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ref_array(ref, args): sz = len(args) _args = (ref * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ast_ref(a, ctx): k = _ast_kind(ctx, a) if k == Z3_SORT_AST: return _to_sort_ref(a, ctx) elif k == Z3_FUNC_DECL_AST: return _to_func_decl_ref(a, ctx) else: return _to_expr_ref(a, ctx) ######################################### # # Sorts # ######################################### def _sort_kind(ctx, s): return Z3_get_sort_kind(ctx.ref(), s) class SortRef(AstRef): """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node.""" def as_ast(self): return Z3_sort_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def kind(self): """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts. >>> b = BoolSort() >>> b.kind() == Z3_BOOL_SORT True >>> b.kind() == Z3_INT_SORT False >>> A = ArraySort(IntSort(), IntSort()) >>> A.kind() == Z3_ARRAY_SORT True >>> A.kind() == Z3_INT_SORT False """ return _sort_kind(self.ctx, self.ast) def subsort(self, other): """Return `True` if `self` is a subsort of `other`. >>> IntSort().subsort(RealSort()) True """ return False def cast(self, val): """Try to cast `val` as an element of sort `self`. This method is used in Z3Py to convert Python objects such as integers, floats, longs and strings into Z3 expressions. >>> x = Int('x') >>> RealSort().cast(x) ToReal(x) """ if __debug__: _z3_assert(is_expr(val), "Z3 expression expected") _z3_assert(self.eq(val.sort()), "Sort mismatch") return val def name(self): """Return the name (string) of sort `self`. >>> BoolSort().name() 'Bool' >>> ArraySort(IntSort(), IntSort()).name() 'Array' """ return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast)) def __eq__(self, other): """Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False """ if other is None: return False return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __ne__(self, other): """Return `True` if `self` and `other` are not the same Z3 sort. >>> p = Bool('p') >>> p.sort() != BoolSort() False >>> p.sort() != IntSort() True """ return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def is_sort(s): """Return `True` if `s` is a Z3 sort. >>> is_sort(IntSort()) True >>> is_sort(Int('x')) False >>> is_expr(Int('x')) True """ return isinstance(s, SortRef) def _to_sort_ref(s, ctx): if __debug__: _z3_assert(isinstance(s, Sort), "Z3 Sort expected") k = _sort_kind(ctx, s) if k == Z3_BOOL_SORT: return BoolSortRef(s, ctx) elif k == Z3_INT_SORT or k == Z3_REAL_SORT: return ArithSortRef(s, ctx) elif k == Z3_BV_SORT: return BitVecSortRef(s, ctx) elif k == Z3_ARRAY_SORT: return ArraySortRef(s, ctx) elif k == Z3_DATATYPE_SORT: return DatatypeSortRef(s, ctx) elif k == Z3_FINITE_DOMAIN_SORT: return FiniteDomainSortRef(s, ctx) elif k == Z3_FLOATING_POINT_SORT: return FPSortRef(s, ctx) elif k == Z3_ROUNDING_MODE_SORT: return FPRMSortRef(s, ctx) return SortRef(s, ctx) def _sort(ctx, a): return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx) def DeclareSort(name, ctx=None): """Create a new uninterpreted sort named `name`. If `ctx=None`, then the new sort is declared in the global Z3Py context. >>> A = DeclareSort('A') >>> a = Const('a', A) >>> b = Const('b', A) >>> a.sort() == A True >>> b.sort() == A True >>> a == b a == b """ ctx = _get_ctx(ctx) return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx) ######################################### # # Function Declarations # ######################################### class FuncDeclRef(AstRef): """Function declaration. Every constant and function have an associated declaration. The declaration assigns a name, a sort (i.e., type), and for function the sort (i.e., type) of each of its arguments. Note that, in Z3, a constant is a function with 0 arguments. """ def as_ast(self): return Z3_func_decl_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def as_func_decl(self): return self.ast def name(self): """Return the name of the function declaration `self`. >>> f = Function('f', IntSort(), IntSort()) >>> f.name() 'f' >>> isinstance(f.name(), str) True """ return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast)) def arity(self): """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.arity() 2 """ return int(Z3_get_arity(self.ctx_ref(), self.ast)) def domain(self, i): """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.domain(0) Int >>> f.domain(1) Real """ if __debug__: _z3_assert(i < self.arity(), "Index out of bounds") return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the sort of the range of a function declaration. For constants, this is the sort of the constant. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.range() Bool """ return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx) def kind(self): """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc. >>> x = Int('x') >>> d = (x + 1).decl() >>> d.kind() == Z3_OP_ADD True >>> d.kind() == Z3_OP_MUL False """ return Z3_get_decl_kind(self.ctx_ref(), self.ast) def params(self): ctx = self.ctx n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast) result = [ None for i in range(n) ] for i in range(n): k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i) if k == Z3_PARAMETER_INT: result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_DOUBLE: result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_RATIONAL: result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SYMBOL: result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SORT: result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_AST: result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_FUNC_DECL: result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx) else: assert(False) return result def __call__(self, *args): """Create a Z3 application expression using the function `self`, and the given arguments. The arguments must be Z3 expressions. This method assumes that the sorts of the elements in `args` match the sorts of the domain. Limited coercion is supported. For example, if args[0] is a Python integer, and the function expects a Z3 integer, then the argument is automatically converted into a Z3 integer. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> x = Int('x') >>> y = Real('y') >>> f(x, y) f(x, y) >>> f(x, x) f(x, ToReal(x)) """ args = _get_args(args) num = len(args) if __debug__: _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self) _args = (Ast * num)() saved = [] for i in range(num): # self.domain(i).cast(args[i]) may create a new Z3 expression, # then we must save in 'saved' to prevent it from being garbage collected. tmp = self.domain(i).cast(args[i]) saved.append(tmp) _args[i] = tmp.as_ast() return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx) def is_func_decl(a): """Return `True` if `a` is a Z3 function declaration. >>> f = Function('f', IntSort(), IntSort()) >>> is_func_decl(f) True >>> x = Real('x') >>> is_func_decl(x) False """ return isinstance(a, FuncDeclRef) def Function(name, *sig): """Create a new Z3 uninterpreted function with the given sorts. >>> f = Function('f', IntSort(), IntSort()) >>> f(f(0)) f(f(0)) """ sig = _get_args(sig) if __debug__: _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if __debug__: _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if __debug__: _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def _to_func_decl_ref(a, ctx): return FuncDeclRef(a, ctx) def RecFunction(name, *sig): """Create a new Z3 recursive with the given sorts.""" sig = _get_args(sig) if __debug__: _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if __debug__: _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if __debug__: _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def RecAddDefinition(f, args, body): """Set the body of a recursive function. Recursive definitions are only unfolded during search. >>> ctx = Context() >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx)) >>> n = Int('n', ctx) >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1))) >>> simplify(fac(5)) fac(5) >>> s = Solver(ctx=ctx) >>> s.add(fac(n) < 3) >>> s.check() sat >>> s.model().eval(fac(5)) 120 """ if is_app(args): args = [args] ctx = body.ctx args = _get_args(args) n = len(args) _args = (Ast * n)() for i in range(n): _args[i] = args[i].ast Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast) ######################################### # # Expressions # ######################################### class ExprRef(AstRef): """Constraints, formulas and terms are expressions in Z3. Expressions are ASTs. Every expression has a sort. There are three main kinds of expressions: function applications, quantifiers and bounded variables. A constant is a function application with 0 arguments. For quantifier free problems, all expressions are function applications. """ def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the sort of expression `self`. >>> x = Int('x') >>> (x + 1).sort() Int >>> y = Real('y') >>> (x + y).sort() Real """ return _sort(self.ctx, self.as_ast()) def sort_kind(self): """Shorthand for `self.sort().kind()`. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort_kind() == Z3_ARRAY_SORT True >>> a.sort_kind() == Z3_INT_SORT False """ return self.sort().kind() def __eq__(self, other): """Return a Z3 expression that represents the constraint `self == other`. If `other` is `None`, then this method simply returns `False`. >>> a = Int('a') >>> b = Int('b') >>> a == b a == b >>> a is None False """ if other is None: return False a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def __ne__(self, other): """Return a Z3 expression that represents the constraint `self != other`. If `other` is `None`, then this method simply returns `True`. >>> a = Int('a') >>> b = Int('b') >>> a != b a != b >>> a is not None True """ if other is None: return True a, b = _coerce_exprs(self, other) _args, sz = _to_ast_array((a, b)) return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx) def params(self): return self.decl().params() def decl(self): """Return the Z3 function declaration associated with a Z3 application. >>> f = Function('f', IntSort(), IntSort()) >>> a = Int('a') >>> t = f(a) >>> eq(t.decl(), f) True >>> (a + 1).decl() + """ if __debug__: _z3_assert(is_app(self), "Z3 application expected") return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx) def num_args(self): """Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3 """ if __debug__: _z3_assert(is_app(self), "Z3 application expected") return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast())) def arg(self, idx): """Return argument `idx` of the application `self`. This method assumes that `self` is a function application with at least `idx+1` arguments. >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.arg(0) a >>> t.arg(1) b >>> t.arg(2) 0 """ if __debug__: _z3_assert(is_app(self), "Z3 application expected") _z3_assert(idx < self.num_args(), "Invalid argument index") return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx) def children(self): """Return a list containing the children of the given expression >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.children() [a, b, 0] """ if is_app(self): return [self.arg(i) for i in range(self.num_args())] else: return [] def _to_expr_ref(a, ctx): if isinstance(a, Pattern): return PatternRef(a, ctx) ctx_ref = ctx.ref() k = Z3_get_ast_kind(ctx_ref, a) if k == Z3_QUANTIFIER_AST: return QuantifierRef(a, ctx) sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a)) if sk == Z3_BOOL_SORT: return BoolRef(a, ctx) if sk == Z3_INT_SORT: if k == Z3_NUMERAL_AST: return IntNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_REAL_SORT: if k == Z3_NUMERAL_AST: return RatNumRef(a, ctx) if _is_algebraic(ctx, a): return AlgebraicNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_BV_SORT: if k == Z3_NUMERAL_AST: return BitVecNumRef(a, ctx) else: return BitVecRef(a, ctx) if sk == Z3_ARRAY_SORT: return ArrayRef(a, ctx) if sk == Z3_DATATYPE_SORT: return DatatypeRef(a, ctx) if sk == Z3_FLOATING_POINT_SORT: if k == Z3_APP_AST and _is_numeral(ctx, a): return FPNumRef(a, ctx) else: return FPRef(a, ctx) if sk == Z3_FINITE_DOMAIN_SORT: if k == Z3_NUMERAL_AST: return FiniteDomainNumRef(a, ctx) else: return FiniteDomainRef(a, ctx) if sk == Z3_ROUNDING_MODE_SORT: return FPRMRef(a, ctx) if sk == Z3_SEQ_SORT: return SeqRef(a, ctx) if sk == Z3_RE_SORT: return ReRef(a, ctx) return ExprRef(a, ctx) def _coerce_expr_merge(s, a): if is_expr(a): s1 = a.sort() if s is None: return s1 if s1.eq(s): return s elif s.subsort(s1): return s1 elif s1.subsort(s): return s else: if __debug__: _z3_assert(s1.ctx == s.ctx, "context mismatch") _z3_assert(False, "sort mismatch") else: return s def _coerce_exprs(a, b, ctx=None): if not is_expr(a) and not is_expr(b): a = _py2expr(a, ctx) b = _py2expr(b, ctx) s = None s = _coerce_expr_merge(s, a) s = _coerce_expr_merge(s, b) a = s.cast(a) b = s.cast(b) return (a, b) def _reduce(f, l, a): r = a for e in l: r = f(r, e) return r def _coerce_expr_list(alist, ctx=None): has_expr = False for a in alist: if is_expr(a): has_expr = True break if not has_expr: alist = [ _py2expr(a, ctx) for a in alist ] s = _reduce(_coerce_expr_merge, alist, None) return [ s.cast(a) for a in alist ] def is_expr(a): """Return `True` if `a` is a Z3 expression. >>> a = Int('a') >>> is_expr(a) True >>> is_expr(a + 1) True >>> is_expr(IntSort()) False >>> is_expr(1) False >>> is_expr(IntVal(1)) True >>> x = Int('x') >>> is_expr(ForAll(x, x >= 0)) True >>> is_expr(FPVal(1.0)) True """ return isinstance(a, ExprRef) def is_app(a): """Return `True` if `a` is a Z3 function application. Note that, constants are function applications with 0 arguments. >>> a = Int('a') >>> is_app(a) True >>> is_app(a + 1) True >>> is_app(IntSort()) False >>> is_app(1) False >>> is_app(IntVal(1)) True >>> x = Int('x') >>> is_app(ForAll(x, x >= 0)) False """ if not isinstance(a, ExprRef): return False k = _ast_kind(a.ctx, a) return k == Z3_NUMERAL_AST or k == Z3_APP_AST def is_const(a): """Return `True` if `a` is Z3 constant/variable expression. >>> a = Int('a') >>> is_const(a) True >>> is_const(a + 1) False >>> is_const(1) False >>> is_const(IntVal(1)) True >>> x = Int('x') >>> is_const(ForAll(x, x >= 0)) False """ return is_app(a) and a.num_args() == 0 def is_var(a): """Return `True` if `a` is variable. Z3 uses de-Bruijn indices for representing bound variables in quantifiers. >>> x = Int('x') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort()) >>> # Z3 replaces x with bound variables when ForAll is executed. >>> q = ForAll(x, f(x) == x) >>> b = q.body() >>> b f(Var(0)) == Var(0) >>> b.arg(1) Var(0) >>> is_var(b.arg(1)) True """ return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST def get_var_index(a): """Return the de-Bruijn index of the Z3 bounded variable `a`. >>> x = Int('x') >>> y = Int('y') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # Z3 replaces x and y with bound variables when ForAll is executed. >>> q = ForAll([x, y], f(x, y) == x + y) >>> q.body() f(Var(1), Var(0)) == Var(1) + Var(0) >>> b = q.body() >>> b.arg(0) f(Var(1), Var(0)) >>> v1 = b.arg(0).arg(0) >>> v2 = b.arg(0).arg(1) >>> v1 Var(1) >>> v2 Var(0) >>> get_var_index(v1) 1 >>> get_var_index(v2) 0 """ if __debug__: _z3_assert(is_var(a), "Z3 bound variable expected") return int(Z3_get_index_value(a.ctx.ref(), a.as_ast())) def is_app_of(a, k): """Return `True` if `a` is an application of the given kind `k`. >>> x = Int('x') >>> n = x + 1 >>> is_app_of(n, Z3_OP_ADD) True >>> is_app_of(n, Z3_OP_MUL) False """ return is_app(a) and a.decl().kind() == k def If(a, b, c, ctx=None): """Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x) """ if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic): return Cond(a, b, c, ctx) else: ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx)) s = BoolSort(ctx) a = s.cast(a) b, c = _coerce_exprs(b, c, ctx) if __debug__: _z3_assert(a.ctx == b.ctx, "Context mismatch") return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def Distinct(*args): """Create a Z3 distinct expression. >>> x = Int('x') >>> y = Int('y') >>> Distinct(x, y) x != y >>> z = Int('z') >>> Distinct(x, y, z) Distinct(x, y, z) >>> simplify(Distinct(x, y, z)) Distinct(x, y, z) >>> simplify(Distinct(x, y, z), blast_distinct=True) And(Not(x == y), Not(x == z), Not(y == z)) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) if __debug__: _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx) def _mk_bin(f, a, b): args = (Ast * 2)() if __debug__: _z3_assert(a.ctx == b.ctx, "Context mismatch") args[0] = a.as_ast() args[1] = b.as_ast() return f(a.ctx.ref(), 2, args) def Const(name, sort): """Create a constant of the given sort. >>> Const('x', IntSort()) x """ if __debug__: _z3_assert(isinstance(sort, SortRef), "Z3 sort expected") ctx = sort.ctx return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx) def Consts(names, sort): """Create a several constants of the given sort. `names` is a string containing the names of all constants to be created. Blank spaces separate the names of different constants. >>> x, y, z = Consts('x y z', IntSort()) >>> x + y + z x + y + z """ if isinstance(names, str): names = names.split(" ") return [Const(name, sort) for name in names] def FreshConst(sort, prefix='c'): """Create a fresh constant of a specified sort""" ctx = _get_ctx(sort.ctx) return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx) def Var(idx, s): """Create a Z3 free variable. Free variables are used to create quantified formulas. >>> Var(0, IntSort()) Var(0) >>> eq(Var(0, IntSort()), Var(0, BoolSort())) False """ if __debug__: _z3_assert(is_sort(s), "Z3 sort expected") return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx) def RealVar(idx, ctx=None): """ Create a real free variable. Free variables are used to create quantified formulas. They are also used to create polynomials. >>> RealVar(0) Var(0) """ return Var(idx, RealSort(ctx)) def RealVarVector(n, ctx=None): """ Create a list of Real free variables. The variables have ids: 0, 1, ..., n-1 >>> x0, x1, x2, x3 = RealVarVector(4) >>> x2 Var(2) """ return [ RealVar(i, ctx) for i in range(n) ] ######################################### # # Booleans # ######################################### class BoolSortRef(SortRef): """Boolean sort.""" def cast(self, val): """Try to cast `val` as a Boolean. >>> x = BoolSort().cast(True) >>> x True >>> is_expr(x) True >>> is_expr(True) False >>> x.sort() Bool """ if isinstance(val, bool): return BoolVal(val, self.ctx) if __debug__: if not is_expr(val): _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val) if not self.eq(val.sort()): _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value") return val def subsort(self, other): return isinstance(other, ArithSortRef) def is_int(self): return True def is_bool(self): return True class BoolRef(ExprRef): """All Boolean expressions are instances of this class.""" def sort(self): return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __rmul__(self, other): return self * other def __mul__(self, other): """Create the Z3 expression `self * other`. """ if other == 1: return self if other == 0: return 0 return If(self, other, 0) def is_bool(a): """Return `True` if `a` is a Z3 Boolean expression. >>> p = Bool('p') >>> is_bool(p) True >>> q = Bool('q') >>> is_bool(And(p, q)) True >>> x = Real('x') >>> is_bool(x) False >>> is_bool(x == 0) True """ return isinstance(a, BoolRef) def is_true(a): """Return `True` if `a` is the Z3 true expression. >>> p = Bool('p') >>> is_true(p) False >>> is_true(simplify(p == p)) True >>> x = Real('x') >>> is_true(x == 0) False >>> # True is a Python Boolean expression >>> is_true(True) False """ return is_app_of(a, Z3_OP_TRUE) def is_false(a): """Return `True` if `a` is the Z3 false expression. >>> p = Bool('p') >>> is_false(p) False >>> is_false(False) False >>> is_false(BoolVal(False)) True """ return is_app_of(a, Z3_OP_FALSE) def is_and(a): """Return `True` if `a` is a Z3 and expression. >>> p, q = Bools('p q') >>> is_and(And(p, q)) True >>> is_and(Or(p, q)) False """ return is_app_of(a, Z3_OP_AND) def is_or(a): """Return `True` if `a` is a Z3 or expression. >>> p, q = Bools('p q') >>> is_or(Or(p, q)) True >>> is_or(And(p, q)) False """ return is_app_of(a, Z3_OP_OR) def is_implies(a): """Return `True` if `a` is a Z3 implication expression. >>> p, q = Bools('p q') >>> is_implies(Implies(p, q)) True >>> is_implies(And(p, q)) False """ return is_app_of(a, Z3_OP_IMPLIES) def is_not(a): """Return `True` if `a` is a Z3 not expression. >>> p = Bool('p') >>> is_not(p) False >>> is_not(Not(p)) True """ return is_app_of(a, Z3_OP_NOT) def is_eq(a): """Return `True` if `a` is a Z3 equality expression. >>> x, y = Ints('x y') >>> is_eq(x == y) True """ return is_app_of(a, Z3_OP_EQ) def is_distinct(a): """Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True """ return is_app_of(a, Z3_OP_DISTINCT) def BoolSort(ctx=None): """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used. >>> BoolSort() Bool >>> p = Const('p', BoolSort()) >>> is_bool(p) True >>> r = Function('r', IntSort(), IntSort(), BoolSort()) >>> r(0, 1) r(0, 1) >>> is_bool(r(0, 1)) True """ ctx = _get_ctx(ctx) return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx) def BoolVal(val, ctx=None): """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used. >>> BoolVal(True) True >>> is_true(BoolVal(True)) True >>> is_true(True) False >>> is_false(BoolVal(False)) True """ ctx = _get_ctx(ctx) if val == False: return BoolRef(Z3_mk_false(ctx.ref()), ctx) else: return BoolRef(Z3_mk_true(ctx.ref()), ctx) def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) def Bools(names, ctx=None): """Return a tuple of Boolean constants. `names` is a single string containing all names separated by blank spaces. If `ctx=None`, then the global context is used. >>> p, q, r = Bools('p q r') >>> And(p, Or(q, r)) And(p, Or(q, r)) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Bool(name, ctx) for name in names] def BoolVector(prefix, sz, ctx=None): """Return a list of Boolean constants of size `sz`. The constants are named using the given prefix. If `ctx=None`, then the global context is used. >>> P = BoolVector('p', 3) >>> P [p__0, p__1, p__2] >>> And(P) And(p__0, p__1, p__2) """ return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshBool(prefix='b', ctx=None): """Return a fresh Boolean constant in the given context using the given prefix. If `ctx=None`, then the global context is used. >>> b1 = FreshBool() >>> b2 = FreshBool() >>> eq(b1, b2) False """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx) def Implies(a, b, ctx=None): """Create a Z3 implies expression. >>> p, q = Bools('p q') >>> Implies(p, q) Implies(p, q) >>> simplify(Implies(p, q)) Or(Not(p), q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Xor(a, b, ctx=None): """Create a Z3 Xor expression. >>> p, q = Bools('p q') >>> Xor(p, q) Xor(p, q) >>> simplify(Xor(p, q)) Not(p) == q """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Not(a, ctx=None): """Create a Z3 not expression or probe. >>> p = Bool('p') >>> Not(Not(p)) Not(Not(p)) >>> simplify(Not(Not(p))) p """ ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) if is_probe(a): # Not is also used to build probes return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx) else: s = BoolSort(ctx) a = s.cast(a) return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx) def mk_not(a): if is_not(a): return a.arg(0) else: return Not(a) def _has_probe(args): """Return `True` if one of the elements of the given collection is a Z3 probe.""" for arg in args: if is_probe(arg): return True return False def And(*args): """Create a Z3 and-expression or and-probe. >>> p, q, r = Bools('p q r') >>> And(p, q, r) And(p, q, r) >>> P = BoolVector('p', 5) >>> And(P) And(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args)-1] if isinstance(last_arg, Context): ctx = args[len(args)-1] args = args[:len(args)-1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = main_ctx() args = _get_args(args) ctx_args = _ctx_from_ast_arg_list(args, ctx) if __debug__: _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch") _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_and(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx) def Or(*args): """Create a Z3 or-expression or or-probe. >>> p, q, r = Bools('p q r') >>> Or(p, q, r) Or(p, q, r) >>> P = BoolVector('p', 5) >>> Or(P) Or(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args)-1] if isinstance(last_arg, Context): ctx = args[len(args)-1] args = args[:len(args)-1] else: ctx = main_ctx() args = _get_args(args) ctx_args = _ctx_from_ast_arg_list(args, ctx) if __debug__: _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch") _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_or(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx) ######################################### # # Patterns # ######################################### class PatternRef(ExprRef): """Patterns are hints for quantifier instantiation. """ def as_ast(self): return Z3_pattern_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def is_pattern(a): """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ]) >>> q ForAll(x, f(x) == 0) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) f(Var(0)) """ return isinstance(a, PatternRef) def MultiPattern(*args): """Create a Z3 multi-pattern using the given expressions `*args` >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ]) >>> q ForAll(x, f(x) != g(x)) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) MultiPattern(f(Var(0)), g(Var(0))) """ if __debug__: _z3_assert(len(args) > 0, "At least one argument expected") _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected") ctx = args[0].ctx args, sz = _to_ast_array(args) return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx) def _to_pattern(arg): if is_pattern(arg): return arg else: return MultiPattern(arg) ######################################### # # Quantifiers # ######################################### class QuantifierRef(BoolRef): """Universally and Existentially quantified formulas.""" def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the Boolean sort or sort of Lambda.""" if self.is_lambda(): return _sort(self.ctx, self.as_ast()) return BoolSort(self.ctx) def is_forall(self): """Return `True` if `self` is a universal quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_forall() True >>> q = Exists(x, f(x) != 0) >>> q.is_forall() False """ return Z3_is_quantifier_forall(self.ctx_ref(), self.ast) def is_exists(self): """Return `True` if `self` is an existential quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_exists() False >>> q = Exists(x, f(x) != 0) >>> q.is_exists() True """ return Z3_is_quantifier_exists(self.ctx_ref(), self.ast) def is_lambda(self): """Return `True` if `self` is a lambda expression. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = Lambda(x, f(x)) >>> q.is_lambda() True >>> q = Exists(x, f(x) != 0) >>> q.is_lambda() False """ return Z3_is_lambda(self.ctx_ref(), self.ast) def weight(self): """Return the weight annotation of `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.weight() 1 >>> q = ForAll(x, f(x) == 0, weight=10) >>> q.weight() 10 """ return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast)) def num_patterns(self): """Return the number of patterns (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 """ return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast)) def pattern(self, idx): """Return a pattern (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 >>> q.pattern(0) f(Var(0)) >>> q.pattern(1) g(Var(0)) """ if __debug__: _z3_assert(idx < self.num_patterns(), "Invalid pattern idx") return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def num_no_patterns(self): """Return the number of no-patterns.""" return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast) def no_pattern(self, idx): """Return a no-pattern.""" if __debug__: _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx") return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def body(self): """Return the expression being quantified. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.body() f(Var(0)) == 0 """ return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx) def num_vars(self): """Return the number of variables bounded by this quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.num_vars() 2 """ return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast)) def var_name(self, idx): """Return a string representing a name used when displaying the quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_name(0) 'x' >>> q.var_name(1) 'y' """ if __debug__: _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx)) def var_sort(self, idx): """Return the sort of a bound variable. >>> f = Function('f', IntSort(), RealSort(), IntSort()) >>> x = Int('x') >>> y = Real('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_sort(0) Int >>> q.var_sort(1) Real """ if __debug__: _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx) def children(self): """Return a list containing a single element self.body() >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.children() [f(Var(0)) == 0] """ return [ self.body() ] def is_quantifier(a): """Return `True` if `a` is a Z3 quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> is_quantifier(q) True >>> is_quantifier(f(x)) False """ return isinstance(a, QuantifierRef) def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): if __debug__: _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected") _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)") _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected") _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions") if is_app(vs): ctx = vs.ctx vs = [vs] else: ctx = vs[0].ctx if not is_expr(body): body = BoolVal(body, ctx) num_vars = len(vs) if num_vars == 0: return body _vs = (Ast * num_vars)() for i in range(num_vars): ## TODO: Check if is constant _vs[i] = vs[i].as_ast() patterns = [ _to_pattern(p) for p in patterns ] num_pats = len(patterns) _pats = (Pattern * num_pats)() for i in range(num_pats): _pats[i] = patterns[i].ast _no_pats, num_no_pats = _to_ast_array(no_patterns) qid = to_symbol(qid, ctx) skid = to_symbol(skid, ctx) return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid, num_vars, _vs, num_pats, _pats, num_no_pats, _no_pats, body.as_ast()), ctx) def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 forall formula. The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> ForAll([x, y], f(x, y) >= x) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ]) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, weight=10) ForAll([x, y], f(x, y) >= x) """ return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns) def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 exists formula. The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = Exists([x, y], f(x, y) >= x, skid="foo") >>> q Exists([x, y], f(x, y) >= x) >>> is_quantifier(q) True >>> r = Tactic('nnf')(q).as_expr() >>> is_quantifier(r) False """ return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns) def Lambda(vs, body): """Create a Z3 lambda expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> mem0 = Array('mem0', IntSort(), IntSort()) >>> lo, hi, e, i = Ints('lo hi e i') >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i])) >>> mem1 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i])) """ ctx = body.ctx if is_app(vs): vs = [vs] num_vars = len(vs) _vs = (Ast * num_vars)() for i in range(num_vars): ## TODO: Check if is constant _vs[i] = vs[i].as_ast() return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) ######################################### # # Arithmetic # ######################################### class ArithSortRef(SortRef): """Real and Integer sorts.""" def is_real(self): """Return `True` if `self` is of the sort Real. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True >>> x = Int('x') >>> x.is_real() False """ return self.kind() == Z3_REAL_SORT def is_int(self): """Return `True` if `self` is of the sort Integer. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> x = Real('x') >>> x.is_int() False """ return self.kind() == Z3_INT_SORT def subsort(self, other): """Return `True` if `self` is a subsort of `other`.""" return self.is_int() and is_arith_sort(other) and other.is_real() def cast(self, val): """Try to cast `val` as an Integer or Real. >>> IntSort().cast(10) 10 >>> is_int(IntSort().cast(10)) True >>> is_int(10) False >>> RealSort().cast(10) 10 >>> is_real(RealSort().cast(10)) True """ if is_expr(val): if __debug__: _z3_assert(self.ctx == val.ctx, "Context mismatch") val_s = val.sort() if self.eq(val_s): return val if val_s.is_int() and self.is_real(): return ToReal(val) if val_s.is_bool() and self.is_int(): return If(val, 1, 0) if val_s.is_bool() and self.is_real(): return ToReal(If(val, 1, 0)) if __debug__: _z3_assert(False, "Z3 Integer/Real expression expected" ) else: if self.is_int(): return IntVal(val, self.ctx) if self.is_real(): return RealVal(val, self.ctx) if __debug__: _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self) def is_arith_sort(s): """Return `True` if s is an arithmetical sort (type). >>> is_arith_sort(IntSort()) True >>> is_arith_sort(RealSort()) True >>> is_arith_sort(BoolSort()) False >>> n = Int('x') + 1 >>> is_arith_sort(n.sort()) True """ return isinstance(s, ArithSortRef) class ArithRef(ExprRef): """Integer and Real expressions.""" def sort(self): """Return the sort (type) of the arithmetical expression `self`. >>> Int('x').sort() Int >>> (Real('x') + 1).sort() Real """ return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def is_int(self): """Return `True` if `self` is an integer expression. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> y = Real('y') >>> (x + y).is_int() False """ return self.sort().is_int() def is_real(self): """Return `True` if `self` is an real expression. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True """ return self.sort().is_real() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = Int('x') >>> y = Int('y') >>> x + y x + y >>> (x + y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = Int('x') >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = Real('x') >>> y = Real('y') >>> x * y x*y >>> (x * y).sort() Real """ if isinstance(other, BoolRef): return If(other, self, 0) a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = Real('x') >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = Int('x') >>> y = Int('y') >>> x - y x - y >>> (x - y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = Int('x') >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx) def __pow__(self, other): """Create the Z3 expression `self**other` (** is the power operator). >>> x = Real('x') >>> x**3 x**3 >>> (x**3).sort() Real >>> simplify(IntVal(2)**8) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rpow__(self, other): """Create the Z3 expression `other**self` (** is the power operator). >>> x = Real('x') >>> 2**x 2**x >>> (2**x).sort() Real >>> simplify(2**IntVal(8)) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> y = Int('y') >>> x/y x/y >>> (x/y).sort() Int >>> (x/y).sexpr() '(div x y)' >>> x = Real('x') >>> y = Real('y') >>> x/y x/y >>> (x/y).sort() Real >>> (x/y).sexpr() '(/ x y)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> 10/x 10/x >>> (10/x).sexpr() '(div 10 x)' >>> x = Real('x') >>> 10/x 10/x >>> (10/x).sexpr() '(/ 10.0 x)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> y = Int('y') >>> x % y x%y >>> simplify(IntVal(10) % IntVal(3)) 1 """ a, b = _coerce_exprs(self, other) if __debug__: _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> 10 % x 10%x """ a, b = _coerce_exprs(self, other) if __debug__: _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __neg__(self): """Return an expression representing `-self`. >>> x = Int('x') >>> -x -x >>> simplify(-(-x)) x """ return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = Int('x') >>> +x x """ return self def __le__(self, other): """Create the Z3 expression `other <= self`. >>> x, y = Ints('x y') >>> x <= y x <= y >>> y = Real('y') >>> x <= y ToReal(x) <= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression `other < self`. >>> x, y = Ints('x y') >>> x < y x < y >>> y = Real('y') >>> x < y ToReal(x) < y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression `other > self`. >>> x, y = Ints('x y') >>> x > y x > y >>> y = Real('y') >>> x > y ToReal(x) > y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression `other >= self`. >>> x, y = Ints('x y') >>> x >= y x >= y >>> y = Real('y') >>> x >= y ToReal(x) >= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def is_arith(a): """Return `True` if `a` is an arithmetical expression. >>> x = Int('x') >>> is_arith(x) True >>> is_arith(x + 1) True >>> is_arith(1) False >>> is_arith(IntVal(1)) True >>> y = Real('y') >>> is_arith(y) True >>> is_arith(y + 1) True """ return isinstance(a, ArithRef) def is_int(a): """Return `True` if `a` is an integer expression. >>> x = Int('x') >>> is_int(x + 1) True >>> is_int(1) False >>> is_int(IntVal(1)) True >>> y = Real('y') >>> is_int(y) False >>> is_int(y + 1) False """ return is_arith(a) and a.is_int() def is_real(a): """Return `True` if `a` is a real expression. >>> x = Int('x') >>> is_real(x + 1) False >>> y = Real('y') >>> is_real(y) True >>> is_real(y + 1) True >>> is_real(1) False >>> is_real(RealVal(1)) True """ return is_arith(a) and a.is_real() def _is_numeral(ctx, a): return Z3_is_numeral_ast(ctx.ref(), a) def _is_algebraic(ctx, a): return Z3_is_algebraic_number(ctx.ref(), a) def is_int_value(a): """Return `True` if `a` is an integer value of sort Int. >>> is_int_value(IntVal(1)) True >>> is_int_value(1) False >>> is_int_value(Int('x')) False >>> n = Int('x') + 1 >>> n x + 1 >>> n.arg(1) 1 >>> is_int_value(n.arg(1)) True >>> is_int_value(RealVal("1/3")) False >>> is_int_value(RealVal(1)) False """ return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast()) def is_rational_value(a): """Return `True` if `a` is rational value of sort Real. >>> is_rational_value(RealVal(1)) True >>> is_rational_value(RealVal("3/5")) True >>> is_rational_value(IntVal(1)) False >>> is_rational_value(1) False >>> n = Real('x') + 1 >>> n.arg(1) 1 >>> is_rational_value(n.arg(1)) True >>> is_rational_value(Real('x')) False """ return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast()) def is_algebraic_value(a): """Return `True` if `a` is an algebraic value of sort Real. >>> is_algebraic_value(RealVal("3/5")) False >>> n = simplify(Sqrt(2)) >>> n 1.4142135623? >>> is_algebraic_value(n) True """ return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast()) def is_add(a): """Return `True` if `a` is an expression of the form b + c. >>> x, y = Ints('x y') >>> is_add(x + y) True >>> is_add(x - y) False """ return is_app_of(a, Z3_OP_ADD) def is_mul(a): """Return `True` if `a` is an expression of the form b * c. >>> x, y = Ints('x y') >>> is_mul(x * y) True >>> is_mul(x - y) False """ return is_app_of(a, Z3_OP_MUL) def is_sub(a): """Return `True` if `a` is an expression of the form b - c. >>> x, y = Ints('x y') >>> is_sub(x - y) True >>> is_sub(x + y) False """ return is_app_of(a, Z3_OP_SUB) def is_div(a): """Return `True` if `a` is an expression of the form b / c. >>> x, y = Reals('x y') >>> is_div(x / y) True >>> is_div(x + y) False >>> x, y = Ints('x y') >>> is_div(x / y) False >>> is_idiv(x / y) True """ return is_app_of(a, Z3_OP_DIV) def is_idiv(a): """Return `True` if `a` is an expression of the form b div c. >>> x, y = Ints('x y') >>> is_idiv(x / y) True >>> is_idiv(x + y) False """ return is_app_of(a, Z3_OP_IDIV) def is_mod(a): """Return `True` if `a` is an expression of the form b % c. >>> x, y = Ints('x y') >>> is_mod(x % y) True >>> is_mod(x + y) False """ return is_app_of(a, Z3_OP_MOD) def is_le(a): """Return `True` if `a` is an expression of the form b <= c. >>> x, y = Ints('x y') >>> is_le(x <= y) True >>> is_le(x < y) False """ return is_app_of(a, Z3_OP_LE) def is_lt(a): """Return `True` if `a` is an expression of the form b < c. >>> x, y = Ints('x y') >>> is_lt(x < y) True >>> is_lt(x == y) False """ return is_app_of(a, Z3_OP_LT) def is_ge(a): """Return `True` if `a` is an expression of the form b >= c. >>> x, y = Ints('x y') >>> is_ge(x >= y) True >>> is_ge(x == y) False """ return is_app_of(a, Z3_OP_GE) def is_gt(a): """Return `True` if `a` is an expression of the form b > c. >>> x, y = Ints('x y') >>> is_gt(x > y) True >>> is_gt(x == y) False """ return is_app_of(a, Z3_OP_GT) def is_is_int(a): """Return `True` if `a` is an expression of the form IsInt(b). >>> x = Real('x') >>> is_is_int(IsInt(x)) True >>> is_is_int(x) False """ return is_app_of(a, Z3_OP_IS_INT) def is_to_real(a): """Return `True` if `a` is an expression of the form ToReal(b). >>> x = Int('x') >>> n = ToReal(x) >>> n ToReal(x) >>> is_to_real(n) True >>> is_to_real(x) False """ return is_app_of(a, Z3_OP_TO_REAL) def is_to_int(a): """Return `True` if `a` is an expression of the form ToInt(b). >>> x = Real('x') >>> n = ToInt(x) >>> n ToInt(x) >>> is_to_int(n) True >>> is_to_int(x) False """ return is_app_of(a, Z3_OP_TO_INT) class IntNumRef(ArithRef): """Integer values.""" def as_long(self): """Return a Z3 integer numeral as a Python long (bignum) numeral. >>> v = IntVal(1) >>> v + 1 1 + 1 >>> v.as_long() + 1 2 """ if __debug__: _z3_assert(self.is_int(), "Integer value expected") return int(self.as_string()) def as_string(self): """Return a Z3 integer numeral as a Python string. >>> v = IntVal(100) >>> v.as_string() '100' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) class RatNumRef(ArithRef): """Rational values.""" def numerator(self): """ Return the numerator of a Z3 rational numeral. >>> is_rational_value(RealVal("3/5")) True >>> n = RealVal("3/5") >>> n.numerator() 3 >>> is_rational_value(Q(3,5)) True >>> Q(3,5).numerator() 3 """ return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def denominator(self): """ Return the denominator of a Z3 rational numeral. >>> is_rational_value(Q(3,5)) True >>> n = Q(3,5) >>> n.denominator() 5 """ return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator_as_long(self): """ Return the numerator as a Python long. >>> v = RealVal(10000000000) >>> v 10000000000 >>> v + 1 10000000000 + 1 >>> v.numerator_as_long() + 1 == 10000000001 True """ return self.numerator().as_long() def denominator_as_long(self): """ Return the denominator as a Python long. >>> v = RealVal("1/3") >>> v 1/3 >>> v.denominator_as_long() 3 """ return self.denominator().as_long() def is_int(self): return False def is_real(self): return True def is_int_value(self): return self.denominator().is_int() and self.denominator_as_long() == 1 def as_long(self): _z3_assert(self.is_int_value(), "Expected integer fraction") return self.numerator_as_long() def as_decimal(self, prec): """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places. >>> v = RealVal("1/5") >>> v.as_decimal(3) '0.2' >>> v = RealVal("1/3") >>> v.as_decimal(3) '0.333?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def as_string(self): """Return a Z3 rational numeral as a Python string. >>> v = Q(3,6) >>> v.as_string() '1/2' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_fraction(self): """Return a Z3 rational as a Python Fraction object. >>> v = RealVal("1/5") >>> v.as_fraction() Fraction(1, 5) """ return Fraction(self.numerator_as_long(), self.denominator_as_long()) class AlgebraicNumRef(ArithRef): """Algebraic irrational values.""" def approx(self, precision=10): """Return a Z3 rational number that approximates the algebraic number `self`. The result `r` is such that |r - self| <= 1/10^precision >>> x = simplify(Sqrt(2)) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 """ return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def as_decimal(self, prec): """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places >>> x = simplify(Sqrt(2)) >>> x.as_decimal(10) '1.4142135623?' >>> x.as_decimal(20) '1.41421356237309504880?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def _py2expr(a, ctx=None): if isinstance(a, bool): return BoolVal(a, ctx) if _is_int(a): return IntVal(a, ctx) if isinstance(a, float): return RealVal(a, ctx) if is_expr(a): return a if __debug__: _z3_assert(False, "Python bool, int, long or float expected") def IntSort(ctx=None): """Return the integer sort in the given context. If `ctx=None`, then the global context is used. >>> IntSort() Int >>> x = Const('x', IntSort()) >>> is_int(x) True >>> x.sort() == IntSort() True >>> x.sort() == BoolSort() False """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx) def RealSort(ctx=None): """Return the real sort in the given context. If `ctx=None`, then the global context is used. >>> RealSort() Real >>> x = Const('x', RealSort()) >>> is_real(x) True >>> is_int(x) False >>> x.sort() == RealSort() True """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx) def _to_int_str(val): if isinstance(val, float): return str(int(val)) elif isinstance(val, bool): if val: return "1" else: return "0" elif _is_int(val): return str(val) elif isinstance(val, str): return val if __debug__: _z3_assert(False, "Python value cannot be used as a Z3 integer") def IntVal(val, ctx=None): """Return a Z3 integer value. If `ctx=None`, then the global context is used. >>> IntVal(1) 1 >>> IntVal("100") 100 """ ctx = _get_ctx(ctx) return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx) def RealVal(val, ctx=None): """Return a Z3 real value. `val` may be a Python int, long, float or string representing a number in decimal or rational notation. If `ctx=None`, then the global context is used. >>> RealVal(1) 1 >>> RealVal(1).sort() Real >>> RealVal("3/5") 3/5 >>> RealVal("1.5") 3/2 """ ctx = _get_ctx(ctx) return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx) def RatVal(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> RatVal(3,5) 3/5 >>> RatVal(3,5).sort() Real """ if __debug__: _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer") _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer") return simplify(RealVal(a, ctx)/RealVal(b, ctx)) def Q(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> Q(3,5) 3/5 >>> Q(3,5).sort() Real """ return simplify(RatVal(a, b)) def Int(name, ctx=None): """Return an integer constant named `name`. If `ctx=None`, then the global context is used. >>> x = Int('x') >>> is_int(x) True >>> is_int(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx) def Ints(names, ctx=None): """Return a tuple of Integer constants. >>> x, y, z = Ints('x y z') >>> Sum(x, y, z) x + y + z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Int(name, ctx) for name in names] def IntVector(prefix, sz, ctx=None): """Return a list of integer constants of size `sz`. >>> X = IntVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 """ return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshInt(prefix='x', ctx=None): """Return a fresh integer constant in the given context using the given prefix. >>> x = FreshInt() >>> y = FreshInt() >>> eq(x, y) False >>> x.sort() Int """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx) def Real(name, ctx=None): """Return a real constant named `name`. If `ctx=None`, then the global context is used. >>> x = Real('x') >>> is_real(x) True >>> is_real(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx) def Reals(names, ctx=None): """Return a tuple of real constants. >>> x, y, z = Reals('x y z') >>> Sum(x, y, z) x + y + z >>> Sum(x, y, z).sort() Real """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Real(name, ctx) for name in names] def RealVector(prefix, sz, ctx=None): """Return a list of real constants of size `sz`. >>> X = RealVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 >>> Sum(X).sort() Real """ return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshReal(prefix='b', ctx=None): """Return a fresh real constant in the given context using the given prefix. >>> x = FreshReal() >>> y = FreshReal() >>> eq(x, y) False >>> x.sort() Real """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx) def ToReal(a): """ Return the Z3 expression ToReal(a). >>> x = Int('x') >>> x.sort() Int >>> n = ToReal(x) >>> n ToReal(x) >>> n.sort() Real """ if __debug__: _z3_assert(a.is_int(), "Z3 integer expression expected.") ctx = a.ctx return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx) def ToInt(a): """ Return the Z3 expression ToInt(a). >>> x = Real('x') >>> x.sort() Real >>> n = ToInt(x) >>> n ToInt(x) >>> n.sort() Int """ if __debug__: _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx) def IsInt(a): """ Return the Z3 predicate IsInt(a). >>> x = Real('x') >>> IsInt(x + "1/2") IsInt(x + 1/2) >>> solve(IsInt(x + "1/2"), x > 0, x < 1) [x = 1/2] >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2") no solution """ if __debug__: _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx) def Sqrt(a, ctx=None): """ Return a Z3 expression which represents the square root of a. >>> x = Real('x') >>> Sqrt(x) x**(1/2) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/2" def Cbrt(a, ctx=None): """ Return a Z3 expression which represents the cubic root of a. >>> x = Real('x') >>> Cbrt(x) x**(1/3) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/3" ######################################### # # Bit-Vectors # ######################################### class BitVecSortRef(SortRef): """Bit-vector sort.""" def size(self): """Return the size (number of bits) of the bit-vector sort `self`. >>> b = BitVecSort(32) >>> b.size() 32 """ return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast)) def subsort(self, other): return is_bv_sort(other) and self.size() < other.size() def cast(self, val): """Try to cast `val` as a Bit-Vector. >>> b = BitVecSort(32) >>> b.cast(10) 10 >>> b.cast(10).sexpr() '#x0000000a' """ if is_expr(val): if __debug__: _z3_assert(self.ctx == val.ctx, "Context mismatch") # Idea: use sign_extend if sort of val is a bitvector of smaller size return val else: return BitVecVal(val, self) def is_bv_sort(s): """Return True if `s` is a Z3 bit-vector sort. >>> is_bv_sort(BitVecSort(32)) True >>> is_bv_sort(IntSort()) False """ return isinstance(s, BitVecSortRef) class BitVecRef(ExprRef): """Bit-vector expressions.""" def sort(self): """Return the sort of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> x.sort() BitVec(32) >>> x.sort() == BitVecSort(32) True """ return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def size(self): """Return the number of bits of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> (x + 1).size() 32 >>> Concat(x, x).size() 64 """ return self.sort().size() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x + y x + y >>> (x + y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = BitVec('x', 32) >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x * y x*y >>> (x * y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = BitVec('x', 32) >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x - y x - y >>> (x - y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = BitVec('x', 32) >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __or__(self, other): """Create the Z3 expression bitwise-or `self | other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x | y x | y >>> (x | y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ror__(self, other): """Create the Z3 expression bitwise-or `other | self`. >>> x = BitVec('x', 32) >>> 10 | x 10 | x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __and__(self, other): """Create the Z3 expression bitwise-and `self & other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x & y x & y >>> (x & y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rand__(self, other): """Create the Z3 expression bitwise-or `other & self`. >>> x = BitVec('x', 32) >>> 10 & x 10 & x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __xor__(self, other): """Create the Z3 expression bitwise-xor `self ^ other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x ^ y x ^ y >>> (x ^ y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rxor__(self, other): """Create the Z3 expression bitwise-xor `other ^ self`. >>> x = BitVec('x', 32) >>> 10 ^ x 10 ^ x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = BitVec('x', 32) >>> +x x """ return self def __neg__(self): """Return an expression representing `-self`. >>> x = BitVec('x', 32) >>> -x -x >>> simplify(-(-x)) x """ return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx) def __invert__(self): """Create the Z3 expression bitwise-not `~self`. >>> x = BitVec('x', 32) >>> ~x ~x >>> simplify(~(~x)) x """ return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression (signed) division `self / other`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression (signed) division `other / self`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> 10 / x 10/x >>> (10 / x).sexpr() '(bvsdiv #x0000000a x)' >>> UDiv(10, x).sexpr() '(bvudiv #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression (signed) division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression (signed) mod `self % other`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x % y x%y >>> (x % y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression (signed) mod `other % self`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> 10 % x 10%x >>> (10 % x).sexpr() '(bvsmod #x0000000a x)' >>> URem(10, x).sexpr() '(bvurem #x0000000a x)' >>> SRem(10, x).sexpr() '(bvsrem #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __le__(self, other): """Create the Z3 expression (signed) `other <= self`. Use the function ULE() for unsigned less than or equal to. >>> x, y = BitVecs('x y', 32) >>> x <= y x <= y >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression (signed) `other < self`. Use the function ULT() for unsigned less than. >>> x, y = BitVecs('x y', 32) >>> x < y x < y >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression (signed) `other > self`. Use the function UGT() for unsigned greater than. >>> x, y = BitVecs('x y', 32) >>> x > y x > y >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression (signed) `other >= self`. Use the function UGE() for unsigned greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> x >= y x >= y >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rshift__(self, other): """Create the Z3 expression (arithmetical) right shift `self >> other` Use the function LShR() for the right logical shift >>> x, y = BitVecs('x y', 32) >>> x >> y x >> y >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lshift__(self, other): """Create the Z3 expression left shift `self << other` >>> x, y = BitVecs('x y', 32) >>> x << y x << y >>> (x << y).sexpr() '(bvshl x y)' >>> simplify(BitVecVal(2, 3) << 1) 4 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rrshift__(self, other): """Create the Z3 expression (arithmetical) right shift `other` >> `self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 >> x 10 >> x >>> (10 >> x).sexpr() '(bvashr #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rlshift__(self, other): """Create the Z3 expression left shift `other << self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 << x 10 << x >>> (10 << x).sexpr() '(bvshl #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) class BitVecNumRef(BitVecRef): """Bit-vector values.""" def as_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. >>> v = BitVecVal(0xbadc0de, 32) >>> v 195936478 >>> print("0x%.8x" % v.as_long()) 0x0badc0de """ return int(self.as_string()) def as_signed_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign. >>> BitVecVal(4, 3).as_signed_long() -4 >>> BitVecVal(7, 3).as_signed_long() -1 >>> BitVecVal(3, 3).as_signed_long() 3 >>> BitVecVal(2**32 - 1, 32).as_signed_long() -1 >>> BitVecVal(2**64 - 1, 64).as_signed_long() -1 """ sz = self.size() val = self.as_long() if val >= 2**(sz - 1): val = val - 2**sz if val < -2**(sz - 1): val = val + 2**sz return int(val) def as_string(self): return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def is_bv(a): """Return `True` if `a` is a Z3 bit-vector expression. >>> b = BitVec('b', 32) >>> is_bv(b) True >>> is_bv(b + 10) True >>> is_bv(Int('x')) False """ return isinstance(a, BitVecRef) def is_bv_value(a): """Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True """ return is_bv(a) and _is_numeral(a.ctx, a.as_ast()) def BV2Int(a, is_signed=False): """Return the Z3 expression BV2Int(a). >>> b = BitVec('b', 3) >>> BV2Int(b).sort() Int >>> x = Int('x') >>> x > BV2Int(b) x > BV2Int(b) >>> x > BV2Int(b, is_signed=False) x > BV2Int(b) >>> x > BV2Int(b, is_signed=True) x > If(b < 0, BV2Int(b) - 8, BV2Int(b)) >>> solve(x > BV2Int(b), b == 1, x < 3) [b = 1, x = 2] """ if __debug__: _z3_assert(is_bv(a), "Z3 bit-vector expression expected") ctx = a.ctx ## investigate problem with bv2int return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx) def Int2BV(a, num_bits): """Return the z3 expression Int2BV(a, num_bits). It is a bit-vector of width num_bits and represents the modulo of a by 2^num_bits """ ctx = a.ctx return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx) def BitVecSort(sz, ctx=None): """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used. >>> Byte = BitVecSort(8) >>> Word = BitVecSort(16) >>> Byte BitVec(8) >>> x = Const('x', Byte) >>> eq(x, BitVec('x', 8)) True """ ctx = _get_ctx(ctx) return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx) def BitVecVal(val, bv, ctx=None): """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used. >>> v = BitVecVal(10, 32) >>> v 10 >>> print("0x%.8x" % v.as_long()) 0x0000000a """ if is_bv_sort(bv): ctx = bv.ctx return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx) else: ctx = _get_ctx(ctx) return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx) def BitVec(name, bv, ctx=None): """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort. If `ctx=None`, then the global context is used. >>> x = BitVec('x', 16) >>> is_bv(x) True >>> x.size() 16 >>> x.sort() BitVec(16) >>> word = BitVecSort(16) >>> x2 = BitVec('x', word) >>> eq(x, x2) True """ if isinstance(bv, BitVecSortRef): ctx = bv.ctx else: ctx = _get_ctx(ctx) bv = BitVecSort(bv, ctx) return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) def BitVecs(names, bv, ctx=None): """Return a tuple of bit-vector constants of size bv. >>> x, y, z = BitVecs('x y z', 16) >>> x.size() 16 >>> x.sort() BitVec(16) >>> Sum(x, y, z) 0 + x + y + z >>> Product(x, y, z) 1*x*y*z >>> simplify(Product(x, y, z)) x*y*z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [BitVec(name, bv, ctx) for name in names] def Concat(*args): """Create a Z3 bit-vector concatenation expression. >>> v = BitVecVal(1, 4) >>> Concat(v, v+1, v) Concat(Concat(1, 1 + 1), 1) >>> simplify(Concat(v, v+1, v)) 289 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long()) 121 """ args = _get_args(args) sz = len(args) if __debug__: _z3_assert(sz >= 2, "At least two arguments expected.") ctx = None for a in args: if is_expr(a): ctx = a.ctx break if is_seq(args[0]) or isinstance(args[0], str): args = [_coerce_seq(s, ctx) for s in args] if __debug__: _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx) if is_re(args[0]): if __debug__: _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx) if __debug__: _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.") r = args[0] for i in range(sz - 1): r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx) return r def Extract(high, low, a): """Create a Z3 bit-vector extraction expression, or create a string extraction expression. >>> x = BitVec('x', 8) >>> Extract(6, 2, x) Extract(6, 2, x) >>> Extract(6, 2, x).sort() BitVec(5) >>> simplify(Extract(StringVal("abcd"),2,1)) c """ if isinstance(high, str): high = StringVal(high) if is_seq(high): s = high offset, length = _coerce_exprs(low, a, s.ctx) return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx) if __debug__: _z3_assert(low <= high, "First argument must be greater than or equal to second argument") _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers") _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx) def _check_bv_args(a, b): if __debug__: _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression") def ULE(a, b): """Create the Z3 expression (unsigned) `other <= self`. Use the operator <= for signed less than or equal to. >>> x, y = BitVecs('x y', 32) >>> ULE(x, y) ULE(x, y) >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def ULT(a, b): """Create the Z3 expression (unsigned) `other < self`. Use the operator < for signed less than. >>> x, y = BitVecs('x y', 32) >>> ULT(x, y) ULT(x, y) >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGE(a, b): """Create the Z3 expression (unsigned) `other >= self`. Use the operator >= for signed greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> UGE(x, y) UGE(x, y) >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGT(a, b): """Create the Z3 expression (unsigned) `other > self`. Use the operator > for signed greater than. >>> x, y = BitVecs('x y', 32) >>> UGT(x, y) UGT(x, y) >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UDiv(a, b): """Create the Z3 expression (unsigned) division `self / other`. Use the operator / for signed division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> UDiv(x, y) UDiv(x, y) >>> UDiv(x, y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def URem(a, b): """Create the Z3 expression (unsigned) remainder `self % other`. Use the operator % for signed modulus, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> URem(x, y) URem(x, y) >>> URem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SRem(a, b): """Create the Z3 expression signed remainder. Use the operator % for signed modulus, and URem() for unsigned remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> SRem(x, y) SRem(x, y) >>> SRem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def LShR(a, b): """Create the Z3 expression logical right shift. Use the operator >> for the arithmetical right shift. >>> x, y = BitVecs('x y', 32) >>> LShR(x, y) LShR(x, y) >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateLeft(a, b): """Return an expression representing `a` rotated to the left `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateLeft(a, b) RotateLeft(a, b) >>> simplify(RotateLeft(a, 0)) a >>> simplify(RotateLeft(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateRight(a, b): """Return an expression representing `a` rotated to the right `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateRight(a, b) RotateRight(a, b) >>> simplify(RotateRight(a, 0)) a >>> simplify(RotateRight(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SignExt(n, a): """Return a bit-vector expression with `n` extra sign-bits. >>> x = BitVec('x', 16) >>> n = SignExt(8, x) >>> n.size() 24 >>> n SignExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(SignExt(6, v0)) >>> v 254 >>> v.size() 8 >>> print("%.x" % v.as_long()) fe """ if __debug__: _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def ZeroExt(n, a): """Return a bit-vector expression with `n` extra zero-bits. >>> x = BitVec('x', 16) >>> n = ZeroExt(8, x) >>> n.size() 24 >>> n ZeroExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(ZeroExt(6, v0)) >>> v 2 >>> v.size() 8 """ if __debug__: _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def RepeatBitVec(n, a): """Return an expression representing `n` copies of `a`. >>> x = BitVec('x', 8) >>> n = RepeatBitVec(4, x) >>> n RepeatBitVec(4, x) >>> n.size() 32 >>> v0 = BitVecVal(10, 4) >>> print("%.x" % v0.as_long()) a >>> v = simplify(RepeatBitVec(4, v0)) >>> v.size() 16 >>> print("%.x" % v.as_long()) aaaa """ if __debug__: _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx) def BVRedAnd(a): """Return the reduction-and expression of `a`.""" if __debug__: _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx) def BVRedOr(a): """Return the reduction-or expression of `a`.""" if __debug__: _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression") return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx) def BVAddNoOverflow(a, b, signed): """A predicate the determines that bit-vector addition does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVAddNoUnderflow(a, b): """A predicate the determines that signed bit-vector addition does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoOverflow(a, b): """A predicate the determines that bit-vector subtraction does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoUnderflow(a, b, signed): """A predicate the determines that bit-vector subtraction does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVSDivNoOverflow(a, b): """A predicate the determines that bit-vector signed division does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSNegNoOverflow(a): """A predicate the determines that bit-vector unary negation does not overflow""" if __debug__: _z3_assert(is_bv(a), "Argument should be a bit-vector") return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx) def BVMulNoOverflow(a, b, signed): """A predicate the determines that bit-vector multiplication does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVMulNoUnderflow(a, b): """A predicate the determines that bit-vector signed multiplication does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) ######################################### # # Arrays # ######################################### class ArraySortRef(SortRef): """Array sorts.""" def domain(self): """Return the domain of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.domain() Int """ return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx) def range(self): """Return the range of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.range() Bool """ return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx) class ArrayRef(ExprRef): """Array expressions. """ def sort(self): """Return the array sort of the array expression `self`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.sort() Array(Int, Bool) """ return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def domain(self): """Shorthand for `self.sort().domain()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.domain() Int """ return self.sort().domain() def range(self): """Shorthand for `self.sort().range()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.range() Bool """ return self.sort().range() def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. >>> a = Array('a', IntSort(), BoolSort()) >>> i = Int('i') >>> a[i] a[i] >>> a[i].sexpr() '(select a i)' """ arg = self.domain().cast(arg) return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx) def default(self): return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) def is_array(a): """Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False """ return isinstance(a, ArrayRef) def is_const_array(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_const_array(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_const_array(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_K(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_K(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_K(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_map(a): """Return `True` if `a` is a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> a Map(f, b) >>> is_map(a) True >>> is_map(b) False """ return is_app_of(a, Z3_OP_ARRAY_MAP) def is_default(a): """Return `True` if `a` is a Z3 default array expression. >>> d = Default(K(IntSort(), 10)) >>> is_default(d) True """ return is_app_of(a, Z3_OP_ARRAY_DEFAULT) def get_map_func(a): """Return the function declaration associated with a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> eq(f, get_map_func(a)) True >>> get_map_func(a) f >>> get_map_func(a)(0) f(0) """ if __debug__: _z3_assert(is_map(a), "Z3 array map expression expected.") return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx) def ArraySort(*sig): """Return the Z3 array sort with the given domain and range sorts. >>> A = ArraySort(IntSort(), BoolSort()) >>> A Array(Int, Bool) >>> A.domain() Int >>> A.range() Bool >>> AA = ArraySort(IntSort(), A) >>> AA Array(Int, Array(Int, Bool)) """ sig = _get_args(sig) if __debug__: _z3_assert(len(sig) > 1, "At least two arguments expected") arity = len(sig) - 1 r = sig[arity] d = sig[0] if __debug__: for s in sig: _z3_assert(is_sort(s), "Z3 sort expected") _z3_assert(s.ctx == r.ctx, "Context mismatch") ctx = d.ctx if len(sig) == 2: return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx) dom = (Sort * arity)() for i in range(arity): dom[i] = sig[i].ast return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx) def Array(name, dom, rng): """Return an array constant named `name` with the given domain and range sorts. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort() Array(Int, Int) >>> a[0] a[0] """ s = ArraySort(dom, rng) ctx = s.ctx return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) def Update(a, i, v): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Update(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ if __debug__: _z3_assert(is_array(a), "First argument must be a Z3 array expression") i = a.domain().cast(i) v = a.range().cast(v) ctx = a.ctx return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) def Default(a): """ Return a default value for array expression. >>> b = K(IntSort(), 1) >>> prove(Default(b) == 1) proved """ if __debug__: _z3_assert(is_array(a), "First argument must be a Z3 array expression") return a.default() def Store(a, i, v): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Store(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ return Update(a, i, v) def Select(a, i): """Return a Z3 select array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i = Int('i') >>> Select(a, i) a[i] >>> eq(Select(a, i), a[i]) True """ if __debug__: _z3_assert(is_array(a), "First argument must be a Z3 array expression") return a[i] def Map(f, *args): """Return a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> a1 = Array('a1', IntSort(), IntSort()) >>> a2 = Array('a2', IntSort(), IntSort()) >>> b = Map(f, a1, a2) >>> b Map(f, a1, a2) >>> prove(b[0] == f(a1[0], a2[0])) proved """ args = _get_args(args) if __debug__: _z3_assert(len(args) > 0, "At least one Z3 array expression expected") _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration") _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected") _z3_assert(len(args) == f.arity(), "Number of arguments mismatch") _args, sz = _to_ast_array(args) ctx = f.ctx return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx) def K(dom, v): """Return a Z3 constant array expression. >>> a = K(IntSort(), 10) >>> a K(Int, 10) >>> a.sort() Array(Int, Int) >>> i = Int('i') >>> a[i] K(Int, 10)[i] >>> simplify(a[i]) 10 """ if __debug__: _z3_assert(is_sort(dom), "Z3 sort expected") ctx = dom.ctx if not is_expr(v): v = _py2expr(v, ctx) return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx) def Ext(a, b): """Return extensionality index for arrays. """ if __debug__: _z3_assert(is_array(a) and is_array(b)) return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast())); def is_select(a): """Return `True` if `a` is a Z3 array select application. >>> a = Array('a', IntSort(), IntSort()) >>> is_select(a) False >>> i = Int('i') >>> is_select(a[i]) True """ return is_app_of(a, Z3_OP_SELECT) def is_store(a): """Return `True` if `a` is a Z3 array store application. >>> a = Array('a', IntSort(), IntSort()) >>> is_store(a) False >>> is_store(Store(a, 0, 1)) True """ return is_app_of(a, Z3_OP_STORE) ######################################### # # Sets # ######################################### def SetSort(s): """ Create a set sort over element sort s""" return ArraySort(s, BoolSort()) def EmptySet(s): """Create the empty set >>> EmptySet(IntSort()) K(Int, False) """ ctx = s.ctx return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx) def FullSet(s): """Create the full set >>> FullSet(IntSort()) K(Int, True) """ ctx = s.ctx return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx) def SetUnion(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetUnion(a, b) union(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx) def SetIntersect(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetIntersect(a, b) intersect(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx) def SetAdd(s, e): """ Add element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetAdd(a, 1) Store(a, 1, True) """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetDel(s, e): """ Remove element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetDel(a, 1) Store(a, 1, False) """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetComplement(s): """ The complement of set s >>> a = Const('a', SetSort(IntSort())) >>> SetComplement(a) complement(a) """ ctx = s.ctx return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx) def SetDifference(a, b): """ The set difference of a and b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetDifference(a, b) difference(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def IsMember(e, s): """ Check if e is a member of set s >>> a = Const('a', SetSort(IntSort())) >>> IsMember(1, a) a[1] """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx) def IsSubset(a, b): """ Check if a is a subset of b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> IsSubset(a, b) subset(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx) ######################################### # # Datatypes # ######################################### def _valid_accessor(acc): """Return `True` if acc is pair of the form (String, Datatype or Sort). """ return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])) class Datatype: """Helper class for declaring Z3 datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) >>> List.cons(10, List.nil).sort() List >>> cons = List.cons >>> nil = List.nil >>> car = List.car >>> cdr = List.cdr >>> n = cons(1, cons(0, nil)) >>> n cons(1, cons(0, nil)) >>> simplify(cdr(n)) cons(0, nil) >>> simplify(car(n)) 1 """ def __init__(self, name, ctx=None): self.ctx = _get_ctx(ctx) self.name = name self.constructors = [] def __deepcopy__(self, memo={}): r = Datatype(self.name, self.ctx) r.constructors = copy.deepcopy(self.constructors) return r def declare_core(self, name, rec_name, *args): if __debug__: _z3_assert(isinstance(name, str), "String expected") _z3_assert(isinstance(rec_name, str), "String expected") _z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)") self.constructors.append((name, rec_name, args)) def declare(self, name, *args): """Declare constructor named `name` with the given accessors `args`. Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared. In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))` declares the constructor named `cons` that builds a new List using an integer and a List. It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() """ if __debug__: _z3_assert(isinstance(name, str), "String expected") _z3_assert(name != "", "Constructor name cannot be empty") return self.declare_core(name, "is-" + name, *args) def __repr__(self): return "Datatype(%s, %s)" % (self.name, self.constructors) def create(self): """Create a Z3 datatype based on the constructors declared using the method `declare()`. The function `CreateDatatypes()` must be used to define mutually recursive datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) """ return CreateDatatypes([self])[0] class ScopedConstructor: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None: Z3_del_constructor(self.ctx.ref(), self.c) class ScopedConstructorList: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None: Z3_del_constructor_list(self.ctx.ref(), self.c) def CreateDatatypes(*ds): """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects. In the following example we define a Tree-List using two mutually recursive datatypes. >>> TreeList = Datatype('TreeList') >>> Tree = Datatype('Tree') >>> # Tree has two constructors: leaf and node >>> Tree.declare('leaf', ('val', IntSort())) >>> # a node contains a list of trees >>> Tree.declare('node', ('children', TreeList)) >>> TreeList.declare('nil') >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList)) >>> Tree, TreeList = CreateDatatypes(Tree, TreeList) >>> Tree.val(Tree.leaf(10)) val(leaf(10)) >>> simplify(Tree.val(Tree.leaf(10))) 10 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil))) >>> n1 node(cons(leaf(10), cons(leaf(20), nil))) >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil)) >>> simplify(n2 == n1) False >>> simplify(TreeList.car(Tree.children(n2)) == n1) True """ ds = _get_args(ds) if __debug__: _z3_assert(len(ds) > 0, "At least one Datatype must be specified") _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes") _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch") _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected") ctx = ds[0].ctx num = len(ds) names = (Symbol * num)() out = (Sort * num)() clists = (ConstructorList * num)() to_delete = [] for i in range(num): d = ds[i] names[i] = to_symbol(d.name, ctx) num_cs = len(d.constructors) cs = (Constructor * num_cs)() for j in range(num_cs): c = d.constructors[j] cname = to_symbol(c[0], ctx) rname = to_symbol(c[1], ctx) fs = c[2] num_fs = len(fs) fnames = (Symbol * num_fs)() sorts = (Sort * num_fs)() refs = (ctypes.c_uint * num_fs)() for k in range(num_fs): fname = fs[k][0] ftype = fs[k][1] fnames[k] = to_symbol(fname, ctx) if isinstance(ftype, Datatype): if __debug__: _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected") sorts[k] = None refs[k] = ds.index(ftype) else: if __debug__: _z3_assert(is_sort(ftype), "Z3 sort expected") sorts[k] = ftype.ast refs[k] = 0 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs) to_delete.append(ScopedConstructor(cs[j], ctx)) clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs) to_delete.append(ScopedConstructorList(clists[i], ctx)) Z3_mk_datatypes(ctx.ref(), num, names, out, clists) result = [] ## Create a field for every constructor, recognizer and accessor for i in range(num): dref = DatatypeSortRef(out[i], ctx) num_cs = dref.num_constructors() for j in range(num_cs): cref = dref.constructor(j) cref_name = cref.name() cref_arity = cref.arity() if cref.arity() == 0: cref = cref() setattr(dref, cref_name, cref) rref = dref.recognizer(j) setattr(dref, "is_" + cref_name, rref) for k in range(cref_arity): aref = dref.accessor(j, k) setattr(dref, aref.name(), aref) result.append(dref) return tuple(result) class DatatypeSortRef(SortRef): """Datatype sorts.""" def num_constructors(self): """Return the number of constructors in the given Z3 datatype. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 """ return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast)) def constructor(self, idx): """Return a constructor of the datatype `self`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> List.constructor(1) nil """ if __debug__: _z3_assert(idx < self.num_constructors(), "Invalid constructor index") return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx) def recognizer(self, idx): """In Z3, each constructor has an associated recognizer predicate. If the constructor is named `name`, then the recognizer `is_name`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.recognizer(0) is(cons) >>> List.recognizer(1) is(nil) >>> simplify(List.is_nil(List.cons(10, List.nil))) False >>> simplify(List.is_cons(List.cons(10, List.nil))) True >>> l = Const('l', List) >>> simplify(List.is_cons(l)) is(cons, l) """ if __debug__: _z3_assert(idx < self.num_constructors(), "Invalid recognizer index") return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx) def accessor(self, i, j): """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> num_accs = List.constructor(0).arity() >>> num_accs 2 >>> List.accessor(0, 0) car >>> List.accessor(0, 1) cdr >>> List.constructor(1) nil >>> num_accs = List.constructor(1).arity() >>> num_accs 0 """ if __debug__: _z3_assert(i < self.num_constructors(), "Invalid constructor index") _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index") return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx) class DatatypeRef(ExprRef): """Datatype expressions.""" def sort(self): """Return the datatype sort of the datatype expression `self`.""" return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def EnumSort(name, values, ctx=None): """Return a new enumeration sort named `name` containing the given values. The result is a pair (sort, list of constants). Example: >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue']) """ if __debug__: _z3_assert(isinstance(name, str), "Name must be a string") _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings") _z3_assert(len(values) > 0, "At least one value expected") ctx = _get_ctx(ctx) num = len(values) _val_names = (Symbol * num)() for i in range(num): _val_names[i] = to_symbol(values[i]) _values = (FuncDecl * num)() _testers = (FuncDecl * num)() name = to_symbol(name) S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx) V = [] for i in range(num): V.append(FuncDeclRef(_values[i], ctx)) V = [a() for a in V] return S, V ######################################### # # Parameter Sets # ######################################### class ParamsRef: """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3. Consider using the function `args2params` to create instances of this object. """ def __init__(self, ctx=None, params=None): self.ctx = _get_ctx(ctx) if params is None: self.params = Z3_mk_params(self.ctx.ref()) else: self.params = params Z3_params_inc_ref(self.ctx.ref(), self.params) def __deepcopy__(self, memo={}): return ParamsRef(self.ctx, self.params) def __del__(self): if self.ctx.ref() is not None: Z3_params_dec_ref(self.ctx.ref(), self.params) def set(self, name, val): """Set parameter name with value val.""" if __debug__: _z3_assert(isinstance(name, str), "parameter name must be a string") name_sym = to_symbol(name, self.ctx) if isinstance(val, bool): Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val) elif _is_int(val): Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, float): Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, str): Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx)) else: if __debug__: _z3_assert(False, "invalid parameter value") def __repr__(self): return Z3_params_to_string(self.ctx.ref(), self.params) def validate(self, ds): _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected") Z3_params_validate(self.ctx.ref(), self.params, ds.descr) def args2params(arguments, keywords, ctx=None): """Convert python arguments into a Z3_params object. A ':' is added to the keywords, and '_' is replaced with '-' >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True}) (params model true relevancy 2 elim_and true) """ if __debug__: _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.") prev = None r = ParamsRef(ctx) for a in arguments: if prev is None: prev = a else: r.set(prev, a) prev = None for k in keywords: v = keywords[k] r.set(k, v) return r class ParamDescrsRef: """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3. """ def __init__(self, descr, ctx=None): _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected") self.ctx = _get_ctx(ctx) self.descr = descr Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr) def __deepcopy__(self, memo={}): return ParamsDescrsRef(self.descr, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr) def size(self): """Return the size of in the parameter description `self`. """ return int(Z3_param_descrs_size(self.ctx.ref(), self.descr)) def __len__(self): """Return the size of in the parameter description `self`. """ return self.size() def get_name(self, i): """Return the i-th parameter name in the parameter description `self`. """ return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i)) def get_kind(self, n): """Return the kind of the parameter named `n`. """ return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def get_documentation(self, n): """Return the documentation string of the parameter named `n`. """ return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def __getitem__(self, arg): if _is_int(arg): return self.get_name(arg) else: return self.get_kind(arg) def __repr__(self): return Z3_param_descrs_to_string(self.ctx.ref(), self.descr) ######################################### # # Goals # ######################################### class Goal(Z3PPObject): """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible). Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals. A goal has a solution if one of its subgoals has a solution. A goal is unsatisfiable if all subgoals are unsatisfiable. """ def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None): if __debug__: _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None") self.ctx = _get_ctx(ctx) self.goal = goal if self.goal is None: self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs) Z3_goal_inc_ref(self.ctx.ref(), self.goal) def __deepcopy__(self, memo={}): return Goal(False, False, False, self.ctx, self.goal) def __del__(self): if self.goal is not None and self.ctx.ref() is not None: Z3_goal_dec_ref(self.ctx.ref(), self.goal) def depth(self): """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`. >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x == 0, y >= x + 1) >>> g.depth() 0 >>> r = Then('simplify', 'solve-eqs')(g) >>> # r has 1 subgoal >>> len(r) 1 >>> r[0].depth() 2 """ return int(Z3_goal_depth(self.ctx.ref(), self.goal)) def inconsistent(self): """Return `True` if `self` contains the `False` constraints. >>> x, y = Ints('x y') >>> g = Goal() >>> g.inconsistent() False >>> g.add(x == 0, x == 1) >>> g [x == 0, x == 1] >>> g.inconsistent() False >>> g2 = Tactic('propagate-values')(g)[0] >>> g2.inconsistent() True """ return Z3_goal_inconsistent(self.ctx.ref(), self.goal) def prec(self): """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`. >>> g = Goal() >>> g.prec() == Z3_GOAL_PRECISE True >>> x, y = Ints('x y') >>> g.add(x == y + 1) >>> g.prec() == Z3_GOAL_PRECISE True >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10) >>> g2 = t(g)[0] >>> g2 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0] >>> g2.prec() == Z3_GOAL_PRECISE False >>> g2.prec() == Z3_GOAL_UNDER True """ return Z3_goal_precision(self.ctx.ref(), self.goal) def precision(self): """Alias for `prec()`. >>> g = Goal() >>> g.precision() == Z3_GOAL_PRECISE True """ return self.prec() def size(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> g.size() 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.size() 2 """ return int(Z3_goal_size(self.ctx.ref(), self.goal)) def __len__(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> len(g) 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> len(g) 2 """ return self.size() def get(self, i): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.get(0) x == 0 >>> g.get(1) y > x """ return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx) def __getitem__(self, arg): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g[0] x == 0 >>> g[1] y > x """ if arg >= len(self): raise IndexError return self.get(arg) def assert_exprs(self, *args): """Assert constraints into the goal. >>> x = Int('x') >>> g = Goal() >>> g.assert_exprs(x > 0, x < 2) >>> g [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: arg = s.cast(arg) Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast()) def append(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.append(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.insert(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def add(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def convert_model(self, model): """Retrieve model from a satisfiable goal >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs')) >>> r = t(g) >>> r[0] [Or(b == 0, b == 1), Not(0 <= b)] >>> r[1] [Or(b == 0, b == 1), Not(1 <= b)] >>> # Remark: the subgoal r[0] is unsatisfiable >>> # Creating a solver for solving the second subgoal >>> s = Solver() >>> s.add(r[1]) >>> s.check() sat >>> s.model() [b = 0] >>> # Model s.model() does not assign a value to `a` >>> # It is a model for subgoal `r[1]`, but not for goal `g` >>> # The method convert_model creates a model for `g` from a model for `r[1]`. >>> r[1].convert_model(s.model()) [b = 0, a = 1] """ if __debug__: _z3_assert(isinstance(model, ModelRef), "Z3 Model expected") return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the goal.""" return Z3_goal_to_string(self.ctx.ref(), self.goal) def dimacs(self): """Return a textual representation of the goal in DIMACS format.""" return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal) def translate(self, target): """Copy goal `self` to context `target`. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 10) >>> g [x > 10] >>> c2 = Context() >>> g2 = g.translate(c2) >>> g2 [x > 10] >>> g.ctx == main_ctx() True >>> g2.ctx == c2 True >>> g2.ctx == main_ctx() False """ if __debug__: _z3_assert(isinstance(target, Context), "target must be a context") return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self): return self.translate(self.ctx) def simplify(self, *arguments, **keywords): """Return a new simplified goal. This method is essentially invoking the simplify tactic. >>> g = Goal() >>> x = Int('x') >>> g.add(x + 1 >= 2) >>> g [x + 1 >= 2] >>> g2 = g.simplify() >>> g2 [x >= 1] >>> # g was not modified >>> g [x + 1 >= 2] """ t = Tactic('simplify') return t.apply(self, *arguments, **keywords)[0] def as_expr(self): """Return goal `self` as a single Z3 expression. >>> x = Int('x') >>> g = Goal() >>> g.as_expr() True >>> g.add(x > 1) >>> g.as_expr() x > 1 >>> g.add(x < 10) >>> g.as_expr() And(x > 1, x < 10) """ sz = len(self) if sz == 0: return BoolVal(True, self.ctx) elif sz == 1: return self.get(0) else: return And([ self.get(i) for i in range(len(self)) ], self.ctx) ######################################### # # AST Vector # ######################################### class AstVector(Z3PPObject): """A collection (vector) of ASTs.""" def __init__(self, v=None, ctx=None): self.vector = None if v is None: self.ctx = _get_ctx(ctx) self.vector = Z3_mk_ast_vector(self.ctx.ref()) else: self.vector = v assert ctx is not None self.ctx = ctx Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector) def __deepcopy__(self, memo={}): return AstVector(self.vector, self.ctx) def __del__(self): if self.vector is not None and self.ctx.ref() is not None: Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector) def __len__(self): """Return the size of the vector `self`. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> A.push(Int('x')) >>> len(A) 2 """ return int(Z3_ast_vector_size(self.ctx.ref(), self.vector)) def __getitem__(self, i): """Return the AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[1] y """ if isinstance(i, int): if i < 0: i += self.__len__() if i >= self.__len__(): raise IndexError return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx) elif isinstance(i, slice): return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))] def __setitem__(self, i, v): """Update AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[0] = Int('x') >>> A[0] x """ if i >= self.__len__(): raise IndexError Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast()) def push(self, v): """Add `v` in the end of the vector. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> len(A) 1 """ Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast()) def resize(self, sz): """Resize the vector to `sz` elements. >>> A = AstVector() >>> A.resize(10) >>> len(A) 10 >>> for i in range(10): A[i] = Int('x') >>> A[5] x """ Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz) def __contains__(self, item): """Return `True` if the vector contains `item`. >>> x = Int('x') >>> A = AstVector() >>> x in A False >>> A.push(x) >>> x in A True >>> (x+1) in A False >>> A.push(x+1) >>> (x+1) in A True >>> A [x, x + 1] """ for elem in self: if elem.eq(item): return True return False def translate(self, other_ctx): """Copy vector `self` to context `other_ctx`. >>> x = Int('x') >>> A = AstVector() >>> A.push(x) >>> c2 = Context() >>> B = A.translate(c2) >>> B [x] """ return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self): return self.translate(self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the vector.""" return Z3_ast_vector_to_string(self.ctx.ref(), self.vector) ######################################### # # AST Map # ######################################### class AstMap: """A mapping from ASTs to ASTs.""" def __init__(self, m=None, ctx=None): self.map = None if m is None: self.ctx = _get_ctx(ctx) self.map = Z3_mk_ast_map(self.ctx.ref()) else: self.map = m assert ctx is not None self.ctx = ctx Z3_ast_map_inc_ref(self.ctx.ref(), self.map) def __deepcopy__(self, memo={}): return AstMap(self.map, self.ctx) def __del__(self): if self.map is not None and self.ctx.ref() is not None: Z3_ast_map_dec_ref(self.ctx.ref(), self.map) def __len__(self): """Return the size of the map. >>> M = AstMap() >>> len(M) 0 >>> x = Int('x') >>> M[x] = IntVal(1) >>> len(M) 1 """ return int(Z3_ast_map_size(self.ctx.ref(), self.map)) def __contains__(self, key): """Return `True` if the map contains key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> x in M True >>> x+1 in M False """ return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast()) def __getitem__(self, key): """Retrieve the value associated with key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x] x + 1 """ return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx) def __setitem__(self, k, v): """Add/Update key `k` with value `v`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M[x] x + 1 >>> M[x] = IntVal(1) >>> M[x] 1 """ Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast()) def __repr__(self): return Z3_ast_map_to_string(self.ctx.ref(), self.map) def erase(self, k): """Remove the entry associated with key `k`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M.erase(x) >>> len(M) 0 """ Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast()) def reset(self): """Remove all entries from the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> len(M) 2 >>> M.reset() >>> len(M) 0 """ Z3_ast_map_reset(self.ctx.ref(), self.map) def keys(self): """Return an AstVector containing all keys in the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> M.keys() [x, x + x] """ return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx) ######################################### # # Model # ######################################### class FuncEntry: """Store the value of the interpretation of a function in a particular point.""" def __init__(self, entry, ctx): self.entry = entry self.ctx = ctx Z3_func_entry_inc_ref(self.ctx.ref(), self.entry) def __deepcopy__(self, memo={}): return FuncEntry(self.entry, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_func_entry_dec_ref(self.ctx.ref(), self.entry) def num_args(self): """Return the number of arguments in the given entry. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.num_args() 2 """ return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry)) def arg_value(self, idx): """Return the value of argument `idx`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.arg_value(0) 1 >>> e.arg_value(1) 2 >>> try: ... e.arg_value(2) ... except IndexError: ... print("index error") index error """ if idx >= self.num_args(): raise IndexError return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx) def value(self): """Return the value of the function at point `self`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.value() 20 """ return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx) def as_list(self): """Return entry `self` as a Python list. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.as_list() [1, 2, 20] """ args = [ self.arg_value(i) for i in range(self.num_args())] args.append(self.value()) return args def __repr__(self): return repr(self.as_list()) class FuncInterp(Z3PPObject): """Stores the interpretation of a function in a Z3 model.""" def __init__(self, f, ctx): self.f = f self.ctx = ctx if self.f is not None: Z3_func_interp_inc_ref(self.ctx.ref(), self.f) def __deepcopy__(self, memo={}): return FuncInterp(self.f, self.ctx) def __del__(self): if self.f is not None and self.ctx.ref() is not None: Z3_func_interp_dec_ref(self.ctx.ref(), self.f) def else_value(self): """ Return the `else` value for a function interpretation. Return None if Z3 did not specify the `else` value for this object. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].else_value() 1 """ r = Z3_func_interp_get_else(self.ctx.ref(), self.f) if r: return _to_expr_ref(r, self.ctx) else: return None def num_entries(self): """Return the number of entries/points in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 """ return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f)) def arity(self): """Return the number of arguments for each entry in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f].arity() 1 """ return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f)) def entry(self, idx): """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 >>> m[f].entry(0) [2, 0] """ if idx >= self.num_entries(): raise IndexError return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx) def translate(self, other_ctx): """Copy model 'self' to context 'other_ctx'. """ return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self): return self.translate(self.ctx) def as_list(self): """Return the function interpretation as a Python list. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].as_list() [[2, 0], 1] """ r = [ self.entry(i).as_list() for i in range(self.num_entries())] r.append(self.else_value()) return r def __repr__(self): return obj_to_string(self) class ModelRef(Z3PPObject): """Model/Solution of a satisfiability problem (aka system of constraints).""" def __init__(self, m, ctx): assert ctx is not None self.model = m self.ctx = ctx Z3_model_inc_ref(self.ctx.ref(), self.model) def __del__(self): if self.ctx.ref() is not None: Z3_model_dec_ref(self.ctx.ref(), self.model) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the model.""" return Z3_model_to_string(self.ctx.ref(), self.model) def eval(self, t, model_completion=False): """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.eval(x + 1) 2 >>> m.eval(x == 1) True >>> y = Int('y') >>> m.eval(y + x) 1 + y >>> m.eval(y) y >>> m.eval(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.eval(y + x) 1 """ r = (Ast * 1)() if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r): return _to_expr_ref(r[0], self.ctx) raise Z3Exception("failed to evaluate expression in the model") def evaluate(self, t, model_completion=False): """Alias for `eval`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.evaluate(x + 1) 2 >>> m.evaluate(x == 1) True >>> y = Int('y') >>> m.evaluate(y + x) 1 + y >>> m.evaluate(y) y >>> m.evaluate(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.evaluate(y + x) 1 """ return self.eval(t, model_completion) def __len__(self): """Return the number of constant and function declarations in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, f(x) != x) >>> s.check() sat >>> m = s.model() >>> len(m) 2 """ return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) def get_interp(self, decl): """Return the interpretation for a given declaration or constant. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1 >>> m[f] [else -> 0] """ if __debug__: _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected") if is_const(decl): decl = decl.decl() try: if decl.arity() == 0: _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast) if _r.value is None: return None r = _to_expr_ref(_r, self.ctx) if is_as_array(r): return self.get_interp(get_as_array_func(r)) else: return r else: return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) except Z3Exception: return None def num_sorts(self): """Return the number of uninterpreted sorts that contain an interpretation in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 1 """ return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model)) def get_sort(self, idx): """Return the uninterpreted sort at position `idx` < self.num_sorts(). >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 2 >>> m.get_sort(0) A >>> m.get_sort(1) B """ if idx >= self.num_sorts(): raise IndexError return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx) def sorts(self): """Return all uninterpreted sorts that have an interpretation in the model `self`. >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.sorts() [A, B] """ return [ self.get_sort(i) for i in range(self.num_sorts()) ] def get_universe(self, s): """Return the interpretation for the uninterpreted sort `s` in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.get_universe(A) [A!val!0, A!val!1] """ if __debug__: _z3_assert(isinstance(s, SortRef), "Z3 sort expected") try: return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx) except Z3Exception: return None def __getitem__(self, idx): """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned. The elements can be retrieved using position or the actual declaration. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> len(m) 2 >>> m[0] x >>> m[1] f >>> m[x] 1 >>> m[f] [else -> 0] >>> for d in m: print("%s -> %s" % (d, m[d])) x -> 1 f -> [else -> 0] """ if _is_int(idx): if idx >= len(self): raise IndexError num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model) if (idx < num_consts): return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx) else: return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx) if isinstance(idx, FuncDeclRef): return self.get_interp(idx) if is_const(idx): return self.get_interp(idx.decl()) if isinstance(idx, SortRef): return self.get_universe(idx) if __debug__: _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected") return None def decls(self): """Return a list with all symbols that have an interpretation in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m.decls() [x, f] """ r = [] for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx)) for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx)) return r def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. """ if __debug__: _z3_assert(isinstance(target, Context), "argument must be a Z3 context") model = Z3_model_translate(self.ctx.ref(), self.model, target.ref()) return Model(model, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self): return self.translate(self.ctx) def Model(ctx = None): ctx = _get_ctx(ctx) return ModelRef(Z3_mk_model(ctx.ref()), ctx) def is_as_array(n): """Return true if n is a Z3 expression of the form (_ as-array f).""" return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast()) def get_as_array_func(n): """Return the function declaration f associated with a Z3 expression of the form (_ as-array f).""" if __debug__: _z3_assert(is_as_array(n), "as-array Z3 expression expected.") return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx) ######################################### # # Statistics # ######################################### class Statistics: """Statistics for `Solver.check()`.""" def __init__(self, stats, ctx): self.stats = stats self.ctx = ctx Z3_stats_inc_ref(self.ctx.ref(), self.stats) def __deepcopy__(self, memo={}): return Statistics(self.stats, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_stats_dec_ref(self.ctx.ref(), self.stats) def __repr__(self): if in_html_mode(): out = io.StringIO() even = True out.write(u('<table border="1" cellpadding="2" cellspacing="0">')) for k, v in self: if even: out.write(u('<tr style="background-color:#CFCFCF">')) even = False else: out.write(u('<tr>')) even = True out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v))) out.write(u('</table>')) return out.getvalue() else: return Z3_stats_to_string(self.ctx.ref(), self.stats) def __len__(self): """Return the number of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 """ return int(Z3_stats_size(self.ctx.ref(), self.stats)) def __getitem__(self, idx): """Return the value of statistical counter at position `idx`. The result is a pair (key, value). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 >>> st[0] ('nlsat propagations', 2) >>> st[1] ('nlsat stages', 2) """ if idx >= len(self): raise IndexError if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val) def keys(self): """Return the list of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() """ return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))] def get_key_value(self, key): """Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2 """ for idx in range(len(self)): if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) raise Z3Exception("unknown key") def __getattr__(self, name): """Access the value of statistical using attributes. Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'), we should use '_' (e.g., 'nlsat_propagations'). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.nlsat_propagations 2 >>> st.nlsat_stages 2 """ key = name.replace('_', ' ') try: return self.get_key_value(key) except Z3Exception: raise AttributeError ######################################### # # Solver # ######################################### class CheckSatResult: """Represents the result of a satisfiability check: sat, unsat, unknown. >>> s = Solver() >>> s.check() sat >>> r = s.check() >>> isinstance(r, CheckSatResult) True """ def __init__(self, r): self.r = r def __deepcopy__(self, memo={}): return CheckSatResult(self.r) def __eq__(self, other): return isinstance(other, CheckSatResult) and self.r == other.r def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if in_html_mode(): if self.r == Z3_L_TRUE: return "<b>sat</b>" elif self.r == Z3_L_FALSE: return "<b>unsat</b>" else: return "<b>unknown</b>" else: if self.r == Z3_L_TRUE: return "sat" elif self.r == Z3_L_FALSE: return "unsat" else: return "unknown" sat = CheckSatResult(Z3_L_TRUE) unsat = CheckSatResult(Z3_L_FALSE) unknown = CheckSatResult(Z3_L_UNDEF) class Solver(Z3PPObject): """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc.""" def __init__(self, solver=None, ctx=None): assert solver is None or ctx is not None self.ctx = _get_ctx(ctx) self.backtrack_level = 4000000000 self.solver = None if solver is None: self.solver = Z3_mk_solver(self.ctx.ref()) else: self.solver = solver Z3_solver_inc_ref(self.ctx.ref(), self.solver) def __del__(self): if self.solver is not None and self.ctx.ref() is not None: Z3_solver_dec_ref(self.ctx.ref(), self.solver) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. >>> s = Solver() >>> # The option MBQI can be set using three different approaches. >>> s.set(mbqi=True) >>> s.set('MBQI', True) >>> s.set(':mbqi', True) """ p = args2params(args, keys, self.ctx) Z3_solver_set_params(self.ctx.ref(), self.solver, p.params) def push(self): """Create a backtracking point. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_push(self.ctx.ref(), self.solver) def pop(self, num=1): """Backtrack \c num backtracking points. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_pop(self.ctx.ref(), self.solver, num) def num_scopes(self): """Return the current number of backtracking points. >>> s = Solver() >>> s.num_scopes() 0L >>> s.push() >>> s.num_scopes() 1L >>> s.push() >>> s.num_scopes() 2L >>> s.pop() >>> s.num_scopes() 1L """ return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver) def reset(self): """Remove all asserted constraints and backtracking points created using `push()`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.reset() >>> s [] """ Z3_solver_reset(self.ctx.ref(), self.solver) def assert_exprs(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.assert_exprs(x > 0, x < 2) >>> s [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast()) else: arg = s.cast(arg) Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast()) def add(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.append(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.insert(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Solver() >>> s.set(unsat_core=True) >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast()) def check(self, *assumptions): """Check whether the assertions in the given solver plus the optional assumptions are consistent or not. >>> x = Int('x') >>> s = Solver() >>> s.check() sat >>> s.add(x > 0, x < 2) >>> s.check() sat >>> s.model().eval(x) 1 >>> s.add(x < 1) >>> s.check() unsat >>> s.reset() >>> s.add(2**x == 4) >>> s.check() unknown """ assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions) return CheckSatResult(r) def model(self): """Return a model for the last `check()`. This function raises an exception if a model is not available (e.g., last `check()` returned unsat). >>> s = Solver() >>> a = Int('a') >>> s.add(a + 2 == 0) >>> s.check() sat >>> s.model() [a = -2] """ try: return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def unsat_core(self): """Return a subset (as an AST vector) of the assumptions provided to the last check(). These are the assumptions Z3 used in the unsatisfiability proof. Assumptions are available in Z3. They are used to extract unsatisfiable cores. They may be also used to "retract" assumptions. Note that, assumptions are not really "soft constraints", but they can be used to implement them. >>> p1, p2, p3 = Bools('p1 p2 p3') >>> x, y = Ints('x y') >>> s = Solver() >>> s.add(Implies(p1, x > 0)) >>> s.add(Implies(p2, y > x)) >>> s.add(Implies(p2, y < 1)) >>> s.add(Implies(p3, y > -3)) >>> s.check(p1, p2, p3) unsat >>> core = s.unsat_core() >>> len(core) 2 >>> p1 in core True >>> p2 in core True >>> p3 in core False >>> # "Retracting" p2 >>> s.check(p1, p3) sat """ return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx) def consequences(self, assumptions, variables): """Determine fixed values for the variables based on the solver state and assumptions. >>> s = Solver() >>> a, b, c, d = Bools('a b c d') >>> s.add(Implies(a,b), Implies(b, c)) >>> s.consequences([a],[b,c,d]) (sat, [Implies(a, b), Implies(a, c)]) >>> s.consequences([Not(c),d],[a,b,c,d]) (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))]) """ if isinstance(assumptions, list): _asms = AstVector(None, self.ctx) for a in assumptions: _asms.push(a) assumptions = _asms if isinstance(variables, list): _vars = AstVector(None, self.ctx) for a in variables: _vars.push(a) variables = _vars _z3_assert(isinstance(assumptions, AstVector), "ast vector expected") _z3_assert(isinstance(variables, AstVector), "ast vector expected") consequences = AstVector(None, self.ctx) r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector) sz = len(consequences) consequences = [ consequences[i] for i in range(sz) ] return CheckSatResult(r), consequences def from_file(self, filename): """Parse assertions from a file""" Z3_solver_from_file(self.ctx.ref(), self.solver, filename) def from_string(self, s): """Parse assertions from a string""" Z3_solver_from_string(self.ctx.ref(), self.solver, s) def cube(self, vars = None): """Get set of cubes The method takes an optional set of variables that restrict which variables may be used as a starting point for cubing. If vars is not None, then the first case split is based on a variable in this set. """ self.cube_vs = AstVector(None, self.ctx) if vars is not None: for v in vars: self.cube_vs.push(v) while True: lvl = self.backtrack_level self.backtrack_level = 4000000000 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx) if (len(r) == 1 and is_false(r[0])): return yield r if (len(r) == 0): return def cube_vars(self): """Access the set of variables that were touched by the most recently generated cube. This set of variables can be used as a starting point for additional cubes. The idea is that variables that appear in clauses that are reduced by the most recent cube are likely more useful to cube on.""" return self.cube_vs def proof(self): """Return a proof for the last `check()`. Proof construction must be enabled.""" return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx) def assertions(self): """Return an AST vector containing all added constraints. >>> s = Solver() >>> s.assertions() [] >>> a = Int('a') >>> s.add(a > 0) >>> s.add(a < 10) >>> s.assertions() [a > 0, a < 10] """ return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx) def units(self): """Return an AST vector containing all currently inferred units. """ return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx) def non_units(self): """Return an AST vector containing all atomic formulas in solver state that are not units. """ return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx) def statistics(self): """Return statistics for the last `check()`. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('final checks') 1 >>> len(st) > 0 True >>> st[0] != 0 True """ return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx) def reason_unknown(self): """Return a string describing why the last `check()` returned `unknown`. >>> x = Int('x') >>> s = SimpleSolver() >>> s.add(2**x == 4) >>> s.check() unknown >>> s.reason_unknown() '(incomplete (theory arithmetic))' """ return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver) def help(self): """Display a string describing all available options.""" print(Z3_solver_get_help(self.ctx.ref(), self.solver)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx) def __repr__(self): """Return a formatted string with all added constraints.""" return obj_to_string(self) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> s1 = Solver(ctx=c1) >>> s2 = s1.translate(c2) """ if __debug__: _z3_assert(isinstance(target, Context), "argument must be a Z3 context") solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref()) return Solver(solver, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self): return self.translate(self.ctx) def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s.add(x < 2) >>> r = s.sexpr() """ return Z3_solver_to_string(self.ctx.ref(), self.solver) def dimacs(self): """Return a textual representation of the solver in DIMACS format.""" return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver) def to_smt2(self): """return SMTLIB2 formatted benchmark for solver's assertions""" es = self.assertions() sz = len(es) sz1 = sz if sz1 > 0: sz1 -= 1 v = (Ast * sz1)() for i in range(sz1): v[i] = es[i].as_ast() if sz > 0: e = es[sz1].as_ast() else: e = BoolVal(True, self.ctx).as_ast() return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e) def SolverFor(logic, ctx=None): """Create a solver customized for the given logic. The parameter `logic` is a string. It should be contains the name of a SMT-LIB logic. See http://www.smtlib.org/ for the name of all available logics. >>> s = SolverFor("QF_LIA") >>> x = Int('x') >>> s.add(x > 0) >>> s.add(x < 2) >>> s.check() sat >>> s.model() [x = 1] """ ctx = _get_ctx(ctx) logic = to_symbol(logic) return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx) def SimpleSolver(ctx=None): """Return a simple general purpose solver with limited amount of preprocessing. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat """ ctx = _get_ctx(ctx) return Solver(Z3_mk_simple_solver(ctx.ref()), ctx) ######################################### # # Fixedpoint # ######################################### class Fixedpoint(Z3PPObject): """Fixedpoint API provides methods for solving with recursive predicates""" def __init__(self, fixedpoint=None, ctx=None): assert fixedpoint is None or ctx is not None self.ctx = _get_ctx(ctx) self.fixedpoint = None if fixedpoint is None: self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref()) else: self.fixedpoint = fixedpoint Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint) self.vars = [] def __deepcopy__(self, memo={}): return FixedPoint(self.fixedpoint, self.ctx) def __del__(self): if self.fixedpoint is not None and self.ctx.ref() is not None: Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params) def help(self): """Display a string describing all available options.""" print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the fixedpoint solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: f = self.abstract(f) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast()) else: arg = s.cast(arg) arg = self.abstract(arg) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def insert(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def add_rule(self, head, body = None, name = None): """Assert rules defining recursive predicates to the fixedpoint solver. >>> a = Bool('a') >>> b = Bool('b') >>> s = Fixedpoint() >>> s.register_relation(a.decl()) >>> s.register_relation(b.decl()) >>> s.fact(a) >>> s.rule(b, a) >>> s.query(b) sat """ if name is None: name = "" name = to_symbol(name, self.ctx) if body is None: head = self.abstract(head) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name) else: body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx),head)) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def rule(self, head, body = None, name = None): """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, body, name) def fact(self, head, name = None): """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, None, name) def query(self, *query): """Query the fixedpoint engine whether formula is derivable. You can also pass an tuple or list of recursive predicates. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDeclRef): _decls = (FuncDecl * sz)() i = 0 for q in query: _decls[i] = q.ast i = i + 1 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls) else: if sz == 1: query = query[0] else: query = And(query, self.ctx) query = self.abstract(query, False) r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast()) return CheckSatResult(r) def query_from_lvl (self, lvl, *query): """Query the fixedpoint engine whether formula is derivable starting at the given query level. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDecl): _z3_assert (False, "unsupported") else: if sz == 1: query = query[0] else: query = And(query) query = self.abstract(query, False) r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl) return CheckSatResult(r) def push(self): """create a backtracking point for added rules, facts and assertions""" Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint) def pop(self): """restore to previously created backtracking point""" Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint) def update_rule(self, head, body, name): """update rule""" if name is None: name = "" name = to_symbol(name, self.ctx) body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx),head)) Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def get_answer(self): """Retrieve answer from last query call.""" r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_ground_sat_answer(self): """Retrieve a ground cex from last query call.""" r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_rules_along_trace(self): """retrieve rules along the counterexample trace""" return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx) def get_rule_names_along_trace(self): """retrieve rule names along the counterexample trace""" # this is a hack as I don't know how to return a list of symbols from C++; # obtain names as a single string separated by semicolons names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint)) # split into individual names return names.split (';') def get_num_levels(self, predicate): """Retrieve number of levels used for predicate in PDR engine""" return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast) def get_cover_delta(self, level, predicate): """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)""" r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast) return _to_expr_ref(r, self.ctx) def add_cover(self, level, predicate, property): """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)""" Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast) def register_relation(self, *relations): """Register relation as recursive""" relations = _get_args(relations) for f in relations: Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast) def set_predicate_representation(self, f, *representations): """Control how relation is represented""" representations = _get_args(representations) representations = [to_symbol(s) for s in representations] sz = len(representations) args = (Symbol * sz)() for i in range(sz): args[i] = representations[i] Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args) def parse_string(self, s): """Parse rules and queries from a string""" return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx) def parse_file(self, f): """Parse rules and queries from a file""" return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx) def get_rules(self): """retrieve rules that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx) def get_assertions(self): """retrieve assertions that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)()) def to_string(self, queries): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. Include also queries. """ args, len = _to_ast_array(queries) return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args) def statistics(self): """Return statistics for the last `query()`. """ return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx) def reason_unknown(self): """Return a string describing why the last `query()` returned `unknown`. """ return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint) def declare_var(self, *vars): """Add variable or several variables. The added variable or variables will be bound in the rules and queries """ vars = _get_args(vars) for v in vars: self.vars += [v] def abstract(self, fml, is_forall=True): if self.vars == []: return fml if is_forall: return ForAll(self.vars, fml) else: return Exists(self.vars, fml) ######################################### # # Finite domains # ######################################### class FiniteDomainSortRef(SortRef): """Finite domain sort.""" def size(self): """Return the size of the finite domain sort""" r = (ctypes.c_ulonglong * 1)() if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r): return r[0] else: raise Z3Exception("Failed to retrieve finite domain sort size") def FiniteDomainSort(name, sz, ctx=None): """Create a named finite domain sort of a given size sz""" if not isinstance(name, Symbol): name = to_symbol(name) ctx = _get_ctx(ctx) return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx) def is_finite_domain_sort(s): """Return True if `s` is a Z3 finite-domain sort. >>> is_finite_domain_sort(FiniteDomainSort('S', 100)) True >>> is_finite_domain_sort(IntSort()) False """ return isinstance(s, FiniteDomainSortRef) class FiniteDomainRef(ExprRef): """Finite-domain expressions.""" def sort(self): """Return the sort of the finite-domain expression `self`.""" return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def is_finite_domain(a): """Return `True` if `a` is a Z3 finite-domain expression. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain(b) True >>> is_finite_domain(Int('x')) False """ return isinstance(a, FiniteDomainRef) class FiniteDomainNumRef(FiniteDomainRef): """Integer values.""" def as_long(self): """Return a Z3 finite-domain numeral as a Python long (bignum) numeral. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(3, s) >>> v 3 >>> v.as_long() + 1 4 """ return int(self.as_string()) def as_string(self): """Return a Z3 finite-domain numeral as a Python string. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(42, s) >>> v.as_string() '42' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def FiniteDomainVal(val, sort, ctx=None): """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used. >>> s = FiniteDomainSort('S', 256) >>> FiniteDomainVal(255, s) 255 >>> FiniteDomainVal('100', s) 100 """ if __debug__: _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" ) ctx = sort.ctx return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx) def is_finite_domain_value(a): """Return `True` if `a` is a Z3 finite-domain value. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain_value(b) False >>> b = FiniteDomainVal(10, s) >>> b 10 >>> is_finite_domain_value(b) True """ return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast()) ######################################### # # Optimize # ######################################### class OptimizeObjective: def __init__(self, opt, value, is_max): self._opt = opt self._value = value self._is_max = is_max def lower(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def lower_values(self): opt = self._opt return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper_values(self): opt = self._opt return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def value(self): if self._is_max: return self.upper() else: return self.lower() def __str__(self): return "%s:%s" % (self._value, self._is_max) class Optimize(Z3PPObject): """Optimize API provides methods for solving using objective functions and weighted soft constraints""" def __init__(self, ctx=None): self.ctx = _get_ctx(ctx) self.optimize = Z3_mk_optimize(self.ctx.ref()) Z3_optimize_inc_ref(self.ctx.ref(), self.optimize) def __deepcopy__(self, memo={}): return Optimize(self.optimize, self.ctx) def __del__(self): if self.optimize is not None and self.ctx.ref() is not None: Z3_optimize_dec_ref(self.ctx.ref(), self.optimize) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params) def help(self): """Display a string describing all available options.""" print(Z3_optimize_get_help(self.ctx.ref(), self.optimize)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the optimize solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast()) else: arg = s.cast(arg) Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the optimize solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def add_soft(self, arg, weight = "1", id = None): """Add soft constraint with optional weight and optional identifier. If no weight is supplied, then the penalty for violating the soft constraint is 1. Soft constraints are grouped by identifiers. Soft constraints that are added without identifiers are grouped by default. """ if _is_int(weight): weight = "%d" % weight elif isinstance(weight, float): weight = "%f" % weight if not isinstance(weight, str): raise Z3Exception("weight should be a string or an integer") if id is None: id = "" id = to_symbol(id, self.ctx) v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id) return OptimizeObjective(self, v, False) def maximize(self, arg): """Add objective function to maximize.""" return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True) def minimize(self, arg): """Add objective function to minimize.""" return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False) def push(self): """create a backtracking point for added rules, facts and assertions""" Z3_optimize_push(self.ctx.ref(), self.optimize) def pop(self): """restore to previously created backtracking point""" Z3_optimize_pop(self.ctx.ref(), self.optimize) def check(self, *assumptions): """Check satisfiability while optimizing objective functions.""" assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions)) def reason_unknown(self): """Return a string that describes why the last `check()` returned `unknown`.""" return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize) def model(self): """Return a model for the last check().""" try: return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def unsat_core(self): return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx) def lower(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower() def upper(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper() def lower_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower_values() def upper_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper_values() def from_file(self, filename): """Parse assertions and objectives from a file""" Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename) def from_string(self, s): """Parse assertions and objectives from a string""" Z3_optimize_from_string(self.ctx.ref(), self.optimize, s) def assertions(self): """Return an AST vector containing all added constraints.""" return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx) def objectives(self): """returns set of objective functions""" return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_optimize_to_string(self.ctx.ref(), self.optimize) def statistics(self): """Return statistics for the last check`. """ return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx) ######################################### # # ApplyResult # ######################################### class ApplyResult(Z3PPObject): """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters.""" def __init__(self, result, ctx): self.result = result self.ctx = ctx Z3_apply_result_inc_ref(self.ctx.ref(), self.result) def __deepcopy__(self, memo={}): return ApplyResult(self.result, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_apply_result_dec_ref(self.ctx.ref(), self.result) def __len__(self): """Return the number of subgoals in `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> len(r) 2 >>> t = Then(Tactic('split-clause'), Tactic('split-clause')) >>> len(t(g)) 4 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values')) >>> len(t(g)) 1 """ return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result)) def __getitem__(self, idx): """Return one of the subgoals stored in ApplyResult object `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> r[0] [a == 0, Or(b == 0, b == 1), a > b] >>> r[1] [a == 1, Or(b == 0, b == 1), a > b] """ if idx >= len(self): raise IndexError return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the set of subgoals in `self`.""" return Z3_apply_result_to_string(self.ctx.ref(), self.result) def as_expr(self): """Return a Z3 expression consisting of all subgoals. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 1) >>> g.add(Or(x == 2, x == 3)) >>> r = Tactic('simplify')(g) >>> r [[Not(x <= 1), Or(x == 2, x == 3)]] >>> r.as_expr() And(Not(x <= 1), Or(x == 2, x == 3)) >>> r = Tactic('split-clause')(g) >>> r [[x > 1, x == 2], [x > 1, x == 3]] >>> r.as_expr() Or(And(x > 1, x == 2), And(x > 1, x == 3)) """ sz = len(self) if sz == 0: return BoolVal(False, self.ctx) elif sz == 1: return self[0].as_expr() else: return Or([ self[i].as_expr() for i in range(len(self)) ]) ######################################### # # Tactics # ######################################### class Tactic: """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver(). Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond(). """ def __init__(self, tactic, ctx=None): self.ctx = _get_ctx(ctx) self.tactic = None if isinstance(tactic, TacticObj): self.tactic = tactic else: if __debug__: _z3_assert(isinstance(tactic, str), "tactic name expected") try: self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic)) except Z3Exception: raise Z3Exception("unknown tactic '%s'" % tactic) Z3_tactic_inc_ref(self.ctx.ref(), self.tactic) def __deepcopy__(self, memo={}): return Tactic(self.tactic, self.ctx) def __del__(self): if self.tactic is not None and self.ctx.ref() is not None: Z3_tactic_dec_ref(self.ctx.ref(), self.tactic) def solver(self): """Create a solver using the tactic `self`. The solver supports the methods `push()` and `pop()`, but it will always solve each `check()` from scratch. >>> t = Then('simplify', 'nlsat') >>> s = t.solver() >>> x = Real('x') >>> s.add(x**2 == 2, x > 0) >>> s.check() sat >>> s.model() [x = 1.4142135623?] """ return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx) def apply(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t.apply(And(x == 0, y >= x + 1)) [[y >= 1]] """ if __debug__: _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected") goal = _to_goal(goal) if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, self.ctx) return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx) else: return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx) def __call__(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t(And(x == 0, y >= x + 1)) [[y >= 1]] """ return self.apply(goal, *arguments, **keywords) def help(self): """Display a string containing a description of the available options for the `self` tactic.""" print(Z3_tactic_get_help(self.ctx.ref(), self.tactic)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx) def _to_goal(a): if isinstance(a, BoolRef): goal = Goal(ctx = a.ctx) goal.add(a) return goal else: return a def _to_tactic(t, ctx=None): if isinstance(t, Tactic): return t else: return Tactic(t, ctx) def _and_then(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if __debug__: _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def _or_else(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if __debug__: _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def AndThen(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. >>> x, y = Ints('x y') >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ if __debug__: _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get('ctx', None) num = len(ts) r = ts[0] for i in range(num - 1): r = _and_then(r, ts[i+1], ctx) return r def Then(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks). >>> x, y = Ints('x y') >>> t = Then(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ return AndThen(*ts, **ks) def OrElse(*ts, **ks): """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = OrElse(Tactic('split-clause'), Tactic('skip')) >>> # Tactic split-clause fails if there is no clause in the given goal. >>> t(x == 0) [[x == 0]] >>> t(Or(x == 0, x == 1)) [[x == 0], [x == 1]] """ if __debug__: _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get('ctx', None) num = len(ts) r = ts[0] for i in range(num - 1): r = _or_else(r, ts[i+1], ctx) return r def ParOr(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = ParOr(Tactic('simplify'), Tactic('fail')) >>> t(x + 1 == 2) [[x == 1]] """ if __debug__: _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = _get_ctx(ks.get('ctx', None)) ts = [ _to_tactic(t, ctx) for t in ts ] sz = len(ts) _args = (TacticObj * sz)() for i in range(sz): _args[i] = ts[i].tactic return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx) def ParThen(t1, t2, ctx=None): """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel. >>> x, y = Ints('x y') >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values')) >>> t(And(Or(x == 1, x == 2), y == x + 1)) [[x == 1, y == 2], [x == 2, y == 3]] """ t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if __debug__: _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def ParAndThen(t1, t2, ctx=None): """Alias for ParThen(t1, t2, ctx).""" return ParThen(t1, t2, ctx) def With(t, *args, **keys): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> t = With(Tactic('simplify'), som=True) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ ctx = keys.pop('ctx', None) t = _to_tactic(t, ctx) p = args2params(args, keys, t.ctx) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def WithParams(t, p): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> p = ParamsRef() >>> p.set("som", True) >>> t = WithParams(Tactic('simplify'), p) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ t = _to_tactic(t, None) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def Repeat(t, max=4294967295, ctx=None): """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached. >>> x, y = Ints('x y') >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y) >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) >>> r = t(c) >>> for subgoal in r: print(subgoal) [x == 0, y == 0, x > y] [x == 0, y == 1, x > y] [x == 1, y == 0, x > y] [x == 1, y == 1, x > y] >>> t = Then(t, Tactic('propagate-values')) >>> t(c) [[x == 1, y == 0]] """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx) def TryFor(t, ms, ctx=None): """Return a tactic that applies `t` to a given goal for `ms` milliseconds. If `t` does not terminate in `ms` milliseconds, then it fails. """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx) def tactics(ctx=None): """Return a list of all available tactics in Z3. >>> l = tactics() >>> l.count('simplify') == 1 True """ ctx = _get_ctx(ctx) return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ] def tactic_description(name, ctx=None): """Return a short description for the tactic named `name`. >>> d = tactic_description('simplify') """ ctx = _get_ctx(ctx) return Z3_tactic_get_descr(ctx.ref(), name) def describe_tactics(): """Display a (tabular) description of all available tactics in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for t in tactics(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print('<tr>') even = True print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40))) print('</table>') else: for t in tactics(): print('%s : %s' % (t, tactic_description(t))) class Probe: """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used.""" def __init__(self, probe, ctx=None): self.ctx = _get_ctx(ctx) self.probe = None if isinstance(probe, ProbeObj): self.probe = probe elif isinstance(probe, float): self.probe = Z3_probe_const(self.ctx.ref(), probe) elif _is_int(probe): self.probe = Z3_probe_const(self.ctx.ref(), float(probe)) elif isinstance(probe, bool): if probe: self.probe = Z3_probe_const(self.ctx.ref(), 1.0) else: self.probe = Z3_probe_const(self.ctx.ref(), 0.0) else: if __debug__: _z3_assert(isinstance(probe, str), "probe name expected") try: self.probe = Z3_mk_probe(self.ctx.ref(), probe) except Z3Exception: raise Z3Exception("unknown probe '%s'" % probe) Z3_probe_inc_ref(self.ctx.ref(), self.probe) def __deepcopy__(self, memo={}): return Probe(self.probe, self.ctx) def __del__(self): if self.probe is not None and self.ctx.ref() is not None: Z3_probe_dec_ref(self.ctx.ref(), self.probe) def __lt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`. >>> p = Probe('size') < 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __gt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`. >>> p = Probe('size') > 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __le__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`. >>> p = Probe('size') <= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ge__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`. >>> p = Probe('size') >= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __eq__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`. >>> p = Probe('size') == 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ne__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`. >>> p = Probe('size') != 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ p = self.__eq__(other) return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx) def __call__(self, goal): """Evaluate the probe `self` in the given goal. >>> p = Probe('size') >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 2.0 >>> g.add(x < 20) >>> p(g) 3.0 >>> p = Probe('num-consts') >>> p(g) 1.0 >>> p = Probe('is-propositional') >>> p(g) 0.0 >>> p = Probe('is-qflia') >>> p(g) 1.0 """ if __debug__: _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected") goal = _to_goal(goal) return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal) def is_probe(p): """Return `True` if `p` is a Z3 probe. >>> is_probe(Int('x')) False >>> is_probe(Probe('memory')) True """ return isinstance(p, Probe) def _to_probe(p, ctx=None): if is_probe(p): return p else: return Probe(p, ctx) def probes(ctx=None): """Return a list of all available probes in Z3. >>> l = probes() >>> l.count('memory') == 1 True """ ctx = _get_ctx(ctx) return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ] def probe_description(name, ctx=None): """Return a short description for the probe named `name`. >>> d = probe_description('memory') """ ctx = _get_ctx(ctx) return Z3_probe_get_descr(ctx.ref(), name) def describe_probes(): """Display a (tabular) description of all available probes in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for p in probes(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print('<tr>') even = True print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40))) print('</table>') else: for p in probes(): print('%s : %s' % (p, probe_description(p))) def _probe_nary(f, args, ctx): if __debug__: _z3_assert(len(args) > 0, "At least one argument expected") num = len(args) r = _to_probe(args[0], ctx) for i in range(num - 1): r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx) return r def _probe_and(args, ctx): return _probe_nary(Z3_probe_and, args, ctx) def _probe_or(args, ctx): return _probe_nary(Z3_probe_or, args, ctx) def FailIf(p, ctx=None): """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal. >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx) def When(p, t, ctx=None): """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. >>> t = When(Probe('size') > 2, Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) t = _to_tactic(t, ctx) return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx) def Cond(p, t1, t2, ctx=None): """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise. >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt')) """ p = _to_probe(p, ctx) t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx) ######################################### # # Utils # ######################################### def simplify(a, *arguments, **keywords): """Simplify the expression `a` using the given options. This function has many options. Use `help_simplify` to obtain the complete list. >>> x = Int('x') >>> y = Int('y') >>> simplify(x + 1 + y + x + 1) 2 + 2*x + y >>> simplify((x + 1)*(y + 1), som=True) 1 + x + y + x*y >>> simplify(Distinct(x, y, 1), blast_distinct=True) And(Not(x == y), Not(x == 1), Not(y == 1)) >>> simplify(And(x == 0, y == 1), elim_and=True) Not(Or(Not(x == 0), Not(y == 1))) """ if __debug__: _z3_assert(is_expr(a), "Z3 expression expected") if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, a.ctx) return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx) else: return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx) def help_simplify(): """Return a string describing all options available for Z3 `simplify` procedure.""" print(Z3_simplify_get_help(main_ctx().ref())) def simplify_param_descrs(): """Return the set of parameter descriptions for Z3 `simplify` procedure.""" return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx()) def substitute(t, *m): """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to. >>> x = Int('x') >>> y = Int('y') >>> substitute(x + 1, (x, y + 1)) y + 1 + 1 >>> f = Function('f', IntSort(), IntSort()) >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1))) 1 + 1 """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if __debug__: _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.") num = len(m) _from = (Ast * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_ast() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def substitute_vars(t, *m): """Substitute the free variables in t with the expression in m. >>> v0 = Var(0, IntSort()) >>> v1 = Var(1, IntSort()) >>> x = Int('x') >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # replace v0 with x+1 and v1 with x >>> substitute_vars(f(v0, v1), x + 1, x) f(x + 1, x) """ if __debug__: _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.") num = len(m) _to = (Ast * num)() for i in range(num): _to[i] = m[i].as_ast() return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx) def Sum(*args): """Create the sum of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Sum(a, b, c) a + b + c >>> Sum([a, b, c]) a + b + c >>> A = IntVector('a', 5) >>> Sum(A) a__0 + a__1 + a__2 + a__3 + a__4 """ args = _get_args(args) if len(args) == 0: return 0 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a + b, args, 0) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a + b, args, 0) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx) def Product(*args): """Create the product of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Product(a, b, c) a*b*c >>> Product([a, b, c]) a*b*c >>> A = IntVector('a', 5) >>> Product(A) a__0*a__1*a__2*a__3*a__4 """ args = _get_args(args) if len(args) == 0: return 1 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a * b, args, 1) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a * b, args, 1) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx) def AtMost(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtMost(a, b, c, 2) """ args = _get_args(args) if __debug__: _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if __debug__: _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx) def AtLeast(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtLeast(a, b, c, 2) """ args = _get_args(args) if __debug__: _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if __debug__: _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx) def _pb_args_coeffs(args, default_ctx = None): args = _get_args_ast_list(args) if len(args) == 0: return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)() args, coeffs = zip(*args) if __debug__: _z3_assert(len(args) > 0, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if __debug__: _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) _coeffs = (ctypes.c_int * len(coeffs))() for i in range(len(coeffs)): _z3_check_cint_overflow(coeffs[i], "coefficient") _coeffs[i] = coeffs[i] return ctx, sz, _args, _coeffs def PbLe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbLe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbGe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbGe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbEq(args, k, ctx = None): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbEq(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx) def solve(*args, **keywords): """Solve the constraints `*args`. This is a simple function for creating demonstrations. It creates a solver, configure it using the options in `keywords`, adds the constraints in `args`, and invokes check. >>> a = Int('a') >>> solve(a > 0, a < 2) [a = 1] """ s = Solver() s.set(**keywords) s.add(*args) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: print(s.model()) def solve_using(s, *args, **keywords): """Solve the constraints `*args` using solver `s`. This is a simple function for creating demonstrations. It is similar to `solve`, but it uses the given solver `s`. It configures solver `s` using the options in `keywords`, adds the constraints in `args`, and invokes check. """ if __debug__: _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if keywords.get('show', False): print("Problem:") print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("Solution:") print(s.model()) def prove(claim, **keywords): """Try to prove the given claim. This is a simple function for creating demonstrations. It tries to prove `claim` by showing the negation is unsatisfiable. >>> p, q = Bools('p q') >>> prove(Not(And(p, q)) == Or(Not(p), Not(q))) proved """ if __debug__: _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("proved") elif r == unknown: print("failed to prove") print(s.model()) else: print("counterexample") print(s.model()) def _solve_html(*args, **keywords): """Version of function `solve` used in RiSE4Fun.""" s = Solver() s.set(**keywords) s.add(*args) if keywords.get('show', False): print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("<b>Solution:</b>") print(s.model()) def _solve_using_html(s, *args, **keywords): """Version of function `solve_using` used in RiSE4Fun.""" if __debug__: _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if keywords.get('show', False): print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("<b>Solution:</b>") print(s.model()) def _prove_html(claim, **keywords): """Version of function `prove` used in RiSE4Fun.""" if __debug__: _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("<b>proved</b>") elif r == unknown: print("<b>failed to prove</b>") print(s.model()) else: print("<b>counterexample</b>") print(s.model()) def _dict2sarray(sorts, ctx): sz = len(sorts) _names = (Symbol * sz)() _sorts = (Sort * sz) () i = 0 for k in sorts: v = sorts[k] if __debug__: _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_sort(v), "Z3 sort expected") _names[i] = to_symbol(k, ctx) _sorts[i] = v.ast i = i + 1 return sz, _names, _sorts def _dict2darray(decls, ctx): sz = len(decls) _names = (Symbol * sz)() _decls = (FuncDecl * sz) () i = 0 for k in decls: v = decls[k] if __debug__: _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected") _names[i] = to_symbol(k, ctx) if is_const(v): _decls[i] = v.decl().ast else: _decls[i] = v.ast i = i + 1 return sz, _names, _decls def parse_smt2_string(s, sorts={}, decls={}, ctx=None): """Parse a string in SMT 2.0 format using the given sorts and decls. The arguments sorts and decls are Python dictionaries used to initialize the symbol table used for the SMT 2.0 parser. >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))') [x > 0, x < 10] >>> x, y = Ints('x y') >>> f = Function('f', IntSort(), IntSort()) >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f}) [x + f(y) > 0] >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() }) [a > 0] """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) def parse_smt2_file(f, sorts={}, decls={}, ctx=None): """Parse a file in SMT 2.0 format using the given sorts and decls. This function is similar to parse_smt2_string(). """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) ######################################### # # Floating-Point Arithmetic # ######################################### # Global default rounding mode _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO _dflt_fpsort_ebits = 11 _dflt_fpsort_sbits = 53 def get_default_rounding_mode(ctx=None): """Retrieves the global default rounding mode.""" global _dflt_rounding_mode if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO: return RTZ(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE: return RTN(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE: return RTP(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: return RNE(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: return RNA(ctx) def set_default_rounding_mode(rm, ctx=None): global _dflt_rounding_mode if is_fprm_value(rm): _dflt_rounding_mode = rm.decl().kind() else: _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY, "illegal rounding mode") _dflt_rounding_mode = rm def get_default_fp_sort(ctx=None): return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx) def set_default_fp_sort(ebits, sbits, ctx=None): global _dflt_fpsort_ebits global _dflt_fpsort_sbits _dflt_fpsort_ebits = ebits _dflt_fpsort_sbits = sbits def _dflt_rm(ctx=None): return get_default_rounding_mode(ctx) def _dflt_fps(ctx=None): return get_default_fp_sort(ctx) def _coerce_fp_expr_list(alist, ctx): first_fp_sort = None for a in alist: if is_fp(a): if first_fp_sort is None: first_fp_sort = a.sort() elif first_fp_sort == a.sort(): pass # OK, same as before else: # we saw at least 2 different float sorts; something will # throw a sort mismatch later, for now assume None. first_fp_sort = None break r = [] for i in range(len(alist)): a = alist[i] if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool): r.append(FPVal(a, None, first_fp_sort, ctx)) else: r.append(a) return _coerce_expr_list(r, ctx) ### FP Sorts class FPSortRef(SortRef): """Floating-point sort.""" def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast)) def sbits(self): """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast)) def cast(self, val): """Try to cast `val` as a floating-point expression. >>> b = FPSort(8, 24) >>> b.cast(1.0) 1 >>> b.cast(1.0).sexpr() '(fp #b0 #x7f #b00000000000000000000000)' """ if is_expr(val): if __debug__: _z3_assert(self.ctx == val.ctx, "Context mismatch") return val else: return FPVal(val, None, self, self.ctx) def Float16(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx) def FloatHalf(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx) def Float32(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx) def FloatSingle(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) def Float64(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx) def FloatDouble(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) def Float128(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx) def FloatQuadruple(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx) class FPRMSortRef(SortRef): """"Floating-point rounding mode sort.""" def is_fp_sort(s): """Return True if `s` is a Z3 floating-point sort. >>> is_fp_sort(FPSort(8, 24)) True >>> is_fp_sort(IntSort()) False """ return isinstance(s, FPSortRef) def is_fprm_sort(s): """Return True if `s` is a Z3 floating-point rounding mode sort. >>> is_fprm_sort(FPSort(8, 24)) False >>> is_fprm_sort(RNE().sort()) True """ return isinstance(s, FPRMSortRef) ### FP Expressions class FPRef(ExprRef): """Floating-point expressions.""" def sort(self): """Return the sort of the floating-point expression `self`. >>> x = FP('1.0', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sort() == FPSort(8, 24) True """ return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return self.sort().ebits(); def sbits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return self.sort().sbits(); def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return fpLEQ(self, other, self.ctx) def __lt__(self, other): return fpLT(self, other, self.ctx) def __ge__(self, other): return fpGEQ(self, other, self.ctx) def __gt__(self, other): return fpGT(self, other, self.ctx) def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x + y x + y >>> (x + y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 + x 1.25*(2**3) + x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x - y x - y >>> (x - y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 - x 1.25*(2**3) - x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> (x * y).sort() FPSort(8, 24) >>> 10 * y 1.25*(2**3) * y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> x * 10 x * 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __pos__(self): """Create the Z3 expression `+self`.""" return self def __neg__(self): """Create the Z3 expression `-self`. >>> x = FP('x', Float32()) >>> -x -x """ return fpNeg(self) def __div__(self, other): """Create the Z3 expression `self / other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> (x / y).sort() FPSort(8, 24) >>> 10 / y 1.25*(2**3) / y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __rdiv__(self, other): """Create the Z3 expression `other / self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> x / 10 x / 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) if not sys.version < '3': def __truediv__(self, other): """Create the Z3 expression division `self / other`.""" return self.__div__(other) def __rtruediv__(self, other): """Create the Z3 expression division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression mod `self % other`.""" return fpRem(self, other) def __rmod__(self, other): """Create the Z3 expression mod `other % self`.""" return fpRem(other, self) class FPRMRef(ExprRef): """Floating-point rounding mode expressions""" def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def RoundNearestTiesToEven(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RNE (ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RoundNearestTiesToAway(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RNA (ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RoundTowardPositive(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RTP(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RoundTowardNegative(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RTN(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RoundTowardZero(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def RTZ(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def is_fprm(a): """Return `True` if `a` is a Z3 floating-point rounding mode expression. >>> rm = RNE() >>> is_fprm(rm) True >>> rm = 1.0 >>> is_fprm(rm) False """ return isinstance(a, FPRMRef) def is_fprm_value(a): """Return `True` if `a` is a Z3 floating-point rounding mode numeral value.""" return is_fprm(a) and _is_numeral(a.ctx, a.ast) ### FP Numerals class FPNumRef(FPRef): """The sign of the numeral. >>> x = FPVal(+1.0, FPSort(8, 24)) >>> x.sign() False >>> x = FPVal(-1.0, FPSort(8, 24)) >>> x.sign() True """ def sign(self): l = (ctypes.c_int)() if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False: raise Z3Exception("error retrieving the sign of a numeral.") return l.value != 0 """The sign of a floating-point numeral as a bit-vector expression. Remark: NaN's are invalid arguments. """ def sign_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The significand of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand() 1.25 """ def significand(self): return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast()) """The significand of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand_as_long() 1.25 """ def significand_as_long(self): ptr = (ctypes.c_ulonglong * 1)() if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr): raise Z3Exception("error retrieving the significand of a numeral.") return ptr[0] """The significand of the numeral as a bit-vector expression. Remark: NaN are invalid arguments. """ def significand_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The exponent of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent() 1 """ def exponent(self, biased=True): return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased) """The exponent of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent_as_long() 1 """ def exponent_as_long(self, biased=True): ptr = (ctypes.c_longlong * 1)() if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased): raise Z3Exception("error retrieving the exponent of a numeral.") return ptr[0] """The exponent of the numeral as a bit-vector expression. Remark: NaNs are invalid arguments. """ def exponent_as_bv(self, biased=True): return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx) """Indicates whether the numeral is a NaN.""" def isNaN(self): return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +oo or -oo.""" def isInf(self): return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +zero or -zero.""" def isZero(self): return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is normal.""" def isNormal(self): return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is subnormal.""" def isSubnormal(self): return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is positive.""" def isPositive(self): return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is negative.""" def isNegative(self): return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast()) """ The string representation of the numeral. >>> x = FPVal(20, FPSort(8, 24)) >>> x.as_string() 1.25*(2**4) """ def as_string(self): s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast()) return ("FPVal(%s, %s)" % (s, self.sort())) def is_fp(a): """Return `True` if `a` is a Z3 floating-point expression. >>> b = FP('b', FPSort(8, 24)) >>> is_fp(b) True >>> is_fp(b + 1.0) True >>> is_fp(Int('x')) False """ return isinstance(a, FPRef) def is_fp_value(a): """Return `True` if `a` is a Z3 floating-point numeral value. >>> b = FP('b', FPSort(8, 24)) >>> is_fp_value(b) False >>> b = FPVal(1.0, FPSort(8, 24)) >>> b 1 >>> is_fp_value(b) True """ return is_fp(a) and _is_numeral(a.ctx, a.ast) def FPSort(ebits, sbits, ctx=None): """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used. >>> Single = FPSort(8, 24) >>> Double = FPSort(11, 53) >>> Single FPSort(8, 24) >>> x = Const('x', Single) >>> eq(x, FP('x', FPSort(8, 24))) True """ ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx) def _to_float_str(val, exp=0): if isinstance(val, float): if math.isnan(val): res = "NaN" elif val == 0.0: sone = math.copysign(1.0, val) if sone < 0.0: return "-0.0" else: return "+0.0" elif val == float("+inf"): res = "+oo" elif val == float("-inf"): res = "-oo" else: v = val.as_integer_ratio() num = v[0] den = v[1] rvs = str(num) + '/' + str(den) res = rvs + 'p' + _to_int_str(exp) elif isinstance(val, bool): if val: res = "1.0" else: res = "0.0" elif _is_int(val): res = str(val) elif isinstance(val, str): inx = val.find('*(2**') if inx == -1: res = val elif val[-1] == ')': res = val[0:inx] exp = str(int(val[inx+5:-1]) + int(exp)) else: _z3_assert(False, "String does not have floating-point numeral form.") elif __debug__: _z3_assert(False, "Python value cannot be used to create floating-point numerals.") if exp == 0: return res else: return res + 'p' + exp def fpNaN(s): """Create a Z3 floating-point NaN term. >>> s = FPSort(8, 24) >>> set_fpa_pretty(True) >>> fpNaN(s) NaN >>> pb = get_fpa_pretty() >>> set_fpa_pretty(False) >>> fpNaN(s) fpNaN(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx) def fpPlusInfinity(s): """Create a Z3 floating-point +oo term. >>> s = FPSort(8, 24) >>> pb = get_fpa_pretty() >>> set_fpa_pretty(True) >>> fpPlusInfinity(s) +oo >>> set_fpa_pretty(False) >>> fpPlusInfinity(s) fpPlusInfinity(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusInfinity(s): """Create a Z3 floating-point -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx) def fpInfinity(s, negative): """Create a Z3 floating-point +oo or -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) def fpPlusZero(s): """Create a Z3 floating-point +0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusZero(s): """Create a Z3 floating-point -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx) def fpZero(s, negative): """Create a Z3 floating-point +0.0 or -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx) def FPVal(sig, exp=None, fps=None, ctx=None): """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used. >>> v = FPVal(20.0, FPSort(8, 24)) >>> v 1.25*(2**4) >>> print("0x%.8x" % v.exponent_as_long(False)) 0x00000004 >>> v = FPVal(2.25, FPSort(8, 24)) >>> v 1.125*(2**1) >>> v = FPVal(-2.25, FPSort(8, 24)) >>> v -1.125*(2**1) >>> FPVal(-0.0, FPSort(8, 24)) -0.0 >>> FPVal(0.0, FPSort(8, 24)) +0.0 >>> FPVal(+0.0, FPSort(8, 24)) +0.0 """ ctx = _get_ctx(ctx) if is_fp_sort(exp): fps = exp exp = None elif fps is None: fps = _dflt_fps(ctx) _z3_assert(is_fp_sort(fps), "sort mismatch") if exp is None: exp = 0 val = _to_float_str(sig) if val == "NaN" or val == "nan": return fpNaN(fps) elif val == "-0.0": return fpMinusZero(fps) elif val == "0.0" or val == "+0.0": return fpPlusZero(fps) elif val == "+oo" or val == "+inf" or val == "+Inf": return fpPlusInfinity(fps) elif val == "-oo" or val == "-inf" or val == "-Inf": return fpMinusInfinity(fps) else: return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx) def FP(name, fpsort, ctx=None): """Return a floating-point constant named `name`. `fpsort` is the floating-point sort. If `ctx=None`, then the global context is used. >>> x = FP('x', FPSort(8, 24)) >>> is_fp(x) True >>> x.ebits() 8 >>> x.sort() FPSort(8, 24) >>> word = FPSort(8, 24) >>> x2 = FP('x', word) >>> eq(x, x2) True """ if isinstance(fpsort, FPSortRef) and ctx is None: ctx = fpsort.ctx else: ctx = _get_ctx(ctx) return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx) def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) fpMul(RNE(), fpAdd(RNE(), x, y), z) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [FP(name, fpsort, ctx) for name in names] def fpAbs(a, ctx=None): """Create a Z3 floating-point absolute value expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FPVal(1.0, s) >>> fpAbs(x) fpAbs(1) >>> y = FPVal(-20.0, s) >>> y -1.25*(2**4) >>> fpAbs(y) fpAbs(-1.25*(2**4)) >>> fpAbs(-1.25*(2**4)) fpAbs(-1.25*(2**4)) >>> fpAbs(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx) def fpNeg(a, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx) def _mk_fp_unary(f, rm, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx) def _mk_fp_unary_norm(f, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if __debug__: _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), a.as_ast()), ctx) def _mk_fp_unary_pred(f, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if __debug__: _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast()), ctx) def _mk_fp_bin(f, rm, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_norm(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if __debug__: _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_pred(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if __debug__: _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_tern(f, rm, a, b, c, ctx): ctx = _get_ctx(ctx) [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx) if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def fpAdd(rm, a, b, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpAdd(rm, x, y) fpAdd(RNE(), x, y) >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ x + y >>> fpAdd(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx) def fpSub(rm, a, b, ctx=None): """Create a Z3 floating-point subtraction expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpSub(rm, x, y) fpSub(RNE(), x, y) >>> fpSub(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx) def fpMul(rm, a, b, ctx=None): """Create a Z3 floating-point multiplication expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMul(rm, x, y) fpMul(RNE(), x, y) >>> fpMul(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx) def fpDiv(rm, a, b, ctx=None): """Create a Z3 floating-point division expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpDiv(rm, x, y) fpDiv(RNE(), x, y) >>> fpDiv(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx) def fpRem(a, b, ctx=None): """Create a Z3 floating-point remainder expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpRem(x, y) fpRem(x, y) >>> fpRem(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx) def fpMin(a, b, ctx=None): """Create a Z3 floating-point minimum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMin(x, y) fpMin(x, y) >>> fpMin(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx) def fpMax(a, b, ctx=None): """Create a Z3 floating-point maximum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMax(x, y) fpMax(x, y) >>> fpMax(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx) def fpFMA(rm, a, b, c, ctx=None): """Create a Z3 floating-point fused multiply-add expression. """ return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx) def fpSqrt(rm, a, ctx=None): """Create a Z3 floating-point square root expression. """ return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx) def fpRoundToIntegral(rm, a, ctx=None): """Create a Z3 floating-point roundToIntegral expression. """ return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx) def fpIsNaN(a, ctx=None): """Create a Z3 floating-point isNaN expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpIsNaN(x) fpIsNaN(x) """ return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx) def fpIsInf(a, ctx=None): """Create a Z3 floating-point isInfinite expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> fpIsInf(x) fpIsInf(x) """ return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx) def fpIsZero(a, ctx=None): """Create a Z3 floating-point isZero expression. """ return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx) def fpIsNormal(a, ctx=None): """Create a Z3 floating-point isNormal expression. """ return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx) def fpIsSubnormal(a, ctx=None): """Create a Z3 floating-point isSubnormal expression. """ return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx) def fpIsNegative(a, ctx=None): """Create a Z3 floating-point isNegative expression. """ return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx) def fpIsPositive(a, ctx=None): """Create a Z3 floating-point isPositive expression. """ return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx) return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx) def _check_fp_args(a, b): if __debug__: _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression") def fpLT(a, b, ctx=None): """Create the Z3 floating-point expression `other < self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLT(x, y) x < y >>> (x < y).sexpr() '(fp.lt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx) def fpLEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other <= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLEQ(x, y) x <= y >>> (x <= y).sexpr() '(fp.leq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx) def fpGT(a, b, ctx=None): """Create the Z3 floating-point expression `other > self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGT(x, y) x > y >>> (x > y).sexpr() '(fp.gt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx) def fpGEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other >= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGEQ(x, y) x >= y >>> (x >= y).sexpr() '(fp.geq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx) def fpEQ(a, b, ctx=None): """Create the Z3 floating-point expression `fpEQ(other, self)`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpEQ(x, y) fpEQ(x, y) >>> fpEQ(x, y).sexpr() '(fp.eq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx) def fpNEQ(a, b, ctx=None): """Create the Z3 floating-point expression `Not(fpEQ(other, self))`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpNEQ(x, y) Not(fpEQ(x, y)) >>> (x != y).sexpr() '(distinct x y)' """ return Not(fpEQ(a, b, ctx)) def fpFP(sgn, exp, sig, ctx=None): """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp. >>> s = FPSort(8, 24) >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23)) >>> print(x) fpFP(1, 127, 4194304) >>> xv = FPVal(-1.5, s) >>> print(xv) -1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() sat >>> xv = FPVal(+1.5, s) >>> print(xv) 1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() unsat """ _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch") _z3_assert(sgn.sort().size() == 1, "sort mismatch") ctx = _get_ctx(ctx) _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch") return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx) def fpToFP(a1, a2=None, a3=None, ctx=None): """Create a Z3 floating-point conversion expression from other term sorts to floating-point. From a bit-vector term in IEEE 754-2008 format: >>> x = FPVal(1.0, Float32()) >>> x_bv = fpToIEEEBV(x) >>> simplify(fpToFP(x_bv, Float32())) 1 From a floating-point term with different precision: >>> x = FPVal(1.0, Float32()) >>> x_db = fpToFP(RNE(), x, Float64()) >>> x_db.sort() FPSort(11, 53) From a real term: >>> x_r = RealVal(1.5) >>> simplify(fpToFP(RNE(), x_r, Float32())) 1.5 From a signed bit-vector term: >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> simplify(fpToFP(RNE(), x_signed, Float32())) -1.25*(2**2) """ ctx = _get_ctx(ctx) if is_bv(a1) and is_fp_sort(a2): return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx) elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) else: raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.") def fpBVToFP(v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a bit-vector term to a floating-point term. >>> x_bv = BitVecVal(0x3F800000, 32) >>> x_fp = fpBVToFP(x_bv, Float32()) >>> x_fp fpToFP(1065353216) >>> simplify(x_fp) 1 """ _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx) def fpFPToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a floating-point term to a floating-point term of different precision. >>> x_sgl = FPVal(1.0, Float32()) >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64()) >>> x_dbl fpToFP(RNE(), 1) >>> simplify(x_dbl) 1 >>> x_dbl.sort() FPSort(11, 53) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpRealToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a real term to a floating-point term. >>> x_r = RealVal(1.5) >>> x_fp = fpRealToFP(RNE(), x_r, Float32()) >>> x_fp fpToFP(RNE(), 3/2) >>> simplify(x_fp) 1.5 """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpSignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a signed bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFP(RNE(), 4294967291) >>> simplify(x_fp) -1.25*(2**2) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpUnsignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFPUnsigned(RNE(), 4294967291) >>> simplify(x_fp) 1*(2**32) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpToFPUnsigned(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression.""" if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx) def fpToSBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToSBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToUBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToUBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if __debug__: _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToReal(x, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to real. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToReal(x) >>> print(is_fp(x)) True >>> print(is_real(y)) True >>> print(is_fp(y)) False >>> print(is_real(x)) False """ if __debug__: _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx) def fpToIEEEBV(x, ctx=None): """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format. The size of the resulting bit-vector is automatically determined. Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion knows only one NaN and it will always produce the same bit-vector representation of that NaN. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToIEEEBV(x) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if __debug__: _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx) ######################################### # # Strings, Sequences and Regular expressions # ######################################### class SeqSortRef(SortRef): """Sequence sort.""" def is_string(self): """Determine if sort is a string >>> s = StringSort() >>> s.is_string() True >>> s = SeqSort(IntSort()) >>> s.is_string() False """ return Z3_is_string_sort(self.ctx_ref(), self.ast) def StringSort(ctx=None): """Create a string sort >>> s = StringSort() >>> print(s) String """ ctx = _get_ctx(ctx) return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx) def SeqSort(s): """Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True """ return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx) class SeqRef(ExprRef): """Sequence expression.""" def sort(self): return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __add__(self, other): return Concat(self, other) def __radd__(self, other): return Concat(other, self) def __getitem__(self, i): if _is_int(i): i = IntVal(i, self.ctx) return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def is_string(self): return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast())) def is_string_value(self): return Z3_is_string(self.ctx_ref(), self.as_ast()) def as_string(self): """Return a string representation of sequence expression.""" if self.is_string_value(): return Z3_get_string(self.ctx_ref(), self.as_ast()) return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def _coerce_seq(s, ctx=None): if isinstance(s, str): ctx = _get_ctx(ctx) s = StringVal(s, ctx) if not is_expr(s): raise Z3Exception("Non-expression passed as a sequence") if not is_seq(s): raise Z3Exception("Non-sequence passed as a sequence") return s def _get_ctx2(a, b, ctx=None): if is_expr(a): return a.ctx if is_expr(b): return b.ctx if ctx is None: ctx = main_ctx() return ctx def is_seq(a): """Return `True` if `a` is a Z3 sequence expression. >>> print (is_seq(Unit(IntVal(0)))) True >>> print (is_seq(StringVal("abc"))) True """ return isinstance(a, SeqRef) def is_string(a): """Return `True` if `a` is a Z3 string expression. >>> print (is_string(StringVal("ab"))) True """ return isinstance(a, SeqRef) and a.is_string() def is_string_value(a): """return 'True' if 'a' is a Z3 string constant expression. >>> print (is_string_value(StringVal("a"))) True >>> print (is_string_value(StringVal("a") + StringVal("b"))) False """ return isinstance(a, SeqRef) and a.is_string_value() def StringVal(s, ctx=None): """create a string expression""" ctx = _get_ctx(ctx) return SeqRef(Z3_mk_string(ctx.ref(), s), ctx) def String(name, ctx=None): """Return a string constant named `name`. If `ctx=None`, then the global context is used. >>> x = String('x') """ ctx = _get_ctx(ctx) return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx) def SubString(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def SubSeq(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def Strings(names, ctx=None): """Return a tuple of String constants. """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [String(name, ctx) for name in names] def Empty(s): """Create the empty sequence of the given sort >>> e = Empty(StringSort()) >>> e2 = StringVal("") >>> print(e.eq(e2)) True >>> e3 = Empty(SeqSort(IntSort())) >>> print(e3) seq.empty >>> e4 = Empty(ReSort(SeqSort(IntSort()))) >>> print(e4) re.empty """ if isinstance(s, SeqSortRef): return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx) if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty") def Full(s): """Create the regular expression that accepts the universal language >>> e = Full(ReSort(SeqSort(IntSort()))) >>> print(e) re.all >>> e1 = Full(ReSort(StringSort())) >>> print(e1) re.all """ if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Full") def Unit(a): """Create a singleton sequence""" return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx) def PrefixOf(a, b): """Check if 'a' is a prefix of 'b' >>> s1 = PrefixOf("ab", "abc") >>> simplify(s1) True >>> s2 = PrefixOf("bc", "abc") >>> simplify(s2) False """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SuffixOf(a, b): """Check if 'a' is a suffix of 'b' >>> s1 = SuffixOf("ab", "abc") >>> simplify(s1) False >>> s2 = SuffixOf("bc", "abc") >>> simplify(s2) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Contains(a, b): """Check if 'a' contains 'b' >>> s1 = Contains("abc", "ab") >>> simplify(s1) True >>> s2 = Contains("abc", "bc") >>> simplify(s2) True >>> x, y, z = Strings('x y z') >>> s3 = Contains(Concat(x,y,z), y) >>> simplify(s3) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Replace(s, src, dst): """Replace the first occurrence of 'src' by 'dst' in 's' >>> r = Replace("aaa", "a", "b") >>> simplify(r) baa """ ctx = _get_ctx2(dst, s) if ctx is None and is_expr(src): ctx = src.ctx src = _coerce_seq(src, ctx) dst = _coerce_seq(dst, ctx) s = _coerce_seq(s, ctx) return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx) def IndexOf(s, substr): return IndexOf(s, substr, IntVal(0)) def IndexOf(s, substr, offset): """Retrieve the index of substring within a string starting at a specified offset. >>> simplify(IndexOf("abcabc", "bc", 0)) 1 >>> simplify(IndexOf("abcabc", "bc", 2)) 4 """ ctx = None if is_expr(offset): ctx = offset.ctx ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) if _is_int(offset): offset = IntVal(offset, ctx) return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) def Length(s): """Obtain the length of a sequence 's' >>> l = Length(StringVal("abc")) >>> simplify(l) 3 """ s = _coerce_seq(s) return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx) def StrToInt(s): """Convert string expression to integer >>> a = StrToInt("1") >>> simplify(1 == a) True >>> b = StrToInt("2") >>> simplify(1 == b) False >>> c = StrToInt(IntToStr(2)) >>> simplify(1 == c) False """ s = _coerce_seq(s) return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx) def IntToStr(s): """Convert integer expression to string""" if not is_expr(s): s = _py2expr(s) return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx) def Re(s, ctx=None): """The regular expression that accepts sequence 's' >>> s1 = Re("ab") >>> s2 = Re(StringVal("ab")) >>> s3 = Re(Unit(BoolVal(True))) """ s = _coerce_seq(s, ctx) return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx) ## Regular expressions class ReSortRef(SortRef): """Regular expression sort.""" def ReSort(s): if is_ast(s): return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx) if s is None or isinstance(s, Context): ctx = _get_ctx(s) return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx) raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument") class ReRef(ExprRef): """Regular expressions.""" def __add__(self, other): return Union(self, other) def is_re(s): return isinstance(s, ReRef) def InRe(s, re): """Create regular expression membership test >>> re = Union(Re("a"),Re("b")) >>> print (simplify(InRe("a", re))) True >>> print (simplify(InRe("b", re))) True >>> print (simplify(InRe("c", re))) False """ s = _coerce_seq(s, re.ctx) return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx) def Union(*args): """Create union of regular expressions. >>> re = Union(Re("a"), Re("b"), Re("c")) >>> print (simplify(InRe("d", re))) False """ args = _get_args(args) sz = len(args) if __debug__: _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx) def Plus(re): """Create the regular expression accepting one or more repetitions of argument. >>> re = Plus(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx) def Option(re): """Create the regular expression that optionally accepts the argument. >>> re = Option(Re("a")) >>> print(simplify(InRe("a", re))) True >>> print(simplify(InRe("", re))) True >>> print(simplify(InRe("aa", re))) False """ return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx) def Complement(re): """Create the complement regular expression.""" return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx) def Star(re): """Create the regular expression accepting zero or more repetitions of argument. >>> re = Star(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) True """ return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx) def Loop(re, lo, hi=0): """Create the regular expression accepting between a lower and upper bound repetitions >>> re = Loop(Re("a"), 1, 3) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("aaaa", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3.py
z3.py
import sys, io, z3 from .z3consts import * from .z3core import * from ctypes import * def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) ############################## # # Configuration # ############################## # Z3 operator names to Z3Py _z3_op_to_str = { Z3_OP_TRUE : 'True', Z3_OP_FALSE : 'False', Z3_OP_EQ : '==', Z3_OP_DISTINCT : 'Distinct', Z3_OP_ITE : 'If', Z3_OP_AND : 'And', Z3_OP_OR : 'Or', Z3_OP_IFF : '==', Z3_OP_XOR : 'Xor', Z3_OP_NOT : 'Not', Z3_OP_IMPLIES : 'Implies', Z3_OP_IDIV : '/', Z3_OP_MOD : '%', Z3_OP_TO_REAL : 'ToReal', Z3_OP_TO_INT : 'ToInt', Z3_OP_POWER : '**', Z3_OP_IS_INT : 'IsInt', Z3_OP_BADD : '+', Z3_OP_BSUB : '-', Z3_OP_BMUL : '*', Z3_OP_BOR : '|', Z3_OP_BAND : '&', Z3_OP_BNOT : '~', Z3_OP_BXOR : '^', Z3_OP_BNEG : '-', Z3_OP_BUDIV : 'UDiv', Z3_OP_BSDIV : '/', Z3_OP_BSMOD : '%', Z3_OP_BSREM : 'SRem', Z3_OP_BUREM : 'URem', Z3_OP_EXT_ROTATE_LEFT : 'RotateLeft', Z3_OP_EXT_ROTATE_RIGHT : 'RotateRight', Z3_OP_SLEQ : '<=', Z3_OP_SLT : '<', Z3_OP_SGEQ : '>=', Z3_OP_SGT : '>', Z3_OP_ULEQ : 'ULE', Z3_OP_ULT : 'ULT', Z3_OP_UGEQ : 'UGE', Z3_OP_UGT : 'UGT', Z3_OP_SIGN_EXT : 'SignExt', Z3_OP_ZERO_EXT : 'ZeroExt', Z3_OP_REPEAT : 'RepeatBitVec', Z3_OP_BASHR : '>>', Z3_OP_BSHL : '<<', Z3_OP_BLSHR : 'LShR', Z3_OP_CONCAT : 'Concat', Z3_OP_EXTRACT : 'Extract', Z3_OP_BV2INT : 'BV2Int', Z3_OP_ARRAY_MAP : 'Map', Z3_OP_SELECT : 'Select', Z3_OP_STORE : 'Store', Z3_OP_CONST_ARRAY : 'K', Z3_OP_ARRAY_EXT : 'Ext', Z3_OP_PB_AT_MOST : 'AtMost', Z3_OP_PB_LE : 'PbLe', Z3_OP_PB_GE : 'PbGe', Z3_OP_PB_EQ : 'PbEq' } # List of infix operators _z3_infix = [ Z3_OP_EQ, Z3_OP_IFF, Z3_OP_ADD, Z3_OP_SUB, Z3_OP_MUL, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_POWER, Z3_OP_LE, Z3_OP_LT, Z3_OP_GE, Z3_OP_GT, Z3_OP_BADD, Z3_OP_BSUB, Z3_OP_BMUL, Z3_OP_BSDIV, Z3_OP_BSMOD, Z3_OP_BOR, Z3_OP_BAND, Z3_OP_BXOR, Z3_OP_BSDIV, Z3_OP_SLEQ, Z3_OP_SLT, Z3_OP_SGEQ, Z3_OP_SGT, Z3_OP_BASHR, Z3_OP_BSHL ] _z3_unary = [ Z3_OP_UMINUS, Z3_OP_BNOT, Z3_OP_BNEG ] # Precedence _z3_precedence = { Z3_OP_POWER : 0, Z3_OP_UMINUS : 1, Z3_OP_BNEG : 1, Z3_OP_BNOT : 1, Z3_OP_MUL : 2, Z3_OP_DIV : 2, Z3_OP_IDIV : 2, Z3_OP_MOD : 2, Z3_OP_BMUL : 2, Z3_OP_BSDIV : 2, Z3_OP_BSMOD : 2, Z3_OP_ADD : 3, Z3_OP_SUB : 3, Z3_OP_BADD : 3, Z3_OP_BSUB : 3, Z3_OP_BASHR : 4, Z3_OP_BSHL : 4, Z3_OP_BAND : 5, Z3_OP_BXOR : 6, Z3_OP_BOR : 7, Z3_OP_LE : 8, Z3_OP_LT : 8, Z3_OP_GE : 8, Z3_OP_GT : 8, Z3_OP_EQ : 8, Z3_OP_SLEQ : 8, Z3_OP_SLT : 8, Z3_OP_SGEQ : 8, Z3_OP_SGT : 8, Z3_OP_IFF : 8, Z3_OP_FPA_NEG : 1, Z3_OP_FPA_MUL : 2, Z3_OP_FPA_DIV : 2, Z3_OP_FPA_REM : 2, Z3_OP_FPA_FMA : 2, Z3_OP_FPA_ADD: 3, Z3_OP_FPA_SUB : 3, Z3_OP_FPA_LE : 8, Z3_OP_FPA_LT : 8, Z3_OP_FPA_GE : 8, Z3_OP_FPA_GT : 8, Z3_OP_FPA_EQ : 8 } # FPA operators _z3_op_to_fpa_normal_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RoundNearestTiesToEven()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RoundNearestTiesToAway()', Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RoundTowardPositive()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RoundTowardNegative()', Z3_OP_FPA_RM_TOWARD_ZERO : 'RoundTowardZero()', Z3_OP_FPA_PLUS_INF : 'fpPlusInfinity', Z3_OP_FPA_MINUS_INF : 'fpMinusInfinity', Z3_OP_FPA_NAN : 'fpNaN', Z3_OP_FPA_PLUS_ZERO : 'fpPZero', Z3_OP_FPA_MINUS_ZERO : 'fpNZero', Z3_OP_FPA_ADD : 'fpAdd', Z3_OP_FPA_SUB : 'fpSub', Z3_OP_FPA_NEG : 'fpNeg', Z3_OP_FPA_MUL : 'fpMul', Z3_OP_FPA_DIV : 'fpDiv', Z3_OP_FPA_REM : 'fpRem', Z3_OP_FPA_ABS : 'fpAbs', Z3_OP_FPA_MIN : 'fpMin', Z3_OP_FPA_MAX : 'fpMax', Z3_OP_FPA_FMA : 'fpFMA', Z3_OP_FPA_SQRT : 'fpSqrt', Z3_OP_FPA_ROUND_TO_INTEGRAL : 'fpRoundToIntegral', Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : 'fpLT', Z3_OP_FPA_GT : 'fpGT', Z3_OP_FPA_LE : 'fpLEQ', Z3_OP_FPA_GE : 'fpGEQ', Z3_OP_FPA_IS_NAN : 'fpIsNaN', Z3_OP_FPA_IS_INF : 'fpIsInf', Z3_OP_FPA_IS_ZERO : 'fpIsZero', Z3_OP_FPA_IS_NORMAL : 'fpIsNormal', Z3_OP_FPA_IS_SUBNORMAL : 'fpIsSubnormal', Z3_OP_FPA_IS_NEGATIVE : 'fpIsNegative', Z3_OP_FPA_IS_POSITIVE : 'fpIsPositive', Z3_OP_FPA_FP : 'fpFP', Z3_OP_FPA_TO_FP : 'fpToFP', Z3_OP_FPA_TO_FP_UNSIGNED: 'fpToFPUnsigned', Z3_OP_FPA_TO_UBV : 'fpToUBV', Z3_OP_FPA_TO_SBV : 'fpToSBV', Z3_OP_FPA_TO_REAL: 'fpToReal', Z3_OP_FPA_TO_IEEE_BV : 'fpToIEEEBV' } _z3_op_to_fpa_pretty_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RNE()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RNA()', Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RTP()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RTN()', Z3_OP_FPA_RM_TOWARD_ZERO : 'RTZ()', Z3_OP_FPA_PLUS_INF : '+oo', Z3_OP_FPA_MINUS_INF : '-oo', Z3_OP_FPA_NAN : 'NaN', Z3_OP_FPA_PLUS_ZERO : '+0.0', Z3_OP_FPA_MINUS_ZERO : '-0.0', Z3_OP_FPA_ADD : '+', Z3_OP_FPA_SUB : '-', Z3_OP_FPA_MUL : '*', Z3_OP_FPA_DIV : '/', Z3_OP_FPA_REM : '%', Z3_OP_FPA_NEG : '-', Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : '<', Z3_OP_FPA_GT : '>', Z3_OP_FPA_LE : '<=', Z3_OP_FPA_GE : '>=' } _z3_fpa_infix = [ Z3_OP_FPA_ADD, Z3_OP_FPA_SUB, Z3_OP_FPA_MUL, Z3_OP_FPA_DIV, Z3_OP_FPA_REM, Z3_OP_FPA_LT, Z3_OP_FPA_GT, Z3_OP_FPA_LE, Z3_OP_FPA_GE ] def _is_assoc(k): return k == Z3_OP_BOR or k == Z3_OP_BXOR or k == Z3_OP_BAND or k == Z3_OP_ADD or k == Z3_OP_BADD or k == Z3_OP_MUL or k == Z3_OP_BMUL def _is_left_assoc(k): return _is_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_html_assoc(k): return k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IFF or _is_assoc(k) def _is_html_left_assoc(k): return _is_html_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_add(k): return k == Z3_OP_ADD or k == Z3_OP_BADD def _is_sub(k): return k == Z3_OP_SUB or k == Z3_OP_BSUB import sys if sys.version < '3': import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x _z3_infix_compact = [ Z3_OP_MUL, Z3_OP_BMUL, Z3_OP_POWER, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_BSDIV, Z3_OP_BSMOD ] _ellipses = '...' _html_ellipses = '&hellip;' # Overwrite some of the operators for HTML _z3_pre_html_op_to_str = { Z3_OP_EQ : '=', Z3_OP_IFF : '=', Z3_OP_NOT : '&not;', Z3_OP_AND : '&and;', Z3_OP_OR : '&or;', Z3_OP_IMPLIES : '&rArr;', Z3_OP_LT : '&lt;', Z3_OP_GT : '&gt;', Z3_OP_LE : '&le;', Z3_OP_GE : '&ge;', Z3_OP_MUL : '&middot;', Z3_OP_SLEQ : '&le;', Z3_OP_SLT : '&lt;', Z3_OP_SGEQ : '&ge;', Z3_OP_SGT : '&gt;', Z3_OP_ULEQ : '&le;<sub>u</sub>', Z3_OP_ULT : '&lt;<sub>u</sub>', Z3_OP_UGEQ : '&ge;<sub>u</sub>', Z3_OP_UGT : '&gt;<sub>u</sub>', Z3_OP_BMUL : '&middot;', Z3_OP_BUDIV : '/<sub>u</sub>', Z3_OP_BUREM : '%<sub>u</sub>', Z3_OP_BASHR : '&gt;&gt;', Z3_OP_BSHL : '&lt;&lt;', Z3_OP_BLSHR : '&gt;&gt;<sub>u</sub>' } # Extra operators that are infix/unary for HTML _z3_html_infix = [ Z3_OP_AND, Z3_OP_OR, Z3_OP_IMPLIES, Z3_OP_ULEQ, Z3_OP_ULT, Z3_OP_UGEQ, Z3_OP_UGT, Z3_OP_BUDIV, Z3_OP_BUREM, Z3_OP_BLSHR ] _z3_html_unary = [ Z3_OP_NOT ] # Extra Precedence for HTML _z3_pre_html_precedence = { Z3_OP_BUDIV : 2, Z3_OP_BUREM : 2, Z3_OP_BLSHR : 4, Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, Z3_OP_UGEQ : 8, Z3_OP_UGT : 8, Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, Z3_OP_UGEQ : 8, Z3_OP_UGT : 8, Z3_OP_NOT : 1, Z3_OP_AND : 10, Z3_OP_OR : 11, Z3_OP_IMPLIES : 12 } ############################## # # End of Configuration # ############################## def _support_pp(a): return isinstance(a, z3.Z3PPObject) or isinstance(a, list) or isinstance(a, tuple) _infix_map = {} _unary_map = {} _infix_compact_map = {} for _k in _z3_infix: _infix_map[_k] = True for _k in _z3_unary: _unary_map[_k] = True for _k in _z3_infix_compact: _infix_compact_map[_k] = True def _is_infix(k): global _infix_map return _infix_map.get(k, False) def _is_infix_compact(k): global _infix_compact_map return _infix_compact_map.get(k, False) def _is_unary(k): global _unary_map return _unary_map.get(k, False) def _op_name(a): if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_op_to_str.get(k, None) if n == None: return f.name() else: return n def _get_precedence(k): global _z3_precedence return _z3_precedence.get(k, 100000) _z3_html_op_to_str = {} for _k in _z3_op_to_str: _v = _z3_op_to_str[_k] _z3_html_op_to_str[_k] = _v for _k in _z3_pre_html_op_to_str: _v = _z3_pre_html_op_to_str[_k] _z3_html_op_to_str[_k] = _v _z3_html_precedence = {} for _k in _z3_precedence: _v = _z3_precedence[_k] _z3_html_precedence[_k] = _v for _k in _z3_pre_html_precedence: _v = _z3_pre_html_precedence[_k] _z3_html_precedence[_k] = _v _html_infix_map = {} _html_unary_map = {} for _k in _z3_infix: _html_infix_map[_k] = True for _k in _z3_html_infix: _html_infix_map[_k] = True for _k in _z3_unary: _html_unary_map[_k] = True for _k in _z3_html_unary: _html_unary_map[_k] = True def _is_html_infix(k): global _html_infix_map return _html_infix_map.get(k, False) def _is_html_unary(k): global _html_unary_map return _html_unary_map.get(k, False) def _html_op_name(a): global _z3_html_op_to_str if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_html_op_to_str.get(k, None) if n == None: sym = Z3_get_decl_name(f.ctx_ref(), f.ast) if Z3_get_symbol_kind(f.ctx_ref(), sym) == Z3_INT_SYMBOL: return "&#950;<sub>%s</sub>" % Z3_get_symbol_int(f.ctx_ref(), sym) else: # Sanitize the string return f.name() else: return n def _get_html_precedence(k): global _z3_html_predence return _z3_html_precedence.get(k, 100000) class FormatObject: def is_compose(self): return False def is_choice(self): return False def is_indent(self): return False def is_string(self): return False def is_linebreak(self): return False def is_nil(self): return True def children(self): return [] def as_tuple(self): return None def space_upto_nl(self): return (0, False) def flat(self): return self class NAryFormatObject(FormatObject): def __init__(self, fs): assert all([isinstance(a, FormatObject) for a in fs]) self.children = fs def children(self): return self.children class ComposeFormatObject(NAryFormatObject): def is_compose(sef): return True def as_tuple(self): return ('compose', [ a.as_tuple() for a in self.children ]) def space_upto_nl(self): r = 0 for child in self.children: s, nl = child.space_upto_nl() r = r + s if nl: return (r, True) return (r, False) def flat(self): return compose([a.flat() for a in self.children ]) class ChoiceFormatObject(NAryFormatObject): def is_choice(sef): return True def as_tuple(self): return ('choice', [ a.as_tuple() for a in self.children ]) def space_upto_nl(self): return self.children[0].space_upto_nl() def flat(self): return self.children[0].flat() class IndentFormatObject(FormatObject): def __init__(self, indent, child): assert isinstance(child, FormatObject) self.indent = indent self.child = child def children(self): return [self.child] def as_tuple(self): return ('indent', self.indent, self.child.as_tuple()) def space_upto_nl(self): return self.child.space_upto_nl() def flat(self): return indent(self.indent, self.child.flat()) def is_indent(self): return True class LineBreakFormatObject(FormatObject): def __init__(self): self.space = ' ' def is_linebreak(self): return True def as_tuple(self): return '<line-break>' def space_upto_nl(self): return (0, True) def flat(self): return to_format(self.space) class StringFormatObject(FormatObject): def __init__(self, string): assert isinstance(string, str) self.string = string def is_string(self): return True def as_tuple(self): return self.string def space_upto_nl(self): return (getattr(self, 'size', len(self.string)), False) def fits(f, space_left): s, nl = f.space_upto_nl() return s <= space_left def to_format(arg, size=None): if isinstance(arg, FormatObject): return arg else: r = StringFormatObject(str(arg)) if size != None: r.size = size return r def compose(*args): if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): args = args[0] return ComposeFormatObject(args) def indent(i, arg): return IndentFormatObject(i, arg) def group(arg): return ChoiceFormatObject([arg.flat(), arg]) def line_break(): return LineBreakFormatObject() def _len(a): if isinstance(a, StringFormatObject): return getattr(a, 'size', len(a.string)) else: return len(a) def seq(args, sep=',', space=True): nl = line_break() if not space: nl.space = '' r = [] r.append(args[0]) num = len(args) for i in range(num - 1): r.append(to_format(sep)) r.append(nl) r.append(args[i+1]) return compose(r) def seq1(header, args, lp='(', rp=')'): return group(compose(to_format(header), to_format(lp), indent(len(lp) + _len(header), seq(args)), to_format(rp))) def seq2(header, args, i=4, lp='(', rp=')'): if len(args) == 0: return compose(to_format(header), to_format(lp), to_format(rp)) else: return group(compose(indent(len(lp), compose(to_format(lp), to_format(header))), indent(i, compose(seq(args), to_format(rp))))) def seq3(args, lp='(', rp=')'): if len(args) == 0: return compose(to_format(lp), to_format(rp)) else: return group(indent(len(lp), compose(to_format(lp), seq(args), to_format(rp)))) class StopPPException(Exception): def __str__(self): return 'pp-interrupted' class PP: def __init__(self): self.max_lines = 200 self.max_width = 60 self.bounded = False self.max_indent = 40 def pp_string(self, f, indent): if not self.bounded or self.pos <= self.max_width: sz = _len(f) if self.bounded and self.pos + sz > self.max_width: self.out.write(u(_ellipses)) else: self.pos = self.pos + sz self.ribbon_pos = self.ribbon_pos + sz self.out.write(u(f.string)) def pp_compose(self, f, indent): for c in f.children: self.pp(c, indent) def pp_choice(self, f, indent): space_left = self.max_width - self.pos if space_left > 0 and fits(f.children[0], space_left): self.pp(f.children[0], indent) else: self.pp(f.children[1], indent) def pp_line_break(self, f, indent): self.pos = indent self.ribbon_pos = 0 self.line = self.line + 1 if self.line < self.max_lines: self.out.write(u('\n')) for i in range(indent): self.out.write(u(' ')) else: self.out.write(u('\n...')) raise StopPPException() def pp(self, f, indent): if isinstance(f, str): sef.pp_string(f, indent) elif f.is_string(): self.pp_string(f, indent) elif f.is_indent(): self.pp(f.child, min(indent + f.indent, self.max_indent)) elif f.is_compose(): self.pp_compose(f, indent) elif f.is_choice(): self.pp_choice(f, indent) elif f.is_linebreak(): self.pp_line_break(f, indent) else: return def __call__(self, out, f): try: self.pos = 0 self.ribbon_pos = 0 self.line = 0 self.out = out self.pp(f, 0) except StopPPException: return class Formatter: def __init__(self): global _ellipses self.max_depth = 20 self.max_args = 128 self.rational_to_decimal = False self.precision = 10 self.ellipses = to_format(_ellipses) self.max_visited = 10000 self.fpa_pretty = True def pp_ellipses(self): return self.ellipses def pp_arrow(self): return ' ->' def pp_unknown(self): return '<unknown>' def pp_name(self, a): return to_format(_op_name(a)) def is_infix(self, a): return _is_infix(a) def is_unary(self, a): return _is_unary(a) def get_precedence(self, a): return _get_precedence(a) def is_infix_compact(self, a): return _is_infix_compact(a) def is_infix_unary(self, a): return self.is_infix(a) or self.is_unary(a) def add_paren(self, a): return compose(to_format('('), indent(1, a), to_format(')')) def pp_sort(self, s): if isinstance(s, z3.ArraySortRef): return seq1('Array', (self.pp_sort(s.domain()), self.pp_sort(s.range()))) elif isinstance(s, z3.BitVecSortRef): return seq1('BitVec', (to_format(s.size()), )) elif isinstance(s, z3.FPSortRef): return seq1('FPSort', (to_format(s.ebits()), to_format(s.sbits()))) else: return to_format(s.name()) def pp_const(self, a): return self.pp_name(a) def pp_int(self, a): return to_format(a.as_string()) def pp_rational(self, a): if not self.rational_to_decimal: return to_format(a.as_string()) else: return to_format(a.as_decimal(self.precision)) def pp_algebraic(self, a): return to_format(a.as_decimal(self.precision)) def pp_string(self, a): return to_format(a.as_string()) def pp_bv(self, a): return to_format(a.as_string()) def pp_fd(self, a): return to_format(a.as_string()) def pp_fprm_value(self, a): _z3_assert(z3.is_fprm_value(a), 'expected FPRMNumRef') if self.fpa_pretty and (a.decl().kind() in _z3_op_to_fpa_pretty_str): return to_format(_z3_op_to_fpa_pretty_str.get(a.decl().kind())) else: return to_format(_z3_op_to_fpa_normal_str.get(a.decl().kind())) def pp_fp_value(self, a): _z3_assert(isinstance(a, z3.FPNumRef), 'type mismatch') if not self.fpa_pretty: r = [] if (a.isNaN()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_NAN])) r.append(to_format('(')) r.append(to_format(a.sort())) r.append(to_format(')')) return compose(r) elif (a.isInf()): if (a.isNegative()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_MINUS_INF])) else: r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_PLUS_INF])) r.append(to_format('(')) r.append(to_format(a.sort())) r.append(to_format(')')) return compose(r) elif (a.isZero()): if (a.isNegative()): return to_format('-zero') else: return to_format('+zero') else: _z3_assert(z3.is_fp_value(a), 'expecting FP num ast') r = [] sgn = c_int(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) r.append(to_format('FPVal(')) if sgnb and sgn.value != 0: r.append(to_format('-')) r.append(to_format(sig)) r.append(to_format('*(2**')) r.append(to_format(exp)) r.append(to_format(', ')) r.append(to_format(a.sort())) r.append(to_format('))')) return compose(r) else: if (a.isNaN()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_NAN]) elif (a.isInf()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_INF]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_INF]) elif (a.isZero()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_ZERO]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_ZERO]) else: _z3_assert(z3.is_fp_value(a), 'expecting FP num ast') r = [] sgn = (ctypes.c_int)(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) if sgnb and sgn.value != 0: r.append(to_format('-')) r.append(to_format(sig)) if (exp != '0'): r.append(to_format('*(2**')) r.append(to_format(exp)) r.append(to_format(')')) return compose(r) def pp_fp(self, a, d, xs): _z3_assert(isinstance(a, z3.FPRef), "type mismatch") k = a.decl().kind() op = '?' if (self.fpa_pretty and k in _z3_op_to_fpa_pretty_str): op = _z3_op_to_fpa_pretty_str[k] elif k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] elif k in _z3_op_to_str: op = _z3_op_to_str[k] n = a.num_args() if self.fpa_pretty: if self.is_infix(k) and n >= 3: rm = a.arg(0) if z3.is_fprm_value(rm) and z3.get_default_rounding_mode(a.ctx).eq(rm): arg1 = to_format(self.pp_expr(a.arg(1), d+1, xs)) arg2 = to_format(self.pp_expr(a.arg(2), d+1, xs)) r = [] r.append(arg1) r.append(to_format(' ')) r.append(to_format(op)) r.append(to_format(' ')) r.append(arg2) return compose(r) elif k == Z3_OP_FPA_NEG: return compose([to_format('-') , to_format(self.pp_expr(a.arg(0), d+1, xs))]) if k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] r = [] r.append(to_format(op)) if not z3.is_const(a): r.append(to_format('(')) first = True for c in a.children(): if first: first = False else: r.append(to_format(', ')) r.append(self.pp_expr(c, d+1, xs)) r.append(to_format(')')) return compose(r) else: return to_format(a.as_string()) def pp_prefix(self, a, d, xs): r = [] sz = 0 for child in a.children(): r.append(self.pp_expr(child, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def is_assoc(self, k): return _is_assoc(k) def is_left_assoc(self, k): return _is_left_assoc(k) def infix_args_core(self, a, d, xs, r): sz = len(r) k = a.decl().kind() p = self.get_precedence(k) first = True for child in a.children(): child_pp = self.pp_expr(child, d+1, xs) child_k = None if z3.is_app(child): child_k = child.decl().kind() if k == child_k and (self.is_assoc(k) or (first and self.is_left_assoc(k))): self.infix_args_core(child, d, xs, r) sz = len(r) if sz > self.max_args: return elif self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p > child_p or (_is_add(k) and _is_sub(child_k)) or (_is_sub(k) and first and _is_add(child_k)): r.append(child_pp) else: r.append(self.add_paren(child_pp)) sz = sz + 1 elif z3.is_quantifier(child): r.append(self.add_paren(child_pp)) else: r.append(child_pp) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) return first = False def infix_args(self, a, d, xs): r = [] self.infix_args_core(a, d, xs, r) return r def pp_infix(self, a, d, xs): k = a.decl().kind() if self.is_infix_compact(k): op = self.pp_name(a) return group(seq(self.infix_args(a, d, xs), op, False)) else: op = self.pp_name(a) sz = _len(op) op.string = ' ' + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) def pp_unary(self, a, d, xs): k = a.decl().kind() p = self.get_precedence(k) child = a.children()[0] child_k = None if z3.is_app(child): child_k = child.decl().kind() child_pp = self.pp_expr(child, d+1, xs) if k != child_k and self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p <= child_p: child_pp = self.add_paren(child_pp) if z3.is_quantifier(child): child_pp = self.add_paren(child_pp) name = self.pp_name(a) return compose(to_format(name), indent(_len(name), child_pp)) def pp_power_arg(self, arg, d, xs): r = self.pp_expr(arg, d+1, xs) k = None if z3.is_app(arg): k = arg.decl().kind() if self.is_infix_unary(k) or (z3.is_rational_value(arg) and arg.denominator_as_long() != 1): return self.add_paren(r) else: return r def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs) arg2_pp = self.pp_power_arg(a.arg(1), d+1, xs) return group(seq((arg1_pp, arg2_pp), '**', False)) def pp_neq(self): return to_format("!=") def pp_distinct(self, a, d, xs): if a.num_args() == 2: op = self.pp_neq() sz = _len(op) op.string = ' ' + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) else: return self.pp_prefix(a, d, xs) def pp_select(self, a, d, xs): if a.num_args() != 2: return self.pp_prefix(a, d, xs) else: arg1_pp = self.pp_expr(a.arg(0), d+1, xs) arg2_pp = self.pp_expr(a.arg(1), d+1, xs) return compose(arg1_pp, indent(2, compose(to_format('['), arg2_pp, to_format(']')))) def pp_unary_param(self, a, d, xs): p = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d+1, xs) return seq1(self.pp_name(a), [ to_format(p), arg ]) def pp_extract(self, a, d, xs): h = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) l = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) arg = self.pp_expr(a.arg(0), d+1, xs) return seq1(self.pp_name(a), [ to_format(h), to_format(l), arg ]) def pp_pattern(self, a, d, xs): if a.num_args() == 1: return self.pp_expr(a.arg(0), d, xs) else: return seq1('MultiPattern', [ self.pp_expr(arg, d+1, xs) for arg in a.children() ]) def pp_is(self, a, d, xs): f = a.params()[0] return self.pp_fdecl(f, a, d, xs) def pp_map(self, a, d, xs): f = z3.get_map_func(a) return self.pp_fdecl(f, a, d, xs) def pp_fdecl(self, f, a, d, xs): r = [] sz = 0 r.append(to_format(f.name())) for child in a.children(): r.append(self.pp_expr(child, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def pp_K(self, a, d, xs): return seq1(self.pp_name(a), [ self.pp_sort(a.domain()), self.pp_expr(a.arg(0), d+1, xs) ]) def pp_atmost(self, a, d, f, xs): k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) return seq1(self.pp_name(a), [seq3([ self.pp_expr(ch, d+1, xs) for ch in a.children()]), to_format(k)]) def pp_pbcmp(self, a, d, f, xs): chs = a.children() rchs = range(len(chs)) k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) ks = [Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, i+1) for i in rchs] ls = [ seq3([self.pp_expr(chs[i], d+1,xs), to_format(ks[i])]) for i in rchs] return seq1(self.pp_name(a), [seq3(ls), to_format(k)]) def pp_app(self, a, d, xs): if z3.is_int_value(a): return self.pp_int(a) elif z3.is_rational_value(a): return self.pp_rational(a) elif z3.is_algebraic_value(a): return self.pp_algebraic(a) elif z3.is_bv_value(a): return self.pp_bv(a) elif z3.is_finite_domain_value(a): return self.pp_fd(a) elif z3.is_fprm_value(a): return self.pp_fprm_value(a) elif z3.is_fp_value(a): return self.pp_fp_value(a) elif z3.is_fp(a): return self.pp_fp(a, d, xs) elif z3.is_string_value(a): return self.pp_string(a) elif z3.is_const(a): return self.pp_const(a) else: f = a.decl() k = f.kind() if k == Z3_OP_POWER: return self.pp_power(a, d, xs) elif k == Z3_OP_DISTINCT: return self.pp_distinct(a, d, xs) elif k == Z3_OP_SELECT: return self.pp_select(a, d, xs) elif k == Z3_OP_SIGN_EXT or k == Z3_OP_ZERO_EXT or k == Z3_OP_REPEAT: return self.pp_unary_param(a, d, xs) elif k == Z3_OP_EXTRACT: return self.pp_extract(a, d, xs) elif k == Z3_OP_DT_IS: return self.pp_is(a, d, xs) elif k == Z3_OP_ARRAY_MAP: return self.pp_map(a, d, xs) elif k == Z3_OP_CONST_ARRAY: return self.pp_K(a, d, xs) elif k == Z3_OP_PB_AT_MOST: return self.pp_atmost(a, d, f, xs) elif k == Z3_OP_PB_LE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_GE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_EQ: return self.pp_pbcmp(a, d, f, xs) elif z3.is_pattern(a): return self.pp_pattern(a, d, xs) elif self.is_infix(k): return self.pp_infix(a, d, xs) elif self.is_unary(k): return self.pp_unary(a, d, xs) else: return self.pp_prefix(a, d, xs) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: return seq1('Var', (to_format(idx),)) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d+1, new_xs) if len(ys) == 1: ys_pp = ys[0] else: ys_pp = seq3(ys, '[', ']') if a.is_forall(): header = 'ForAll' elif a.is_exists(): header = 'Exists' else: header = 'Lambda' return seq1(header, (ys_pp, body_pp)) def pp_expr(self, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() if z3.is_app(a): return self.pp_app(a, d, xs) elif z3.is_quantifier(a): return self.pp_quantifier(a, d, xs) elif z3.is_var(a): return self.pp_var(a, d, xs) else: return to_format(self.pp_unknown()) def pp_decl(self, f): k = f.kind() if k == Z3_OP_DT_IS or k == Z3_OP_ARRAY_MAP: g = f.params()[0] r = [ to_format(g.name()) ] return seq1(self.pp_name(f), r) return self.pp_name(f) def pp_seq_core(self, f, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() r = [] sz = 0 for elem in a: r.append(f(elem, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, '[', ']') def pp_seq(self, a, d, xs): return self.pp_seq_core(self.pp_expr, a, d, xs) def pp_seq_seq(self, a, d, xs): return self.pp_seq_core(self.pp_seq, a, d, xs) def pp_model(self, m): r = [] sz = 0 for d in m: i = m[d] if isinstance(i, z3.FuncInterp): i_pp = self.pp_func_interp(i) else: i_pp = self.pp_expr(i, 0, []) name = self.pp_name(d) r.append(compose(name, to_format(' = '), indent(_len(name) + 3, i_pp))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, '[', ']') def pp_func_entry(self, e): num = e.num_args() if num > 1: args = [] for i in range(num): args.append(self.pp_expr(e.arg_value(i), 0, [])) args_pp = group(seq3(args)) else: args_pp = self.pp_expr(e.arg_value(0), 0, []) value_pp = self.pp_expr(e.value(), 0, []) return group(seq((args_pp, value_pp), self.pp_arrow())) def pp_func_interp(self, f): r = [] sz = 0 num = f.num_entries() for i in range(num): r.append(self.pp_func_entry(f.entry(i))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if sz <= self.max_args: else_val = f.else_value() if else_val == None: else_pp = to_format('#unspecified') else: else_pp = self.pp_expr(else_val, 0, []) r.append(group(seq((to_format('else'), else_pp), self.pp_arrow()))) return seq3(r, '[', ']') def pp_list(self, a): r = [] sz = 0 for elem in a: if _support_pp(elem): r.append(self.main(elem)) else: r.append(to_format(str(elem))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if isinstance(a, tuple): return seq3(r) else: return seq3(r, '[', ']') def main(self, a): if z3.is_expr(a): return self.pp_expr(a, 0, []) elif z3.is_sort(a): return self.pp_sort(a) elif z3.is_func_decl(a): return self.pp_decl(a) elif isinstance(a, z3.Goal) or isinstance(a, z3.AstVector): return self.pp_seq(a, 0, []) elif isinstance(a, z3.Solver): return self.pp_seq(a.assertions(), 0, []) elif isinstance(a, z3.Fixedpoint): return a.sexpr() elif isinstance(a, z3.Optimize): return a.sexpr() elif isinstance(a, z3.ApplyResult): return self.pp_seq_seq(a, 0, []) elif isinstance(a, z3.ModelRef): return self.pp_model(a) elif isinstance(a, z3.FuncInterp): return self.pp_func_interp(a) elif isinstance(a, list) or isinstance(a, tuple): return self.pp_list(a) else: return to_format(self.pp_unknown()) def __call__(self, a): self.visited = 0 return self.main(a) class HTMLFormatter(Formatter): def __init__(self): Formatter.__init__(self) global _html_ellipses self.ellipses = to_format(_html_ellipses) def pp_arrow(self): return to_format(' &rarr;', 1) def pp_unknown(self): return '<b>unknown</b>' def pp_name(self, a): r = _html_op_name(a) if r[0] == '&' or r[0] == '/' or r[0] == '%': return to_format(r, 1) else: pos = r.find('__') if pos == -1 or pos == 0: return to_format(r) else: sz = len(r) if pos + 2 == sz: return to_format(r) else: return to_format('%s<sub>%s</sub>' % (r[0:pos], r[pos+2:sz]), sz - 2) def is_assoc(self, k): return _is_html_assoc(k) def is_left_assoc(self, k): return _is_html_left_assoc(k) def is_infix(self, a): return _is_html_infix(a) def is_unary(self, a): return _is_html_unary(a) def get_precedence(self, a): return _get_html_precedence(a) def pp_neq(self): return to_format("&ne;") def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs) arg2_pp = self.pp_expr(a.arg(1), d+1, xs) return compose(arg1_pp, to_format('<sup>', 1), arg2_pp, to_format('</sup>', 1)) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: # 957 is the greek letter nu return to_format('&#957;<sub>%s</sub>' % idx, 1) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d+1, new_xs) ys_pp = group(seq(ys)) if a.is_forall(): header = '&forall;' else: header = '&exist;' return group(compose(to_format(header, 1), indent(1, compose(ys_pp, to_format(' :'), line_break(), body_pp)))) _PP = PP() _Formatter = Formatter() def set_pp_option(k, v): if k == 'html_mode': if v: set_html_mode(True) else: set_html_mode(False) return True if k == 'fpa_pretty': if v: set_fpa_pretty(True) else: set_fpa_pretty(False) return True val = getattr(_PP, k, None) if val != None: _z3_assert(type(v) == type(val), "Invalid pretty print option value") setattr(_PP, k, v) return True val = getattr(_Formatter, k, None) if val != None: _z3_assert(type(v) == type(val), "Invalid pretty print option value") setattr(_Formatter, k, v) return True return False def obj_to_string(a): out = io.StringIO() _PP(out, _Formatter(a)) return out.getvalue() _html_out = None def set_html_mode(flag=True): global _Formatter if flag: _Formatter = HTMLFormatter() else: _Formatter = Formatter() def set_fpa_pretty(flag=True): global _Formatter global _z3_op_to_str _Formatter.fpa_pretty = flag if flag: for (_k,_v) in _z3_op_to_fpa_pretty_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = True else: for (_k,_v) in _z3_op_to_fpa_normal_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = False set_fpa_pretty(True) def get_fpa_pretty(): global Formatter return _Formatter.fpa_pretty def in_html_mode(): return isinstance(_Formatter, HTMLFormatter) def pp(a): if _support_pp(a): print(obj_to_string(a)) else: print(a) def print_matrix(m): _z3_assert(isinstance(m, list) or isinstance(m, tuple), "matrix expected") if not in_html_mode(): print(obj_to_string(m)) else: print('<table cellpadding="2", cellspacing="0", border="1">') for r in m: _z3_assert(isinstance(r, list) or isinstance(r, tuple), "matrix expected") print('<tr>') for c in r: print('<td>%s</td>' % c) print('</tr>') print('</table>') def insert_line_breaks(s, width): """Break s in lines of size width (approx)""" sz = len(s) if sz <= width: return s new_str = io.StringIO() w = 0 for i in range(sz): if w > width and s[i] == ' ': new_str.write(u('<br />')) w = 0 else: new_str.write(u(s[i])) w = w + 1 return new_str.getvalue()
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3printer.py
z3printer.py
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction from .z3 import _get_ctx def _to_numeral(num, ctx=None): if isinstance(num, Numeral): return num else: return Numeral(num, ctx) class Numeral: """ A Z3 numeral can be used to perform computations over arbitrary precision integers, rationals and real algebraic numbers. It also automatically converts python numeric values. >>> Numeral(2) 2 >>> Numeral("3/2") + 1 5/2 >>> Numeral(Sqrt(2)) 1.4142135623? >>> Numeral(Sqrt(2)) + 2 3.4142135623? >>> Numeral(Sqrt(2)) + Numeral(Sqrt(3)) 3.1462643699? Z3 numerals can be used to perform computations with values in a Z3 model. >>> s = Solver() >>> x = Real('x') >>> s.add(x*x == 2) >>> s.add(x > 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1.4142135623? >>> m[x] + 1 1.4142135623? + 1 The previous result is a Z3 expression. >>> (m[x] + 1).sexpr() '(+ (root-obj (+ (^ x 2) (- 2)) 2) 1.0)' >>> Numeral(m[x]) + 1 2.4142135623? >>> Numeral(m[x]).is_pos() True >>> Numeral(m[x])**2 2 We can also isolate the roots of polynomials. >>> x0, x1, x2 = RealVarVector(3) >>> r0 = isolate_roots(x0**5 - x0 - 1) >>> r0 [1.1673039782?] In the following example, we are isolating the roots of a univariate polynomial (on x1) obtained after substituting x0 -> r0[0] >>> r1 = isolate_roots(x1**2 - x0 + 1, [ r0[0] ]) >>> r1 [-0.4090280898?, 0.4090280898?] Similarly, in the next example we isolate the roots of a univariate polynomial (on x2) obtained after substituting x0 -> r0[0] and x1 -> r1[0] >>> isolate_roots(x1*x2 + x0, [ r0[0], r1[0] ]) [2.8538479564?] """ def __init__(self, num, ctx=None): if isinstance(num, Ast): self.ast = num self.ctx = _get_ctx(ctx) elif isinstance(num, RatNumRef) or isinstance(num, AlgebraicNumRef): self.ast = num.ast self.ctx = num.ctx elif isinstance(num, ArithRef): r = simplify(num) self.ast = r.ast self.ctx = r.ctx else: v = RealVal(num, ctx) self.ast = v.ast self.ctx = v.ctx Z3_inc_ref(self.ctx_ref(), self.as_ast()) assert Z3_algebraic_is_value(self.ctx_ref(), self.ast) def __del__(self): Z3_dec_ref(self.ctx_ref(), self.as_ast()) def is_integer(self): """ Return True if the numeral is integer. >>> Numeral(2).is_integer() True >>> (Numeral(Sqrt(2)) * Numeral(Sqrt(2))).is_integer() True >>> Numeral(Sqrt(2)).is_integer() False >>> Numeral("2/3").is_integer() False """ return self.is_rational() and self.denominator() == 1 def is_rational(self): """ Return True if the numeral is rational. >>> Numeral(2).is_rational() True >>> Numeral("2/3").is_rational() True >>> Numeral(Sqrt(2)).is_rational() False """ return Z3_get_ast_kind(self.ctx_ref(), self.as_ast()) == Z3_NUMERAL_AST def denominator(self): """ Return the denominator if `self` is rational. >>> Numeral("2/3").denominator() 3 """ assert(self.is_rational()) return Numeral(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator(self): """ Return the numerator if `self` is rational. >>> Numeral("2/3").numerator() 2 """ assert(self.is_rational()) return Numeral(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def is_irrational(self): """ Return True if the numeral is irrational. >>> Numeral(2).is_irrational() False >>> Numeral("2/3").is_irrational() False >>> Numeral(Sqrt(2)).is_irrational() True """ return not self.is_rational() def as_long(self): """ Return a numeral (that is an integer) as a Python long. """ assert(self.is_integer()) if sys.version_info[0] >= 3: return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) else: return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) def as_fraction(self): """ Return a numeral (that is a rational) as a Python Fraction. >>> Numeral("1/5").as_fraction() Fraction(1, 5) """ assert(self.is_rational()) return Fraction(self.numerator().as_long(), self.denominator().as_long()) def approx(self, precision=10): """Return a numeral that approximates the numeral `self`. The result `r` is such that |r - self| <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 >>> Numeral(2).approx(10) 2 """ return self.upper(precision) def upper(self, precision=10): """Return a upper bound that approximates the numeral `self`. The result `r` is such that r - self <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.upper(20) 6838717160008073720548335/4835703278458516698824704 >>> x.upper(5) 2965821/2097152 >>> Numeral(2).upper(10) 2 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def lower(self, precision=10): """Return a lower bound that approximates the numeral `self`. The result `r` is such that self - r <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.lower(20) 1709679290002018430137083/1208925819614629174706176 >>> Numeral("2/3").lower(10) 2/3 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_lower(self.ctx_ref(), self.as_ast(), precision), self.ctx) def sign(self): """ Return the sign of the numeral. >>> Numeral(2).sign() 1 >>> Numeral(-3).sign() -1 >>> Numeral(0).sign() 0 """ return Z3_algebraic_sign(self.ctx_ref(), self.ast) def is_pos(self): """ Return True if the numeral is positive. >>> Numeral(2).is_pos() True >>> Numeral(-3).is_pos() False >>> Numeral(0).is_pos() False """ return Z3_algebraic_is_pos(self.ctx_ref(), self.ast) def is_neg(self): """ Return True if the numeral is negative. >>> Numeral(2).is_neg() False >>> Numeral(-3).is_neg() True >>> Numeral(0).is_neg() False """ return Z3_algebraic_is_neg(self.ctx_ref(), self.ast) def is_zero(self): """ Return True if the numeral is zero. >>> Numeral(2).is_zero() False >>> Numeral(-3).is_zero() False >>> Numeral(0).is_zero() True >>> sqrt2 = Numeral(2).root(2) >>> sqrt2.is_zero() False >>> (sqrt2 - sqrt2).is_zero() True """ return Z3_algebraic_is_zero(self.ctx_ref(), self.ast) def __add__(self, other): """ Return the numeral `self + other`. >>> Numeral(2) + 3 5 >>> Numeral(2) + Numeral(4) 6 >>> Numeral("2/3") + 1 5/3 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __radd__(self, other): """ Return the numeral `other + self`. >>> 3 + Numeral(2) 5 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __sub__(self, other): """ Return the numeral `self - other`. >>> Numeral(2) - 3 -1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rsub__(self, other): """ Return the numeral `other - self`. >>> 3 - Numeral(2) 1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __mul__(self, other): """ Return the numeral `self * other`. >>> Numeral(2) * 3 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rmul__(self, other): """ Return the numeral `other * mul`. >>> 3 * Numeral(2) 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __div__(self, other): """ Return the numeral `self / other`. >>> Numeral(2) / 3 2/3 >>> Numeral(2).root(2) / 3 0.4714045207? >>> Numeral(Sqrt(2)) / Numeral(Sqrt(3)) 0.8164965809? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): """ Return the numeral `other / self`. >>> 3 / Numeral(2) 3/2 >>> 3 / Numeral(2).root(2) 2.1213203435? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __rtruediv__(self, other): return self.__rdiv__(other) def root(self, k): """ Return the numeral `self^(1/k)`. >>> sqrt2 = Numeral(2).root(2) >>> sqrt2 1.4142135623? >>> sqrt2 * sqrt2 2 >>> sqrt2 * 2 + 1 3.8284271247? >>> (sqrt2 * 2 + 1).sexpr() '(root-obj (+ (^ x 2) (* (- 2) x) (- 7)) 2)' """ return Numeral(Z3_algebraic_root(self.ctx_ref(), self.ast, k), self.ctx) def power(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3 """ return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx) def __pow__(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3**2 3 """ return self.power(k) def __lt__(self, other): """ Return True if `self < other`. >>> Numeral(Sqrt(2)) < 2 True >>> Numeral(Sqrt(3)) < Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) < Numeral(Sqrt(2)) False """ return Z3_algebraic_lt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rlt__(self, other): """ Return True if `other < self`. >>> 2 < Numeral(Sqrt(2)) False """ return self > other def __gt__(self, other): """ Return True if `self > other`. >>> Numeral(Sqrt(2)) > 2 False >>> Numeral(Sqrt(3)) > Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) > Numeral(Sqrt(2)) False """ return Z3_algebraic_gt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rgt__(self, other): """ Return True if `other > self`. >>> 2 > Numeral(Sqrt(2)) True """ return self < other def __le__(self, other): """ Return True if `self <= other`. >>> Numeral(Sqrt(2)) <= 2 True >>> Numeral(Sqrt(3)) <= Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) <= Numeral(Sqrt(2)) True """ return Z3_algebraic_le(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rle__(self, other): """ Return True if `other <= self`. >>> 2 <= Numeral(Sqrt(2)) False """ return self >= other def __ge__(self, other): """ Return True if `self >= other`. >>> Numeral(Sqrt(2)) >= 2 False >>> Numeral(Sqrt(3)) >= Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) >= Numeral(Sqrt(2)) True """ return Z3_algebraic_ge(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rge__(self, other): """ Return True if `other >= self`. >>> 2 >= Numeral(Sqrt(2)) True """ return self <= other def __eq__(self, other): """ Return True if `self == other`. >>> Numeral(Sqrt(2)) == 2 False >>> Numeral(Sqrt(3)) == Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) == Numeral(Sqrt(2)) True """ return Z3_algebraic_eq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __ne__(self, other): """ Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False """ return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __str__(self): if Z3_is_numeral_ast(self.ctx_ref(), self.ast): return str(RatNumRef(self.ast, self.ctx)) else: return str(AlgebraicNumRef(self.ast, self.ctx)) def __repr__(self): return self.__str__() def sexpr(self): return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): return self.ast def ctx_ref(self): return self.ctx.ref() def eval_sign_at(p, vs): """ Evaluate the sign of the polynomial `p` at `vs`. `p` is a Z3 Expression containing arithmetic operators: +, -, *, ^k where k is an integer; and free variables x that is_var(x) is True. Moreover, all variables must be real. The result is 1 if the polynomial is positive at the given point, -1 if negative, and 0 if zero. >>> x0, x1, x2 = RealVarVector(3) >>> eval_sign_at(x0**2 + x1*x2 + 1, (Numeral(0), Numeral(1), Numeral(2))) 1 >>> eval_sign_at(x0**2 - 2, [ Numeral(Sqrt(2)) ]) 0 >>> eval_sign_at((x0 + x1)*(x0 + x2), (Numeral(0), Numeral(Sqrt(2)), Numeral(Sqrt(3)))) 1 """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast return Z3_algebraic_eval(p.ctx_ref(), p.as_ast(), num, _vs) def isolate_roots(p, vs=[]): """ Given a multivariate polynomial p(x_0, ..., x_{n-1}, x_n), returns the roots of the univariate polynomial p(vs[0], ..., vs[len(vs)-1], x_n). Remarks: * p is a Z3 expression that contains only arithmetic terms and free variables. * forall i in [0, n) vs is a numeral. The result is a list of numerals >>> x0 = RealVar(0) >>> isolate_roots(x0**5 - x0 - 1) [1.1673039782?] >>> x1 = RealVar(1) >>> isolate_roots(x0**2 - x1**4 - 1, [ Numeral(Sqrt(3)) ]) [-1.1892071150?, 1.1892071150?] >>> x2 = RealVar(2) >>> isolate_roots(x2**2 + x0 - x1, [ Numeral(Sqrt(3)), Numeral(Sqrt(2)) ]) [] """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast _roots = AstVector(Z3_algebraic_roots(p.ctx_ref(), p.as_ast(), num, _vs), p.ctx) return [ Numeral(r) for r in _roots ]
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3num.py
z3num.py
from .z3 import * def vset(seq, idfun=None, as_list=True): # This functions preserves the order of arguments while removing duplicates. # This function is from https://code.google.com/p/common-python-vu/source/browse/vu_common.py # (Thanhu's personal code). It has been copied here to avoid a dependency on vu_common.py. """ order preserving >>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr) [[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]] """ def _uniq_normal(seq): d_ = {} for s in seq: if s not in d_: d_[s] = None yield s def _uniq_idfun(seq,idfun): d_ = {} for s in seq: h_ = idfun(s) if h_ not in d_: d_[h_] = None yield s if idfun is None: res = _uniq_normal(seq) else: res = _uniq_idfun(seq,idfun) return list(res) if as_list else res def get_z3_version(as_str=False): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major,minor,build,rev) rs = map(int,(major.value,minor.value,build.value,rev.value)) if as_str: return "{}.{}.{}.{}".format(*rs) else: return rs def ehash(v): """ Returns a 'stronger' hash value than the default hash() method. The result from hash() is not enough to distinguish between 2 z3 expressions in some cases. Note: the following doctests will fail with Python 2.x as the default formatting doesn't match that of 3.x. >>> x1 = Bool('x'); x2 = Bool('x'); x3 = Int('x') >>> print(x1.hash(),x2.hash(),x3.hash()) #BAD: all same hash values 783810685 783810685 783810685 >>> print(ehash(x1), ehash(x2), ehash(x3)) x_783810685_1 x_783810685_1 x_783810685_2 """ if __debug__: assert is_expr(v) return "{}_{}_{}".format(str(v),v.hash(),v.sort_kind()) """ In Z3, variables are called *uninterpreted* consts and variables are *interpreted* consts. """ def is_expr_var(v): """ EXAMPLES: >>> is_expr_var(Int('7')) True >>> is_expr_var(IntVal('7')) False >>> is_expr_var(Bool('y')) True >>> is_expr_var(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_var(LOnOff) False >>> is_expr_var(On) False >>> is_expr_var(Block) True >>> is_expr_var(SafetyInjection) True """ return is_const(v) and v.decl().kind()==Z3_OP_UNINTERPRETED def is_expr_val(v): """ EXAMPLES: >>> is_expr_val(Int('7')) False >>> is_expr_val(IntVal('7')) True >>> is_expr_val(Bool('y')) False >>> is_expr_val(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_val(LOnOff) False >>> is_expr_val(On) True >>> is_expr_val(Block) False >>> is_expr_val(SafetyInjection) False """ return is_const(v) and v.decl().kind()!=Z3_OP_UNINTERPRETED def get_vars(f,rs=[]): """ >>> x,y = Ints('x y') >>> a,b = Bools('a b') >>> get_vars(Implies(And(x+y==0,x*2==10),Or(a,Implies(a,b==False)))) [x, y, a, b] """ if __debug__: assert is_expr(f) if is_const(f): if is_expr_val(f): return rs else: #variable return vset(rs + [f],str) else: for f_ in f.children(): rs = get_vars(f_,rs) return vset(rs,str) def mk_var(name,vsort): if vsort.kind() == Z3_INT_SORT: v = Int(name) elif vsort.kind() == Z3_REAL_SORT: v = Real(name) elif vsort.kind() == Z3_BOOL_SORT: v = Bool(name) elif vsort.kind() == Z3_DATATYPE_SORT: v = Const(name,vsort) else: assert False, 'Cannot handle this sort (s: %sid: %d)'\ %(vsort,vsort.kind()) return v def prove(claim,assume=None,verbose=0): """ >>> r,m = prove(BoolVal(True),verbose=0); r,model_str(m,as_str=False) (True, None) #infinite counter example when proving contradiction >>> r,m = prove(BoolVal(False)); r,model_str(m,as_str=False) (False, []) >>> x,y,z=Bools('x y z') >>> r,m = prove(And(x,Not(x))); r,model_str(m,as_str=True) (False, '[]') >>> r,m = prove(True,assume=And(x,Not(x)),verbose=0) Traceback (most recent call last): ... AssertionError: Assumption is always False! >>> r,m = prove(Implies(x,x),assume=y,verbose=2); r,model_str(m,as_str=False) assume: y claim: Implies(x, x) to_prove: Implies(y, Implies(x, x)) (True, None) >>> r,m = prove(And(x,True),assume=y,verbose=0); r,model_str(m,as_str=False) (False, [(x, False), (y, True)]) >>> r,m = prove(And(x,y),assume=y,verbose=0) >>> print(r) False >>> print(model_str(m,as_str=True)) x = False y = True >>> a,b = Ints('a b') >>> r,m = prove(a**b == b**a,assume=None,verbose=0) E: cannot solve ! >>> r is None and m is None True """ if __debug__: assert not assume or is_expr(assume) to_prove = claim if assume: if __debug__: is_proved,_ = prove(Not(assume)) def _f(): emsg = "Assumption is always False!" if verbose >= 2: emsg = "{}\n{}".format(assume,emsg) return emsg assert is_proved==False, _f() to_prove = Implies(assume,to_prove) if verbose >= 2: print('assume: ') print(assume) print('claim: ') print(claim) print('to_prove: ') print(to_prove) f = Not(to_prove) models = get_models(f,k=1) if models is None: #unknown print('E: cannot solve !') return None, None elif models == False: #unsat return True,None else: #sat if __debug__: assert isinstance(models,list) if models: return False, models[0] #the first counterexample else: return False, [] #infinite counterexample,models def get_models(f,k): """ Returns the first k models satisfiying f. If f is not satisfiable, returns False. If f cannot be solved, returns None If f is satisfiable, returns the first k models Note that if f is a tautology, e.g.\ True, then the result is [] Based on http://stackoverflow.com/questions/11867611/z3py-checking-all-solutions-for-equation EXAMPLES: >>> x, y = Ints('x y') >>> len(get_models(And(0<=x,x <= 4),k=11)) 5 >>> get_models(And(0<=x**y,x <= 1),k=2) is None True >>> get_models(And(0<=x,x <= -1),k=2) False >>> len(get_models(x+y==7,5)) 5 >>> len(get_models(And(x<=5,x>=1),7)) 5 >>> get_models(And(x<=0,x>=5),7) False >>> x = Bool('x') >>> get_models(And(x,Not(x)),k=1) False >>> get_models(Implies(x,x),k=1) [] >>> get_models(BoolVal(True),k=1) [] """ if __debug__: assert is_expr(f) assert k>=1 s = Solver() s.add(f) models = [] i = 0 while s.check() == sat and i < k: i = i + 1 m = s.model() if not m: #if m == [] break models.append(m) #create new constraint to block the current model block = Not(And([v() == m[v] for v in m])) s.add(block) if s.check() == unknown: return None elif s.check() == unsat and i==0: return False else: return models def is_tautology(claim,verbose=0): """ >>> is_tautology(Implies(Bool('x'),Bool('x'))) True >>> is_tautology(Implies(Bool('x'),Bool('y'))) False >>> is_tautology(BoolVal(True)) True >>> is_tautology(BoolVal(False)) False """ return prove(claim=claim,assume=None,verbose=verbose)[0] def is_contradiction(claim,verbose=0): """ >>> x,y=Bools('x y') >>> is_contradiction(BoolVal(False)) True >>> is_contradiction(BoolVal(True)) False >>> is_contradiction(x) False >>> is_contradiction(Implies(x,y)) False >>> is_contradiction(Implies(x,x)) False >>> is_contradiction(And(x,Not(x))) True """ return prove(claim=Not(claim),assume=None,verbose=verbose)[0] def exact_one_model(f): """ return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False """ models = get_models(f,k=2) if isinstance(models,list): return len(models)==1 else: return False def myBinOp(op,*L): """ >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd(*[Bool('x'),None]) x >>> myAnd(*[Bool('x')]) x >>> myAnd(*[]) >>> myAnd(Bool('x'),Bool('y')) And(x, y) >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd([Bool('x'),Bool('y')]) And(x, y) >>> myAnd((Bool('x'),Bool('y'))) And(x, y) >>> myAnd(*[Bool('x'),Bool('y'),True]) Traceback (most recent call last): ... AssertionError """ if __debug__: assert op == Z3_OP_OR or op == Z3_OP_AND or op == Z3_OP_IMPLIES if len(L)==1 and (isinstance(L[0],list) or isinstance(L[0],tuple)): L = L[0] if __debug__: assert all(not isinstance(l,bool) for l in L) L = [l for l in L if is_expr(l)] if L: if len(L)==1: return L[0] else: if op == Z3_OP_OR: return Or(L) elif op == Z3_OP_AND: return And(L) else: #IMPLIES return Implies(L[0],L[1]) else: return None def myAnd(*L): return myBinOp(Z3_OP_AND,*L) def myOr(*L): return myBinOp(Z3_OP_OR,*L) def myImplies(a,b):return myBinOp(Z3_OP_IMPLIES,[a,b]) Iff = lambda f: And(Implies(f[0],f[1]),Implies(f[1],f[0])) def model_str(m,as_str=True): """ Returned a 'sorted' model (so that it's easier to see) The model is sorted by its key, e.g. if the model is y = 3 , x = 10, then the result is x = 10, y = 3 EXAMPLES: see doctest exampels from function prove() """ if __debug__: assert m is None or m == [] or isinstance(m,ModelRef) if m : vs = [(v,m[v]) for v in m] vs = sorted(vs,key=lambda a,_: str(a)) if as_str: return '\n'.join(['{} = {}'.format(k,v) for (k,v) in vs]) else: return vs else: return str(m) if as_str else m
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3util.py
z3util.py
import ctypes class Z3Exception(Exception): def __init__(self, value): self.value = value def __str__(self): return str(self.value) class ContextObj(ctypes.c_void_p): def __init__(self, context): self._as_parameter_ = context def from_param(obj): return obj class Config(ctypes.c_void_p): def __init__(self, config): self._as_parameter_ = config def from_param(obj): return obj class Symbol(ctypes.c_void_p): def __init__(self, symbol): self._as_parameter_ = symbol def from_param(obj): return obj class Sort(ctypes.c_void_p): def __init__(self, sort): self._as_parameter_ = sort def from_param(obj): return obj class FuncDecl(ctypes.c_void_p): def __init__(self, decl): self._as_parameter_ = decl def from_param(obj): return obj class Ast(ctypes.c_void_p): def __init__(self, ast): self._as_parameter_ = ast def from_param(obj): return obj class Pattern(ctypes.c_void_p): def __init__(self, pattern): self._as_parameter_ = pattern def from_param(obj): return obj class Model(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class Literals(ctypes.c_void_p): def __init__(self, literals): self._as_parameter_ = literals def from_param(obj): return obj class Constructor(ctypes.c_void_p): def __init__(self, constructor): self._as_parameter_ = constructor def from_param(obj): return obj class ConstructorList(ctypes.c_void_p): def __init__(self, constructor_list): self._as_parameter_ = constructor_list def from_param(obj): return obj class GoalObj(ctypes.c_void_p): def __init__(self, goal): self._as_parameter_ = goal def from_param(obj): return obj class TacticObj(ctypes.c_void_p): def __init__(self, tactic): self._as_parameter_ = tactic def from_param(obj): return obj class ProbeObj(ctypes.c_void_p): def __init__(self, probe): self._as_parameter_ = probe def from_param(obj): return obj class ApplyResultObj(ctypes.c_void_p): def __init__(self, obj): self._as_parameter_ = obj def from_param(obj): return obj class StatsObj(ctypes.c_void_p): def __init__(self, statistics): self._as_parameter_ = statistics def from_param(obj): return obj class SolverObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class FixedpointObj(ctypes.c_void_p): def __init__(self, fixedpoint): self._as_parameter_ = fixedpoint def from_param(obj): return obj class OptimizeObj(ctypes.c_void_p): def __init__(self, optimize): self._as_parameter_ = optimize def from_param(obj): return obj class ModelObj(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class AstVectorObj(ctypes.c_void_p): def __init__(self, vector): self._as_parameter_ = vector def from_param(obj): return obj class AstMapObj(ctypes.c_void_p): def __init__(self, ast_map): self._as_parameter_ = ast_map def from_param(obj): return obj class Params(ctypes.c_void_p): def __init__(self, params): self._as_parameter_ = params def from_param(obj): return obj class ParamDescrs(ctypes.c_void_p): def __init__(self, paramdescrs): self._as_parameter_ = paramdescrs def from_param(obj): return obj class FuncInterpObj(ctypes.c_void_p): def __init__(self, f): self._as_parameter_ = f def from_param(obj): return obj class FuncEntryObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj class RCFNumObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj
z3-solver-mythril
/z3_solver_mythril-4.8.4.1-py3-none-manylinux1_x86_64.whl/z3/z3types.py
z3types.py
On Windows, to build Z3, you should executed the following command in the Z3 root directory at the Visual Studio Command Prompt msbuild /p:configuration=external If you are using a 64-bit Python interpreter, you should use msbuild /p:configuration=external /p:platform=x64 On Linux and macOS, you must install python bindings, before trying example.py. To install python on Linux and macOS, you should execute the following command in the Z3 root directory sudo make install-z3py
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/README.txt
README.txt
from .z3 import * from .z3core import * from .z3printer import * def _to_rcfnum(num, ctx=None): if isinstance(num, RCFNum): return num else: return RCFNum(num, ctx) def Pi(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_pi(ctx.ref()), ctx) def E(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_e(ctx.ref()), ctx) def MkInfinitesimal(name="eps", ctx=None): # Todo: remove parameter name. # For now, we keep it for backward compatibility. ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_infinitesimal(ctx.ref()), ctx) def MkRoots(p, ctx=None): ctx = z3.get_ctx(ctx) num = len(p) _tmp = [] _as = (RCFNumObj * num)() _rs = (RCFNumObj * num)() for i in range(num): _a = _to_rcfnum(p[i], ctx) _tmp.append(_a) # prevent GC _as[i] = _a.num nr = Z3_rcf_mk_roots(ctx.ref(), num, _as, _rs) r = [] for i in range(nr): r.append(RCFNum(_rs[i], ctx)) return r class RCFNum: def __init__(self, num, ctx=None): # TODO: add support for converting AST numeral values into RCFNum if isinstance(num, RCFNumObj): self.num = num self.ctx = z3.get_ctx(ctx) else: self.ctx = z3.get_ctx(ctx) self.num = Z3_rcf_mk_rational(self.ctx_ref(), str(num)) def __del__(self): Z3_rcf_del(self.ctx_ref(), self.num) def ctx_ref(self): return self.ctx.ref() def __repr__(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, False, in_html_mode()) def compact_str(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, True, in_html_mode()) def __add__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), self.num, v.num), self.ctx) def __radd__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), v.num, self.num), self.ctx) def __mul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), self.num, v.num), self.ctx) def __rmul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), v.num, self.num), self.ctx) def __sub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), self.num, v.num), self.ctx) def __rsub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), v.num, self.num), self.ctx) def __div__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), self.num, v.num), self.ctx) def __rdiv__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), v.num, self.num), self.ctx) def __neg__(self): return self.__rsub__(0) def power(self, k): return RCFNum(Z3_rcf_power(self.ctx_ref(), self.num, k), self.ctx) def __pow__(self, k): return self.power(k) def decimal(self, prec=5): return Z3_rcf_num_to_decimal_string(self.ctx_ref(), self.num, prec) def __lt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), self.num, v.num) def __rlt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), v.num, self.num) def __gt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), self.num, v.num) def __rgt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), v.num, self.num) def __le__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), self.num, v.num) def __rle__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), v.num, self.num) def __ge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), self.num, v.num) def __rge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), v.num, self.num) def __eq__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_eq(self.ctx_ref(), self.num, v.num) def __ne__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_neq(self.ctx_ref(), self.num, v.num) def split(self): n = (RCFNumObj * 1)() d = (RCFNumObj * 1)() Z3_rcf_get_numerator_denominator(self.ctx_ref(), self.num, n, d) return (RCFNum(n[0], self.ctx), RCFNum(d[0], self.ctx))
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3rcf.py
z3rcf.py
from . import z3core from .z3core import * from .z3types import * from .z3consts import * from .z3printer import * from fractions import Fraction import sys import io import math import copy if sys.version_info.major >= 3: from typing import Iterable Z3_DEBUG = __debug__ def z3_debug(): global Z3_DEBUG return Z3_DEBUG if sys.version_info.major < 3: def _is_int(v): return isinstance(v, (int, long)) else: def _is_int(v): return isinstance(v, int) def enable_trace(msg): Z3_enable_trace(msg) def disable_trace(msg): Z3_disable_trace(msg) def get_version_string(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return "%s.%s.%s" % (major.value, minor.value, build.value) def get_version(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return (major.value, minor.value, build.value, rev.value) def get_full_version(): return Z3_get_full_version() def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) def _z3_check_cint_overflow(n, name): _z3_assert(ctypes.c_int(n).value == n, name + " is too large") def open_log(fname): """Log interaction to a file. This function must be invoked immediately after init(). """ Z3_open_log(fname) def append_log(s): """Append user-defined string to interaction log. """ Z3_append_log(s) def to_symbol(s, ctx=None): """Convert an integer or string into a Z3 symbol.""" if _is_int(s): return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s) else: return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s) def _symbol2py(ctx, s): """Convert a Z3 symbol back into a Python object. """ if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL: return "k!%s" % Z3_get_symbol_int(ctx.ref(), s) else: return Z3_get_symbol_string(ctx.ref(), s) # Hack for having nary functions that can receive one argument that is the # list of arguments. # Use this when function takes a single list of arguments def _get_args(args): try: if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): return args[0] elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)): return [arg for arg in args[0]] else: return args except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?) return args # Use this when function takes multiple arguments def _get_args_ast_list(args): try: if isinstance(args, (set, AstVector, tuple)): return [arg for arg in args] else: return args except Exception: return args def _to_param_value(val): if isinstance(val, bool): return "true" if val else "false" return str(val) def z3_error_handler(c, e): # Do nothing error handler, just avoid exit(0) # The wrappers in z3core.py will raise a Z3Exception if an error is detected return class Context: """A Context manages all other Z3 objects, global configuration options, etc. Z3Py uses a default global context. For most applications this is sufficient. An application may use multiple Z3 contexts. Objects created in one context cannot be used in another one. However, several objects may be "translated" from one context to another. It is not safe to access Z3 objects from multiple threads. The only exception is the method `interrupt()` that can be used to interrupt() a long computation. The initialization method receives global configuration options for the new context. """ def __init__(self, *args, **kws): if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") conf = Z3_mk_config() for key in kws: value = kws[key] Z3_set_param_value(conf, str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_set_param_value(conf, str(prev), _to_param_value(a)) prev = None self.ctx = Z3_mk_context_rc(conf) self.owner = True self.eh = Z3_set_error_handler(self.ctx, z3_error_handler) Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT) Z3_del_config(conf) def __del__(self): if Z3_del_context is not None and self.owner: Z3_del_context(self.ctx) self.ctx = None self.eh = None def ref(self): """Return a reference to the actual C pointer to the Z3 context.""" return self.ctx def interrupt(self): """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions. This method can be invoked from a thread different from the one executing the interruptible procedure. """ Z3_interrupt(self.ref()) def param_descrs(self): """Return the global parameter description set.""" return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self) # Global Z3 context _main_ctx = None def main_ctx(): """Return a reference to the global Z3 context. >>> x = Real('x') >>> x.ctx == main_ctx() True >>> c = Context() >>> c == main_ctx() False >>> x2 = Real('x', c) >>> x2.ctx == c True >>> eq(x, x2) False """ global _main_ctx if _main_ctx is None: _main_ctx = Context() return _main_ctx def _get_ctx(ctx): if ctx is None: return main_ctx() else: return ctx def get_ctx(ctx): return _get_ctx(ctx) def set_param(*args, **kws): """Set Z3 global (or module) parameters. >>> set_param(precision=10) """ if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") new_kws = {} for k in kws: v = kws[k] if not set_pp_option(k, v): new_kws[k] = v for key in new_kws: value = new_kws[key] Z3_global_param_set(str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_global_param_set(str(prev), _to_param_value(a)) prev = None def reset_params(): """Reset all global (or module) parameters. """ Z3_global_param_reset_all() def set_option(*args, **kws): """Alias for 'set_param' for backward compatibility. """ return set_param(*args, **kws) def get_param(name): """Return the value of a Z3 global (or module) parameter >>> get_param('nlsat.reorder') 'true' """ ptr = (ctypes.c_char_p * 1)() if Z3_global_param_get(str(name), ptr): r = z3core._to_pystr(ptr[0]) return r raise Z3Exception("failed to retrieve value for '%s'" % name) ######################################### # # ASTs base class # ######################################### # Mark objects that use pretty printer class Z3PPObject: """Superclass for all Z3 objects that have support for pretty printing.""" def use_pp(self): return True def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res class AstRef(Z3PPObject): """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions.""" def __init__(self, ast, ctx=None): self.ast = ast self.ctx = _get_ctx(ctx) Z3_inc_ref(self.ctx.ref(), self.as_ast()) def __del__(self): if self.ctx.ref() is not None and self.ast is not None and Z3_dec_ref is not None: Z3_dec_ref(self.ctx.ref(), self.as_ast()) self.ast = None def __deepcopy__(self, memo={}): return _to_ast_ref(self.ast, self.ctx) def __str__(self): return obj_to_string(self) def __repr__(self): return obj_to_string(self) def __eq__(self, other): return self.eq(other) def __hash__(self): return self.hash() def __nonzero__(self): return self.__bool__() def __bool__(self): if is_true(self): return True elif is_false(self): return False elif is_eq(self) and self.num_args() == 2: return self.arg(0).eq(self.arg(1)) else: raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.") def sexpr(self): """Return a string representing the AST node in s-expression notation. >>> x = Int('x') >>> ((x + 1)*x).sexpr() '(* (+ x 1) x)' """ return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): """Return a pointer to the corresponding C Z3_ast object.""" return self.ast def get_id(self): """Return unique identifier for object. It can be used for hash-tables and maps.""" return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def ctx_ref(self): """Return a reference to the C context where this AST node is stored.""" return self.ctx.ref() def eq(self, other): """Return `True` if `self` and `other` are structurally identical. >>> x = Int('x') >>> n1 = x + 1 >>> n2 = 1 + x >>> n1.eq(n2) False >>> n1 = simplify(n1) >>> n2 = simplify(n2) >>> n1.eq(n2) True """ if z3_debug(): _z3_assert(is_ast(other), "Z3 AST expected") return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast()) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> x = Int('x', c1) >>> y = Int('y', c2) >>> # Nodes in different contexts can't be mixed. >>> # However, we can translate nodes from one context to another. >>> x.translate(c2) + y x + y """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target) def __copy__(self): return self.translate(self.ctx) def hash(self): """Return a hashcode for the `self`. >>> n1 = simplify(Int('x') + 1) >>> n2 = simplify(2 + Int('x') - 1) >>> n1.hash() == n2.hash() True """ return Z3_get_ast_hash(self.ctx_ref(), self.as_ast()) def is_ast(a): """Return `True` if `a` is an AST node. >>> is_ast(10) False >>> is_ast(IntVal(10)) True >>> is_ast(Int('x')) True >>> is_ast(BoolSort()) True >>> is_ast(Function('f', IntSort(), IntSort())) True >>> is_ast("x") False >>> is_ast(Solver()) False """ return isinstance(a, AstRef) def eq(a, b): """Return `True` if `a` and `b` are structurally identical AST nodes. >>> x = Int('x') >>> y = Int('y') >>> eq(x, y) False >>> eq(x + 1, x + 1) True >>> eq(x + 1, 1 + x) False >>> eq(simplify(x + 1), simplify(1 + x)) True """ if z3_debug(): _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected") return a.eq(b) def _ast_kind(ctx, a): if is_ast(a): a = a.as_ast() return Z3_get_ast_kind(ctx.ref(), a) def _ctx_from_ast_arg_list(args, default_ctx=None): ctx = None for a in args: if is_ast(a) or is_probe(a): if ctx is None: ctx = a.ctx else: if z3_debug(): _z3_assert(ctx == a.ctx, "Context mismatch") if ctx is None: ctx = default_ctx return ctx def _ctx_from_ast_args(*args): return _ctx_from_ast_arg_list(args) def _to_func_decl_array(args): sz = len(args) _args = (FuncDecl * sz)() for i in range(sz): _args[i] = args[i].as_func_decl() return _args, sz def _to_ast_array(args): sz = len(args) _args = (Ast * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ref_array(ref, args): sz = len(args) _args = (ref * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ast_ref(a, ctx): k = _ast_kind(ctx, a) if k == Z3_SORT_AST: return _to_sort_ref(a, ctx) elif k == Z3_FUNC_DECL_AST: return _to_func_decl_ref(a, ctx) else: return _to_expr_ref(a, ctx) ######################################### # # Sorts # ######################################### def _sort_kind(ctx, s): return Z3_get_sort_kind(ctx.ref(), s) class SortRef(AstRef): """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node.""" def as_ast(self): return Z3_sort_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def kind(self): """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts. >>> b = BoolSort() >>> b.kind() == Z3_BOOL_SORT True >>> b.kind() == Z3_INT_SORT False >>> A = ArraySort(IntSort(), IntSort()) >>> A.kind() == Z3_ARRAY_SORT True >>> A.kind() == Z3_INT_SORT False """ return _sort_kind(self.ctx, self.ast) def subsort(self, other): """Return `True` if `self` is a subsort of `other`. >>> IntSort().subsort(RealSort()) True """ return False def cast(self, val): """Try to cast `val` as an element of sort `self`. This method is used in Z3Py to convert Python objects such as integers, floats, longs and strings into Z3 expressions. >>> x = Int('x') >>> RealSort().cast(x) ToReal(x) """ if z3_debug(): _z3_assert(is_expr(val), "Z3 expression expected") _z3_assert(self.eq(val.sort()), "Sort mismatch") return val def name(self): """Return the name (string) of sort `self`. >>> BoolSort().name() 'Bool' >>> ArraySort(IntSort(), IntSort()).name() 'Array' """ return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast)) def __eq__(self, other): """Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False """ if other is None: return False return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __ne__(self, other): """Return `True` if `self` and `other` are not the same Z3 sort. >>> p = Bool('p') >>> p.sort() != BoolSort() False >>> p.sort() != IntSort() True """ return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def is_sort(s): """Return `True` if `s` is a Z3 sort. >>> is_sort(IntSort()) True >>> is_sort(Int('x')) False >>> is_expr(Int('x')) True """ return isinstance(s, SortRef) def _to_sort_ref(s, ctx): if z3_debug(): _z3_assert(isinstance(s, Sort), "Z3 Sort expected") k = _sort_kind(ctx, s) if k == Z3_BOOL_SORT: return BoolSortRef(s, ctx) elif k == Z3_INT_SORT or k == Z3_REAL_SORT: return ArithSortRef(s, ctx) elif k == Z3_BV_SORT: return BitVecSortRef(s, ctx) elif k == Z3_ARRAY_SORT: return ArraySortRef(s, ctx) elif k == Z3_DATATYPE_SORT: return DatatypeSortRef(s, ctx) elif k == Z3_FINITE_DOMAIN_SORT: return FiniteDomainSortRef(s, ctx) elif k == Z3_FLOATING_POINT_SORT: return FPSortRef(s, ctx) elif k == Z3_ROUNDING_MODE_SORT: return FPRMSortRef(s, ctx) elif k == Z3_RE_SORT: return ReSortRef(s, ctx) elif k == Z3_SEQ_SORT: return SeqSortRef(s, ctx) elif k == Z3_CHAR_SORT: return CharSortRef(s, ctx) return SortRef(s, ctx) def _sort(ctx, a): return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx) def DeclareSort(name, ctx=None): """Create a new uninterpreted sort named `name`. If `ctx=None`, then the new sort is declared in the global Z3Py context. >>> A = DeclareSort('A') >>> a = Const('a', A) >>> b = Const('b', A) >>> a.sort() == A True >>> b.sort() == A True >>> a == b a == b """ ctx = _get_ctx(ctx) return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx) ######################################### # # Function Declarations # ######################################### class FuncDeclRef(AstRef): """Function declaration. Every constant and function have an associated declaration. The declaration assigns a name, a sort (i.e., type), and for function the sort (i.e., type) of each of its arguments. Note that, in Z3, a constant is a function with 0 arguments. """ def as_ast(self): return Z3_func_decl_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def as_func_decl(self): return self.ast def name(self): """Return the name of the function declaration `self`. >>> f = Function('f', IntSort(), IntSort()) >>> f.name() 'f' >>> isinstance(f.name(), str) True """ return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast)) def arity(self): """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.arity() 2 """ return int(Z3_get_arity(self.ctx_ref(), self.ast)) def domain(self, i): """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.domain(0) Int >>> f.domain(1) Real """ return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the sort of the range of a function declaration. For constants, this is the sort of the constant. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.range() Bool """ return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx) def kind(self): """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc. >>> x = Int('x') >>> d = (x + 1).decl() >>> d.kind() == Z3_OP_ADD True >>> d.kind() == Z3_OP_MUL False """ return Z3_get_decl_kind(self.ctx_ref(), self.ast) def params(self): ctx = self.ctx n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast) result = [None for i in range(n)] for i in range(n): k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i) if k == Z3_PARAMETER_INT: result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_DOUBLE: result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_RATIONAL: result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SYMBOL: result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SORT: result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_AST: result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_FUNC_DECL: result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx) else: assert(False) return result def __call__(self, *args): """Create a Z3 application expression using the function `self`, and the given arguments. The arguments must be Z3 expressions. This method assumes that the sorts of the elements in `args` match the sorts of the domain. Limited coercion is supported. For example, if args[0] is a Python integer, and the function expects a Z3 integer, then the argument is automatically converted into a Z3 integer. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> x = Int('x') >>> y = Real('y') >>> f(x, y) f(x, y) >>> f(x, x) f(x, ToReal(x)) """ args = _get_args(args) num = len(args) _args = (Ast * num)() saved = [] for i in range(num): # self.domain(i).cast(args[i]) may create a new Z3 expression, # then we must save in 'saved' to prevent it from being garbage collected. tmp = self.domain(i).cast(args[i]) saved.append(tmp) _args[i] = tmp.as_ast() return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx) def is_func_decl(a): """Return `True` if `a` is a Z3 function declaration. >>> f = Function('f', IntSort(), IntSort()) >>> is_func_decl(f) True >>> x = Real('x') >>> is_func_decl(x) False """ return isinstance(a, FuncDeclRef) def Function(name, *sig): """Create a new Z3 uninterpreted function with the given sorts. >>> f = Function('f', IntSort(), IntSort()) >>> f(f(0)) f(f(0)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def FreshFunction(*sig): """Create a new fresh Z3 uninterpreted function with the given sorts. """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (z3.Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx) def _to_func_decl_ref(a, ctx): return FuncDeclRef(a, ctx) def RecFunction(name, *sig): """Create a new Z3 recursive with the given sorts.""" sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def RecAddDefinition(f, args, body): """Set the body of a recursive function. Recursive definitions can be simplified if they are applied to ground arguments. >>> ctx = Context() >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx)) >>> n = Int('n', ctx) >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1))) >>> simplify(fac(5)) 120 >>> s = Solver(ctx=ctx) >>> s.add(fac(n) < 3) >>> s.check() sat >>> s.model().eval(fac(5)) 120 """ if is_app(args): args = [args] ctx = body.ctx args = _get_args(args) n = len(args) _args = (Ast * n)() for i in range(n): _args[i] = args[i].ast Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast) ######################################### # # Expressions # ######################################### class ExprRef(AstRef): """Constraints, formulas and terms are expressions in Z3. Expressions are ASTs. Every expression has a sort. There are three main kinds of expressions: function applications, quantifiers and bounded variables. A constant is a function application with 0 arguments. For quantifier free problems, all expressions are function applications. """ def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the sort of expression `self`. >>> x = Int('x') >>> (x + 1).sort() Int >>> y = Real('y') >>> (x + y).sort() Real """ return _sort(self.ctx, self.as_ast()) def sort_kind(self): """Shorthand for `self.sort().kind()`. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort_kind() == Z3_ARRAY_SORT True >>> a.sort_kind() == Z3_INT_SORT False """ return self.sort().kind() def __eq__(self, other): """Return a Z3 expression that represents the constraint `self == other`. If `other` is `None`, then this method simply returns `False`. >>> a = Int('a') >>> b = Int('b') >>> a == b a == b >>> a is None False """ if other is None: return False a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def __ne__(self, other): """Return a Z3 expression that represents the constraint `self != other`. If `other` is `None`, then this method simply returns `True`. >>> a = Int('a') >>> b = Int('b') >>> a != b a != b >>> a is not None True """ if other is None: return True a, b = _coerce_exprs(self, other) _args, sz = _to_ast_array((a, b)) return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx) def params(self): return self.decl().params() def decl(self): """Return the Z3 function declaration associated with a Z3 application. >>> f = Function('f', IntSort(), IntSort()) >>> a = Int('a') >>> t = f(a) >>> eq(t.decl(), f) True >>> (a + 1).decl() + """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx) def num_args(self): """Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast())) def arg(self, idx): """Return argument `idx` of the application `self`. This method assumes that `self` is a function application with at least `idx+1` arguments. >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.arg(0) a >>> t.arg(1) b >>> t.arg(2) 0 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") _z3_assert(idx < self.num_args(), "Invalid argument index") return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx) def children(self): """Return a list containing the children of the given expression >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.children() [a, b, 0] """ if is_app(self): return [self.arg(i) for i in range(self.num_args())] else: return [] def from_string(self, s): pass def serialize(self): s = Solver() f = Function('F', self.sort(), BoolSort(self.ctx)) s.add(f(self)) return s.sexpr() def deserialize(st): """inverse function to the serialize method on ExprRef. It is made available to make it easier for users to serialize expressions back and forth between strings. Solvers can be serialized using the 'sexpr()' method. """ s = Solver() s.from_string(st) if len(s.assertions()) != 1: raise Z3Exception("single assertion expected") fml = s.assertions()[0] if fml.num_args() != 1: raise Z3Exception("dummy function 'F' expected") return fml.arg(0) def _to_expr_ref(a, ctx): if isinstance(a, Pattern): return PatternRef(a, ctx) ctx_ref = ctx.ref() k = Z3_get_ast_kind(ctx_ref, a) if k == Z3_QUANTIFIER_AST: return QuantifierRef(a, ctx) sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a)) if sk == Z3_BOOL_SORT: return BoolRef(a, ctx) if sk == Z3_INT_SORT: if k == Z3_NUMERAL_AST: return IntNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_REAL_SORT: if k == Z3_NUMERAL_AST: return RatNumRef(a, ctx) if _is_algebraic(ctx, a): return AlgebraicNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_BV_SORT: if k == Z3_NUMERAL_AST: return BitVecNumRef(a, ctx) else: return BitVecRef(a, ctx) if sk == Z3_ARRAY_SORT: return ArrayRef(a, ctx) if sk == Z3_DATATYPE_SORT: return DatatypeRef(a, ctx) if sk == Z3_FLOATING_POINT_SORT: if k == Z3_APP_AST and _is_numeral(ctx, a): return FPNumRef(a, ctx) else: return FPRef(a, ctx) if sk == Z3_FINITE_DOMAIN_SORT: if k == Z3_NUMERAL_AST: return FiniteDomainNumRef(a, ctx) else: return FiniteDomainRef(a, ctx) if sk == Z3_ROUNDING_MODE_SORT: return FPRMRef(a, ctx) if sk == Z3_SEQ_SORT: return SeqRef(a, ctx) if sk == Z3_CHAR_SORT: return CharRef(a, ctx) if sk == Z3_RE_SORT: return ReRef(a, ctx) return ExprRef(a, ctx) def _coerce_expr_merge(s, a): if is_expr(a): s1 = a.sort() if s is None: return s1 if s1.eq(s): return s elif s.subsort(s1): return s1 elif s1.subsort(s): return s else: if z3_debug(): _z3_assert(s1.ctx == s.ctx, "context mismatch") _z3_assert(False, "sort mismatch") else: return s def _coerce_exprs(a, b, ctx=None): if not is_expr(a) and not is_expr(b): a = _py2expr(a, ctx) b = _py2expr(b, ctx) if isinstance(a, str) and isinstance(b, SeqRef): a = StringVal(a, b.ctx) if isinstance(b, str) and isinstance(a, SeqRef): b = StringVal(b, a.ctx) if isinstance(a, float) and isinstance(b, ArithRef): a = RealVal(a, b.ctx) if isinstance(b, float) and isinstance(a, ArithRef): b = RealVal(b, a.ctx) s = None s = _coerce_expr_merge(s, a) s = _coerce_expr_merge(s, b) a = s.cast(a) b = s.cast(b) return (a, b) def _reduce(func, sequence, initial): result = initial for element in sequence: result = func(result, element) return result def _coerce_expr_list(alist, ctx=None): has_expr = False for a in alist: if is_expr(a): has_expr = True break if not has_expr: alist = [_py2expr(a, ctx) for a in alist] s = _reduce(_coerce_expr_merge, alist, None) return [s.cast(a) for a in alist] def is_expr(a): """Return `True` if `a` is a Z3 expression. >>> a = Int('a') >>> is_expr(a) True >>> is_expr(a + 1) True >>> is_expr(IntSort()) False >>> is_expr(1) False >>> is_expr(IntVal(1)) True >>> x = Int('x') >>> is_expr(ForAll(x, x >= 0)) True >>> is_expr(FPVal(1.0)) True """ return isinstance(a, ExprRef) def is_app(a): """Return `True` if `a` is a Z3 function application. Note that, constants are function applications with 0 arguments. >>> a = Int('a') >>> is_app(a) True >>> is_app(a + 1) True >>> is_app(IntSort()) False >>> is_app(1) False >>> is_app(IntVal(1)) True >>> x = Int('x') >>> is_app(ForAll(x, x >= 0)) False """ if not isinstance(a, ExprRef): return False k = _ast_kind(a.ctx, a) return k == Z3_NUMERAL_AST or k == Z3_APP_AST def is_const(a): """Return `True` if `a` is Z3 constant/variable expression. >>> a = Int('a') >>> is_const(a) True >>> is_const(a + 1) False >>> is_const(1) False >>> is_const(IntVal(1)) True >>> x = Int('x') >>> is_const(ForAll(x, x >= 0)) False """ return is_app(a) and a.num_args() == 0 def is_var(a): """Return `True` if `a` is variable. Z3 uses de-Bruijn indices for representing bound variables in quantifiers. >>> x = Int('x') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort()) >>> # Z3 replaces x with bound variables when ForAll is executed. >>> q = ForAll(x, f(x) == x) >>> b = q.body() >>> b f(Var(0)) == Var(0) >>> b.arg(1) Var(0) >>> is_var(b.arg(1)) True """ return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST def get_var_index(a): """Return the de-Bruijn index of the Z3 bounded variable `a`. >>> x = Int('x') >>> y = Int('y') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # Z3 replaces x and y with bound variables when ForAll is executed. >>> q = ForAll([x, y], f(x, y) == x + y) >>> q.body() f(Var(1), Var(0)) == Var(1) + Var(0) >>> b = q.body() >>> b.arg(0) f(Var(1), Var(0)) >>> v1 = b.arg(0).arg(0) >>> v2 = b.arg(0).arg(1) >>> v1 Var(1) >>> v2 Var(0) >>> get_var_index(v1) 1 >>> get_var_index(v2) 0 """ if z3_debug(): _z3_assert(is_var(a), "Z3 bound variable expected") return int(Z3_get_index_value(a.ctx.ref(), a.as_ast())) def is_app_of(a, k): """Return `True` if `a` is an application of the given kind `k`. >>> x = Int('x') >>> n = x + 1 >>> is_app_of(n, Z3_OP_ADD) True >>> is_app_of(n, Z3_OP_MUL) False """ return is_app(a) and a.decl().kind() == k def If(a, b, c, ctx=None): """Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x) """ if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic): return Cond(a, b, c, ctx) else: ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx)) s = BoolSort(ctx) a = s.cast(a) b, c = _coerce_exprs(b, c, ctx) if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def Distinct(*args): """Create a Z3 distinct expression. >>> x = Int('x') >>> y = Int('y') >>> Distinct(x, y) x != y >>> z = Int('z') >>> Distinct(x, y, z) Distinct(x, y, z) >>> simplify(Distinct(x, y, z)) Distinct(x, y, z) >>> simplify(Distinct(x, y, z), blast_distinct=True) And(Not(x == y), Not(x == z), Not(y == z)) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx) def _mk_bin(f, a, b): args = (Ast * 2)() if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") args[0] = a.as_ast() args[1] = b.as_ast() return f(a.ctx.ref(), 2, args) def Const(name, sort): """Create a constant of the given sort. >>> Const('x', IntSort()) x """ if z3_debug(): _z3_assert(isinstance(sort, SortRef), "Z3 sort expected") ctx = sort.ctx return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx) def Consts(names, sort): """Create several constants of the given sort. `names` is a string containing the names of all constants to be created. Blank spaces separate the names of different constants. >>> x, y, z = Consts('x y z', IntSort()) >>> x + y + z x + y + z """ if isinstance(names, str): names = names.split(" ") return [Const(name, sort) for name in names] def FreshConst(sort, prefix="c"): """Create a fresh constant of a specified sort""" ctx = _get_ctx(sort.ctx) return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx) def Var(idx, s): """Create a Z3 free variable. Free variables are used to create quantified formulas. A free variable with index n is bound when it occurs within the scope of n+1 quantified declarations. >>> Var(0, IntSort()) Var(0) >>> eq(Var(0, IntSort()), Var(0, BoolSort())) False """ if z3_debug(): _z3_assert(is_sort(s), "Z3 sort expected") return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx) def RealVar(idx, ctx=None): """ Create a real free variable. Free variables are used to create quantified formulas. They are also used to create polynomials. >>> RealVar(0) Var(0) """ return Var(idx, RealSort(ctx)) def RealVarVector(n, ctx=None): """ Create a list of Real free variables. The variables have ids: 0, 1, ..., n-1 >>> x0, x1, x2, x3 = RealVarVector(4) >>> x2 Var(2) """ return [RealVar(i, ctx) for i in range(n)] ######################################### # # Booleans # ######################################### class BoolSortRef(SortRef): """Boolean sort.""" def cast(self, val): """Try to cast `val` as a Boolean. >>> x = BoolSort().cast(True) >>> x True >>> is_expr(x) True >>> is_expr(True) False >>> x.sort() Bool """ if isinstance(val, bool): return BoolVal(val, self.ctx) if z3_debug(): if not is_expr(val): msg = "True, False or Z3 Boolean expression expected. Received %s of type %s" _z3_assert(is_expr(val), msg % (val, type(val))) if not self.eq(val.sort()): _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value") return val def subsort(self, other): return isinstance(other, ArithSortRef) def is_int(self): return True def is_bool(self): return True class BoolRef(ExprRef): """All Boolean expressions are instances of this class.""" def sort(self): return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __rmul__(self, other): return self * other def __mul__(self, other): """Create the Z3 expression `self * other`. """ if isinstance(other, int) and other == 1: return If(self, 1, 0) if isinstance(other, int) and other == 0: return IntVal(0, self.ctx) if isinstance(other, BoolRef): other = If(other, 1, 0) return If(self, other, 0) def is_bool(a): """Return `True` if `a` is a Z3 Boolean expression. >>> p = Bool('p') >>> is_bool(p) True >>> q = Bool('q') >>> is_bool(And(p, q)) True >>> x = Real('x') >>> is_bool(x) False >>> is_bool(x == 0) True """ return isinstance(a, BoolRef) def is_true(a): """Return `True` if `a` is the Z3 true expression. >>> p = Bool('p') >>> is_true(p) False >>> is_true(simplify(p == p)) True >>> x = Real('x') >>> is_true(x == 0) False >>> # True is a Python Boolean expression >>> is_true(True) False """ return is_app_of(a, Z3_OP_TRUE) def is_false(a): """Return `True` if `a` is the Z3 false expression. >>> p = Bool('p') >>> is_false(p) False >>> is_false(False) False >>> is_false(BoolVal(False)) True """ return is_app_of(a, Z3_OP_FALSE) def is_and(a): """Return `True` if `a` is a Z3 and expression. >>> p, q = Bools('p q') >>> is_and(And(p, q)) True >>> is_and(Or(p, q)) False """ return is_app_of(a, Z3_OP_AND) def is_or(a): """Return `True` if `a` is a Z3 or expression. >>> p, q = Bools('p q') >>> is_or(Or(p, q)) True >>> is_or(And(p, q)) False """ return is_app_of(a, Z3_OP_OR) def is_implies(a): """Return `True` if `a` is a Z3 implication expression. >>> p, q = Bools('p q') >>> is_implies(Implies(p, q)) True >>> is_implies(And(p, q)) False """ return is_app_of(a, Z3_OP_IMPLIES) def is_not(a): """Return `True` if `a` is a Z3 not expression. >>> p = Bool('p') >>> is_not(p) False >>> is_not(Not(p)) True """ return is_app_of(a, Z3_OP_NOT) def is_eq(a): """Return `True` if `a` is a Z3 equality expression. >>> x, y = Ints('x y') >>> is_eq(x == y) True """ return is_app_of(a, Z3_OP_EQ) def is_distinct(a): """Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True """ return is_app_of(a, Z3_OP_DISTINCT) def BoolSort(ctx=None): """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used. >>> BoolSort() Bool >>> p = Const('p', BoolSort()) >>> is_bool(p) True >>> r = Function('r', IntSort(), IntSort(), BoolSort()) >>> r(0, 1) r(0, 1) >>> is_bool(r(0, 1)) True """ ctx = _get_ctx(ctx) return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx) def BoolVal(val, ctx=None): """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used. >>> BoolVal(True) True >>> is_true(BoolVal(True)) True >>> is_true(True) False >>> is_false(BoolVal(False)) True """ ctx = _get_ctx(ctx) if val: return BoolRef(Z3_mk_true(ctx.ref()), ctx) else: return BoolRef(Z3_mk_false(ctx.ref()), ctx) def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) def Bools(names, ctx=None): """Return a tuple of Boolean constants. `names` is a single string containing all names separated by blank spaces. If `ctx=None`, then the global context is used. >>> p, q, r = Bools('p q r') >>> And(p, Or(q, r)) And(p, Or(q, r)) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Bool(name, ctx) for name in names] def BoolVector(prefix, sz, ctx=None): """Return a list of Boolean constants of size `sz`. The constants are named using the given prefix. If `ctx=None`, then the global context is used. >>> P = BoolVector('p', 3) >>> P [p__0, p__1, p__2] >>> And(P) And(p__0, p__1, p__2) """ return [Bool("%s__%s" % (prefix, i)) for i in range(sz)] def FreshBool(prefix="b", ctx=None): """Return a fresh Boolean constant in the given context using the given prefix. If `ctx=None`, then the global context is used. >>> b1 = FreshBool() >>> b2 = FreshBool() >>> eq(b1, b2) False """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx) def Implies(a, b, ctx=None): """Create a Z3 implies expression. >>> p, q = Bools('p q') >>> Implies(p, q) Implies(p, q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Xor(a, b, ctx=None): """Create a Z3 Xor expression. >>> p, q = Bools('p q') >>> Xor(p, q) Xor(p, q) >>> simplify(Xor(p, q)) Not(p == q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Not(a, ctx=None): """Create a Z3 not expression or probe. >>> p = Bool('p') >>> Not(Not(p)) Not(Not(p)) >>> simplify(Not(Not(p))) p """ ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) if is_probe(a): # Not is also used to build probes return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx) else: s = BoolSort(ctx) a = s.cast(a) return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx) def mk_not(a): if is_not(a): return a.arg(0) else: return Not(a) def _has_probe(args): """Return `True` if one of the elements of the given collection is a Z3 probe.""" for arg in args: if is_probe(arg): return True return False def And(*args): """Create a Z3 and-expression or and-probe. >>> p, q, r = Bools('p q r') >>> And(p, q, r) And(p, q, r) >>> P = BoolVector('p', 5) >>> And(P) And(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args) - 1] if isinstance(last_arg, Context): ctx = args[len(args) - 1] args = args[:len(args) - 1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_and(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx) def Or(*args): """Create a Z3 or-expression or or-probe. >>> p, q, r = Bools('p q r') >>> Or(p, q, r) Or(p, q, r) >>> P = BoolVector('p', 5) >>> Or(P) Or(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args) - 1] if isinstance(last_arg, Context): ctx = args[len(args) - 1] args = args[:len(args) - 1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_or(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx) ######################################### # # Patterns # ######################################### class PatternRef(ExprRef): """Patterns are hints for quantifier instantiation. """ def as_ast(self): return Z3_pattern_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def is_pattern(a): """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ]) >>> q ForAll(x, f(x) == 0) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) f(Var(0)) """ return isinstance(a, PatternRef) def MultiPattern(*args): """Create a Z3 multi-pattern using the given expressions `*args` >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ]) >>> q ForAll(x, f(x) != g(x)) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) MultiPattern(f(Var(0)), g(Var(0))) """ if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected") ctx = args[0].ctx args, sz = _to_ast_array(args) return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx) def _to_pattern(arg): if is_pattern(arg): return arg else: return MultiPattern(arg) ######################################### # # Quantifiers # ######################################### class QuantifierRef(BoolRef): """Universally and Existentially quantified formulas.""" def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the Boolean sort or sort of Lambda.""" if self.is_lambda(): return _sort(self.ctx, self.as_ast()) return BoolSort(self.ctx) def is_forall(self): """Return `True` if `self` is a universal quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_forall() True >>> q = Exists(x, f(x) != 0) >>> q.is_forall() False """ return Z3_is_quantifier_forall(self.ctx_ref(), self.ast) def is_exists(self): """Return `True` if `self` is an existential quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_exists() False >>> q = Exists(x, f(x) != 0) >>> q.is_exists() True """ return Z3_is_quantifier_exists(self.ctx_ref(), self.ast) def is_lambda(self): """Return `True` if `self` is a lambda expression. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = Lambda(x, f(x)) >>> q.is_lambda() True >>> q = Exists(x, f(x) != 0) >>> q.is_lambda() False """ return Z3_is_lambda(self.ctx_ref(), self.ast) def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. """ if z3_debug(): _z3_assert(self.is_lambda(), "quantifier should be a lambda expression") return _array_select(self, arg) def weight(self): """Return the weight annotation of `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.weight() 1 >>> q = ForAll(x, f(x) == 0, weight=10) >>> q.weight() 10 """ return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast)) def num_patterns(self): """Return the number of patterns (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 """ return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast)) def pattern(self, idx): """Return a pattern (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 >>> q.pattern(0) f(Var(0)) >>> q.pattern(1) g(Var(0)) """ if z3_debug(): _z3_assert(idx < self.num_patterns(), "Invalid pattern idx") return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def num_no_patterns(self): """Return the number of no-patterns.""" return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast) def no_pattern(self, idx): """Return a no-pattern.""" if z3_debug(): _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx") return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def body(self): """Return the expression being quantified. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.body() f(Var(0)) == 0 """ return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx) def num_vars(self): """Return the number of variables bounded by this quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.num_vars() 2 """ return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast)) def var_name(self, idx): """Return a string representing a name used when displaying the quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_name(0) 'x' >>> q.var_name(1) 'y' """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx)) def var_sort(self, idx): """Return the sort of a bound variable. >>> f = Function('f', IntSort(), RealSort(), IntSort()) >>> x = Int('x') >>> y = Real('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_sort(0) Int >>> q.var_sort(1) Real """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx) def children(self): """Return a list containing a single element self.body() >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.children() [f(Var(0)) == 0] """ return [self.body()] def is_quantifier(a): """Return `True` if `a` is a Z3 quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> is_quantifier(q) True >>> is_quantifier(f(x)) False """ return isinstance(a, QuantifierRef) def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): if z3_debug(): _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected") _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)") _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected") _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions") if is_app(vs): ctx = vs.ctx vs = [vs] else: ctx = vs[0].ctx if not is_expr(body): body = BoolVal(body, ctx) num_vars = len(vs) if num_vars == 0: return body _vs = (Ast * num_vars)() for i in range(num_vars): # TODO: Check if is constant _vs[i] = vs[i].as_ast() patterns = [_to_pattern(p) for p in patterns] num_pats = len(patterns) _pats = (Pattern * num_pats)() for i in range(num_pats): _pats[i] = patterns[i].ast _no_pats, num_no_pats = _to_ast_array(no_patterns) qid = to_symbol(qid, ctx) skid = to_symbol(skid, ctx) return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid, num_vars, _vs, num_pats, _pats, num_no_pats, _no_pats, body.as_ast()), ctx) def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 forall formula. The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> ForAll([x, y], f(x, y) >= x) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ]) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, weight=10) ForAll([x, y], f(x, y) >= x) """ return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns) def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 exists formula. The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = Exists([x, y], f(x, y) >= x, skid="foo") >>> q Exists([x, y], f(x, y) >= x) >>> is_quantifier(q) True >>> r = Tactic('nnf')(q).as_expr() >>> is_quantifier(r) False """ return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns) def Lambda(vs, body): """Create a Z3 lambda expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> mem0 = Array('mem0', IntSort(), IntSort()) >>> lo, hi, e, i = Ints('lo hi e i') >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i])) >>> mem1 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i])) """ ctx = body.ctx if is_app(vs): vs = [vs] num_vars = len(vs) _vs = (Ast * num_vars)() for i in range(num_vars): # TODO: Check if is constant _vs[i] = vs[i].as_ast() return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) ######################################### # # Arithmetic # ######################################### class ArithSortRef(SortRef): """Real and Integer sorts.""" def is_real(self): """Return `True` if `self` is of the sort Real. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True >>> x = Int('x') >>> x.is_real() False """ return self.kind() == Z3_REAL_SORT def is_int(self): """Return `True` if `self` is of the sort Integer. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> x = Real('x') >>> x.is_int() False """ return self.kind() == Z3_INT_SORT def is_bool(self): return False def subsort(self, other): """Return `True` if `self` is a subsort of `other`.""" return self.is_int() and is_arith_sort(other) and other.is_real() def cast(self, val): """Try to cast `val` as an Integer or Real. >>> IntSort().cast(10) 10 >>> is_int(IntSort().cast(10)) True >>> is_int(10) False >>> RealSort().cast(10) 10 >>> is_real(RealSort().cast(10)) True """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") val_s = val.sort() if self.eq(val_s): return val if val_s.is_int() and self.is_real(): return ToReal(val) if val_s.is_bool() and self.is_int(): return If(val, 1, 0) if val_s.is_bool() and self.is_real(): return ToReal(If(val, 1, 0)) if z3_debug(): _z3_assert(False, "Z3 Integer/Real expression expected") else: if self.is_int(): return IntVal(val, self.ctx) if self.is_real(): return RealVal(val, self.ctx) if z3_debug(): msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" _z3_assert(False, msg % self) def is_arith_sort(s): """Return `True` if s is an arithmetical sort (type). >>> is_arith_sort(IntSort()) True >>> is_arith_sort(RealSort()) True >>> is_arith_sort(BoolSort()) False >>> n = Int('x') + 1 >>> is_arith_sort(n.sort()) True """ return isinstance(s, ArithSortRef) class ArithRef(ExprRef): """Integer and Real expressions.""" def sort(self): """Return the sort (type) of the arithmetical expression `self`. >>> Int('x').sort() Int >>> (Real('x') + 1).sort() Real """ return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def is_int(self): """Return `True` if `self` is an integer expression. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> y = Real('y') >>> (x + y).is_int() False """ return self.sort().is_int() def is_real(self): """Return `True` if `self` is an real expression. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True """ return self.sort().is_real() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = Int('x') >>> y = Int('y') >>> x + y x + y >>> (x + y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = Int('x') >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = Real('x') >>> y = Real('y') >>> x * y x*y >>> (x * y).sort() Real """ if isinstance(other, BoolRef): return If(other, self, 0) a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = Real('x') >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = Int('x') >>> y = Int('y') >>> x - y x - y >>> (x - y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = Int('x') >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx) def __pow__(self, other): """Create the Z3 expression `self**other` (** is the power operator). >>> x = Real('x') >>> x**3 x**3 >>> (x**3).sort() Real >>> simplify(IntVal(2)**8) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rpow__(self, other): """Create the Z3 expression `other**self` (** is the power operator). >>> x = Real('x') >>> 2**x 2**x >>> (2**x).sort() Real >>> simplify(2**IntVal(8)) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> y = Int('y') >>> x/y x/y >>> (x/y).sort() Int >>> (x/y).sexpr() '(div x y)' >>> x = Real('x') >>> y = Real('y') >>> x/y x/y >>> (x/y).sort() Real >>> (x/y).sexpr() '(/ x y)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> 10/x 10/x >>> (10/x).sexpr() '(div 10 x)' >>> x = Real('x') >>> 10/x 10/x >>> (10/x).sexpr() '(/ 10.0 x)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> y = Int('y') >>> x % y x%y >>> simplify(IntVal(10) % IntVal(3)) 1 """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> 10 % x 10%x """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __neg__(self): """Return an expression representing `-self`. >>> x = Int('x') >>> -x -x >>> simplify(-(-x)) x """ return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = Int('x') >>> +x x """ return self def __le__(self, other): """Create the Z3 expression `other <= self`. >>> x, y = Ints('x y') >>> x <= y x <= y >>> y = Real('y') >>> x <= y ToReal(x) <= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression `other < self`. >>> x, y = Ints('x y') >>> x < y x < y >>> y = Real('y') >>> x < y ToReal(x) < y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression `other > self`. >>> x, y = Ints('x y') >>> x > y x > y >>> y = Real('y') >>> x > y ToReal(x) > y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression `other >= self`. >>> x, y = Ints('x y') >>> x >= y x >= y >>> y = Real('y') >>> x >= y ToReal(x) >= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def is_arith(a): """Return `True` if `a` is an arithmetical expression. >>> x = Int('x') >>> is_arith(x) True >>> is_arith(x + 1) True >>> is_arith(1) False >>> is_arith(IntVal(1)) True >>> y = Real('y') >>> is_arith(y) True >>> is_arith(y + 1) True """ return isinstance(a, ArithRef) def is_int(a): """Return `True` if `a` is an integer expression. >>> x = Int('x') >>> is_int(x + 1) True >>> is_int(1) False >>> is_int(IntVal(1)) True >>> y = Real('y') >>> is_int(y) False >>> is_int(y + 1) False """ return is_arith(a) and a.is_int() def is_real(a): """Return `True` if `a` is a real expression. >>> x = Int('x') >>> is_real(x + 1) False >>> y = Real('y') >>> is_real(y) True >>> is_real(y + 1) True >>> is_real(1) False >>> is_real(RealVal(1)) True """ return is_arith(a) and a.is_real() def _is_numeral(ctx, a): return Z3_is_numeral_ast(ctx.ref(), a) def _is_algebraic(ctx, a): return Z3_is_algebraic_number(ctx.ref(), a) def is_int_value(a): """Return `True` if `a` is an integer value of sort Int. >>> is_int_value(IntVal(1)) True >>> is_int_value(1) False >>> is_int_value(Int('x')) False >>> n = Int('x') + 1 >>> n x + 1 >>> n.arg(1) 1 >>> is_int_value(n.arg(1)) True >>> is_int_value(RealVal("1/3")) False >>> is_int_value(RealVal(1)) False """ return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast()) def is_rational_value(a): """Return `True` if `a` is rational value of sort Real. >>> is_rational_value(RealVal(1)) True >>> is_rational_value(RealVal("3/5")) True >>> is_rational_value(IntVal(1)) False >>> is_rational_value(1) False >>> n = Real('x') + 1 >>> n.arg(1) 1 >>> is_rational_value(n.arg(1)) True >>> is_rational_value(Real('x')) False """ return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast()) def is_algebraic_value(a): """Return `True` if `a` is an algebraic value of sort Real. >>> is_algebraic_value(RealVal("3/5")) False >>> n = simplify(Sqrt(2)) >>> n 1.4142135623? >>> is_algebraic_value(n) True """ return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast()) def is_add(a): """Return `True` if `a` is an expression of the form b + c. >>> x, y = Ints('x y') >>> is_add(x + y) True >>> is_add(x - y) False """ return is_app_of(a, Z3_OP_ADD) def is_mul(a): """Return `True` if `a` is an expression of the form b * c. >>> x, y = Ints('x y') >>> is_mul(x * y) True >>> is_mul(x - y) False """ return is_app_of(a, Z3_OP_MUL) def is_sub(a): """Return `True` if `a` is an expression of the form b - c. >>> x, y = Ints('x y') >>> is_sub(x - y) True >>> is_sub(x + y) False """ return is_app_of(a, Z3_OP_SUB) def is_div(a): """Return `True` if `a` is an expression of the form b / c. >>> x, y = Reals('x y') >>> is_div(x / y) True >>> is_div(x + y) False >>> x, y = Ints('x y') >>> is_div(x / y) False >>> is_idiv(x / y) True """ return is_app_of(a, Z3_OP_DIV) def is_idiv(a): """Return `True` if `a` is an expression of the form b div c. >>> x, y = Ints('x y') >>> is_idiv(x / y) True >>> is_idiv(x + y) False """ return is_app_of(a, Z3_OP_IDIV) def is_mod(a): """Return `True` if `a` is an expression of the form b % c. >>> x, y = Ints('x y') >>> is_mod(x % y) True >>> is_mod(x + y) False """ return is_app_of(a, Z3_OP_MOD) def is_le(a): """Return `True` if `a` is an expression of the form b <= c. >>> x, y = Ints('x y') >>> is_le(x <= y) True >>> is_le(x < y) False """ return is_app_of(a, Z3_OP_LE) def is_lt(a): """Return `True` if `a` is an expression of the form b < c. >>> x, y = Ints('x y') >>> is_lt(x < y) True >>> is_lt(x == y) False """ return is_app_of(a, Z3_OP_LT) def is_ge(a): """Return `True` if `a` is an expression of the form b >= c. >>> x, y = Ints('x y') >>> is_ge(x >= y) True >>> is_ge(x == y) False """ return is_app_of(a, Z3_OP_GE) def is_gt(a): """Return `True` if `a` is an expression of the form b > c. >>> x, y = Ints('x y') >>> is_gt(x > y) True >>> is_gt(x == y) False """ return is_app_of(a, Z3_OP_GT) def is_is_int(a): """Return `True` if `a` is an expression of the form IsInt(b). >>> x = Real('x') >>> is_is_int(IsInt(x)) True >>> is_is_int(x) False """ return is_app_of(a, Z3_OP_IS_INT) def is_to_real(a): """Return `True` if `a` is an expression of the form ToReal(b). >>> x = Int('x') >>> n = ToReal(x) >>> n ToReal(x) >>> is_to_real(n) True >>> is_to_real(x) False """ return is_app_of(a, Z3_OP_TO_REAL) def is_to_int(a): """Return `True` if `a` is an expression of the form ToInt(b). >>> x = Real('x') >>> n = ToInt(x) >>> n ToInt(x) >>> is_to_int(n) True >>> is_to_int(x) False """ return is_app_of(a, Z3_OP_TO_INT) class IntNumRef(ArithRef): """Integer values.""" def as_long(self): """Return a Z3 integer numeral as a Python long (bignum) numeral. >>> v = IntVal(1) >>> v + 1 1 + 1 >>> v.as_long() + 1 2 """ if z3_debug(): _z3_assert(self.is_int(), "Integer value expected") return int(self.as_string()) def as_string(self): """Return a Z3 integer numeral as a Python string. >>> v = IntVal(100) >>> v.as_string() '100' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_binary_string(self): """Return a Z3 integer numeral as a Python binary string. >>> v = IntVal(10) >>> v.as_binary_string() '1010' """ return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast()) class RatNumRef(ArithRef): """Rational values.""" def numerator(self): """ Return the numerator of a Z3 rational numeral. >>> is_rational_value(RealVal("3/5")) True >>> n = RealVal("3/5") >>> n.numerator() 3 >>> is_rational_value(Q(3,5)) True >>> Q(3,5).numerator() 3 """ return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def denominator(self): """ Return the denominator of a Z3 rational numeral. >>> is_rational_value(Q(3,5)) True >>> n = Q(3,5) >>> n.denominator() 5 """ return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator_as_long(self): """ Return the numerator as a Python long. >>> v = RealVal(10000000000) >>> v 10000000000 >>> v + 1 10000000000 + 1 >>> v.numerator_as_long() + 1 == 10000000001 True """ return self.numerator().as_long() def denominator_as_long(self): """ Return the denominator as a Python long. >>> v = RealVal("1/3") >>> v 1/3 >>> v.denominator_as_long() 3 """ return self.denominator().as_long() def is_int(self): return False def is_real(self): return True def is_int_value(self): return self.denominator().is_int() and self.denominator_as_long() == 1 def as_long(self): _z3_assert(self.is_int_value(), "Expected integer fraction") return self.numerator_as_long() def as_decimal(self, prec): """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places. >>> v = RealVal("1/5") >>> v.as_decimal(3) '0.2' >>> v = RealVal("1/3") >>> v.as_decimal(3) '0.333?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def as_string(self): """Return a Z3 rational numeral as a Python string. >>> v = Q(3,6) >>> v.as_string() '1/2' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_fraction(self): """Return a Z3 rational as a Python Fraction object. >>> v = RealVal("1/5") >>> v.as_fraction() Fraction(1, 5) """ return Fraction(self.numerator_as_long(), self.denominator_as_long()) class AlgebraicNumRef(ArithRef): """Algebraic irrational values.""" def approx(self, precision=10): """Return a Z3 rational number that approximates the algebraic number `self`. The result `r` is such that |r - self| <= 1/10^precision >>> x = simplify(Sqrt(2)) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 """ return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def as_decimal(self, prec): """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places. >>> x = simplify(Sqrt(2)) >>> x.as_decimal(10) '1.4142135623?' >>> x.as_decimal(20) '1.41421356237309504880?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def poly(self): return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_ast()), self.ctx) def index(self): return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast()) def _py2expr(a, ctx=None): if isinstance(a, bool): return BoolVal(a, ctx) if _is_int(a): return IntVal(a, ctx) if isinstance(a, float): return RealVal(a, ctx) if isinstance(a, str): return StringVal(a, ctx) if is_expr(a): return a if z3_debug(): _z3_assert(False, "Python bool, int, long or float expected") def IntSort(ctx=None): """Return the integer sort in the given context. If `ctx=None`, then the global context is used. >>> IntSort() Int >>> x = Const('x', IntSort()) >>> is_int(x) True >>> x.sort() == IntSort() True >>> x.sort() == BoolSort() False """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx) def RealSort(ctx=None): """Return the real sort in the given context. If `ctx=None`, then the global context is used. >>> RealSort() Real >>> x = Const('x', RealSort()) >>> is_real(x) True >>> is_int(x) False >>> x.sort() == RealSort() True """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx) def _to_int_str(val): if isinstance(val, float): return str(int(val)) elif isinstance(val, bool): if val: return "1" else: return "0" else: return str(val) def IntVal(val, ctx=None): """Return a Z3 integer value. If `ctx=None`, then the global context is used. >>> IntVal(1) 1 >>> IntVal("100") 100 """ ctx = _get_ctx(ctx) return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx) def RealVal(val, ctx=None): """Return a Z3 real value. `val` may be a Python int, long, float or string representing a number in decimal or rational notation. If `ctx=None`, then the global context is used. >>> RealVal(1) 1 >>> RealVal(1).sort() Real >>> RealVal("3/5") 3/5 >>> RealVal("1.5") 3/2 """ ctx = _get_ctx(ctx) return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx) def RatVal(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> RatVal(3,5) 3/5 >>> RatVal(3,5).sort() Real """ if z3_debug(): _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer") _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer") return simplify(RealVal(a, ctx) / RealVal(b, ctx)) def Q(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> Q(3,5) 3/5 >>> Q(3,5).sort() Real """ return simplify(RatVal(a, b, ctx=ctx)) def Int(name, ctx=None): """Return an integer constant named `name`. If `ctx=None`, then the global context is used. >>> x = Int('x') >>> is_int(x) True >>> is_int(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx) def Ints(names, ctx=None): """Return a tuple of Integer constants. >>> x, y, z = Ints('x y z') >>> Sum(x, y, z) x + y + z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Int(name, ctx) for name in names] def IntVector(prefix, sz, ctx=None): """Return a list of integer constants of size `sz`. >>> X = IntVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 """ ctx = _get_ctx(ctx) return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)] def FreshInt(prefix="x", ctx=None): """Return a fresh integer constant in the given context using the given prefix. >>> x = FreshInt() >>> y = FreshInt() >>> eq(x, y) False >>> x.sort() Int """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx) def Real(name, ctx=None): """Return a real constant named `name`. If `ctx=None`, then the global context is used. >>> x = Real('x') >>> is_real(x) True >>> is_real(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx) def Reals(names, ctx=None): """Return a tuple of real constants. >>> x, y, z = Reals('x y z') >>> Sum(x, y, z) x + y + z >>> Sum(x, y, z).sort() Real """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Real(name, ctx) for name in names] def RealVector(prefix, sz, ctx=None): """Return a list of real constants of size `sz`. >>> X = RealVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 >>> Sum(X).sort() Real """ ctx = _get_ctx(ctx) return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)] def FreshReal(prefix="b", ctx=None): """Return a fresh real constant in the given context using the given prefix. >>> x = FreshReal() >>> y = FreshReal() >>> eq(x, y) False >>> x.sort() Real """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx) def ToReal(a): """ Return the Z3 expression ToReal(a). >>> x = Int('x') >>> x.sort() Int >>> n = ToReal(x) >>> n ToReal(x) >>> n.sort() Real """ if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected.") ctx = a.ctx return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx) def ToInt(a): """ Return the Z3 expression ToInt(a). >>> x = Real('x') >>> x.sort() Real >>> n = ToInt(x) >>> n ToInt(x) >>> n.sort() Int """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx) def IsInt(a): """ Return the Z3 predicate IsInt(a). >>> x = Real('x') >>> IsInt(x + "1/2") IsInt(x + 1/2) >>> solve(IsInt(x + "1/2"), x > 0, x < 1) [x = 1/2] >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2") no solution """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx) def Sqrt(a, ctx=None): """ Return a Z3 expression which represents the square root of a. >>> x = Real('x') >>> Sqrt(x) x**(1/2) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/2" def Cbrt(a, ctx=None): """ Return a Z3 expression which represents the cubic root of a. >>> x = Real('x') >>> Cbrt(x) x**(1/3) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/3" ######################################### # # Bit-Vectors # ######################################### class BitVecSortRef(SortRef): """Bit-vector sort.""" def size(self): """Return the size (number of bits) of the bit-vector sort `self`. >>> b = BitVecSort(32) >>> b.size() 32 """ return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast)) def subsort(self, other): return is_bv_sort(other) and self.size() < other.size() def cast(self, val): """Try to cast `val` as a Bit-Vector. >>> b = BitVecSort(32) >>> b.cast(10) 10 >>> b.cast(10).sexpr() '#x0000000a' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") # Idea: use sign_extend if sort of val is a bitvector of smaller size return val else: return BitVecVal(val, self) def is_bv_sort(s): """Return True if `s` is a Z3 bit-vector sort. >>> is_bv_sort(BitVecSort(32)) True >>> is_bv_sort(IntSort()) False """ return isinstance(s, BitVecSortRef) class BitVecRef(ExprRef): """Bit-vector expressions.""" def sort(self): """Return the sort of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> x.sort() BitVec(32) >>> x.sort() == BitVecSort(32) True """ return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def size(self): """Return the number of bits of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> (x + 1).size() 32 >>> Concat(x, x).size() 64 """ return self.sort().size() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x + y x + y >>> (x + y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = BitVec('x', 32) >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x * y x*y >>> (x * y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = BitVec('x', 32) >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x - y x - y >>> (x - y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = BitVec('x', 32) >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __or__(self, other): """Create the Z3 expression bitwise-or `self | other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x | y x | y >>> (x | y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ror__(self, other): """Create the Z3 expression bitwise-or `other | self`. >>> x = BitVec('x', 32) >>> 10 | x 10 | x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __and__(self, other): """Create the Z3 expression bitwise-and `self & other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x & y x & y >>> (x & y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rand__(self, other): """Create the Z3 expression bitwise-or `other & self`. >>> x = BitVec('x', 32) >>> 10 & x 10 & x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __xor__(self, other): """Create the Z3 expression bitwise-xor `self ^ other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x ^ y x ^ y >>> (x ^ y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rxor__(self, other): """Create the Z3 expression bitwise-xor `other ^ self`. >>> x = BitVec('x', 32) >>> 10 ^ x 10 ^ x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = BitVec('x', 32) >>> +x x """ return self def __neg__(self): """Return an expression representing `-self`. >>> x = BitVec('x', 32) >>> -x -x >>> simplify(-(-x)) x """ return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx) def __invert__(self): """Create the Z3 expression bitwise-not `~self`. >>> x = BitVec('x', 32) >>> ~x ~x >>> simplify(~(~x)) x """ return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression (signed) division `self / other`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression (signed) division `other / self`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> 10 / x 10/x >>> (10 / x).sexpr() '(bvsdiv #x0000000a x)' >>> UDiv(10, x).sexpr() '(bvudiv #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression (signed) division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression (signed) mod `self % other`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x % y x%y >>> (x % y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression (signed) mod `other % self`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> 10 % x 10%x >>> (10 % x).sexpr() '(bvsmod #x0000000a x)' >>> URem(10, x).sexpr() '(bvurem #x0000000a x)' >>> SRem(10, x).sexpr() '(bvsrem #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __le__(self, other): """Create the Z3 expression (signed) `other <= self`. Use the function ULE() for unsigned less than or equal to. >>> x, y = BitVecs('x y', 32) >>> x <= y x <= y >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression (signed) `other < self`. Use the function ULT() for unsigned less than. >>> x, y = BitVecs('x y', 32) >>> x < y x < y >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression (signed) `other > self`. Use the function UGT() for unsigned greater than. >>> x, y = BitVecs('x y', 32) >>> x > y x > y >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression (signed) `other >= self`. Use the function UGE() for unsigned greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> x >= y x >= y >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rshift__(self, other): """Create the Z3 expression (arithmetical) right shift `self >> other` Use the function LShR() for the right logical shift >>> x, y = BitVecs('x y', 32) >>> x >> y x >> y >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lshift__(self, other): """Create the Z3 expression left shift `self << other` >>> x, y = BitVecs('x y', 32) >>> x << y x << y >>> (x << y).sexpr() '(bvshl x y)' >>> simplify(BitVecVal(2, 3) << 1) 4 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rrshift__(self, other): """Create the Z3 expression (arithmetical) right shift `other` >> `self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 >> x 10 >> x >>> (10 >> x).sexpr() '(bvashr #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rlshift__(self, other): """Create the Z3 expression left shift `other << self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 << x 10 << x >>> (10 << x).sexpr() '(bvshl #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) class BitVecNumRef(BitVecRef): """Bit-vector values.""" def as_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. >>> v = BitVecVal(0xbadc0de, 32) >>> v 195936478 >>> print("0x%.8x" % v.as_long()) 0x0badc0de """ return int(self.as_string()) def as_signed_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign. >>> BitVecVal(4, 3).as_signed_long() -4 >>> BitVecVal(7, 3).as_signed_long() -1 >>> BitVecVal(3, 3).as_signed_long() 3 >>> BitVecVal(2**32 - 1, 32).as_signed_long() -1 >>> BitVecVal(2**64 - 1, 64).as_signed_long() -1 """ sz = self.size() val = self.as_long() if val >= 2**(sz - 1): val = val - 2**sz if val < -2**(sz - 1): val = val + 2**sz return int(val) def as_string(self): return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_binary_string(self): return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast()) def is_bv(a): """Return `True` if `a` is a Z3 bit-vector expression. >>> b = BitVec('b', 32) >>> is_bv(b) True >>> is_bv(b + 10) True >>> is_bv(Int('x')) False """ return isinstance(a, BitVecRef) def is_bv_value(a): """Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True """ return is_bv(a) and _is_numeral(a.ctx, a.as_ast()) def BV2Int(a, is_signed=False): """Return the Z3 expression BV2Int(a). >>> b = BitVec('b', 3) >>> BV2Int(b).sort() Int >>> x = Int('x') >>> x > BV2Int(b) x > BV2Int(b) >>> x > BV2Int(b, is_signed=False) x > BV2Int(b) >>> x > BV2Int(b, is_signed=True) x > If(b < 0, BV2Int(b) - 8, BV2Int(b)) >>> solve(x > BV2Int(b), b == 1, x < 3) [x = 2, b = 1] """ if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") ctx = a.ctx # investigate problem with bv2int return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx) def Int2BV(a, num_bits): """Return the z3 expression Int2BV(a, num_bits). It is a bit-vector of width num_bits and represents the modulo of a by 2^num_bits """ ctx = a.ctx return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx) def BitVecSort(sz, ctx=None): """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used. >>> Byte = BitVecSort(8) >>> Word = BitVecSort(16) >>> Byte BitVec(8) >>> x = Const('x', Byte) >>> eq(x, BitVec('x', 8)) True """ ctx = _get_ctx(ctx) return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx) def BitVecVal(val, bv, ctx=None): """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used. >>> v = BitVecVal(10, 32) >>> v 10 >>> print("0x%.8x" % v.as_long()) 0x0000000a """ if is_bv_sort(bv): ctx = bv.ctx return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx) else: ctx = _get_ctx(ctx) return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx) def BitVec(name, bv, ctx=None): """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort. If `ctx=None`, then the global context is used. >>> x = BitVec('x', 16) >>> is_bv(x) True >>> x.size() 16 >>> x.sort() BitVec(16) >>> word = BitVecSort(16) >>> x2 = BitVec('x', word) >>> eq(x, x2) True """ if isinstance(bv, BitVecSortRef): ctx = bv.ctx else: ctx = _get_ctx(ctx) bv = BitVecSort(bv, ctx) return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) def BitVecs(names, bv, ctx=None): """Return a tuple of bit-vector constants of size bv. >>> x, y, z = BitVecs('x y z', 16) >>> x.size() 16 >>> x.sort() BitVec(16) >>> Sum(x, y, z) 0 + x + y + z >>> Product(x, y, z) 1*x*y*z >>> simplify(Product(x, y, z)) x*y*z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [BitVec(name, bv, ctx) for name in names] def Concat(*args): """Create a Z3 bit-vector concatenation expression. >>> v = BitVecVal(1, 4) >>> Concat(v, v+1, v) Concat(Concat(1, 1 + 1), 1) >>> simplify(Concat(v, v+1, v)) 289 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long()) 121 """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz >= 2, "At least two arguments expected.") ctx = None for a in args: if is_expr(a): ctx = a.ctx break if is_seq(args[0]) or isinstance(args[0], str): args = [_coerce_seq(s, ctx) for s in args] if z3_debug(): _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx) if is_re(args[0]): if z3_debug(): _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx) if z3_debug(): _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.") r = args[0] for i in range(sz - 1): r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx) return r def Extract(high, low, a): """Create a Z3 bit-vector extraction expression. Extract is overloaded to also work on sequence extraction. The functions SubString and SubSeq are redirected to Extract. For this case, the arguments are reinterpreted as: high - is a sequence (string) low - is an offset a - is the length to be extracted >>> x = BitVec('x', 8) >>> Extract(6, 2, x) Extract(6, 2, x) >>> Extract(6, 2, x).sort() BitVec(5) >>> simplify(Extract(StringVal("abcd"),2,1)) "c" """ if isinstance(high, str): high = StringVal(high) if is_seq(high): s = high offset, length = _coerce_exprs(low, a, s.ctx) return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx) if z3_debug(): _z3_assert(low <= high, "First argument must be greater than or equal to second argument") _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers") _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx) def _check_bv_args(a, b): if z3_debug(): _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression") def ULE(a, b): """Create the Z3 expression (unsigned) `other <= self`. Use the operator <= for signed less than or equal to. >>> x, y = BitVecs('x y', 32) >>> ULE(x, y) ULE(x, y) >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def ULT(a, b): """Create the Z3 expression (unsigned) `other < self`. Use the operator < for signed less than. >>> x, y = BitVecs('x y', 32) >>> ULT(x, y) ULT(x, y) >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGE(a, b): """Create the Z3 expression (unsigned) `other >= self`. Use the operator >= for signed greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> UGE(x, y) UGE(x, y) >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGT(a, b): """Create the Z3 expression (unsigned) `other > self`. Use the operator > for signed greater than. >>> x, y = BitVecs('x y', 32) >>> UGT(x, y) UGT(x, y) >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UDiv(a, b): """Create the Z3 expression (unsigned) division `self / other`. Use the operator / for signed division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> UDiv(x, y) UDiv(x, y) >>> UDiv(x, y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def URem(a, b): """Create the Z3 expression (unsigned) remainder `self % other`. Use the operator % for signed modulus, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> URem(x, y) URem(x, y) >>> URem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SRem(a, b): """Create the Z3 expression signed remainder. Use the operator % for signed modulus, and URem() for unsigned remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> SRem(x, y) SRem(x, y) >>> SRem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def LShR(a, b): """Create the Z3 expression logical right shift. Use the operator >> for the arithmetical right shift. >>> x, y = BitVecs('x y', 32) >>> LShR(x, y) LShR(x, y) >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateLeft(a, b): """Return an expression representing `a` rotated to the left `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateLeft(a, b) RotateLeft(a, b) >>> simplify(RotateLeft(a, 0)) a >>> simplify(RotateLeft(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateRight(a, b): """Return an expression representing `a` rotated to the right `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateRight(a, b) RotateRight(a, b) >>> simplify(RotateRight(a, 0)) a >>> simplify(RotateRight(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SignExt(n, a): """Return a bit-vector expression with `n` extra sign-bits. >>> x = BitVec('x', 16) >>> n = SignExt(8, x) >>> n.size() 24 >>> n SignExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(SignExt(6, v0)) >>> v 254 >>> v.size() 8 >>> print("%.x" % v.as_long()) fe """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def ZeroExt(n, a): """Return a bit-vector expression with `n` extra zero-bits. >>> x = BitVec('x', 16) >>> n = ZeroExt(8, x) >>> n.size() 24 >>> n ZeroExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(ZeroExt(6, v0)) >>> v 2 >>> v.size() 8 """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def RepeatBitVec(n, a): """Return an expression representing `n` copies of `a`. >>> x = BitVec('x', 8) >>> n = RepeatBitVec(4, x) >>> n RepeatBitVec(4, x) >>> n.size() 32 >>> v0 = BitVecVal(10, 4) >>> print("%.x" % v0.as_long()) a >>> v = simplify(RepeatBitVec(4, v0)) >>> v.size() 16 >>> print("%.x" % v.as_long()) aaaa """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx) def BVRedAnd(a): """Return the reduction-and expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx) def BVRedOr(a): """Return the reduction-or expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx) def BVAddNoOverflow(a, b, signed): """A predicate the determines that bit-vector addition does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVAddNoUnderflow(a, b): """A predicate the determines that signed bit-vector addition does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoOverflow(a, b): """A predicate the determines that bit-vector subtraction does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoUnderflow(a, b, signed): """A predicate the determines that bit-vector subtraction does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVSDivNoOverflow(a, b): """A predicate the determines that bit-vector signed division does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSNegNoOverflow(a): """A predicate the determines that bit-vector unary negation does not overflow""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx) def BVMulNoOverflow(a, b, signed): """A predicate the determines that bit-vector multiplication does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVMulNoUnderflow(a, b): """A predicate the determines that bit-vector signed multiplication does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) ######################################### # # Arrays # ######################################### class ArraySortRef(SortRef): """Array sorts.""" def domain(self): """Return the domain of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.domain() Int """ return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx) def domain_n(self, i): """Return the domain of the array sort `self`. """ return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the range of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.range() Bool """ return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx) class ArrayRef(ExprRef): """Array expressions. """ def sort(self): """Return the array sort of the array expression `self`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.sort() Array(Int, Bool) """ return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def domain(self): """Shorthand for `self.sort().domain()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.domain() Int """ return self.sort().domain() def domain_n(self, i): """Shorthand for self.sort().domain_n(i)`.""" return self.sort().domain_n(i) def range(self): """Shorthand for `self.sort().range()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.range() Bool """ return self.sort().range() def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. >>> a = Array('a', IntSort(), BoolSort()) >>> i = Int('i') >>> a[i] a[i] >>> a[i].sexpr() '(select a i)' """ return _array_select(self, arg) def default(self): return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) def _array_select(ar, arg): if isinstance(arg, tuple): args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))] _args, sz = _to_ast_array(args) return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx) arg = ar.sort().domain().cast(arg) return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx) def is_array_sort(a): return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT def is_array(a): """Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False """ return isinstance(a, ArrayRef) def is_const_array(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_const_array(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_const_array(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_K(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_K(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_K(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_map(a): """Return `True` if `a` is a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> a Map(f, b) >>> is_map(a) True >>> is_map(b) False """ return is_app_of(a, Z3_OP_ARRAY_MAP) def is_default(a): """Return `True` if `a` is a Z3 default array expression. >>> d = Default(K(IntSort(), 10)) >>> is_default(d) True """ return is_app_of(a, Z3_OP_ARRAY_DEFAULT) def get_map_func(a): """Return the function declaration associated with a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> eq(f, get_map_func(a)) True >>> get_map_func(a) f >>> get_map_func(a)(0) f(0) """ if z3_debug(): _z3_assert(is_map(a), "Z3 array map expression expected.") return FuncDeclRef( Z3_to_func_decl( a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0), ), ctx=a.ctx, ) def ArraySort(*sig): """Return the Z3 array sort with the given domain and range sorts. >>> A = ArraySort(IntSort(), BoolSort()) >>> A Array(Int, Bool) >>> A.domain() Int >>> A.range() Bool >>> AA = ArraySort(IntSort(), A) >>> AA Array(Int, Array(Int, Bool)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 1, "At least two arguments expected") arity = len(sig) - 1 r = sig[arity] d = sig[0] if z3_debug(): for s in sig: _z3_assert(is_sort(s), "Z3 sort expected") _z3_assert(s.ctx == r.ctx, "Context mismatch") ctx = d.ctx if len(sig) == 2: return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx) dom = (Sort * arity)() for i in range(arity): dom[i] = sig[i].ast return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx) def Array(name, *sorts): """Return an array constant named `name` with the given domain and range sorts. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort() Array(Int, Int) >>> a[0] a[0] """ s = ArraySort(sorts) ctx = s.ctx return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) def Update(a, *args): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Update(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") args = _get_args(args) ctx = a.ctx if len(args) <= 1: raise Z3Exception("array update requires index and value arguments") if len(args) == 2: i = args[0] v = args[1] i = a.sort().domain().cast(i) v = a.sort().range().cast(v) return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) v = a.sort().range().cast(args[-1]) idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)] _args, sz = _to_ast_array(idxs) return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx) def Default(a): """ Return a default value for array expression. >>> b = K(IntSort(), 1) >>> prove(Default(b) == 1) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a.default() def Store(a, *args): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Store(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ return Update(a, args) def Select(a, *args): """Return a Z3 select array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i = Int('i') >>> Select(a, i) a[i] >>> eq(Select(a, i), a[i]) True """ args = _get_args(args) if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a[args] def Map(f, *args): """Return a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> a1 = Array('a1', IntSort(), IntSort()) >>> a2 = Array('a2', IntSort(), IntSort()) >>> b = Map(f, a1, a2) >>> b Map(f, a1, a2) >>> prove(b[0] == f(a1[0], a2[0])) proved """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 0, "At least one Z3 array expression expected") _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration") _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected") _z3_assert(len(args) == f.arity(), "Number of arguments mismatch") _args, sz = _to_ast_array(args) ctx = f.ctx return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx) def K(dom, v): """Return a Z3 constant array expression. >>> a = K(IntSort(), 10) >>> a K(Int, 10) >>> a.sort() Array(Int, Int) >>> i = Int('i') >>> a[i] K(Int, 10)[i] >>> simplify(a[i]) 10 """ if z3_debug(): _z3_assert(is_sort(dom), "Z3 sort expected") ctx = dom.ctx if not is_expr(v): v = _py2expr(v, ctx) return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx) def Ext(a, b): """Return extensionality index for one-dimensional arrays. >> a, b = Consts('a b', SetSort(IntSort())) >> Ext(a, b) Ext(a, b) """ ctx = a.ctx if z3_debug(): _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays") return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def SetHasSize(a, k): ctx = a.ctx k = _py2expr(k, ctx) return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx) def is_select(a): """Return `True` if `a` is a Z3 array select application. >>> a = Array('a', IntSort(), IntSort()) >>> is_select(a) False >>> i = Int('i') >>> is_select(a[i]) True """ return is_app_of(a, Z3_OP_SELECT) def is_store(a): """Return `True` if `a` is a Z3 array store application. >>> a = Array('a', IntSort(), IntSort()) >>> is_store(a) False >>> is_store(Store(a, 0, 1)) True """ return is_app_of(a, Z3_OP_STORE) ######################################### # # Sets # ######################################### def SetSort(s): """ Create a set sort over element sort s""" return ArraySort(s, BoolSort()) def EmptySet(s): """Create the empty set >>> EmptySet(IntSort()) K(Int, False) """ ctx = s.ctx return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx) def FullSet(s): """Create the full set >>> FullSet(IntSort()) K(Int, True) """ ctx = s.ctx return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx) def SetUnion(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetUnion(a, b) union(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx) def SetIntersect(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetIntersect(a, b) intersection(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx) def SetAdd(s, e): """ Add element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetAdd(a, 1) Store(a, 1, True) """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetDel(s, e): """ Remove element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetDel(a, 1) Store(a, 1, False) """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetComplement(s): """ The complement of set s >>> a = Const('a', SetSort(IntSort())) >>> SetComplement(a) complement(a) """ ctx = s.ctx return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx) def SetDifference(a, b): """ The set difference of a and b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetDifference(a, b) setminus(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def IsMember(e, s): """ Check if e is a member of set s >>> a = Const('a', SetSort(IntSort())) >>> IsMember(1, a) a[1] """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx) def IsSubset(a, b): """ Check if a is a subset of b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> IsSubset(a, b) subset(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx) ######################################### # # Datatypes # ######################################### def _valid_accessor(acc): """Return `True` if acc is pair of the form (String, Datatype or Sort). """ if not isinstance(acc, tuple): return False if len(acc) != 2: return False return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])) class Datatype: """Helper class for declaring Z3 datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) >>> List.cons(10, List.nil).sort() List >>> cons = List.cons >>> nil = List.nil >>> car = List.car >>> cdr = List.cdr >>> n = cons(1, cons(0, nil)) >>> n cons(1, cons(0, nil)) >>> simplify(cdr(n)) cons(0, nil) >>> simplify(car(n)) 1 """ def __init__(self, name, ctx=None): self.ctx = _get_ctx(ctx) self.name = name self.constructors = [] def __deepcopy__(self, memo={}): r = Datatype(self.name, self.ctx) r.constructors = copy.deepcopy(self.constructors) return r def declare_core(self, name, rec_name, *args): if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(isinstance(rec_name, str), "String expected") _z3_assert( all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)", ) self.constructors.append((name, rec_name, args)) def declare(self, name, *args): """Declare constructor named `name` with the given accessors `args`. Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared. In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))` declares the constructor named `cons` that builds a new List using an integer and a List. It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() """ if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(name != "", "Constructor name cannot be empty") return self.declare_core(name, "is-" + name, *args) def __repr__(self): return "Datatype(%s, %s)" % (self.name, self.constructors) def create(self): """Create a Z3 datatype based on the constructors declared using the method `declare()`. The function `CreateDatatypes()` must be used to define mutually recursive datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) """ return CreateDatatypes([self])[0] class ScopedConstructor: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None and Z3_del_constructor is not None: Z3_del_constructor(self.ctx.ref(), self.c) class ScopedConstructorList: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None and Z3_del_constructor_list is not None: Z3_del_constructor_list(self.ctx.ref(), self.c) def CreateDatatypes(*ds): """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects. In the following example we define a Tree-List using two mutually recursive datatypes. >>> TreeList = Datatype('TreeList') >>> Tree = Datatype('Tree') >>> # Tree has two constructors: leaf and node >>> Tree.declare('leaf', ('val', IntSort())) >>> # a node contains a list of trees >>> Tree.declare('node', ('children', TreeList)) >>> TreeList.declare('nil') >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList)) >>> Tree, TreeList = CreateDatatypes(Tree, TreeList) >>> Tree.val(Tree.leaf(10)) val(leaf(10)) >>> simplify(Tree.val(Tree.leaf(10))) 10 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil))) >>> n1 node(cons(leaf(10), cons(leaf(20), nil))) >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil)) >>> simplify(n2 == n1) False >>> simplify(TreeList.car(Tree.children(n2)) == n1) True """ ds = _get_args(ds) if z3_debug(): _z3_assert(len(ds) > 0, "At least one Datatype must be specified") _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes") _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch") _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected") ctx = ds[0].ctx num = len(ds) names = (Symbol * num)() out = (Sort * num)() clists = (ConstructorList * num)() to_delete = [] for i in range(num): d = ds[i] names[i] = to_symbol(d.name, ctx) num_cs = len(d.constructors) cs = (Constructor * num_cs)() for j in range(num_cs): c = d.constructors[j] cname = to_symbol(c[0], ctx) rname = to_symbol(c[1], ctx) fs = c[2] num_fs = len(fs) fnames = (Symbol * num_fs)() sorts = (Sort * num_fs)() refs = (ctypes.c_uint * num_fs)() for k in range(num_fs): fname = fs[k][0] ftype = fs[k][1] fnames[k] = to_symbol(fname, ctx) if isinstance(ftype, Datatype): if z3_debug(): _z3_assert( ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected", ) sorts[k] = None refs[k] = ds.index(ftype) else: if z3_debug(): _z3_assert(is_sort(ftype), "Z3 sort expected") sorts[k] = ftype.ast refs[k] = 0 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs) to_delete.append(ScopedConstructor(cs[j], ctx)) clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs) to_delete.append(ScopedConstructorList(clists[i], ctx)) Z3_mk_datatypes(ctx.ref(), num, names, out, clists) result = [] # Create a field for every constructor, recognizer and accessor for i in range(num): dref = DatatypeSortRef(out[i], ctx) num_cs = dref.num_constructors() for j in range(num_cs): cref = dref.constructor(j) cref_name = cref.name() cref_arity = cref.arity() if cref.arity() == 0: cref = cref() setattr(dref, cref_name, cref) rref = dref.recognizer(j) setattr(dref, "is_" + cref_name, rref) for k in range(cref_arity): aref = dref.accessor(j, k) setattr(dref, aref.name(), aref) result.append(dref) return tuple(result) class DatatypeSortRef(SortRef): """Datatype sorts.""" def num_constructors(self): """Return the number of constructors in the given Z3 datatype. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 """ return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast)) def constructor(self, idx): """Return a constructor of the datatype `self`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> List.constructor(1) nil """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid constructor index") return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx) def recognizer(self, idx): """In Z3, each constructor has an associated recognizer predicate. If the constructor is named `name`, then the recognizer `is_name`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.recognizer(0) is(cons) >>> List.recognizer(1) is(nil) >>> simplify(List.is_nil(List.cons(10, List.nil))) False >>> simplify(List.is_cons(List.cons(10, List.nil))) True >>> l = Const('l', List) >>> simplify(List.is_cons(l)) is(cons, l) """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid recognizer index") return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx) def accessor(self, i, j): """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> num_accs = List.constructor(0).arity() >>> num_accs 2 >>> List.accessor(0, 0) car >>> List.accessor(0, 1) cdr >>> List.constructor(1) nil >>> num_accs = List.constructor(1).arity() >>> num_accs 0 """ if z3_debug(): _z3_assert(i < self.num_constructors(), "Invalid constructor index") _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index") return FuncDeclRef( Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), ctx=self.ctx, ) class DatatypeRef(ExprRef): """Datatype expressions.""" def sort(self): """Return the datatype sort of the datatype expression `self`.""" return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def DatatypeSort(name, ctx = None): """Create a reference to a sort that was declared, or will be declared, as a recursive datatype""" ctx = _get_ctx(ctx) return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), ctx) def TupleSort(name, sorts, ctx=None): """Create a named tuple sort base on a set of underlying sorts Example: >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()]) """ tuple = Datatype(name, ctx) projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))] tuple.declare(name, *projects) tuple = tuple.create() return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))] def DisjointSum(name, sorts, ctx=None): """Create a named tagged union sort base on a set of underlying sorts Example: >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()]) """ sum = Datatype(name, ctx) for i in range(len(sorts)): sum.declare("inject%d" % i, ("project%d" % i, sorts[i])) sum = sum.create() return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))] def EnumSort(name, values, ctx=None): """Return a new enumeration sort named `name` containing the given values. The result is a pair (sort, list of constants). Example: >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue']) """ if z3_debug(): _z3_assert(isinstance(name, str), "Name must be a string") _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings") _z3_assert(len(values) > 0, "At least one value expected") ctx = _get_ctx(ctx) num = len(values) _val_names = (Symbol * num)() for i in range(num): _val_names[i] = to_symbol(values[i]) _values = (FuncDecl * num)() _testers = (FuncDecl * num)() name = to_symbol(name) S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx) V = [] for i in range(num): V.append(FuncDeclRef(_values[i], ctx)) V = [a() for a in V] return S, V ######################################### # # Parameter Sets # ######################################### class ParamsRef: """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3. Consider using the function `args2params` to create instances of this object. """ def __init__(self, ctx=None, params=None): self.ctx = _get_ctx(ctx) if params is None: self.params = Z3_mk_params(self.ctx.ref()) else: self.params = params Z3_params_inc_ref(self.ctx.ref(), self.params) def __deepcopy__(self, memo={}): return ParamsRef(self.ctx, self.params) def __del__(self): if self.ctx.ref() is not None and Z3_params_dec_ref is not None: Z3_params_dec_ref(self.ctx.ref(), self.params) def set(self, name, val): """Set parameter name with value val.""" if z3_debug(): _z3_assert(isinstance(name, str), "parameter name must be a string") name_sym = to_symbol(name, self.ctx) if isinstance(val, bool): Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val) elif _is_int(val): Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, float): Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, str): Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx)) else: if z3_debug(): _z3_assert(False, "invalid parameter value") def __repr__(self): return Z3_params_to_string(self.ctx.ref(), self.params) def validate(self, ds): _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected") Z3_params_validate(self.ctx.ref(), self.params, ds.descr) def args2params(arguments, keywords, ctx=None): """Convert python arguments into a Z3_params object. A ':' is added to the keywords, and '_' is replaced with '-' >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True}) (params model true relevancy 2 elim_and true) """ if z3_debug(): _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.") prev = None r = ParamsRef(ctx) for a in arguments: if prev is None: prev = a else: r.set(prev, a) prev = None for k in keywords: v = keywords[k] r.set(k, v) return r class ParamDescrsRef: """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3. """ def __init__(self, descr, ctx=None): _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected") self.ctx = _get_ctx(ctx) self.descr = descr Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr) def __deepcopy__(self, memo={}): return ParamsDescrsRef(self.descr, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None: Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr) def size(self): """Return the size of in the parameter description `self`. """ return int(Z3_param_descrs_size(self.ctx.ref(), self.descr)) def __len__(self): """Return the size of in the parameter description `self`. """ return self.size() def get_name(self, i): """Return the i-th parameter name in the parameter description `self`. """ return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i)) def get_kind(self, n): """Return the kind of the parameter named `n`. """ return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def get_documentation(self, n): """Return the documentation string of the parameter named `n`. """ return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def __getitem__(self, arg): if _is_int(arg): return self.get_name(arg) else: return self.get_kind(arg) def __repr__(self): return Z3_param_descrs_to_string(self.ctx.ref(), self.descr) ######################################### # # Goals # ######################################### class Goal(Z3PPObject): """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible). Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals. A goal has a solution if one of its subgoals has a solution. A goal is unsatisfiable if all subgoals are unsatisfiable. """ def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None): if z3_debug(): _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None") self.ctx = _get_ctx(ctx) self.goal = goal if self.goal is None: self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs) Z3_goal_inc_ref(self.ctx.ref(), self.goal) def __del__(self): if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None: Z3_goal_dec_ref(self.ctx.ref(), self.goal) def depth(self): """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`. >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x == 0, y >= x + 1) >>> g.depth() 0 >>> r = Then('simplify', 'solve-eqs')(g) >>> # r has 1 subgoal >>> len(r) 1 >>> r[0].depth() 2 """ return int(Z3_goal_depth(self.ctx.ref(), self.goal)) def inconsistent(self): """Return `True` if `self` contains the `False` constraints. >>> x, y = Ints('x y') >>> g = Goal() >>> g.inconsistent() False >>> g.add(x == 0, x == 1) >>> g [x == 0, x == 1] >>> g.inconsistent() False >>> g2 = Tactic('propagate-values')(g)[0] >>> g2.inconsistent() True """ return Z3_goal_inconsistent(self.ctx.ref(), self.goal) def prec(self): """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`. >>> g = Goal() >>> g.prec() == Z3_GOAL_PRECISE True >>> x, y = Ints('x y') >>> g.add(x == y + 1) >>> g.prec() == Z3_GOAL_PRECISE True >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10) >>> g2 = t(g)[0] >>> g2 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0] >>> g2.prec() == Z3_GOAL_PRECISE False >>> g2.prec() == Z3_GOAL_UNDER True """ return Z3_goal_precision(self.ctx.ref(), self.goal) def precision(self): """Alias for `prec()`. >>> g = Goal() >>> g.precision() == Z3_GOAL_PRECISE True """ return self.prec() def size(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> g.size() 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.size() 2 """ return int(Z3_goal_size(self.ctx.ref(), self.goal)) def __len__(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> len(g) 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> len(g) 2 """ return self.size() def get(self, i): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.get(0) x == 0 >>> g.get(1) y > x """ return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx) def __getitem__(self, arg): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g[0] x == 0 >>> g[1] y > x """ if arg >= len(self): raise IndexError return self.get(arg) def assert_exprs(self, *args): """Assert constraints into the goal. >>> x = Int('x') >>> g = Goal() >>> g.assert_exprs(x > 0, x < 2) >>> g [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: arg = s.cast(arg) Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast()) def append(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.append(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.insert(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def add(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def convert_model(self, model): """Retrieve model from a satisfiable goal >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs')) >>> r = t(g) >>> r[0] [Or(b == 0, b == 1), Not(0 <= b)] >>> r[1] [Or(b == 0, b == 1), Not(1 <= b)] >>> # Remark: the subgoal r[0] is unsatisfiable >>> # Creating a solver for solving the second subgoal >>> s = Solver() >>> s.add(r[1]) >>> s.check() sat >>> s.model() [b = 0] >>> # Model s.model() does not assign a value to `a` >>> # It is a model for subgoal `r[1]`, but not for goal `g` >>> # The method convert_model creates a model for `g` from a model for `r[1]`. >>> r[1].convert_model(s.model()) [b = 0, a = 1] """ if z3_debug(): _z3_assert(isinstance(model, ModelRef), "Z3 Model expected") return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the goal.""" return Z3_goal_to_string(self.ctx.ref(), self.goal) def dimacs(self, include_names=True): """Return a textual representation of the goal in DIMACS format.""" return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names) def translate(self, target): """Copy goal `self` to context `target`. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 10) >>> g [x > 10] >>> c2 = Context() >>> g2 = g.translate(c2) >>> g2 [x > 10] >>> g.ctx == main_ctx() True >>> g2.ctx == c2 True >>> g2.ctx == main_ctx() False """ if z3_debug(): _z3_assert(isinstance(target, Context), "target must be a context") return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def simplify(self, *arguments, **keywords): """Return a new simplified goal. This method is essentially invoking the simplify tactic. >>> g = Goal() >>> x = Int('x') >>> g.add(x + 1 >= 2) >>> g [x + 1 >= 2] >>> g2 = g.simplify() >>> g2 [x >= 1] >>> # g was not modified >>> g [x + 1 >= 2] """ t = Tactic("simplify") return t.apply(self, *arguments, **keywords)[0] def as_expr(self): """Return goal `self` as a single Z3 expression. >>> x = Int('x') >>> g = Goal() >>> g.as_expr() True >>> g.add(x > 1) >>> g.as_expr() x > 1 >>> g.add(x < 10) >>> g.as_expr() And(x > 1, x < 10) """ sz = len(self) if sz == 0: return BoolVal(True, self.ctx) elif sz == 1: return self.get(0) else: return And([self.get(i) for i in range(len(self))], self.ctx) ######################################### # # AST Vector # ######################################### class AstVector(Z3PPObject): """A collection (vector) of ASTs.""" def __init__(self, v=None, ctx=None): self.vector = None if v is None: self.ctx = _get_ctx(ctx) self.vector = Z3_mk_ast_vector(self.ctx.ref()) else: self.vector = v assert ctx is not None self.ctx = ctx Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector) def __del__(self): if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None: Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector) def __len__(self): """Return the size of the vector `self`. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> A.push(Int('x')) >>> len(A) 2 """ return int(Z3_ast_vector_size(self.ctx.ref(), self.vector)) def __getitem__(self, i): """Return the AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[1] y """ if isinstance(i, int): if i < 0: i += self.__len__() if i >= self.__len__(): raise IndexError return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx) elif isinstance(i, slice): result = [] for ii in range(*i.indices(self.__len__())): result.append(_to_ast_ref( Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx, )) return result def __setitem__(self, i, v): """Update AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[0] = Int('x') >>> A[0] x """ if i >= self.__len__(): raise IndexError Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast()) def push(self, v): """Add `v` in the end of the vector. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> len(A) 1 """ Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast()) def resize(self, sz): """Resize the vector to `sz` elements. >>> A = AstVector() >>> A.resize(10) >>> len(A) 10 >>> for i in range(10): A[i] = Int('x') >>> A[5] x """ Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz) def __contains__(self, item): """Return `True` if the vector contains `item`. >>> x = Int('x') >>> A = AstVector() >>> x in A False >>> A.push(x) >>> x in A True >>> (x+1) in A False >>> A.push(x+1) >>> (x+1) in A True >>> A [x, x + 1] """ for elem in self: if elem.eq(item): return True return False def translate(self, other_ctx): """Copy vector `self` to context `other_ctx`. >>> x = Int('x') >>> A = AstVector() >>> A.push(x) >>> c2 = Context() >>> B = A.translate(c2) >>> B [x] """ return AstVector( Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), ctx=other_ctx, ) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the vector.""" return Z3_ast_vector_to_string(self.ctx.ref(), self.vector) ######################################### # # AST Map # ######################################### class AstMap: """A mapping from ASTs to ASTs.""" def __init__(self, m=None, ctx=None): self.map = None if m is None: self.ctx = _get_ctx(ctx) self.map = Z3_mk_ast_map(self.ctx.ref()) else: self.map = m assert ctx is not None self.ctx = ctx Z3_ast_map_inc_ref(self.ctx.ref(), self.map) def __deepcopy__(self, memo={}): return AstMap(self.map, self.ctx) def __del__(self): if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None: Z3_ast_map_dec_ref(self.ctx.ref(), self.map) def __len__(self): """Return the size of the map. >>> M = AstMap() >>> len(M) 0 >>> x = Int('x') >>> M[x] = IntVal(1) >>> len(M) 1 """ return int(Z3_ast_map_size(self.ctx.ref(), self.map)) def __contains__(self, key): """Return `True` if the map contains key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> x in M True >>> x+1 in M False """ return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast()) def __getitem__(self, key): """Retrieve the value associated with key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x] x + 1 """ return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx) def __setitem__(self, k, v): """Add/Update key `k` with value `v`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M[x] x + 1 >>> M[x] = IntVal(1) >>> M[x] 1 """ Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast()) def __repr__(self): return Z3_ast_map_to_string(self.ctx.ref(), self.map) def erase(self, k): """Remove the entry associated with key `k`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M.erase(x) >>> len(M) 0 """ Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast()) def reset(self): """Remove all entries from the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> len(M) 2 >>> M.reset() >>> len(M) 0 """ Z3_ast_map_reset(self.ctx.ref(), self.map) def keys(self): """Return an AstVector containing all keys in the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> M.keys() [x, x + x] """ return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx) ######################################### # # Model # ######################################### class FuncEntry: """Store the value of the interpretation of a function in a particular point.""" def __init__(self, entry, ctx): self.entry = entry self.ctx = ctx Z3_func_entry_inc_ref(self.ctx.ref(), self.entry) def __deepcopy__(self, memo={}): return FuncEntry(self.entry, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None: Z3_func_entry_dec_ref(self.ctx.ref(), self.entry) def num_args(self): """Return the number of arguments in the given entry. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.num_args() 2 """ return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry)) def arg_value(self, idx): """Return the value of argument `idx`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.arg_value(0) 1 >>> e.arg_value(1) 2 >>> try: ... e.arg_value(2) ... except IndexError: ... print("index error") index error """ if idx >= self.num_args(): raise IndexError return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx) def value(self): """Return the value of the function at point `self`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.value() 20 """ return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx) def as_list(self): """Return entry `self` as a Python list. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.as_list() [1, 2, 20] """ args = [self.arg_value(i) for i in range(self.num_args())] args.append(self.value()) return args def __repr__(self): return repr(self.as_list()) class FuncInterp(Z3PPObject): """Stores the interpretation of a function in a Z3 model.""" def __init__(self, f, ctx): self.f = f self.ctx = ctx if self.f is not None: Z3_func_interp_inc_ref(self.ctx.ref(), self.f) def __del__(self): if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None: Z3_func_interp_dec_ref(self.ctx.ref(), self.f) def else_value(self): """ Return the `else` value for a function interpretation. Return None if Z3 did not specify the `else` value for this object. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].else_value() 1 """ r = Z3_func_interp_get_else(self.ctx.ref(), self.f) if r: return _to_expr_ref(r, self.ctx) else: return None def num_entries(self): """Return the number of entries/points in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 """ return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f)) def arity(self): """Return the number of arguments for each entry in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f].arity() 1 """ return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f)) def entry(self, idx): """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 >>> m[f].entry(0) [2, 0] """ if idx >= self.num_entries(): raise IndexError return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx) def translate(self, other_ctx): """Copy model 'self' to context 'other_ctx'. """ return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def as_list(self): """Return the function interpretation as a Python list. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].as_list() [[2, 0], 1] """ r = [self.entry(i).as_list() for i in range(self.num_entries())] r.append(self.else_value()) return r def __repr__(self): return obj_to_string(self) class ModelRef(Z3PPObject): """Model/Solution of a satisfiability problem (aka system of constraints).""" def __init__(self, m, ctx): assert ctx is not None self.model = m self.ctx = ctx Z3_model_inc_ref(self.ctx.ref(), self.model) def __del__(self): if self.ctx.ref() is not None and Z3_model_dec_ref is not None: Z3_model_dec_ref(self.ctx.ref(), self.model) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the model.""" return Z3_model_to_string(self.ctx.ref(), self.model) def eval(self, t, model_completion=False): """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.eval(x + 1) 2 >>> m.eval(x == 1) True >>> y = Int('y') >>> m.eval(y + x) 1 + y >>> m.eval(y) y >>> m.eval(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.eval(y + x) 1 """ r = (Ast * 1)() if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r): return _to_expr_ref(r[0], self.ctx) raise Z3Exception("failed to evaluate expression in the model") def evaluate(self, t, model_completion=False): """Alias for `eval`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.evaluate(x + 1) 2 >>> m.evaluate(x == 1) True >>> y = Int('y') >>> m.evaluate(y + x) 1 + y >>> m.evaluate(y) y >>> m.evaluate(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.evaluate(y + x) 1 """ return self.eval(t, model_completion) def __len__(self): """Return the number of constant and function declarations in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, f(x) != x) >>> s.check() sat >>> m = s.model() >>> len(m) 2 """ num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) return num_consts + num_funcs def get_interp(self, decl): """Return the interpretation for a given declaration or constant. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1 >>> m[f] [else -> 0] """ if z3_debug(): _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected") if is_const(decl): decl = decl.decl() try: if decl.arity() == 0: _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast) if _r.value is None: return None r = _to_expr_ref(_r, self.ctx) if is_as_array(r): fi = self.get_interp(get_as_array_func(r)) if fi is None: return fi e = fi.else_value() if e is None: return fi if fi.arity() != 1: return fi srt = decl.range() dom = srt.domain() e = K(dom, e) i = 0 sz = fi.num_entries() n = fi.arity() while i < sz: fe = fi.entry(i) e = Store(e, fe.arg_value(0), fe.value()) i += 1 return e else: return r else: return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) except Z3Exception: return None def num_sorts(self): """Return the number of uninterpreted sorts that contain an interpretation in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 1 """ return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model)) def get_sort(self, idx): """Return the uninterpreted sort at position `idx` < self.num_sorts(). >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 2 >>> m.get_sort(0) A >>> m.get_sort(1) B """ if idx >= self.num_sorts(): raise IndexError return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx) def sorts(self): """Return all uninterpreted sorts that have an interpretation in the model `self`. >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.sorts() [A, B] """ return [self.get_sort(i) for i in range(self.num_sorts())] def get_universe(self, s): """Return the interpretation for the uninterpreted sort `s` in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.get_universe(A) [A!val!1, A!val!0] """ if z3_debug(): _z3_assert(isinstance(s, SortRef), "Z3 sort expected") try: return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx) except Z3Exception: return None def __getitem__(self, idx): """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned. The elements can be retrieved using position or the actual declaration. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> len(m) 2 >>> m[0] x >>> m[1] f >>> m[x] 1 >>> m[f] [else -> 0] >>> for d in m: print("%s -> %s" % (d, m[d])) x -> 1 f -> [else -> 0] """ if _is_int(idx): if idx >= len(self): raise IndexError num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model) if (idx < num_consts): return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx) else: return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx) if isinstance(idx, FuncDeclRef): return self.get_interp(idx) if is_const(idx): return self.get_interp(idx.decl()) if isinstance(idx, SortRef): return self.get_universe(idx) if z3_debug(): _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected") return None def decls(self): """Return a list with all symbols that have an interpretation in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m.decls() [x, f] """ r = [] for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx)) for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx)) return r def update_value(self, x, value): """Update the interpretation of a constant""" if is_expr(x): x = x.decl() if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp): fi1 = value.f fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast); fi2 = FuncInterp(fi2, x.ctx) for i in range(value.num_entries()): e = value.entry(i) n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry) v = AstVector() for j in range(n): v.push(e.arg_value(j)) val = Z3_func_entry_get_value(x.ctx_ref(), e.entry) Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val) return if not is_func_decl(x) or x.arity() != 0: raise Z3Exception("Expecting 0-ary function or constant expression") value = _py2expr(value) Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") model = Z3_model_translate(self.ctx.ref(), self.model, target.ref()) return ModelRef(model, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def Model(ctx=None): ctx = _get_ctx(ctx) return ModelRef(Z3_mk_model(ctx.ref()), ctx) def is_as_array(n): """Return true if n is a Z3 expression of the form (_ as-array f).""" return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast()) def get_as_array_func(n): """Return the function declaration f associated with a Z3 expression of the form (_ as-array f).""" if z3_debug(): _z3_assert(is_as_array(n), "as-array Z3 expression expected.") return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx) ######################################### # # Statistics # ######################################### class Statistics: """Statistics for `Solver.check()`.""" def __init__(self, stats, ctx): self.stats = stats self.ctx = ctx Z3_stats_inc_ref(self.ctx.ref(), self.stats) def __deepcopy__(self, memo={}): return Statistics(self.stats, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_stats_dec_ref is not None: Z3_stats_dec_ref(self.ctx.ref(), self.stats) def __repr__(self): if in_html_mode(): out = io.StringIO() even = True out.write(u('<table border="1" cellpadding="2" cellspacing="0">')) for k, v in self: if even: out.write(u('<tr style="background-color:#CFCFCF">')) even = False else: out.write(u("<tr>")) even = True out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v))) out.write(u("</table>")) return out.getvalue() else: return Z3_stats_to_string(self.ctx.ref(), self.stats) def __len__(self): """Return the number of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 """ return int(Z3_stats_size(self.ctx.ref(), self.stats)) def __getitem__(self, idx): """Return the value of statistical counter at position `idx`. The result is a pair (key, value). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 >>> st[0] ('nlsat propagations', 2) >>> st[1] ('nlsat stages', 2) """ if idx >= len(self): raise IndexError if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val) def keys(self): """Return the list of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() """ return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))] def get_key_value(self, key): """Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2 """ for idx in range(len(self)): if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) raise Z3Exception("unknown key") def __getattr__(self, name): """Access the value of statistical using attributes. Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'), we should use '_' (e.g., 'nlsat_propagations'). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.nlsat_propagations 2 >>> st.nlsat_stages 2 """ key = name.replace("_", " ") try: return self.get_key_value(key) except Z3Exception: raise AttributeError ######################################### # # Solver # ######################################### class CheckSatResult: """Represents the result of a satisfiability check: sat, unsat, unknown. >>> s = Solver() >>> s.check() sat >>> r = s.check() >>> isinstance(r, CheckSatResult) True """ def __init__(self, r): self.r = r def __deepcopy__(self, memo={}): return CheckSatResult(self.r) def __eq__(self, other): return isinstance(other, CheckSatResult) and self.r == other.r def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if in_html_mode(): if self.r == Z3_L_TRUE: return "<b>sat</b>" elif self.r == Z3_L_FALSE: return "<b>unsat</b>" else: return "<b>unknown</b>" else: if self.r == Z3_L_TRUE: return "sat" elif self.r == Z3_L_FALSE: return "unsat" else: return "unknown" def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res sat = CheckSatResult(Z3_L_TRUE) unsat = CheckSatResult(Z3_L_FALSE) unknown = CheckSatResult(Z3_L_UNDEF) class Solver(Z3PPObject): """ Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc. """ def __init__(self, solver=None, ctx=None, logFile=None): assert solver is None or ctx is not None self.ctx = _get_ctx(ctx) self.backtrack_level = 4000000000 self.solver = None if solver is None: self.solver = Z3_mk_solver(self.ctx.ref()) else: self.solver = solver Z3_solver_inc_ref(self.ctx.ref(), self.solver) if logFile is not None: self.set("smtlib2_log", logFile) def __del__(self): if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None: Z3_solver_dec_ref(self.ctx.ref(), self.solver) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. >>> s = Solver() >>> # The option MBQI can be set using three different approaches. >>> s.set(mbqi=True) >>> s.set('MBQI', True) >>> s.set(':mbqi', True) """ p = args2params(args, keys, self.ctx) Z3_solver_set_params(self.ctx.ref(), self.solver, p.params) def push(self): """Create a backtracking point. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_push(self.ctx.ref(), self.solver) def pop(self, num=1): """Backtrack \\c num backtracking points. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_pop(self.ctx.ref(), self.solver, num) def num_scopes(self): """Return the current number of backtracking points. >>> s = Solver() >>> s.num_scopes() 0 >>> s.push() >>> s.num_scopes() 1 >>> s.push() >>> s.num_scopes() 2 >>> s.pop() >>> s.num_scopes() 1 """ return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver) def reset(self): """Remove all asserted constraints and backtracking points created using `push()`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.reset() >>> s [] """ Z3_solver_reset(self.ctx.ref(), self.solver) def assert_exprs(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.assert_exprs(x > 0, x < 2) >>> s [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast()) else: arg = s.cast(arg) Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast()) def add(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.append(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.insert(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Solver() >>> s.set(unsat_core=True) >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast()) def check(self, *assumptions): """Check whether the assertions in the given solver plus the optional assumptions are consistent or not. >>> x = Int('x') >>> s = Solver() >>> s.check() sat >>> s.add(x > 0, x < 2) >>> s.check() sat >>> s.model().eval(x) 1 >>> s.add(x < 1) >>> s.check() unsat >>> s.reset() >>> s.add(2**x == 4) >>> s.check() unknown """ s = BoolSort(self.ctx) assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = s.cast(assumptions[i]).as_ast() r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions) return CheckSatResult(r) def model(self): """Return a model for the last `check()`. This function raises an exception if a model is not available (e.g., last `check()` returned unsat). >>> s = Solver() >>> a = Int('a') >>> s.add(a + 2 == 0) >>> s.check() sat >>> s.model() [a = -2] """ try: return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def import_model_converter(self, other): """Import model converter from other into the current solver""" Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver) def unsat_core(self): """Return a subset (as an AST vector) of the assumptions provided to the last check(). These are the assumptions Z3 used in the unsatisfiability proof. Assumptions are available in Z3. They are used to extract unsatisfiable cores. They may be also used to "retract" assumptions. Note that, assumptions are not really "soft constraints", but they can be used to implement them. >>> p1, p2, p3 = Bools('p1 p2 p3') >>> x, y = Ints('x y') >>> s = Solver() >>> s.add(Implies(p1, x > 0)) >>> s.add(Implies(p2, y > x)) >>> s.add(Implies(p2, y < 1)) >>> s.add(Implies(p3, y > -3)) >>> s.check(p1, p2, p3) unsat >>> core = s.unsat_core() >>> len(core) 2 >>> p1 in core True >>> p2 in core True >>> p3 in core False >>> # "Retracting" p2 >>> s.check(p1, p3) sat """ return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx) def consequences(self, assumptions, variables): """Determine fixed values for the variables based on the solver state and assumptions. >>> s = Solver() >>> a, b, c, d = Bools('a b c d') >>> s.add(Implies(a,b), Implies(b, c)) >>> s.consequences([a],[b,c,d]) (sat, [Implies(a, b), Implies(a, c)]) >>> s.consequences([Not(c),d],[a,b,c,d]) (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))]) """ if isinstance(assumptions, list): _asms = AstVector(None, self.ctx) for a in assumptions: _asms.push(a) assumptions = _asms if isinstance(variables, list): _vars = AstVector(None, self.ctx) for a in variables: _vars.push(a) variables = _vars _z3_assert(isinstance(assumptions, AstVector), "ast vector expected") _z3_assert(isinstance(variables, AstVector), "ast vector expected") consequences = AstVector(None, self.ctx) r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector) sz = len(consequences) consequences = [consequences[i] for i in range(sz)] return CheckSatResult(r), consequences def from_file(self, filename): """Parse assertions from a file""" Z3_solver_from_file(self.ctx.ref(), self.solver, filename) def from_string(self, s): """Parse assertions from a string""" Z3_solver_from_string(self.ctx.ref(), self.solver, s) def cube(self, vars=None): """Get set of cubes The method takes an optional set of variables that restrict which variables may be used as a starting point for cubing. If vars is not None, then the first case split is based on a variable in this set. """ self.cube_vs = AstVector(None, self.ctx) if vars is not None: for v in vars: self.cube_vs.push(v) while True: lvl = self.backtrack_level self.backtrack_level = 4000000000 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx) if (len(r) == 1 and is_false(r[0])): return yield r if (len(r) == 0): return def cube_vars(self): """Access the set of variables that were touched by the most recently generated cube. This set of variables can be used as a starting point for additional cubes. The idea is that variables that appear in clauses that are reduced by the most recent cube are likely more useful to cube on.""" return self.cube_vs def root(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure root of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx) def next(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure sibling of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx) def proof(self): """Return a proof for the last `check()`. Proof construction must be enabled.""" return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx) def assertions(self): """Return an AST vector containing all added constraints. >>> s = Solver() >>> s.assertions() [] >>> a = Int('a') >>> s.add(a > 0) >>> s.add(a < 10) >>> s.assertions() [a > 0, a < 10] """ return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx) def units(self): """Return an AST vector containing all currently inferred units. """ return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx) def non_units(self): """Return an AST vector containing all atomic formulas in solver state that are not units. """ return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx) def trail_levels(self): """Return trail and decision levels of the solver state after a check() call. """ trail = self.trail() levels = (ctypes.c_uint * len(trail))() Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels) return trail, levels def trail(self): """Return trail of the solver state after a check() call. """ return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx) def statistics(self): """Return statistics for the last `check()`. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('final checks') 1 >>> len(st) > 0 True >>> st[0] != 0 True """ return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx) def reason_unknown(self): """Return a string describing why the last `check()` returned `unknown`. >>> x = Int('x') >>> s = SimpleSolver() >>> s.add(2**x == 4) >>> s.check() unknown >>> s.reason_unknown() '(incomplete (theory arithmetic))' """ return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver) def help(self): """Display a string describing all available options.""" print(Z3_solver_get_help(self.ctx.ref(), self.solver)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx) def __repr__(self): """Return a formatted string with all added constraints.""" return obj_to_string(self) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> s1 = Solver(ctx=c1) >>> s2 = s1.translate(c2) """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref()) return Solver(solver, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s.add(x < 2) >>> r = s.sexpr() """ return Z3_solver_to_string(self.ctx.ref(), self.solver) def dimacs(self, include_names=True): """Return a textual representation of the solver in DIMACS format.""" return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names) def to_smt2(self): """return SMTLIB2 formatted benchmark for solver's assertions""" es = self.assertions() sz = len(es) sz1 = sz if sz1 > 0: sz1 -= 1 v = (Ast * sz1)() for i in range(sz1): v[i] = es[i].as_ast() if sz > 0: e = es[sz1].as_ast() else: e = BoolVal(True, self.ctx).as_ast() return Z3_benchmark_to_smtlib_string( self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e, ) def SolverFor(logic, ctx=None, logFile=None): """Create a solver customized for the given logic. The parameter `logic` is a string. It should be contains the name of a SMT-LIB logic. See http://www.smtlib.org/ for the name of all available logics. >>> s = SolverFor("QF_LIA") >>> x = Int('x') >>> s.add(x > 0) >>> s.add(x < 2) >>> s.check() sat >>> s.model() [x = 1] """ ctx = _get_ctx(ctx) logic = to_symbol(logic) return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile) def SimpleSolver(ctx=None, logFile=None): """Return a simple general purpose solver with limited amount of preprocessing. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat """ ctx = _get_ctx(ctx) return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile) ######################################### # # Fixedpoint # ######################################### class Fixedpoint(Z3PPObject): """Fixedpoint API provides methods for solving with recursive predicates""" def __init__(self, fixedpoint=None, ctx=None): assert fixedpoint is None or ctx is not None self.ctx = _get_ctx(ctx) self.fixedpoint = None if fixedpoint is None: self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref()) else: self.fixedpoint = fixedpoint Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint) self.vars = [] def __deepcopy__(self, memo={}): return FixedPoint(self.fixedpoint, self.ctx) def __del__(self): if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None: Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params) def help(self): """Display a string describing all available options.""" print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the fixedpoint solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: f = self.abstract(f) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast()) else: arg = s.cast(arg) arg = self.abstract(arg) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def insert(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def add_rule(self, head, body=None, name=None): """Assert rules defining recursive predicates to the fixedpoint solver. >>> a = Bool('a') >>> b = Bool('b') >>> s = Fixedpoint() >>> s.register_relation(a.decl()) >>> s.register_relation(b.decl()) >>> s.fact(a) >>> s.rule(b, a) >>> s.query(b) sat """ if name is None: name = "" name = to_symbol(name, self.ctx) if body is None: head = self.abstract(head) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name) else: body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx), head)) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def rule(self, head, body=None, name=None): """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, body, name) def fact(self, head, name=None): """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, None, name) def query(self, *query): """Query the fixedpoint engine whether formula is derivable. You can also pass an tuple or list of recursive predicates. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDeclRef): _decls = (FuncDecl * sz)() i = 0 for q in query: _decls[i] = q.ast i = i + 1 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls) else: if sz == 1: query = query[0] else: query = And(query, self.ctx) query = self.abstract(query, False) r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast()) return CheckSatResult(r) def query_from_lvl(self, lvl, *query): """Query the fixedpoint engine whether formula is derivable starting at the given query level. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDecl): _z3_assert(False, "unsupported") else: if sz == 1: query = query[0] else: query = And(query) query = self.abstract(query, False) r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl) return CheckSatResult(r) def update_rule(self, head, body, name): """update rule""" if name is None: name = "" name = to_symbol(name, self.ctx) body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx), head)) Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def get_answer(self): """Retrieve answer from last query call.""" r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_ground_sat_answer(self): """Retrieve a ground cex from last query call.""" r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_rules_along_trace(self): """retrieve rules along the counterexample trace""" return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx) def get_rule_names_along_trace(self): """retrieve rule names along the counterexample trace""" # this is a hack as I don't know how to return a list of symbols from C++; # obtain names as a single string separated by semicolons names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint)) # split into individual names return names.split(";") def get_num_levels(self, predicate): """Retrieve number of levels used for predicate in PDR engine""" return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast) def get_cover_delta(self, level, predicate): """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity) """ r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast) return _to_expr_ref(r, self.ctx) def add_cover(self, level, predicate, property): """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity) """ Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast) def register_relation(self, *relations): """Register relation as recursive""" relations = _get_args(relations) for f in relations: Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast) def set_predicate_representation(self, f, *representations): """Control how relation is represented""" representations = _get_args(representations) representations = [to_symbol(s) for s in representations] sz = len(representations) args = (Symbol * sz)() for i in range(sz): args[i] = representations[i] Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args) def parse_string(self, s): """Parse rules and queries from a string""" return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx) def parse_file(self, f): """Parse rules and queries from a file""" return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx) def get_rules(self): """retrieve rules that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx) def get_assertions(self): """retrieve assertions that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)()) def to_string(self, queries): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. Include also queries. """ args, len = _to_ast_array(queries) return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args) def statistics(self): """Return statistics for the last `query()`. """ return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx) def reason_unknown(self): """Return a string describing why the last `query()` returned `unknown`. """ return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint) def declare_var(self, *vars): """Add variable or several variables. The added variable or variables will be bound in the rules and queries """ vars = _get_args(vars) for v in vars: self.vars += [v] def abstract(self, fml, is_forall=True): if self.vars == []: return fml if is_forall: return ForAll(self.vars, fml) else: return Exists(self.vars, fml) ######################################### # # Finite domains # ######################################### class FiniteDomainSortRef(SortRef): """Finite domain sort.""" def size(self): """Return the size of the finite domain sort""" r = (ctypes.c_ulonglong * 1)() if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r): return r[0] else: raise Z3Exception("Failed to retrieve finite domain sort size") def FiniteDomainSort(name, sz, ctx=None): """Create a named finite domain sort of a given size sz""" if not isinstance(name, Symbol): name = to_symbol(name) ctx = _get_ctx(ctx) return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx) def is_finite_domain_sort(s): """Return True if `s` is a Z3 finite-domain sort. >>> is_finite_domain_sort(FiniteDomainSort('S', 100)) True >>> is_finite_domain_sort(IntSort()) False """ return isinstance(s, FiniteDomainSortRef) class FiniteDomainRef(ExprRef): """Finite-domain expressions.""" def sort(self): """Return the sort of the finite-domain expression `self`.""" return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def is_finite_domain(a): """Return `True` if `a` is a Z3 finite-domain expression. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain(b) True >>> is_finite_domain(Int('x')) False """ return isinstance(a, FiniteDomainRef) class FiniteDomainNumRef(FiniteDomainRef): """Integer values.""" def as_long(self): """Return a Z3 finite-domain numeral as a Python long (bignum) numeral. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(3, s) >>> v 3 >>> v.as_long() + 1 4 """ return int(self.as_string()) def as_string(self): """Return a Z3 finite-domain numeral as a Python string. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(42, s) >>> v.as_string() '42' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def FiniteDomainVal(val, sort, ctx=None): """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used. >>> s = FiniteDomainSort('S', 256) >>> FiniteDomainVal(255, s) 255 >>> FiniteDomainVal('100', s) 100 """ if z3_debug(): _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort") ctx = sort.ctx return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx) def is_finite_domain_value(a): """Return `True` if `a` is a Z3 finite-domain value. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain_value(b) False >>> b = FiniteDomainVal(10, s) >>> b 10 >>> is_finite_domain_value(b) True """ return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast()) ######################################### # # Optimize # ######################################### class OptimizeObjective: def __init__(self, opt, value, is_max): self._opt = opt self._value = value self._is_max = is_max def lower(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def lower_values(self): opt = self._opt return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper_values(self): opt = self._opt return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def value(self): if self._is_max: return self.upper() else: return self.lower() def __str__(self): return "%s:%s" % (self._value, self._is_max) _on_models = {} def _global_on_model(ctx): (fn, mdl) = _on_models[ctx] fn(mdl) _on_model_eh = on_model_eh_type(_global_on_model) class Optimize(Z3PPObject): """Optimize API provides methods for solving using objective functions and weighted soft constraints""" def __init__(self, ctx=None): self.ctx = _get_ctx(ctx) self.optimize = Z3_mk_optimize(self.ctx.ref()) self._on_models_id = None Z3_optimize_inc_ref(self.ctx.ref(), self.optimize) def __deepcopy__(self, memo={}): return Optimize(self.optimize, self.ctx) def __del__(self): if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None: Z3_optimize_dec_ref(self.ctx.ref(), self.optimize) if self._on_models_id is not None: del _on_models[self._on_models_id] def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params) def help(self): """Display a string describing all available options.""" print(Z3_optimize_get_help(self.ctx.ref(), self.optimize)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the optimize solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast()) else: arg = s.cast(arg) Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the optimize solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Optimize() >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast()) def add_soft(self, arg, weight="1", id=None): """Add soft constraint with optional weight and optional identifier. If no weight is supplied, then the penalty for violating the soft constraint is 1. Soft constraints are grouped by identifiers. Soft constraints that are added without identifiers are grouped by default. """ if _is_int(weight): weight = "%d" % weight elif isinstance(weight, float): weight = "%f" % weight if not isinstance(weight, str): raise Z3Exception("weight should be a string or an integer") if id is None: id = "" id = to_symbol(id, self.ctx) def asoft(a): v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id) return OptimizeObjective(self, v, False) if sys.version_info.major >= 3 and isinstance(arg, Iterable): return [asoft(a) for a in arg] return asoft(arg) def maximize(self, arg): """Add objective function to maximize.""" return OptimizeObjective( self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=True, ) def minimize(self, arg): """Add objective function to minimize.""" return OptimizeObjective( self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=False, ) def push(self): """create a backtracking point for added rules, facts and assertions""" Z3_optimize_push(self.ctx.ref(), self.optimize) def pop(self): """restore to previously created backtracking point""" Z3_optimize_pop(self.ctx.ref(), self.optimize) def check(self, *assumptions): """Check satisfiability while optimizing objective functions.""" assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions)) def reason_unknown(self): """Return a string that describes why the last `check()` returned `unknown`.""" return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize) def model(self): """Return a model for the last check().""" try: return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def unsat_core(self): return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx) def lower(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower() def upper(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper() def lower_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower_values() def upper_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper_values() def from_file(self, filename): """Parse assertions and objectives from a file""" Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename) def from_string(self, s): """Parse assertions and objectives from a string""" Z3_optimize_from_string(self.ctx.ref(), self.optimize, s) def assertions(self): """Return an AST vector containing all added constraints.""" return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx) def objectives(self): """returns set of objective functions""" return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_optimize_to_string(self.ctx.ref(), self.optimize) def statistics(self): """Return statistics for the last check`. """ return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx) def set_on_model(self, on_model): """Register a callback that is invoked with every incremental improvement to objective values. The callback takes a model as argument. The life-time of the model is limited to the callback so the model has to be (deep) copied if it is to be used after the callback """ id = len(_on_models) + 41 mdl = Model(self.ctx) _on_models[id] = (on_model, mdl) self._on_models_id = id Z3_optimize_register_model_eh( self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh, ) ######################################### # # ApplyResult # ######################################### class ApplyResult(Z3PPObject): """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters. """ def __init__(self, result, ctx): self.result = result self.ctx = ctx Z3_apply_result_inc_ref(self.ctx.ref(), self.result) def __deepcopy__(self, memo={}): return ApplyResult(self.result, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None: Z3_apply_result_dec_ref(self.ctx.ref(), self.result) def __len__(self): """Return the number of subgoals in `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> len(r) 2 >>> t = Then(Tactic('split-clause'), Tactic('split-clause')) >>> len(t(g)) 4 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values')) >>> len(t(g)) 1 """ return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result)) def __getitem__(self, idx): """Return one of the subgoals stored in ApplyResult object `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> r[0] [a == 0, Or(b == 0, b == 1), a > b] >>> r[1] [a == 1, Or(b == 0, b == 1), a > b] """ if idx >= len(self): raise IndexError return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the set of subgoals in `self`.""" return Z3_apply_result_to_string(self.ctx.ref(), self.result) def as_expr(self): """Return a Z3 expression consisting of all subgoals. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 1) >>> g.add(Or(x == 2, x == 3)) >>> r = Tactic('simplify')(g) >>> r [[Not(x <= 1), Or(x == 2, x == 3)]] >>> r.as_expr() And(Not(x <= 1), Or(x == 2, x == 3)) >>> r = Tactic('split-clause')(g) >>> r [[x > 1, x == 2], [x > 1, x == 3]] >>> r.as_expr() Or(And(x > 1, x == 2), And(x > 1, x == 3)) """ sz = len(self) if sz == 0: return BoolVal(False, self.ctx) elif sz == 1: return self[0].as_expr() else: return Or([self[i].as_expr() for i in range(len(self))]) ######################################### # # Simplifiers # ######################################### class Simplifier: """Simplifiers act as pre-processing utilities for solvers. Build a custom simplifier and add it to a solver""" def __init__(self, simplifier, ctx=None): self.ctx = _get_ctx(ctx) self.simplifier = None if isinstance(simplifier, SimplifierObj): self.simplifier = simplifier elif isinstance(simplifier, list): simps = [Simplifier(s, ctx) for s in simplifier] self.simplifier = simps[0].simplifier for i in range(1, len(simps)): self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) return else: if z3_debug(): _z3_assert(isinstance(simplifier, str), "simplifier name expected") try: self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier)) except Z3Exception: raise Z3Exception("unknown simplifier '%s'" % simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) def __deepcopy__(self, memo={}): return Simplifier(self.simplifier, self.ctx) def __del__(self): if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None: Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier) def using_params(self, *args, **keys): """Return a simplifier that uses the given configuration options""" p = args2params(args, keys, self.ctx) return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx) def add(self, solver): """Return a solver that applies the simplification pre-processing specified by the simplifier""" return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx) def help(self): """Display a string containing a description of the available options for the `self` simplifier.""" print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx) ######################################### # # Tactics # ######################################### class Tactic: """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver(). Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond(). """ def __init__(self, tactic, ctx=None): self.ctx = _get_ctx(ctx) self.tactic = None if isinstance(tactic, TacticObj): self.tactic = tactic else: if z3_debug(): _z3_assert(isinstance(tactic, str), "tactic name expected") try: self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic)) except Z3Exception: raise Z3Exception("unknown tactic '%s'" % tactic) Z3_tactic_inc_ref(self.ctx.ref(), self.tactic) def __deepcopy__(self, memo={}): return Tactic(self.tactic, self.ctx) def __del__(self): if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None: Z3_tactic_dec_ref(self.ctx.ref(), self.tactic) def solver(self, logFile=None): """Create a solver using the tactic `self`. The solver supports the methods `push()` and `pop()`, but it will always solve each `check()` from scratch. >>> t = Then('simplify', 'nlsat') >>> s = t.solver() >>> x = Real('x') >>> s.add(x**2 == 2, x > 0) >>> s.check() sat >>> s.model() [x = 1.4142135623?] """ return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile) def apply(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t.apply(And(x == 0, y >= x + 1)) [[y >= 1]] """ if z3_debug(): _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected") goal = _to_goal(goal) if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, self.ctx) return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx) else: return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx) def __call__(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t(And(x == 0, y >= x + 1)) [[y >= 1]] """ return self.apply(goal, *arguments, **keywords) def help(self): """Display a string containing a description of the available options for the `self` tactic.""" print(Z3_tactic_get_help(self.ctx.ref(), self.tactic)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx) def _to_goal(a): if isinstance(a, BoolRef): goal = Goal(ctx=a.ctx) goal.add(a) return goal else: return a def _to_tactic(t, ctx=None): if isinstance(t, Tactic): return t else: return Tactic(t, ctx) def _and_then(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def _or_else(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def AndThen(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. >>> x, y = Ints('x y') >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get("ctx", None) num = len(ts) r = ts[0] for i in range(num - 1): r = _and_then(r, ts[i + 1], ctx) return r def Then(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks). >>> x, y = Ints('x y') >>> t = Then(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ return AndThen(*ts, **ks) def OrElse(*ts, **ks): """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = OrElse(Tactic('split-clause'), Tactic('skip')) >>> # Tactic split-clause fails if there is no clause in the given goal. >>> t(x == 0) [[x == 0]] >>> t(Or(x == 0, x == 1)) [[x == 0], [x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get("ctx", None) num = len(ts) r = ts[0] for i in range(num - 1): r = _or_else(r, ts[i + 1], ctx) return r def ParOr(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = ParOr(Tactic('simplify'), Tactic('fail')) >>> t(x + 1 == 2) [[x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = _get_ctx(ks.get("ctx", None)) ts = [_to_tactic(t, ctx) for t in ts] sz = len(ts) _args = (TacticObj * sz)() for i in range(sz): _args[i] = ts[i].tactic return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx) def ParThen(t1, t2, ctx=None): """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel. >>> x, y = Ints('x y') >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values')) >>> t(And(Or(x == 1, x == 2), y == x + 1)) [[x == 1, y == 2], [x == 2, y == 3]] """ t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def ParAndThen(t1, t2, ctx=None): """Alias for ParThen(t1, t2, ctx).""" return ParThen(t1, t2, ctx) def With(t, *args, **keys): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> t = With(Tactic('simplify'), som=True) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ ctx = keys.pop("ctx", None) t = _to_tactic(t, ctx) p = args2params(args, keys, t.ctx) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def WithParams(t, p): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> p = ParamsRef() >>> p.set("som", True) >>> t = WithParams(Tactic('simplify'), p) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ t = _to_tactic(t, None) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def Repeat(t, max=4294967295, ctx=None): """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached. >>> x, y = Ints('x y') >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y) >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) >>> r = t(c) >>> for subgoal in r: print(subgoal) [x == 0, y == 0, x > y] [x == 0, y == 1, x > y] [x == 1, y == 0, x > y] [x == 1, y == 1, x > y] >>> t = Then(t, Tactic('propagate-values')) >>> t(c) [[x == 1, y == 0]] """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx) def TryFor(t, ms, ctx=None): """Return a tactic that applies `t` to a given goal for `ms` milliseconds. If `t` does not terminate in `ms` milliseconds, then it fails. """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx) def tactics(ctx=None): """Return a list of all available tactics in Z3. >>> l = tactics() >>> l.count('simplify') == 1 True """ ctx = _get_ctx(ctx) return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))] def tactic_description(name, ctx=None): """Return a short description for the tactic named `name`. >>> d = tactic_description('simplify') """ ctx = _get_ctx(ctx) return Z3_tactic_get_descr(ctx.ref(), name) def describe_tactics(): """Display a (tabular) description of all available tactics in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for t in tactics(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print("<tr>") even = True print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40))) print("</table>") else: for t in tactics(): print("%s : %s" % (t, tactic_description(t))) class Probe: """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used. """ def __init__(self, probe, ctx=None): self.ctx = _get_ctx(ctx) self.probe = None if isinstance(probe, ProbeObj): self.probe = probe elif isinstance(probe, float): self.probe = Z3_probe_const(self.ctx.ref(), probe) elif _is_int(probe): self.probe = Z3_probe_const(self.ctx.ref(), float(probe)) elif isinstance(probe, bool): if probe: self.probe = Z3_probe_const(self.ctx.ref(), 1.0) else: self.probe = Z3_probe_const(self.ctx.ref(), 0.0) else: if z3_debug(): _z3_assert(isinstance(probe, str), "probe name expected") try: self.probe = Z3_mk_probe(self.ctx.ref(), probe) except Z3Exception: raise Z3Exception("unknown probe '%s'" % probe) Z3_probe_inc_ref(self.ctx.ref(), self.probe) def __deepcopy__(self, memo={}): return Probe(self.probe, self.ctx) def __del__(self): if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None: Z3_probe_dec_ref(self.ctx.ref(), self.probe) def __lt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`. >>> p = Probe('size') < 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __gt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`. >>> p = Probe('size') > 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __le__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`. >>> p = Probe('size') <= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ge__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`. >>> p = Probe('size') >= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __eq__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`. >>> p = Probe('size') == 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ne__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`. >>> p = Probe('size') != 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ p = self.__eq__(other) return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx) def __call__(self, goal): """Evaluate the probe `self` in the given goal. >>> p = Probe('size') >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 2.0 >>> g.add(x < 20) >>> p(g) 3.0 >>> p = Probe('num-consts') >>> p(g) 1.0 >>> p = Probe('is-propositional') >>> p(g) 0.0 >>> p = Probe('is-qflia') >>> p(g) 1.0 """ if z3_debug(): _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected") goal = _to_goal(goal) return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal) def is_probe(p): """Return `True` if `p` is a Z3 probe. >>> is_probe(Int('x')) False >>> is_probe(Probe('memory')) True """ return isinstance(p, Probe) def _to_probe(p, ctx=None): if is_probe(p): return p else: return Probe(p, ctx) def probes(ctx=None): """Return a list of all available probes in Z3. >>> l = probes() >>> l.count('memory') == 1 True """ ctx = _get_ctx(ctx) return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))] def probe_description(name, ctx=None): """Return a short description for the probe named `name`. >>> d = probe_description('memory') """ ctx = _get_ctx(ctx) return Z3_probe_get_descr(ctx.ref(), name) def describe_probes(): """Display a (tabular) description of all available probes in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for p in probes(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print("<tr>") even = True print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40))) print("</table>") else: for p in probes(): print("%s : %s" % (p, probe_description(p))) def _probe_nary(f, args, ctx): if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") num = len(args) r = _to_probe(args[0], ctx) for i in range(num - 1): r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx) return r def _probe_and(args, ctx): return _probe_nary(Z3_probe_and, args, ctx) def _probe_or(args, ctx): return _probe_nary(Z3_probe_or, args, ctx) def FailIf(p, ctx=None): """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal. >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx) def When(p, t, ctx=None): """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. >>> t = When(Probe('size') > 2, Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) t = _to_tactic(t, ctx) return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx) def Cond(p, t1, t2, ctx=None): """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise. >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt')) """ p = _to_probe(p, ctx) t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx) ######################################### # # Utils # ######################################### def simplify(a, *arguments, **keywords): """Simplify the expression `a` using the given options. This function has many options. Use `help_simplify` to obtain the complete list. >>> x = Int('x') >>> y = Int('y') >>> simplify(x + 1 + y + x + 1) 2 + 2*x + y >>> simplify((x + 1)*(y + 1), som=True) 1 + x + y + x*y >>> simplify(Distinct(x, y, 1), blast_distinct=True) And(Not(x == y), Not(x == 1), Not(y == 1)) >>> simplify(And(x == 0, y == 1), elim_and=True) Not(Or(Not(x == 0), Not(y == 1))) """ if z3_debug(): _z3_assert(is_expr(a), "Z3 expression expected") if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, a.ctx) return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx) else: return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx) def help_simplify(): """Return a string describing all options available for Z3 `simplify` procedure.""" print(Z3_simplify_get_help(main_ctx().ref())) def simplify_param_descrs(): """Return the set of parameter descriptions for Z3 `simplify` procedure.""" return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx()) def substitute(t, *m): """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to. >>> x = Int('x') >>> y = Int('y') >>> substitute(x + 1, (x, y + 1)) y + 1 + 1 >>> f = Function('f', IntSort(), IntSort()) >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1))) 1 + 1 """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert( all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, expression pairs expected.") _z3_assert( all([p[0].sort().eq(p[1].sort()) for p in m]), 'Z3 invalid substitution, mismatching "from" and "to" sorts.') num = len(m) _from = (Ast * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_ast() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def substitute_vars(t, *m): """Substitute the free variables in t with the expression in m. >>> v0 = Var(0, IntSort()) >>> v1 = Var(1, IntSort()) >>> x = Int('x') >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # replace v0 with x+1 and v1 with x >>> substitute_vars(f(v0, v1), x + 1, x) f(x + 1, x) """ if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.") num = len(m) _to = (Ast * num)() for i in range(num): _to[i] = m[i].as_ast() return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx) def substitute_funs(t, *m): """Apply substitution m on t, m is a list of pairs of a function and expression (from, to) Every occurrence in to of the function from is replaced with the expression to. The expression to can have free variables, that refer to the arguments of from. For examples, see """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, funcion pairs expected.") num = len(m) _from = (FuncDecl * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_func_decl() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def Sum(*args): """Create the sum of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Sum(a, b, c) a + b + c >>> Sum([a, b, c]) a + b + c >>> A = IntVector('a', 5) >>> Sum(A) a__0 + a__1 + a__2 + a__3 + a__4 """ args = _get_args(args) if len(args) == 0: return 0 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a + b, args, 0) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a + b, args, 0) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx) def Product(*args): """Create the product of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Product(a, b, c) a*b*c >>> Product([a, b, c]) a*b*c >>> A = IntVector('a', 5) >>> Product(A) a__0*a__1*a__2*a__3*a__4 """ args = _get_args(args) if len(args) == 0: return 1 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a * b, args, 1) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a * b, args, 1) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx) def Abs(arg): """Create the absolute value of an arithmetic expression""" return If(arg > 0, arg, -arg) def AtMost(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtMost(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx) def AtLeast(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtLeast(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx) def _reorder_pb_arg(arg): a, b = arg if not _is_int(b) and _is_int(a): return b, a return arg def _pb_args_coeffs(args, default_ctx=None): args = _get_args_ast_list(args) if len(args) == 0: return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)() args = [_reorder_pb_arg(arg) for arg in args] args, coeffs = zip(*args) if z3_debug(): _z3_assert(len(args) > 0, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) _coeffs = (ctypes.c_int * len(coeffs))() for i in range(len(coeffs)): _z3_check_cint_overflow(coeffs[i], "coefficient") _coeffs[i] = coeffs[i] return ctx, sz, _args, _coeffs, args def PbLe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbLe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbGe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbGe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbEq(args, k, ctx=None): """Create a Pseudo-Boolean equality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbEq(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx) def solve(*args, **keywords): """Solve the constraints `*args`. This is a simple function for creating demonstrations. It creates a solver, configure it using the options in `keywords`, adds the constraints in `args`, and invokes check. >>> a = Int('a') >>> solve(a > 0, a < 2) [a = 1] """ show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: print(s.model()) def solve_using(s, *args, **keywords): """Solve the constraints `*args` using solver `s`. This is a simple function for creating demonstrations. It is similar to `solve`, but it uses the given solver `s`. It configures solver `s` using the options in `keywords`, adds the constraints in `args`, and invokes check. """ show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: print("Problem:") print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: if show: print("Solution:") print(s.model()) def prove(claim, show=False, **keywords): """Try to prove the given claim. This is a simple function for creating demonstrations. It tries to prove `claim` by showing the negation is unsatisfiable. >>> p, q = Bools('p q') >>> prove(Not(And(p, q)) == Or(Not(p), Not(q))) proved """ if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if show: print(s) r = s.check() if r == unsat: print("proved") elif r == unknown: print("failed to prove") print(s.model()) else: print("counterexample") print(s.model()) def _solve_html(*args, **keywords): """Version of function `solve` that renders HTML output.""" show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if show: print("<b>Solution:</b>") print(s.model()) def _solve_using_html(s, *args, **keywords): """Version of function `solve_using` that renders HTML.""" show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if show: print("<b>Solution:</b>") print(s.model()) def _prove_html(claim, show=False, **keywords): """Version of function `prove` that renders HTML.""" if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if show: print(s) r = s.check() if r == unsat: print("<b>proved</b>") elif r == unknown: print("<b>failed to prove</b>") print(s.model()) else: print("<b>counterexample</b>") print(s.model()) def _dict2sarray(sorts, ctx): sz = len(sorts) _names = (Symbol * sz)() _sorts = (Sort * sz)() i = 0 for k in sorts: v = sorts[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_sort(v), "Z3 sort expected") _names[i] = to_symbol(k, ctx) _sorts[i] = v.ast i = i + 1 return sz, _names, _sorts def _dict2darray(decls, ctx): sz = len(decls) _names = (Symbol * sz)() _decls = (FuncDecl * sz)() i = 0 for k in decls: v = decls[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected") _names[i] = to_symbol(k, ctx) if is_const(v): _decls[i] = v.decl().ast else: _decls[i] = v.ast i = i + 1 return sz, _names, _decls class ParserContext: def __init__(self, ctx= None): self.ctx = _get_ctx(ctx) self.pctx = Z3_mk_parser_context(self.ctx.ref()) Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx) def __del__(self): if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None: Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx) self.pctx = None def add_sort(self, sort): Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast()) def add_decl(self, decl): Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast()) def from_string(self, s): return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx) def parse_smt2_string(s, sorts={}, decls={}, ctx=None): """Parse a string in SMT 2.0 format using the given sorts and decls. The arguments sorts and decls are Python dictionaries used to initialize the symbol table used for the SMT 2.0 parser. >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))') [x > 0, x < 10] >>> x, y = Ints('x y') >>> f = Function('f', IntSort(), IntSort()) >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f}) [x + f(y) > 0] >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() }) [a > 0] """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) def parse_smt2_file(f, sorts={}, decls={}, ctx=None): """Parse a file in SMT 2.0 format using the given sorts and decls. This function is similar to parse_smt2_string(). """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) ######################################### # # Floating-Point Arithmetic # ######################################### # Global default rounding mode _dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN _dflt_fpsort_ebits = 11 _dflt_fpsort_sbits = 53 def get_default_rounding_mode(ctx=None): """Retrieves the global default rounding mode.""" global _dflt_rounding_mode if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO: return RTZ(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE: return RTN(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE: return RTP(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: return RNE(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: return RNA(ctx) _ROUNDING_MODES = frozenset({ Z3_OP_FPA_RM_TOWARD_ZERO, Z3_OP_FPA_RM_TOWARD_NEGATIVE, Z3_OP_FPA_RM_TOWARD_POSITIVE, Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN, Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY }) def set_default_rounding_mode(rm, ctx=None): global _dflt_rounding_mode if is_fprm_value(rm): _dflt_rounding_mode = rm.decl().kind() else: _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode") _dflt_rounding_mode = rm def get_default_fp_sort(ctx=None): return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx) def set_default_fp_sort(ebits, sbits, ctx=None): global _dflt_fpsort_ebits global _dflt_fpsort_sbits _dflt_fpsort_ebits = ebits _dflt_fpsort_sbits = sbits def _dflt_rm(ctx=None): return get_default_rounding_mode(ctx) def _dflt_fps(ctx=None): return get_default_fp_sort(ctx) def _coerce_fp_expr_list(alist, ctx): first_fp_sort = None for a in alist: if is_fp(a): if first_fp_sort is None: first_fp_sort = a.sort() elif first_fp_sort == a.sort(): pass # OK, same as before else: # we saw at least 2 different float sorts; something will # throw a sort mismatch later, for now assume None. first_fp_sort = None break r = [] for i in range(len(alist)): a = alist[i] is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")") if is_repr or _is_int(a) or isinstance(a, (float, bool)): r.append(FPVal(a, None, first_fp_sort, ctx)) else: r.append(a) return _coerce_expr_list(r, ctx) # FP Sorts class FPSortRef(SortRef): """Floating-point sort.""" def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast)) def sbits(self): """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast)) def cast(self, val): """Try to cast `val` as a floating-point expression. >>> b = FPSort(8, 24) >>> b.cast(1.0) 1 >>> b.cast(1.0).sexpr() '(fp #b0 #x7f #b00000000000000000000000)' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") return val else: return FPVal(val, None, self, self.ctx) def Float16(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx) def FloatHalf(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx) def Float32(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx) def FloatSingle(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) def Float64(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx) def FloatDouble(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) def Float128(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx) def FloatQuadruple(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx) class FPRMSortRef(SortRef): """"Floating-point rounding mode sort.""" def is_fp_sort(s): """Return True if `s` is a Z3 floating-point sort. >>> is_fp_sort(FPSort(8, 24)) True >>> is_fp_sort(IntSort()) False """ return isinstance(s, FPSortRef) def is_fprm_sort(s): """Return True if `s` is a Z3 floating-point rounding mode sort. >>> is_fprm_sort(FPSort(8, 24)) False >>> is_fprm_sort(RNE().sort()) True """ return isinstance(s, FPRMSortRef) # FP Expressions class FPRef(ExprRef): """Floating-point expressions.""" def sort(self): """Return the sort of the floating-point expression `self`. >>> x = FP('1.0', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sort() == FPSort(8, 24) True """ return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return self.sort().ebits() def sbits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return self.sort().sbits() def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return fpLEQ(self, other, self.ctx) def __lt__(self, other): return fpLT(self, other, self.ctx) def __ge__(self, other): return fpGEQ(self, other, self.ctx) def __gt__(self, other): return fpGT(self, other, self.ctx) def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x + y x + y >>> (x + y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 + x 1.25*(2**3) + x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x - y x - y >>> (x - y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 - x 1.25*(2**3) - x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> (x * y).sort() FPSort(8, 24) >>> 10 * y 1.25*(2**3) * y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> x * 10 x * 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __pos__(self): """Create the Z3 expression `+self`.""" return self def __neg__(self): """Create the Z3 expression `-self`. >>> x = FP('x', Float32()) >>> -x -x """ return fpNeg(self) def __div__(self, other): """Create the Z3 expression `self / other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> (x / y).sort() FPSort(8, 24) >>> 10 / y 1.25*(2**3) / y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __rdiv__(self, other): """Create the Z3 expression `other / self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> x / 10 x / 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __truediv__(self, other): """Create the Z3 expression division `self / other`.""" return self.__div__(other) def __rtruediv__(self, other): """Create the Z3 expression division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression mod `self % other`.""" return fpRem(self, other) def __rmod__(self, other): """Create the Z3 expression mod `other % self`.""" return fpRem(other, self) class FPRMRef(ExprRef): """Floating-point rounding mode expressions""" def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def RoundNearestTiesToEven(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RNE(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RoundNearestTiesToAway(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RNA(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RoundTowardPositive(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RTP(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RoundTowardNegative(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RTN(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RoundTowardZero(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def RTZ(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def is_fprm(a): """Return `True` if `a` is a Z3 floating-point rounding mode expression. >>> rm = RNE() >>> is_fprm(rm) True >>> rm = 1.0 >>> is_fprm(rm) False """ return isinstance(a, FPRMRef) def is_fprm_value(a): """Return `True` if `a` is a Z3 floating-point rounding mode numeral value.""" return is_fprm(a) and _is_numeral(a.ctx, a.ast) # FP Numerals class FPNumRef(FPRef): """The sign of the numeral. >>> x = FPVal(+1.0, FPSort(8, 24)) >>> x.sign() False >>> x = FPVal(-1.0, FPSort(8, 24)) >>> x.sign() True """ def sign(self): num = (ctypes.c_int)() nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num)) if nsign is False: raise Z3Exception("error retrieving the sign of a numeral.") return num.value != 0 """The sign of a floating-point numeral as a bit-vector expression. Remark: NaN's are invalid arguments. """ def sign_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The significand of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand() 1.25 """ def significand(self): return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast()) """The significand of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand_as_long() 1.25 """ def significand_as_long(self): ptr = (ctypes.c_ulonglong * 1)() if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr): raise Z3Exception("error retrieving the significand of a numeral.") return ptr[0] """The significand of the numeral as a bit-vector expression. Remark: NaN are invalid arguments. """ def significand_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The exponent of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent() 1 """ def exponent(self, biased=True): return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased) """The exponent of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent_as_long() 1 """ def exponent_as_long(self, biased=True): ptr = (ctypes.c_longlong * 1)() if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased): raise Z3Exception("error retrieving the exponent of a numeral.") return ptr[0] """The exponent of the numeral as a bit-vector expression. Remark: NaNs are invalid arguments. """ def exponent_as_bv(self, biased=True): return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx) """Indicates whether the numeral is a NaN.""" def isNaN(self): return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +oo or -oo.""" def isInf(self): return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +zero or -zero.""" def isZero(self): return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is normal.""" def isNormal(self): return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is subnormal.""" def isSubnormal(self): return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is positive.""" def isPositive(self): return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is negative.""" def isNegative(self): return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast()) """ The string representation of the numeral. >>> x = FPVal(20, FPSort(8, 24)) >>> x.as_string() 1.25*(2**4) """ def as_string(self): s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast()) return ("FPVal(%s, %s)" % (s, self.sort())) def is_fp(a): """Return `True` if `a` is a Z3 floating-point expression. >>> b = FP('b', FPSort(8, 24)) >>> is_fp(b) True >>> is_fp(b + 1.0) True >>> is_fp(Int('x')) False """ return isinstance(a, FPRef) def is_fp_value(a): """Return `True` if `a` is a Z3 floating-point numeral value. >>> b = FP('b', FPSort(8, 24)) >>> is_fp_value(b) False >>> b = FPVal(1.0, FPSort(8, 24)) >>> b 1 >>> is_fp_value(b) True """ return is_fp(a) and _is_numeral(a.ctx, a.ast) def FPSort(ebits, sbits, ctx=None): """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used. >>> Single = FPSort(8, 24) >>> Double = FPSort(11, 53) >>> Single FPSort(8, 24) >>> x = Const('x', Single) >>> eq(x, FP('x', FPSort(8, 24))) True """ ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx) def _to_float_str(val, exp=0): if isinstance(val, float): if math.isnan(val): res = "NaN" elif val == 0.0: sone = math.copysign(1.0, val) if sone < 0.0: return "-0.0" else: return "+0.0" elif val == float("+inf"): res = "+oo" elif val == float("-inf"): res = "-oo" else: v = val.as_integer_ratio() num = v[0] den = v[1] rvs = str(num) + "/" + str(den) res = rvs + "p" + _to_int_str(exp) elif isinstance(val, bool): if val: res = "1.0" else: res = "0.0" elif _is_int(val): res = str(val) elif isinstance(val, str): inx = val.find("*(2**") if inx == -1: res = val elif val[-1] == ")": res = val[0:inx] exp = str(int(val[inx + 5:-1]) + int(exp)) else: _z3_assert(False, "String does not have floating-point numeral form.") elif z3_debug(): _z3_assert(False, "Python value cannot be used to create floating-point numerals.") if exp == 0: return res else: return res + "p" + exp def fpNaN(s): """Create a Z3 floating-point NaN term. >>> s = FPSort(8, 24) >>> set_fpa_pretty(True) >>> fpNaN(s) NaN >>> pb = get_fpa_pretty() >>> set_fpa_pretty(False) >>> fpNaN(s) fpNaN(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx) def fpPlusInfinity(s): """Create a Z3 floating-point +oo term. >>> s = FPSort(8, 24) >>> pb = get_fpa_pretty() >>> set_fpa_pretty(True) >>> fpPlusInfinity(s) +oo >>> set_fpa_pretty(False) >>> fpPlusInfinity(s) fpPlusInfinity(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusInfinity(s): """Create a Z3 floating-point -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx) def fpInfinity(s, negative): """Create a Z3 floating-point +oo or -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) def fpPlusZero(s): """Create a Z3 floating-point +0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusZero(s): """Create a Z3 floating-point -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx) def fpZero(s, negative): """Create a Z3 floating-point +0.0 or -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx) def FPVal(sig, exp=None, fps=None, ctx=None): """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used. >>> v = FPVal(20.0, FPSort(8, 24)) >>> v 1.25*(2**4) >>> print("0x%.8x" % v.exponent_as_long(False)) 0x00000004 >>> v = FPVal(2.25, FPSort(8, 24)) >>> v 1.125*(2**1) >>> v = FPVal(-2.25, FPSort(8, 24)) >>> v -1.125*(2**1) >>> FPVal(-0.0, FPSort(8, 24)) -0.0 >>> FPVal(0.0, FPSort(8, 24)) +0.0 >>> FPVal(+0.0, FPSort(8, 24)) +0.0 """ ctx = _get_ctx(ctx) if is_fp_sort(exp): fps = exp exp = None elif fps is None: fps = _dflt_fps(ctx) _z3_assert(is_fp_sort(fps), "sort mismatch") if exp is None: exp = 0 val = _to_float_str(sig) if val == "NaN" or val == "nan": return fpNaN(fps) elif val == "-0.0": return fpMinusZero(fps) elif val == "0.0" or val == "+0.0": return fpPlusZero(fps) elif val == "+oo" or val == "+inf" or val == "+Inf": return fpPlusInfinity(fps) elif val == "-oo" or val == "-inf" or val == "-Inf": return fpMinusInfinity(fps) else: return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx) def FP(name, fpsort, ctx=None): """Return a floating-point constant named `name`. `fpsort` is the floating-point sort. If `ctx=None`, then the global context is used. >>> x = FP('x', FPSort(8, 24)) >>> is_fp(x) True >>> x.ebits() 8 >>> x.sort() FPSort(8, 24) >>> word = FPSort(8, 24) >>> x2 = FP('x', word) >>> eq(x, x2) True """ if isinstance(fpsort, FPSortRef) and ctx is None: ctx = fpsort.ctx else: ctx = _get_ctx(ctx) return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx) def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) x + y * z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [FP(name, fpsort, ctx) for name in names] def fpAbs(a, ctx=None): """Create a Z3 floating-point absolute value expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FPVal(1.0, s) >>> fpAbs(x) fpAbs(1) >>> y = FPVal(-20.0, s) >>> y -1.25*(2**4) >>> fpAbs(y) fpAbs(-1.25*(2**4)) >>> fpAbs(-1.25*(2**4)) fpAbs(-1.25*(2**4)) >>> fpAbs(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx) def fpNeg(a, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx) def _mk_fp_unary(f, rm, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx) def _mk_fp_unary_pred(f, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast()), ctx) def _mk_fp_bin(f, rm, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_norm(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_pred(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_tern(f, rm, a, b, c, ctx): ctx = _get_ctx(ctx) [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b) or is_fp( c), "Second, third or fourth argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def fpAdd(rm, a, b, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpAdd(rm, x, y) x + y >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ fpAdd(RTZ(), x, y) >>> fpAdd(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx) def fpSub(rm, a, b, ctx=None): """Create a Z3 floating-point subtraction expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpSub(rm, x, y) x - y >>> fpSub(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx) def fpMul(rm, a, b, ctx=None): """Create a Z3 floating-point multiplication expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMul(rm, x, y) x * y >>> fpMul(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx) def fpDiv(rm, a, b, ctx=None): """Create a Z3 floating-point division expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpDiv(rm, x, y) x / y >>> fpDiv(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx) def fpRem(a, b, ctx=None): """Create a Z3 floating-point remainder expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpRem(x, y) fpRem(x, y) >>> fpRem(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx) def fpMin(a, b, ctx=None): """Create a Z3 floating-point minimum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMin(x, y) fpMin(x, y) >>> fpMin(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx) def fpMax(a, b, ctx=None): """Create a Z3 floating-point maximum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMax(x, y) fpMax(x, y) >>> fpMax(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx) def fpFMA(rm, a, b, c, ctx=None): """Create a Z3 floating-point fused multiply-add expression. """ return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx) def fpSqrt(rm, a, ctx=None): """Create a Z3 floating-point square root expression. """ return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx) def fpRoundToIntegral(rm, a, ctx=None): """Create a Z3 floating-point roundToIntegral expression. """ return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx) def fpIsNaN(a, ctx=None): """Create a Z3 floating-point isNaN expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpIsNaN(x) fpIsNaN(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx) def fpIsInf(a, ctx=None): """Create a Z3 floating-point isInfinite expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> fpIsInf(x) fpIsInf(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx) def fpIsZero(a, ctx=None): """Create a Z3 floating-point isZero expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx) def fpIsNormal(a, ctx=None): """Create a Z3 floating-point isNormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) def fpIsSubnormal(a, ctx=None): """Create a Z3 floating-point isSubnormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx) def fpIsNegative(a, ctx=None): """Create a Z3 floating-point isNegative expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx) def fpIsPositive(a, ctx=None): """Create a Z3 floating-point isPositive expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx) def _check_fp_args(a, b): if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") def fpLT(a, b, ctx=None): """Create the Z3 floating-point expression `other < self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLT(x, y) x < y >>> (x < y).sexpr() '(fp.lt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx) def fpLEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other <= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLEQ(x, y) x <= y >>> (x <= y).sexpr() '(fp.leq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx) def fpGT(a, b, ctx=None): """Create the Z3 floating-point expression `other > self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGT(x, y) x > y >>> (x > y).sexpr() '(fp.gt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx) def fpGEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other >= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGEQ(x, y) x >= y >>> (x >= y).sexpr() '(fp.geq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx) def fpEQ(a, b, ctx=None): """Create the Z3 floating-point expression `fpEQ(other, self)`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpEQ(x, y) fpEQ(x, y) >>> fpEQ(x, y).sexpr() '(fp.eq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx) def fpNEQ(a, b, ctx=None): """Create the Z3 floating-point expression `Not(fpEQ(other, self))`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpNEQ(x, y) Not(fpEQ(x, y)) >>> (x != y).sexpr() '(distinct x y)' """ return Not(fpEQ(a, b, ctx)) def fpFP(sgn, exp, sig, ctx=None): """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp. >>> s = FPSort(8, 24) >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23)) >>> print(x) fpFP(1, 127, 4194304) >>> xv = FPVal(-1.5, s) >>> print(xv) -1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() sat >>> xv = FPVal(+1.5, s) >>> print(xv) 1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() unsat """ _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch") _z3_assert(sgn.sort().size() == 1, "sort mismatch") ctx = _get_ctx(ctx) _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch") return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx) def fpToFP(a1, a2=None, a3=None, ctx=None): """Create a Z3 floating-point conversion expression from other term sorts to floating-point. From a bit-vector term in IEEE 754-2008 format: >>> x = FPVal(1.0, Float32()) >>> x_bv = fpToIEEEBV(x) >>> simplify(fpToFP(x_bv, Float32())) 1 From a floating-point term with different precision: >>> x = FPVal(1.0, Float32()) >>> x_db = fpToFP(RNE(), x, Float64()) >>> x_db.sort() FPSort(11, 53) From a real term: >>> x_r = RealVal(1.5) >>> simplify(fpToFP(RNE(), x_r, Float32())) 1.5 From a signed bit-vector term: >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> simplify(fpToFP(RNE(), x_signed, Float32())) -1.25*(2**2) """ ctx = _get_ctx(ctx) if is_bv(a1) and is_fp_sort(a2): return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx) elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) else: raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.") def fpBVToFP(v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a bit-vector term to a floating-point term. >>> x_bv = BitVecVal(0x3F800000, 32) >>> x_fp = fpBVToFP(x_bv, Float32()) >>> x_fp fpToFP(1065353216) >>> simplify(x_fp) 1 """ _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx) def fpFPToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a floating-point term to a floating-point term of different precision. >>> x_sgl = FPVal(1.0, Float32()) >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64()) >>> x_dbl fpToFP(RNE(), 1) >>> simplify(x_dbl) 1 >>> x_dbl.sort() FPSort(11, 53) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpRealToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a real term to a floating-point term. >>> x_r = RealVal(1.5) >>> x_fp = fpRealToFP(RNE(), x_r, Float32()) >>> x_fp fpToFP(RNE(), 3/2) >>> simplify(x_fp) 1.5 """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpSignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a signed bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFP(RNE(), 4294967291) >>> simplify(x_fp) -1.25*(2**2) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpUnsignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFPUnsigned(RNE(), 4294967291) >>> simplify(x_fp) 1*(2**32) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpToFPUnsigned(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression.""" if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx) def fpToSBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToSBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToUBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToUBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToReal(x, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to real. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToReal(x) >>> print(is_fp(x)) True >>> print(is_real(y)) True >>> print(is_fp(y)) False >>> print(is_real(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx) def fpToIEEEBV(x, ctx=None): """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format. The size of the resulting bit-vector is automatically determined. Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion knows only one NaN and it will always produce the same bit-vector representation of that NaN. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToIEEEBV(x) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx) ######################################### # # Strings, Sequences and Regular expressions # ######################################### class SeqSortRef(SortRef): """Sequence sort.""" def is_string(self): """Determine if sort is a string >>> s = StringSort() >>> s.is_string() True >>> s = SeqSort(IntSort()) >>> s.is_string() False """ return Z3_is_string_sort(self.ctx_ref(), self.ast) def basis(self): return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx) class CharSortRef(SortRef): """Character sort.""" def StringSort(ctx=None): """Create a string sort >>> s = StringSort() >>> print(s) String """ ctx = _get_ctx(ctx) return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx) def CharSort(ctx=None): """Create a character sort >>> ch = CharSort() >>> print(ch) Char """ ctx = _get_ctx(ctx) return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx) def SeqSort(s): """Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True """ return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx) class SeqRef(ExprRef): """Sequence expression.""" def sort(self): return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __add__(self, other): return Concat(self, other) def __radd__(self, other): return Concat(other, self) def __getitem__(self, i): if _is_int(i): i = IntVal(i, self.ctx) return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def at(self, i): if _is_int(i): i = IntVal(i, self.ctx) return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def is_string(self): return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast())) def is_string_value(self): return Z3_is_string(self.ctx_ref(), self.as_ast()) def as_string(self): """Return a string representation of sequence expression.""" if self.is_string_value(): string_length = ctypes.c_uint() chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length)) return string_at(chars, size=string_length.value).decode("latin-1") return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __lt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __ge__(self, other): return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def __gt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def _coerce_char(ch, ctx=None): if isinstance(ch, str): ctx = _get_ctx(ctx) ch = CharVal(ch, ctx) if not is_expr(ch): raise Z3Exception("Character expression expected") return ch class CharRef(ExprRef): """Character expression.""" def __le__(self, other): other = _coerce_char(other, self.ctx) return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def to_int(self): return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx) def to_bv(self): return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx) def is_digit(self): return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx) def CharVal(ch, ctx=None): ctx = _get_ctx(ctx) if isinstance(ch, str): ch = ord(ch) if not isinstance(ch, int): raise Z3Exception("character value should be an ordinal") return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx) def CharFromBv(ch, ctx=None): if not is_expr(ch): raise Z3Expression("Bit-vector expression needed") return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx) def CharToBv(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_bv() def CharToInt(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_int() def CharIsDigit(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.is_digit() def _coerce_seq(s, ctx=None): if isinstance(s, str): ctx = _get_ctx(ctx) s = StringVal(s, ctx) if not is_expr(s): raise Z3Exception("Non-expression passed as a sequence") if not is_seq(s): raise Z3Exception("Non-sequence passed as a sequence") return s def _get_ctx2(a, b, ctx=None): if is_expr(a): return a.ctx if is_expr(b): return b.ctx if ctx is None: ctx = main_ctx() return ctx def is_seq(a): """Return `True` if `a` is a Z3 sequence expression. >>> print (is_seq(Unit(IntVal(0)))) True >>> print (is_seq(StringVal("abc"))) True """ return isinstance(a, SeqRef) def is_string(a): """Return `True` if `a` is a Z3 string expression. >>> print (is_string(StringVal("ab"))) True """ return isinstance(a, SeqRef) and a.is_string() def is_string_value(a): """return 'True' if 'a' is a Z3 string constant expression. >>> print (is_string_value(StringVal("a"))) True >>> print (is_string_value(StringVal("a") + StringVal("b"))) False """ return isinstance(a, SeqRef) and a.is_string_value() def StringVal(s, ctx=None): """create a string expression""" s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s) ctx = _get_ctx(ctx) return SeqRef(Z3_mk_string(ctx.ref(), s), ctx) def String(name, ctx=None): """Return a string constant named `name`. If `ctx=None`, then the global context is used. >>> x = String('x') """ ctx = _get_ctx(ctx) return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx) def Strings(names, ctx=None): """Return a tuple of String constants. """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [String(name, ctx) for name in names] def SubString(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def SubSeq(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def Empty(s): """Create the empty sequence of the given sort >>> e = Empty(StringSort()) >>> e2 = StringVal("") >>> print(e.eq(e2)) True >>> e3 = Empty(SeqSort(IntSort())) >>> print(e3) Empty(Seq(Int)) >>> e4 = Empty(ReSort(SeqSort(IntSort()))) >>> print(e4) Empty(ReSort(Seq(Int))) """ if isinstance(s, SeqSortRef): return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx) if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty") def Full(s): """Create the regular expression that accepts the universal language >>> e = Full(ReSort(SeqSort(IntSort()))) >>> print(e) Full(ReSort(Seq(Int))) >>> e1 = Full(ReSort(StringSort())) >>> print(e1) Full(ReSort(String)) """ if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Full") def Unit(a): """Create a singleton sequence""" return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx) def PrefixOf(a, b): """Check if 'a' is a prefix of 'b' >>> s1 = PrefixOf("ab", "abc") >>> simplify(s1) True >>> s2 = PrefixOf("bc", "abc") >>> simplify(s2) False """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SuffixOf(a, b): """Check if 'a' is a suffix of 'b' >>> s1 = SuffixOf("ab", "abc") >>> simplify(s1) False >>> s2 = SuffixOf("bc", "abc") >>> simplify(s2) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Contains(a, b): """Check if 'a' contains 'b' >>> s1 = Contains("abc", "ab") >>> simplify(s1) True >>> s2 = Contains("abc", "bc") >>> simplify(s2) True >>> x, y, z = Strings('x y z') >>> s3 = Contains(Concat(x,y,z), y) >>> simplify(s3) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Replace(s, src, dst): """Replace the first occurrence of 'src' by 'dst' in 's' >>> r = Replace("aaa", "a", "b") >>> simplify(r) "baa" """ ctx = _get_ctx2(dst, s) if ctx is None and is_expr(src): ctx = src.ctx src = _coerce_seq(src, ctx) dst = _coerce_seq(dst, ctx) s = _coerce_seq(s, ctx) return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx) def IndexOf(s, substr, offset=None): """Retrieve the index of substring within a string starting at a specified offset. >>> simplify(IndexOf("abcabc", "bc", 0)) 1 >>> simplify(IndexOf("abcabc", "bc", 2)) 4 """ if offset is None: offset = IntVal(0) ctx = None if is_expr(offset): ctx = offset.ctx ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) if _is_int(offset): offset = IntVal(offset, ctx) return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) def LastIndexOf(s, substr): """Retrieve the last index of substring within a string""" ctx = None ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx) def Length(s): """Obtain the length of a sequence 's' >>> l = Length(StringVal("abc")) >>> simplify(l) 3 """ s = _coerce_seq(s) return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx) def StrToInt(s): """Convert string expression to integer >>> a = StrToInt("1") >>> simplify(1 == a) True >>> b = StrToInt("2") >>> simplify(1 == b) False >>> c = StrToInt(IntToStr(2)) >>> simplify(1 == c) False """ s = _coerce_seq(s) return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx) def IntToStr(s): """Convert integer expression to string""" if not is_expr(s): s = _py2expr(s) return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx) def StrToCode(s): """Convert a unit length string to integer code""" if not is_expr(s): s = _py2expr(s) return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx) def StrFromCode(c): """Convert code to a string""" if not is_expr(c): c = _py2expr(c) return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx) def Re(s, ctx=None): """The regular expression that accepts sequence 's' >>> s1 = Re("ab") >>> s2 = Re(StringVal("ab")) >>> s3 = Re(Unit(BoolVal(True))) """ s = _coerce_seq(s, ctx) return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx) # Regular expressions class ReSortRef(SortRef): """Regular expression sort.""" def basis(self): return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx) def ReSort(s): if is_ast(s): return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx) if s is None or isinstance(s, Context): ctx = _get_ctx(s) return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx) raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument") class ReRef(ExprRef): """Regular expressions.""" def __add__(self, other): return Union(self, other) def is_re(s): return isinstance(s, ReRef) def InRe(s, re): """Create regular expression membership test >>> re = Union(Re("a"),Re("b")) >>> print (simplify(InRe("a", re))) True >>> print (simplify(InRe("b", re))) True >>> print (simplify(InRe("c", re))) False """ s = _coerce_seq(s, re.ctx) return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx) def Union(*args): """Create union of regular expressions. >>> re = Union(Re("a"), Re("b"), Re("c")) >>> print (simplify(InRe("d", re))) False """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx) def Intersect(*args): """Create intersection of regular expressions. >>> re = Intersect(Re("a"), Re("b"), Re("c")) """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx) def Plus(re): """Create the regular expression accepting one or more repetitions of argument. >>> re = Plus(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx) def Option(re): """Create the regular expression that optionally accepts the argument. >>> re = Option(Re("a")) >>> print(simplify(InRe("a", re))) True >>> print(simplify(InRe("", re))) True >>> print(simplify(InRe("aa", re))) False """ return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx) def Complement(re): """Create the complement regular expression.""" return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx) def Star(re): """Create the regular expression accepting zero or more repetitions of argument. >>> re = Star(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) True """ return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx) def Loop(re, lo, hi=0): """Create the regular expression accepting between a lower and upper bound repetitions >>> re = Loop(Re("a"), 1, 3) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("aaaa", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx) def Range(lo, hi, ctx=None): """Create the range regular expression over two sequences of length 1 >>> range = Range("a","z") >>> print(simplify(InRe("b", range))) True >>> print(simplify(InRe("bb", range))) False """ lo = _coerce_seq(lo, ctx) hi = _coerce_seq(hi, ctx) return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx) def Diff(a, b, ctx=None): """Create the difference regular expression """ return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx) def AllChar(regex_sort, ctx=None): """Create a regular expression that accepts all single character strings """ return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx) # Special Relations def PartialOrder(a, index): return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx) def LinearOrder(a, index): return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx) def TreeOrder(a, index): return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx) def PiecewiseLinearOrder(a, index): return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx) def TransitiveClosure(f): """Given a binary relation R, such that the two arguments have the same sort create the transitive closure relation R+. The transitive closure R+ is a new relation. """ return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx) def to_Ast(ptr,): ast = Ast(ptr) super(ctypes.c_void_p, ast).__init__(ptr) return ast def to_ContextObj(ptr,): ctx = ContextObj(ptr) super(ctypes.c_void_p, ctx).__init__(ptr) return ctx def to_AstVectorObj(ptr,): v = AstVectorObj(ptr) super(ctypes.c_void_p, v).__init__(ptr) return v # NB. my-hacky-class only works for a single instance of OnClause # it should be replaced with a proper correlation between OnClause # and object references that can be passed over the FFI. # for UserPropagator we use a global dictionary, which isn't great code. _my_hacky_class = None def on_clause_eh(ctx, p, clause): onc = _my_hacky_class p = _to_expr_ref(to_Ast(p), onc.ctx) clause = AstVector(to_AstVectorObj(clause), onc.ctx) onc.on_clause(p, clause) _on_clause_eh = Z3_on_clause_eh(on_clause_eh) class OnClause: def __init__(self, s, on_clause): self.s = s self.ctx = s.ctx self.on_clause = on_clause self.idx = 22 global _my_hacky_class _my_hacky_class = self Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh) class PropClosures: def __init__(self): self.bases = {} self.lock = None def set_threaded(self): if self.lock is None: import threading self.lock = threading.Lock() def get(self, ctx): if self.lock: with self.lock: r = self.bases[ctx] else: r = self.bases[ctx] return r def set(self, ctx, r): if self.lock: with self.lock: self.bases[ctx] = r else: self.bases[ctx] = r def insert(self, r): if self.lock: with self.lock: id = len(self.bases) + 3 self.bases[id] = r else: id = len(self.bases) + 3 self.bases[id] = r return id _prop_closures = None def ensure_prop_closures(): global _prop_closures if _prop_closures is None: _prop_closures = PropClosures() def user_prop_push(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.push() def user_prop_pop(ctx, cb, num_scopes): prop = _prop_closures.get(ctx) prop.cb = cb prop.pop(num_scopes) def user_prop_fresh(ctx, _new_ctx): _prop_closures.set_threaded() prop = _prop_closures.get(ctx) nctx = Context() Z3_del_context(nctx.ctx) new_ctx = to_ContextObj(_new_ctx) nctx.ctx = new_ctx nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler) nctx.owner = False new_prop = prop.fresh(nctx) _prop_closures.set(new_prop.id, new_prop) return new_prop.id def user_prop_fixed(ctx, cb, id, value): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) value = _to_expr_ref(to_Ast(value), prop.ctx()) prop.fixed(id, value) prop.cb = None def user_prop_created(ctx, cb, id): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) prop.created(id) prop.cb = None def user_prop_final(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.final() prop.cb = None def user_prop_eq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.eq(x, y) prop.cb = None def user_prop_diseq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.diseq(x, y) prop.cb = None # TODO The decision callback is not fully implemented. # It needs to handle the ast*, unsigned* idx, and Z3_lbool* def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref): prop = _prop_closures.get(ctx) prop.cb = cb t = _to_expr_ref(to_Ast(t_ref), prop.ctx()) t, idx, phase = prop.decide(t, idx, phase) t_ref = t idx_ref = idx phase_ref = phase prop.cb = None _user_prop_push = Z3_push_eh(user_prop_push) _user_prop_pop = Z3_pop_eh(user_prop_pop) _user_prop_fresh = Z3_fresh_eh(user_prop_fresh) _user_prop_fixed = Z3_fixed_eh(user_prop_fixed) _user_prop_created = Z3_created_eh(user_prop_created) _user_prop_final = Z3_final_eh(user_prop_final) _user_prop_eq = Z3_eq_eh(user_prop_eq) _user_prop_diseq = Z3_eq_eh(user_prop_diseq) _user_prop_decide = Z3_decide_eh(user_prop_decide) def PropagateFunction(name, *sig): """Create a function that gets tracked by user propagator. Every term headed by this function symbol is tracked. If a term is fixed and the fixed callback is registered a callback is invoked that the term headed by this function is fixed. """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) class UserPropagateBase: # # Either solver is set or ctx is set. # Propagators that are created throuh callbacks # to "fresh" inherit the context of that is supplied # as argument to the callback. # This context should not be deleted. It is owned by the solver. # def __init__(self, s, ctx=None): assert s is None or ctx is None ensure_prop_closures() self.solver = s self._ctx = None self.fresh_ctx = None self.cb = None self.id = _prop_closures.insert(self) self.fixed = None self.final = None self.eq = None self.diseq = None self.created = None if ctx: self.fresh_ctx = ctx if s: Z3_solver_propagate_init(self.ctx_ref(), s.solver, ctypes.c_void_p(self.id), _user_prop_push, _user_prop_pop, _user_prop_fresh) def __del__(self): if self._ctx: self._ctx.ctx = None def ctx(self): if self.fresh_ctx: return self.fresh_ctx else: return self.solver.ctx def ctx_ref(self): return self.ctx().ref() def add_fixed(self, fixed): assert not self.fixed assert not self._ctx if self.solver: Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed) self.fixed = fixed def add_created(self, created): assert not self.created assert not self._ctx if self.solver: Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created) self.created = created def add_final(self, final): assert not self.final assert not self._ctx if self.solver: Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final) self.final = final def add_eq(self, eq): assert not self.eq assert not self._ctx if self.solver: Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq) self.eq = eq def add_diseq(self, diseq): assert not self.diseq assert not self._ctx if self.solver: Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq) self.diseq = diseq def add_decide(self, decide): assert not self.decide assert not self._ctx if self.solver: Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide) self.decide = decide def push(self): raise Z3Exception("push needs to be overwritten") def pop(self, num_scopes): raise Z3Exception("pop needs to be overwritten") def fresh(self, new_ctx): raise Z3Exception("fresh needs to be overwritten") def add(self, e): assert not self._ctx if self.solver: Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast) else: Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast) # # Tell the solver to perform the next split on a given term # If the term is a bit-vector the index idx specifies the index of the Boolean variable being # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument. # def next_split(self, t, idx, phase): Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase) # # Propagation can only be invoked as during a fixed or final callback. # def propagate(self, e, ids, eqs=[]): _ids, num_fixed = _to_ast_array(ids) num_eqs = len(eqs) _lhs, _num_lhs = _to_ast_array([x for x, y in eqs]) _rhs, _num_rhs = _to_ast_array([y for x, y in eqs]) Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p( self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast) def conflict(self, deps = [], eqs = []): self.propagate(BoolVal(False, self.ctx()), deps, eqs)
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3.py
z3.py
import sys import io # We want to import submodule z3 here, but there's no way # to do that that works correctly on both Python 2 and 3. if sys.version_info.major < 3: # In Python 2: an implicit-relative import of submodule z3. # In Python 3: an undesirable import of global package z3. import z3 else: # In Python 2: an illegal circular import. # In Python 3: an explicit-relative import of submodule z3. from . import z3 from .z3consts import * from .z3core import * from ctypes import * def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) ############################## # # Configuration # ############################## # Z3 operator names to Z3Py _z3_op_to_str = { Z3_OP_TRUE: "True", Z3_OP_FALSE: "False", Z3_OP_EQ: "==", Z3_OP_DISTINCT: "Distinct", Z3_OP_ITE: "If", Z3_OP_AND: "And", Z3_OP_OR: "Or", Z3_OP_IFF: "==", Z3_OP_XOR: "Xor", Z3_OP_NOT: "Not", Z3_OP_IMPLIES: "Implies", Z3_OP_IDIV: "/", Z3_OP_MOD: "%", Z3_OP_TO_REAL: "ToReal", Z3_OP_TO_INT: "ToInt", Z3_OP_POWER: "**", Z3_OP_IS_INT: "IsInt", Z3_OP_BADD: "+", Z3_OP_BSUB: "-", Z3_OP_BMUL: "*", Z3_OP_BOR: "|", Z3_OP_BAND: "&", Z3_OP_BNOT: "~", Z3_OP_BXOR: "^", Z3_OP_BNEG: "-", Z3_OP_BUDIV: "UDiv", Z3_OP_BSDIV: "/", Z3_OP_BSMOD: "%", Z3_OP_BSREM: "SRem", Z3_OP_BUREM: "URem", Z3_OP_EXT_ROTATE_LEFT: "RotateLeft", Z3_OP_EXT_ROTATE_RIGHT: "RotateRight", Z3_OP_SLEQ: "<=", Z3_OP_SLT: "<", Z3_OP_SGEQ: ">=", Z3_OP_SGT: ">", Z3_OP_ULEQ: "ULE", Z3_OP_ULT: "ULT", Z3_OP_UGEQ: "UGE", Z3_OP_UGT: "UGT", Z3_OP_SIGN_EXT: "SignExt", Z3_OP_ZERO_EXT: "ZeroExt", Z3_OP_REPEAT: "RepeatBitVec", Z3_OP_BASHR: ">>", Z3_OP_BSHL: "<<", Z3_OP_BLSHR: "LShR", Z3_OP_CONCAT: "Concat", Z3_OP_EXTRACT: "Extract", Z3_OP_BV2INT: "BV2Int", Z3_OP_ARRAY_MAP: "Map", Z3_OP_SELECT: "Select", Z3_OP_STORE: "Store", Z3_OP_CONST_ARRAY: "K", Z3_OP_ARRAY_EXT: "Ext", Z3_OP_PB_AT_MOST: "AtMost", Z3_OP_PB_LE: "PbLe", Z3_OP_PB_GE: "PbGe", Z3_OP_PB_EQ: "PbEq", Z3_OP_SEQ_CONCAT: "Concat", Z3_OP_SEQ_PREFIX: "PrefixOf", Z3_OP_SEQ_SUFFIX: "SuffixOf", Z3_OP_SEQ_UNIT: "Unit", Z3_OP_SEQ_CONTAINS: "Contains", Z3_OP_SEQ_REPLACE: "Replace", Z3_OP_SEQ_AT: "At", Z3_OP_SEQ_NTH: "Nth", Z3_OP_SEQ_INDEX: "IndexOf", Z3_OP_SEQ_LAST_INDEX: "LastIndexOf", Z3_OP_SEQ_LENGTH: "Length", Z3_OP_STR_TO_INT: "StrToInt", Z3_OP_INT_TO_STR: "IntToStr", Z3_OP_SEQ_IN_RE: "InRe", Z3_OP_SEQ_TO_RE: "Re", Z3_OP_RE_PLUS: "Plus", Z3_OP_RE_STAR: "Star", Z3_OP_RE_OPTION: "Option", Z3_OP_RE_UNION: "Union", Z3_OP_RE_RANGE: "Range", Z3_OP_RE_INTERSECT: "Intersect", Z3_OP_RE_COMPLEMENT: "Complement", Z3_OP_FPA_IS_NAN: "fpIsNaN", Z3_OP_FPA_IS_INF: "fpIsInf", Z3_OP_FPA_IS_ZERO: "fpIsZero", Z3_OP_FPA_IS_NORMAL: "fpIsNormal", Z3_OP_FPA_IS_SUBNORMAL: "fpIsSubnormal", Z3_OP_FPA_IS_NEGATIVE: "fpIsNegative", Z3_OP_FPA_IS_POSITIVE: "fpIsPositive", } # List of infix operators _z3_infix = [ Z3_OP_EQ, Z3_OP_IFF, Z3_OP_ADD, Z3_OP_SUB, Z3_OP_MUL, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_POWER, Z3_OP_LE, Z3_OP_LT, Z3_OP_GE, Z3_OP_GT, Z3_OP_BADD, Z3_OP_BSUB, Z3_OP_BMUL, Z3_OP_BSDIV, Z3_OP_BSMOD, Z3_OP_BOR, Z3_OP_BAND, Z3_OP_BXOR, Z3_OP_BSDIV, Z3_OP_SLEQ, Z3_OP_SLT, Z3_OP_SGEQ, Z3_OP_SGT, Z3_OP_BASHR, Z3_OP_BSHL, ] _z3_unary = [Z3_OP_UMINUS, Z3_OP_BNOT, Z3_OP_BNEG] # Precedence _z3_precedence = { Z3_OP_POWER: 0, Z3_OP_UMINUS: 1, Z3_OP_BNEG: 1, Z3_OP_BNOT: 1, Z3_OP_MUL: 2, Z3_OP_DIV: 2, Z3_OP_IDIV: 2, Z3_OP_MOD: 2, Z3_OP_BMUL: 2, Z3_OP_BSDIV: 2, Z3_OP_BSMOD: 2, Z3_OP_ADD: 3, Z3_OP_SUB: 3, Z3_OP_BADD: 3, Z3_OP_BSUB: 3, Z3_OP_BASHR: 4, Z3_OP_BSHL: 4, Z3_OP_BAND: 5, Z3_OP_BXOR: 6, Z3_OP_BOR: 7, Z3_OP_LE: 8, Z3_OP_LT: 8, Z3_OP_GE: 8, Z3_OP_GT: 8, Z3_OP_EQ: 8, Z3_OP_SLEQ: 8, Z3_OP_SLT: 8, Z3_OP_SGEQ: 8, Z3_OP_SGT: 8, Z3_OP_IFF: 8, Z3_OP_FPA_NEG: 1, Z3_OP_FPA_MUL: 2, Z3_OP_FPA_DIV: 2, Z3_OP_FPA_REM: 2, Z3_OP_FPA_FMA: 2, Z3_OP_FPA_ADD: 3, Z3_OP_FPA_SUB: 3, Z3_OP_FPA_LE: 8, Z3_OP_FPA_LT: 8, Z3_OP_FPA_GE: 8, Z3_OP_FPA_GT: 8, Z3_OP_FPA_EQ: 8, } # FPA operators _z3_op_to_fpa_normal_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: "RoundNearestTiesToEven()", Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: "RoundNearestTiesToAway()", Z3_OP_FPA_RM_TOWARD_POSITIVE: "RoundTowardPositive()", Z3_OP_FPA_RM_TOWARD_NEGATIVE: "RoundTowardNegative()", Z3_OP_FPA_RM_TOWARD_ZERO: "RoundTowardZero()", Z3_OP_FPA_PLUS_INF: "fpPlusInfinity", Z3_OP_FPA_MINUS_INF: "fpMinusInfinity", Z3_OP_FPA_NAN: "fpNaN", Z3_OP_FPA_PLUS_ZERO: "fpPZero", Z3_OP_FPA_MINUS_ZERO: "fpNZero", Z3_OP_FPA_ADD: "fpAdd", Z3_OP_FPA_SUB: "fpSub", Z3_OP_FPA_NEG: "fpNeg", Z3_OP_FPA_MUL: "fpMul", Z3_OP_FPA_DIV: "fpDiv", Z3_OP_FPA_REM: "fpRem", Z3_OP_FPA_ABS: "fpAbs", Z3_OP_FPA_MIN: "fpMin", Z3_OP_FPA_MAX: "fpMax", Z3_OP_FPA_FMA: "fpFMA", Z3_OP_FPA_SQRT: "fpSqrt", Z3_OP_FPA_ROUND_TO_INTEGRAL: "fpRoundToIntegral", Z3_OP_FPA_EQ: "fpEQ", Z3_OP_FPA_LT: "fpLT", Z3_OP_FPA_GT: "fpGT", Z3_OP_FPA_LE: "fpLEQ", Z3_OP_FPA_GE: "fpGEQ", Z3_OP_FPA_FP: "fpFP", Z3_OP_FPA_TO_FP: "fpToFP", Z3_OP_FPA_TO_FP_UNSIGNED: "fpToFPUnsigned", Z3_OP_FPA_TO_UBV: "fpToUBV", Z3_OP_FPA_TO_SBV: "fpToSBV", Z3_OP_FPA_TO_REAL: "fpToReal", Z3_OP_FPA_TO_IEEE_BV: "fpToIEEEBV", } _z3_op_to_fpa_pretty_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: "RNE()", Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: "RNA()", Z3_OP_FPA_RM_TOWARD_POSITIVE: "RTP()", Z3_OP_FPA_RM_TOWARD_NEGATIVE: "RTN()", Z3_OP_FPA_RM_TOWARD_ZERO: "RTZ()", Z3_OP_FPA_PLUS_INF: "+oo", Z3_OP_FPA_MINUS_INF: "-oo", Z3_OP_FPA_NAN: "NaN", Z3_OP_FPA_PLUS_ZERO: "+0.0", Z3_OP_FPA_MINUS_ZERO: "-0.0", Z3_OP_FPA_ADD: "+", Z3_OP_FPA_SUB: "-", Z3_OP_FPA_MUL: "*", Z3_OP_FPA_DIV: "/", Z3_OP_FPA_REM: "%", Z3_OP_FPA_NEG: "-", Z3_OP_FPA_EQ: "fpEQ", Z3_OP_FPA_LT: "<", Z3_OP_FPA_GT: ">", Z3_OP_FPA_LE: "<=", Z3_OP_FPA_GE: ">=" } _z3_fpa_infix = [ Z3_OP_FPA_ADD, Z3_OP_FPA_SUB, Z3_OP_FPA_MUL, Z3_OP_FPA_DIV, Z3_OP_FPA_REM, Z3_OP_FPA_LT, Z3_OP_FPA_GT, Z3_OP_FPA_LE, Z3_OP_FPA_GE ] _ASSOC_OPS = frozenset({ Z3_OP_BOR, Z3_OP_BXOR, Z3_OP_BAND, Z3_OP_ADD, Z3_OP_BADD, Z3_OP_MUL, Z3_OP_BMUL, }) def _is_assoc(k): return k in _ASSOC_OPS def _is_left_assoc(k): return _is_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_html_assoc(k): return k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IFF or _is_assoc(k) def _is_html_left_assoc(k): return _is_html_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_add(k): return k == Z3_OP_ADD or k == Z3_OP_BADD def _is_sub(k): return k == Z3_OP_SUB or k == Z3_OP_BSUB if sys.version_info.major < 3: import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x _z3_infix_compact = [Z3_OP_MUL, Z3_OP_BMUL, Z3_OP_POWER, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_BSDIV, Z3_OP_BSMOD] _ellipses = "..." _html_ellipses = "&hellip;" # Overwrite some of the operators for HTML _z3_pre_html_op_to_str = {Z3_OP_EQ: "=", Z3_OP_IFF: "=", Z3_OP_NOT: "&not;", Z3_OP_AND: "&and;", Z3_OP_OR: "&or;", Z3_OP_IMPLIES: "&rArr;", Z3_OP_LT: "&lt;", Z3_OP_GT: "&gt;", Z3_OP_LE: "&le;", Z3_OP_GE: "&ge;", Z3_OP_MUL: "&middot;", Z3_OP_SLEQ: "&le;", Z3_OP_SLT: "&lt;", Z3_OP_SGEQ: "&ge;", Z3_OP_SGT: "&gt;", Z3_OP_ULEQ: "&le;<sub>u</sub>", Z3_OP_ULT: "&lt;<sub>u</sub>", Z3_OP_UGEQ: "&ge;<sub>u</sub>", Z3_OP_UGT: "&gt;<sub>u</sub>", Z3_OP_BMUL: "&middot;", Z3_OP_BUDIV: "/<sub>u</sub>", Z3_OP_BUREM: "%<sub>u</sub>", Z3_OP_BASHR: "&gt;&gt;", Z3_OP_BSHL: "&lt;&lt;", Z3_OP_BLSHR: "&gt;&gt;<sub>u</sub>" } # Extra operators that are infix/unary for HTML _z3_html_infix = [Z3_OP_AND, Z3_OP_OR, Z3_OP_IMPLIES, Z3_OP_ULEQ, Z3_OP_ULT, Z3_OP_UGEQ, Z3_OP_UGT, Z3_OP_BUDIV, Z3_OP_BUREM, Z3_OP_BLSHR ] _z3_html_unary = [Z3_OP_NOT] # Extra Precedence for HTML _z3_pre_html_precedence = {Z3_OP_BUDIV: 2, Z3_OP_BUREM: 2, Z3_OP_BLSHR: 4, Z3_OP_ULEQ: 8, Z3_OP_ULT: 8, Z3_OP_UGEQ: 8, Z3_OP_UGT: 8, Z3_OP_ULEQ: 8, Z3_OP_ULT: 8, Z3_OP_UGEQ: 8, Z3_OP_UGT: 8, Z3_OP_NOT: 1, Z3_OP_AND: 10, Z3_OP_OR: 11, Z3_OP_IMPLIES: 12} ############################## # # End of Configuration # ############################## def _support_pp(a): return isinstance(a, z3.Z3PPObject) or isinstance(a, list) or isinstance(a, tuple) _infix_map = {} _unary_map = {} _infix_compact_map = {} for _k in _z3_infix: _infix_map[_k] = True for _k in _z3_unary: _unary_map[_k] = True for _k in _z3_infix_compact: _infix_compact_map[_k] = True def _is_infix(k): global _infix_map return _infix_map.get(k, False) def _is_infix_compact(k): global _infix_compact_map return _infix_compact_map.get(k, False) def _is_unary(k): global _unary_map return _unary_map.get(k, False) def _op_name(a): if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_op_to_str.get(k, None) if n is None: return f.name() else: return n def _get_precedence(k): global _z3_precedence return _z3_precedence.get(k, 100000) _z3_html_op_to_str = {} for _k in _z3_op_to_str: _v = _z3_op_to_str[_k] _z3_html_op_to_str[_k] = _v for _k in _z3_pre_html_op_to_str: _v = _z3_pre_html_op_to_str[_k] _z3_html_op_to_str[_k] = _v _z3_html_precedence = {} for _k in _z3_precedence: _v = _z3_precedence[_k] _z3_html_precedence[_k] = _v for _k in _z3_pre_html_precedence: _v = _z3_pre_html_precedence[_k] _z3_html_precedence[_k] = _v _html_infix_map = {} _html_unary_map = {} for _k in _z3_infix: _html_infix_map[_k] = True for _k in _z3_html_infix: _html_infix_map[_k] = True for _k in _z3_unary: _html_unary_map[_k] = True for _k in _z3_html_unary: _html_unary_map[_k] = True def _is_html_infix(k): global _html_infix_map return _html_infix_map.get(k, False) def _is_html_unary(k): global _html_unary_map return _html_unary_map.get(k, False) def _html_op_name(a): global _z3_html_op_to_str if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_html_op_to_str.get(k, None) if n is None: sym = Z3_get_decl_name(f.ctx_ref(), f.ast) if Z3_get_symbol_kind(f.ctx_ref(), sym) == Z3_INT_SYMBOL: return "&#950;<sub>%s</sub>" % Z3_get_symbol_int(f.ctx_ref(), sym) else: # Sanitize the string return f.name() else: return n def _get_html_precedence(k): global _z3_html_predence return _z3_html_precedence.get(k, 100000) class FormatObject: def is_compose(self): return False def is_choice(self): return False def is_indent(self): return False def is_string(self): return False def is_linebreak(self): return False def is_nil(self): return True def children(self): return [] def as_tuple(self): return None def space_upto_nl(self): return (0, False) def flat(self): return self class NAryFormatObject(FormatObject): def __init__(self, fs): assert all([isinstance(a, FormatObject) for a in fs]) self.children = fs def children(self): return self.children class ComposeFormatObject(NAryFormatObject): def is_compose(sef): return True def as_tuple(self): return ("compose", [a.as_tuple() for a in self.children]) def space_upto_nl(self): r = 0 for child in self.children: s, nl = child.space_upto_nl() r = r + s if nl: return (r, True) return (r, False) def flat(self): return compose([a.flat() for a in self.children]) class ChoiceFormatObject(NAryFormatObject): def is_choice(sef): return True def as_tuple(self): return ("choice", [a.as_tuple() for a in self.children]) def space_upto_nl(self): return self.children[0].space_upto_nl() def flat(self): return self.children[0].flat() class IndentFormatObject(FormatObject): def __init__(self, indent, child): assert isinstance(child, FormatObject) self.indent = indent self.child = child def children(self): return [self.child] def as_tuple(self): return ("indent", self.indent, self.child.as_tuple()) def space_upto_nl(self): return self.child.space_upto_nl() def flat(self): return indent(self.indent, self.child.flat()) def is_indent(self): return True class LineBreakFormatObject(FormatObject): def __init__(self): self.space = " " def is_linebreak(self): return True def as_tuple(self): return "<line-break>" def space_upto_nl(self): return (0, True) def flat(self): return to_format(self.space) class StringFormatObject(FormatObject): def __init__(self, string): assert isinstance(string, str) self.string = string def is_string(self): return True def as_tuple(self): return self.string def space_upto_nl(self): return (getattr(self, "size", len(self.string)), False) def fits(f, space_left): s, nl = f.space_upto_nl() return s <= space_left def to_format(arg, size=None): if isinstance(arg, FormatObject): return arg else: r = StringFormatObject(str(arg)) if size is not None: r.size = size return r def compose(*args): if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): args = args[0] return ComposeFormatObject(args) def indent(i, arg): return IndentFormatObject(i, arg) def group(arg): return ChoiceFormatObject([arg.flat(), arg]) def line_break(): return LineBreakFormatObject() def _len(a): if isinstance(a, StringFormatObject): return getattr(a, "size", len(a.string)) else: return len(a) def seq(args, sep=",", space=True): nl = line_break() if not space: nl.space = "" r = [] r.append(args[0]) num = len(args) for i in range(num - 1): r.append(to_format(sep)) r.append(nl) r.append(args[i + 1]) return compose(r) def seq1(header, args, lp="(", rp=")"): return group(compose(to_format(header), to_format(lp), indent(len(lp) + _len(header), seq(args)), to_format(rp))) def seq2(header, args, i=4, lp="(", rp=")"): if len(args) == 0: return compose(to_format(header), to_format(lp), to_format(rp)) else: return group(compose(indent(len(lp), compose(to_format(lp), to_format(header))), indent(i, compose(seq(args), to_format(rp))))) def seq3(args, lp="(", rp=")"): if len(args) == 0: return compose(to_format(lp), to_format(rp)) else: return group(indent(len(lp), compose(to_format(lp), seq(args), to_format(rp)))) class StopPPException(Exception): def __str__(self): return "pp-interrupted" class PP: def __init__(self): self.max_lines = 200 self.max_width = 60 self.bounded = False self.max_indent = 40 def pp_string(self, f, indent): if not self.bounded or self.pos <= self.max_width: sz = _len(f) if self.bounded and self.pos + sz > self.max_width: self.out.write(u(_ellipses)) else: self.pos = self.pos + sz self.ribbon_pos = self.ribbon_pos + sz self.out.write(u(f.string)) def pp_compose(self, f, indent): for c in f.children: self.pp(c, indent) def pp_choice(self, f, indent): space_left = self.max_width - self.pos if space_left > 0 and fits(f.children[0], space_left): self.pp(f.children[0], indent) else: self.pp(f.children[1], indent) def pp_line_break(self, f, indent): self.pos = indent self.ribbon_pos = 0 self.line = self.line + 1 if self.line < self.max_lines: self.out.write(u("\n")) for i in range(indent): self.out.write(u(" ")) else: self.out.write(u("\n...")) raise StopPPException() def pp(self, f, indent): if isinstance(f, str): self.pp_string(f, indent) elif f.is_string(): self.pp_string(f, indent) elif f.is_indent(): self.pp(f.child, min(indent + f.indent, self.max_indent)) elif f.is_compose(): self.pp_compose(f, indent) elif f.is_choice(): self.pp_choice(f, indent) elif f.is_linebreak(): self.pp_line_break(f, indent) else: return def __call__(self, out, f): try: self.pos = 0 self.ribbon_pos = 0 self.line = 0 self.out = out self.pp(f, 0) except StopPPException: return class Formatter: def __init__(self): global _ellipses self.max_depth = 20 self.max_args = 128 self.rational_to_decimal = False self.precision = 10 self.ellipses = to_format(_ellipses) self.max_visited = 10000 self.fpa_pretty = True def pp_ellipses(self): return self.ellipses def pp_arrow(self): return " ->" def pp_unknown(self): return "<unknown>" def pp_name(self, a): return to_format(_op_name(a)) def is_infix(self, a): return _is_infix(a) def is_unary(self, a): return _is_unary(a) def get_precedence(self, a): return _get_precedence(a) def is_infix_compact(self, a): return _is_infix_compact(a) def is_infix_unary(self, a): return self.is_infix(a) or self.is_unary(a) def add_paren(self, a): return compose(to_format("("), indent(1, a), to_format(")")) def pp_sort(self, s): if isinstance(s, z3.ArraySortRef): return seq1("Array", (self.pp_sort(s.domain()), self.pp_sort(s.range()))) elif isinstance(s, z3.BitVecSortRef): return seq1("BitVec", (to_format(s.size()), )) elif isinstance(s, z3.FPSortRef): return seq1("FPSort", (to_format(s.ebits()), to_format(s.sbits()))) elif isinstance(s, z3.ReSortRef): return seq1("ReSort", (self.pp_sort(s.basis()), )) elif isinstance(s, z3.SeqSortRef): if s.is_string(): return to_format("String") return seq1("Seq", (self.pp_sort(s.basis()), )) elif isinstance(s, z3.CharSortRef): return to_format("Char") else: return to_format(s.name()) def pp_const(self, a): k = a.decl().kind() if k == Z3_OP_RE_EMPTY_SET: return self.pp_set("Empty", a) elif k == Z3_OP_SEQ_EMPTY: return self.pp_set("Empty", a) elif k == Z3_OP_RE_FULL_SET: return self.pp_set("Full", a) elif k == Z3_OP_CHAR_CONST: return self.pp_char(a) return self.pp_name(a) def pp_int(self, a): return to_format(a.as_string()) def pp_rational(self, a): if not self.rational_to_decimal: return to_format(a.as_string()) else: return to_format(a.as_decimal(self.precision)) def pp_algebraic(self, a): return to_format(a.as_decimal(self.precision)) def pp_string(self, a): return to_format("\"" + a.as_string() + "\"") def pp_bv(self, a): return to_format(a.as_string()) def pp_fd(self, a): return to_format(a.as_string()) def pp_fprm_value(self, a): _z3_assert(z3.is_fprm_value(a), "expected FPRMNumRef") if self.fpa_pretty and (a.decl().kind() in _z3_op_to_fpa_pretty_str): return to_format(_z3_op_to_fpa_pretty_str.get(a.decl().kind())) else: return to_format(_z3_op_to_fpa_normal_str.get(a.decl().kind())) def pp_fp_value(self, a): _z3_assert(isinstance(a, z3.FPNumRef), "type mismatch") if not self.fpa_pretty: r = [] if (a.isNaN()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_NAN])) r.append(to_format("(")) r.append(to_format(a.sort())) r.append(to_format(")")) return compose(r) elif (a.isInf()): if (a.isNegative()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_MINUS_INF])) else: r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_PLUS_INF])) r.append(to_format("(")) r.append(to_format(a.sort())) r.append(to_format(")")) return compose(r) elif (a.isZero()): if (a.isNegative()): return to_format("-zero") else: return to_format("+zero") else: _z3_assert(z3.is_fp_value(a), "expecting FP num ast") r = [] sgn = c_int(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) r.append(to_format("FPVal(")) if sgnb and sgn.value != 0: r.append(to_format("-")) r.append(to_format(sig)) r.append(to_format("*(2**")) r.append(to_format(exp)) r.append(to_format(", ")) r.append(to_format(a.sort())) r.append(to_format("))")) return compose(r) else: if (a.isNaN()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_NAN]) elif (a.isInf()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_INF]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_INF]) elif (a.isZero()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_ZERO]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_ZERO]) else: _z3_assert(z3.is_fp_value(a), "expecting FP num ast") r = [] sgn = (ctypes.c_int)(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) if sgnb and sgn.value != 0: r.append(to_format("-")) r.append(to_format(sig)) if (exp != "0"): r.append(to_format("*(2**")) r.append(to_format(exp)) r.append(to_format(")")) return compose(r) def pp_fp(self, a, d, xs): _z3_assert(isinstance(a, z3.FPRef), "type mismatch") k = a.decl().kind() op = "?" if (self.fpa_pretty and k in _z3_op_to_fpa_pretty_str): op = _z3_op_to_fpa_pretty_str[k] elif k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] elif k in _z3_op_to_str: op = _z3_op_to_str[k] n = a.num_args() if self.fpa_pretty: if self.is_infix(k) and n >= 3: rm = a.arg(0) if z3.is_fprm_value(rm) and z3.get_default_rounding_mode(a.ctx).eq(rm): arg1 = to_format(self.pp_expr(a.arg(1), d + 1, xs)) arg2 = to_format(self.pp_expr(a.arg(2), d + 1, xs)) r = [] r.append(arg1) r.append(to_format(" ")) r.append(to_format(op)) r.append(to_format(" ")) r.append(arg2) return compose(r) elif k == Z3_OP_FPA_NEG: return compose([to_format("-"), to_format(self.pp_expr(a.arg(0), d + 1, xs))]) if k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] r = [] r.append(to_format(op)) if not z3.is_const(a): r.append(to_format("(")) first = True for c in a.children(): if first: first = False else: r.append(to_format(", ")) r.append(self.pp_expr(c, d + 1, xs)) r.append(to_format(")")) return compose(r) else: return to_format(a.as_string()) def pp_prefix(self, a, d, xs): r = [] sz = 0 for child in a.children(): r.append(self.pp_expr(child, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def is_assoc(self, k): return _is_assoc(k) def is_left_assoc(self, k): return _is_left_assoc(k) def infix_args_core(self, a, d, xs, r): sz = len(r) k = a.decl().kind() p = self.get_precedence(k) first = True for child in a.children(): child_pp = self.pp_expr(child, d + 1, xs) child_k = None if z3.is_app(child): child_k = child.decl().kind() if k == child_k and (self.is_assoc(k) or (first and self.is_left_assoc(k))): self.infix_args_core(child, d, xs, r) sz = len(r) if sz > self.max_args: return elif self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p > child_p or (_is_add(k) and _is_sub(child_k)) or (_is_sub(k) and first and _is_add(child_k)): r.append(child_pp) else: r.append(self.add_paren(child_pp)) sz = sz + 1 elif z3.is_quantifier(child): r.append(self.add_paren(child_pp)) else: r.append(child_pp) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) return first = False def infix_args(self, a, d, xs): r = [] self.infix_args_core(a, d, xs, r) return r def pp_infix(self, a, d, xs): k = a.decl().kind() if self.is_infix_compact(k): op = self.pp_name(a) return group(seq(self.infix_args(a, d, xs), op, False)) else: op = self.pp_name(a) sz = _len(op) op.string = " " + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) def pp_unary(self, a, d, xs): k = a.decl().kind() p = self.get_precedence(k) child = a.children()[0] child_k = None if z3.is_app(child): child_k = child.decl().kind() child_pp = self.pp_expr(child, d + 1, xs) if k != child_k and self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p <= child_p: child_pp = self.add_paren(child_pp) if z3.is_quantifier(child): child_pp = self.add_paren(child_pp) name = self.pp_name(a) return compose(to_format(name), indent(_len(name), child_pp)) def pp_power_arg(self, arg, d, xs): r = self.pp_expr(arg, d + 1, xs) k = None if z3.is_app(arg): k = arg.decl().kind() if self.is_infix_unary(k) or (z3.is_rational_value(arg) and arg.denominator_as_long() != 1): return self.add_paren(r) else: return r def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d + 1, xs) arg2_pp = self.pp_power_arg(a.arg(1), d + 1, xs) return group(seq((arg1_pp, arg2_pp), "**", False)) def pp_neq(self): return to_format("!=") def pp_distinct(self, a, d, xs): if a.num_args() == 2: op = self.pp_neq() sz = _len(op) op.string = " " + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) else: return self.pp_prefix(a, d, xs) def pp_select(self, a, d, xs): if a.num_args() != 2: return self.pp_prefix(a, d, xs) else: arg1_pp = self.pp_expr(a.arg(0), d + 1, xs) arg2_pp = self.pp_expr(a.arg(1), d + 1, xs) return compose(arg1_pp, indent(2, compose(to_format("["), arg2_pp, to_format("]")))) def pp_unary_param(self, a, d, xs): p = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d + 1, xs) return seq1(self.pp_name(a), [to_format(p), arg]) def pp_extract(self, a, d, xs): high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) low = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) arg = self.pp_expr(a.arg(0), d + 1, xs) return seq1(self.pp_name(a), [to_format(high), to_format(low), arg]) def pp_loop(self, a, d, xs): low = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d + 1, xs) if Z3_get_decl_num_parameters(a.ctx_ref(), a.decl().ast) > 1: high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) return seq1("Loop", [arg, to_format(low), to_format(high)]) return seq1("Loop", [arg, to_format(low)]) def pp_set(self, id, a): return seq1(id, [self.pp_sort(a.sort())]) def pp_char(self, a): n = a.params()[0] return to_format(str(n)) def pp_pattern(self, a, d, xs): if a.num_args() == 1: return self.pp_expr(a.arg(0), d, xs) else: return seq1("MultiPattern", [self.pp_expr(arg, d + 1, xs) for arg in a.children()]) def pp_is(self, a, d, xs): f = a.params()[0] return self.pp_fdecl(f, a, d, xs) def pp_map(self, a, d, xs): f = z3.get_map_func(a) return self.pp_fdecl(f, a, d, xs) def pp_fdecl(self, f, a, d, xs): r = [] sz = 0 r.append(to_format(f.name())) for child in a.children(): r.append(self.pp_expr(child, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def pp_K(self, a, d, xs): return seq1(self.pp_name(a), [self.pp_sort(a.domain()), self.pp_expr(a.arg(0), d + 1, xs)]) def pp_atmost(self, a, d, f, xs): k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) return seq1(self.pp_name(a), [seq3([self.pp_expr(ch, d + 1, xs) for ch in a.children()]), to_format(k)]) def pp_pbcmp(self, a, d, f, xs): chs = a.children() rchs = range(len(chs)) k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) ks = [Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, i + 1) for i in rchs] ls = [seq3([self.pp_expr(chs[i], d + 1, xs), to_format(ks[i])]) for i in rchs] return seq1(self.pp_name(a), [seq3(ls), to_format(k)]) def pp_app(self, a, d, xs): if z3.is_int_value(a): return self.pp_int(a) elif z3.is_rational_value(a): return self.pp_rational(a) elif z3.is_algebraic_value(a): return self.pp_algebraic(a) elif z3.is_bv_value(a): return self.pp_bv(a) elif z3.is_finite_domain_value(a): return self.pp_fd(a) elif z3.is_fprm_value(a): return self.pp_fprm_value(a) elif z3.is_fp_value(a): return self.pp_fp_value(a) elif z3.is_fp(a): return self.pp_fp(a, d, xs) elif z3.is_string_value(a): return self.pp_string(a) elif z3.is_const(a): return self.pp_const(a) else: f = a.decl() k = f.kind() if k == Z3_OP_POWER: return self.pp_power(a, d, xs) elif k == Z3_OP_DISTINCT: return self.pp_distinct(a, d, xs) elif k == Z3_OP_SELECT: return self.pp_select(a, d, xs) elif k == Z3_OP_SIGN_EXT or k == Z3_OP_ZERO_EXT or k == Z3_OP_REPEAT: return self.pp_unary_param(a, d, xs) elif k == Z3_OP_EXTRACT: return self.pp_extract(a, d, xs) elif k == Z3_OP_RE_LOOP: return self.pp_loop(a, d, xs) elif k == Z3_OP_DT_IS: return self.pp_is(a, d, xs) elif k == Z3_OP_ARRAY_MAP: return self.pp_map(a, d, xs) elif k == Z3_OP_CONST_ARRAY: return self.pp_K(a, d, xs) elif k == Z3_OP_PB_AT_MOST: return self.pp_atmost(a, d, f, xs) elif k == Z3_OP_PB_LE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_GE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_EQ: return self.pp_pbcmp(a, d, f, xs) elif z3.is_pattern(a): return self.pp_pattern(a, d, xs) elif self.is_infix(k): return self.pp_infix(a, d, xs) elif self.is_unary(k): return self.pp_unary(a, d, xs) else: return self.pp_prefix(a, d, xs) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: return seq1("Var", (to_format(idx),)) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [to_format(a.var_name(i)) for i in range(a.num_vars())] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d + 1, new_xs) if len(ys) == 1: ys_pp = ys[0] else: ys_pp = seq3(ys, "[", "]") if a.is_forall(): header = "ForAll" elif a.is_exists(): header = "Exists" else: header = "Lambda" return seq1(header, (ys_pp, body_pp)) def pp_expr(self, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() if z3.is_app(a): return self.pp_app(a, d, xs) elif z3.is_quantifier(a): return self.pp_quantifier(a, d, xs) elif z3.is_var(a): return self.pp_var(a, d, xs) else: return to_format(self.pp_unknown()) def pp_decl(self, f): k = f.kind() if k == Z3_OP_DT_IS or k == Z3_OP_ARRAY_MAP: g = f.params()[0] r = [to_format(g.name())] return seq1(self.pp_name(f), r) return self.pp_name(f) def pp_seq_core(self, f, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() r = [] sz = 0 for elem in a: r.append(f(elem, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, "[", "]") def pp_seq(self, a, d, xs): return self.pp_seq_core(self.pp_expr, a, d, xs) def pp_seq_seq(self, a, d, xs): return self.pp_seq_core(self.pp_seq, a, d, xs) def pp_model(self, m): r = [] sz = 0 for d in m: i = m[d] if isinstance(i, z3.FuncInterp): i_pp = self.pp_func_interp(i) else: i_pp = self.pp_expr(i, 0, []) name = self.pp_name(d) r.append(compose(name, to_format(" = "), indent(_len(name) + 3, i_pp))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, "[", "]") def pp_func_entry(self, e): num = e.num_args() if num > 1: args = [] for i in range(num): args.append(self.pp_expr(e.arg_value(i), 0, [])) args_pp = group(seq3(args)) else: args_pp = self.pp_expr(e.arg_value(0), 0, []) value_pp = self.pp_expr(e.value(), 0, []) return group(seq((args_pp, value_pp), self.pp_arrow())) def pp_func_interp(self, f): r = [] sz = 0 num = f.num_entries() for i in range(num): r.append(self.pp_func_entry(f.entry(i))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if sz <= self.max_args: else_val = f.else_value() if else_val is None: else_pp = to_format("#unspecified") else: else_pp = self.pp_expr(else_val, 0, []) r.append(group(seq((to_format("else"), else_pp), self.pp_arrow()))) return seq3(r, "[", "]") def pp_list(self, a): r = [] sz = 0 for elem in a: if _support_pp(elem): r.append(self.main(elem)) else: r.append(to_format(str(elem))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if isinstance(a, tuple): return seq3(r) else: return seq3(r, "[", "]") def main(self, a): if z3.is_expr(a): return self.pp_expr(a, 0, []) elif z3.is_sort(a): return self.pp_sort(a) elif z3.is_func_decl(a): return self.pp_decl(a) elif isinstance(a, z3.Goal) or isinstance(a, z3.AstVector): return self.pp_seq(a, 0, []) elif isinstance(a, z3.Solver): return self.pp_seq(a.assertions(), 0, []) elif isinstance(a, z3.Fixedpoint): return a.sexpr() elif isinstance(a, z3.Optimize): return a.sexpr() elif isinstance(a, z3.ApplyResult): return self.pp_seq_seq(a, 0, []) elif isinstance(a, z3.ModelRef): return self.pp_model(a) elif isinstance(a, z3.FuncInterp): return self.pp_func_interp(a) elif isinstance(a, list) or isinstance(a, tuple): return self.pp_list(a) else: return to_format(self.pp_unknown()) def __call__(self, a): self.visited = 0 return self.main(a) class HTMLFormatter(Formatter): def __init__(self): Formatter.__init__(self) global _html_ellipses self.ellipses = to_format(_html_ellipses) def pp_arrow(self): return to_format(" &rarr;", 1) def pp_unknown(self): return "<b>unknown</b>" def pp_name(self, a): r = _html_op_name(a) if r[0] == "&" or r[0] == "/" or r[0] == "%": return to_format(r, 1) else: pos = r.find("__") if pos == -1 or pos == 0: return to_format(r) else: sz = len(r) if pos + 2 == sz: return to_format(r) else: return to_format("%s<sub>%s</sub>" % (r[0:pos], r[pos + 2:sz]), sz - 2) def is_assoc(self, k): return _is_html_assoc(k) def is_left_assoc(self, k): return _is_html_left_assoc(k) def is_infix(self, a): return _is_html_infix(a) def is_unary(self, a): return _is_html_unary(a) def get_precedence(self, a): return _get_html_precedence(a) def pp_neq(self): return to_format("&ne;") def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d + 1, xs) arg2_pp = self.pp_expr(a.arg(1), d + 1, xs) return compose(arg1_pp, to_format("<sup>", 1), arg2_pp, to_format("</sup>", 1)) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: # 957 is the greek letter nu return to_format("&#957;<sub>%s</sub>" % idx, 1) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [to_format(a.var_name(i)) for i in range(a.num_vars())] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d + 1, new_xs) ys_pp = group(seq(ys)) if a.is_forall(): header = "&forall;" else: header = "&exist;" return group(compose(to_format(header, 1), indent(1, compose(ys_pp, to_format(" :"), line_break(), body_pp)))) _PP = PP() _Formatter = Formatter() def set_pp_option(k, v): if k == "html_mode": if v: set_html_mode(True) else: set_html_mode(False) return True if k == "fpa_pretty": if v: set_fpa_pretty(True) else: set_fpa_pretty(False) return True val = getattr(_PP, k, None) if val is not None: _z3_assert(isinstance(v, type(val)), "Invalid pretty print option value") setattr(_PP, k, v) return True val = getattr(_Formatter, k, None) if val is not None: _z3_assert(isinstance(v, type(val)), "Invalid pretty print option value") setattr(_Formatter, k, v) return True return False def obj_to_string(a): out = io.StringIO() _PP(out, _Formatter(a)) return out.getvalue() _html_out = None def set_html_mode(flag=True): global _Formatter if flag: _Formatter = HTMLFormatter() else: _Formatter = Formatter() def set_fpa_pretty(flag=True): global _Formatter global _z3_op_to_str _Formatter.fpa_pretty = flag if flag: for (_k, _v) in _z3_op_to_fpa_pretty_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = True else: for (_k, _v) in _z3_op_to_fpa_normal_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = False set_fpa_pretty(True) def get_fpa_pretty(): global Formatter return _Formatter.fpa_pretty def in_html_mode(): return isinstance(_Formatter, HTMLFormatter) def pp(a): if _support_pp(a): print(obj_to_string(a)) else: print(a) def print_matrix(m): _z3_assert(isinstance(m, list) or isinstance(m, tuple), "matrix expected") if not in_html_mode(): print(obj_to_string(m)) else: print('<table cellpadding="2", cellspacing="0", border="1">') for r in m: _z3_assert(isinstance(r, list) or isinstance(r, tuple), "matrix expected") print("<tr>") for c in r: print("<td>%s</td>" % c) print("</tr>") print("</table>") def insert_line_breaks(s, width): """Break s in lines of size width (approx)""" sz = len(s) if sz <= width: return s new_str = io.StringIO() w = 0 for i in range(sz): if w > width and s[i] == " ": new_str.write(u("<br />")) w = 0 else: new_str.write(u(s[i])) w = w + 1 return new_str.getvalue()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3printer.py
z3printer.py
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction from .z3 import _get_ctx def _to_numeral(num, ctx=None): if isinstance(num, Numeral): return num else: return Numeral(num, ctx) class Numeral: """ A Z3 numeral can be used to perform computations over arbitrary precision integers, rationals and real algebraic numbers. It also automatically converts python numeric values. >>> Numeral(2) 2 >>> Numeral("3/2") + 1 5/2 >>> Numeral(Sqrt(2)) 1.4142135623? >>> Numeral(Sqrt(2)) + 2 3.4142135623? >>> Numeral(Sqrt(2)) + Numeral(Sqrt(3)) 3.1462643699? Z3 numerals can be used to perform computations with values in a Z3 model. >>> s = Solver() >>> x = Real('x') >>> s.add(x*x == 2) >>> s.add(x > 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1.4142135623? >>> m[x] + 1 1.4142135623? + 1 The previous result is a Z3 expression. >>> (m[x] + 1).sexpr() '(+ (root-obj (+ (^ x 2) (- 2)) 2) 1.0)' >>> Numeral(m[x]) + 1 2.4142135623? >>> Numeral(m[x]).is_pos() True >>> Numeral(m[x])**2 2 We can also isolate the roots of polynomials. >>> x0, x1, x2 = RealVarVector(3) >>> r0 = isolate_roots(x0**5 - x0 - 1) >>> r0 [1.1673039782?] In the following example, we are isolating the roots of a univariate polynomial (on x1) obtained after substituting x0 -> r0[0] >>> r1 = isolate_roots(x1**2 - x0 + 1, [ r0[0] ]) >>> r1 [-0.4090280898?, 0.4090280898?] Similarly, in the next example we isolate the roots of a univariate polynomial (on x2) obtained after substituting x0 -> r0[0] and x1 -> r1[0] >>> isolate_roots(x1*x2 + x0, [ r0[0], r1[0] ]) [2.8538479564?] """ def __init__(self, num, ctx=None): if isinstance(num, Ast): self.ast = num self.ctx = _get_ctx(ctx) elif isinstance(num, RatNumRef) or isinstance(num, AlgebraicNumRef): self.ast = num.ast self.ctx = num.ctx elif isinstance(num, ArithRef): r = simplify(num) self.ast = r.ast self.ctx = r.ctx else: v = RealVal(num, ctx) self.ast = v.ast self.ctx = v.ctx Z3_inc_ref(self.ctx_ref(), self.as_ast()) assert Z3_algebraic_is_value(self.ctx_ref(), self.ast) def __del__(self): Z3_dec_ref(self.ctx_ref(), self.as_ast()) def is_integer(self): """ Return True if the numeral is integer. >>> Numeral(2).is_integer() True >>> (Numeral(Sqrt(2)) * Numeral(Sqrt(2))).is_integer() True >>> Numeral(Sqrt(2)).is_integer() False >>> Numeral("2/3").is_integer() False """ return self.is_rational() and self.denominator() == 1 def is_rational(self): """ Return True if the numeral is rational. >>> Numeral(2).is_rational() True >>> Numeral("2/3").is_rational() True >>> Numeral(Sqrt(2)).is_rational() False """ return Z3_get_ast_kind(self.ctx_ref(), self.as_ast()) == Z3_NUMERAL_AST def denominator(self): """ Return the denominator if `self` is rational. >>> Numeral("2/3").denominator() 3 """ assert(self.is_rational()) return Numeral(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator(self): """ Return the numerator if `self` is rational. >>> Numeral("2/3").numerator() 2 """ assert(self.is_rational()) return Numeral(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def is_irrational(self): """ Return True if the numeral is irrational. >>> Numeral(2).is_irrational() False >>> Numeral("2/3").is_irrational() False >>> Numeral(Sqrt(2)).is_irrational() True """ return not self.is_rational() def as_long(self): """ Return a numeral (that is an integer) as a Python long. """ assert(self.is_integer()) if sys.version_info.major >= 3: return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) else: return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) def as_fraction(self): """ Return a numeral (that is a rational) as a Python Fraction. >>> Numeral("1/5").as_fraction() Fraction(1, 5) """ assert(self.is_rational()) return Fraction(self.numerator().as_long(), self.denominator().as_long()) def approx(self, precision=10): """Return a numeral that approximates the numeral `self`. The result `r` is such that |r - self| <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 >>> Numeral(2).approx(10) 2 """ return self.upper(precision) def upper(self, precision=10): """Return a upper bound that approximates the numeral `self`. The result `r` is such that r - self <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.upper(20) 6838717160008073720548335/4835703278458516698824704 >>> x.upper(5) 2965821/2097152 >>> Numeral(2).upper(10) 2 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def lower(self, precision=10): """Return a lower bound that approximates the numeral `self`. The result `r` is such that self - r <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.lower(20) 1709679290002018430137083/1208925819614629174706176 >>> Numeral("2/3").lower(10) 2/3 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_lower(self.ctx_ref(), self.as_ast(), precision), self.ctx) def sign(self): """ Return the sign of the numeral. >>> Numeral(2).sign() 1 >>> Numeral(-3).sign() -1 >>> Numeral(0).sign() 0 """ return Z3_algebraic_sign(self.ctx_ref(), self.ast) def is_pos(self): """ Return True if the numeral is positive. >>> Numeral(2).is_pos() True >>> Numeral(-3).is_pos() False >>> Numeral(0).is_pos() False """ return Z3_algebraic_is_pos(self.ctx_ref(), self.ast) def is_neg(self): """ Return True if the numeral is negative. >>> Numeral(2).is_neg() False >>> Numeral(-3).is_neg() True >>> Numeral(0).is_neg() False """ return Z3_algebraic_is_neg(self.ctx_ref(), self.ast) def is_zero(self): """ Return True if the numeral is zero. >>> Numeral(2).is_zero() False >>> Numeral(-3).is_zero() False >>> Numeral(0).is_zero() True >>> sqrt2 = Numeral(2).root(2) >>> sqrt2.is_zero() False >>> (sqrt2 - sqrt2).is_zero() True """ return Z3_algebraic_is_zero(self.ctx_ref(), self.ast) def __add__(self, other): """ Return the numeral `self + other`. >>> Numeral(2) + 3 5 >>> Numeral(2) + Numeral(4) 6 >>> Numeral("2/3") + 1 5/3 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __radd__(self, other): """ Return the numeral `other + self`. >>> 3 + Numeral(2) 5 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __sub__(self, other): """ Return the numeral `self - other`. >>> Numeral(2) - 3 -1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rsub__(self, other): """ Return the numeral `other - self`. >>> 3 - Numeral(2) 1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __mul__(self, other): """ Return the numeral `self * other`. >>> Numeral(2) * 3 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rmul__(self, other): """ Return the numeral `other * mul`. >>> 3 * Numeral(2) 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __div__(self, other): """ Return the numeral `self / other`. >>> Numeral(2) / 3 2/3 >>> Numeral(2).root(2) / 3 0.4714045207? >>> Numeral(Sqrt(2)) / Numeral(Sqrt(3)) 0.8164965809? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): """ Return the numeral `other / self`. >>> 3 / Numeral(2) 3/2 >>> 3 / Numeral(2).root(2) 2.1213203435? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __rtruediv__(self, other): return self.__rdiv__(other) def root(self, k): """ Return the numeral `self^(1/k)`. >>> sqrt2 = Numeral(2).root(2) >>> sqrt2 1.4142135623? >>> sqrt2 * sqrt2 2 >>> sqrt2 * 2 + 1 3.8284271247? >>> (sqrt2 * 2 + 1).sexpr() '(root-obj (+ (^ x 2) (* (- 2) x) (- 7)) 2)' """ return Numeral(Z3_algebraic_root(self.ctx_ref(), self.ast, k), self.ctx) def power(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3 """ return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx) def __pow__(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3**2 3 """ return self.power(k) def __lt__(self, other): """ Return True if `self < other`. >>> Numeral(Sqrt(2)) < 2 True >>> Numeral(Sqrt(3)) < Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) < Numeral(Sqrt(2)) False """ return Z3_algebraic_lt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rlt__(self, other): """ Return True if `other < self`. >>> 2 < Numeral(Sqrt(2)) False """ return self > other def __gt__(self, other): """ Return True if `self > other`. >>> Numeral(Sqrt(2)) > 2 False >>> Numeral(Sqrt(3)) > Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) > Numeral(Sqrt(2)) False """ return Z3_algebraic_gt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rgt__(self, other): """ Return True if `other > self`. >>> 2 > Numeral(Sqrt(2)) True """ return self < other def __le__(self, other): """ Return True if `self <= other`. >>> Numeral(Sqrt(2)) <= 2 True >>> Numeral(Sqrt(3)) <= Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) <= Numeral(Sqrt(2)) True """ return Z3_algebraic_le(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rle__(self, other): """ Return True if `other <= self`. >>> 2 <= Numeral(Sqrt(2)) False """ return self >= other def __ge__(self, other): """ Return True if `self >= other`. >>> Numeral(Sqrt(2)) >= 2 False >>> Numeral(Sqrt(3)) >= Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) >= Numeral(Sqrt(2)) True """ return Z3_algebraic_ge(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rge__(self, other): """ Return True if `other >= self`. >>> 2 >= Numeral(Sqrt(2)) True """ return self <= other def __eq__(self, other): """ Return True if `self == other`. >>> Numeral(Sqrt(2)) == 2 False >>> Numeral(Sqrt(3)) == Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) == Numeral(Sqrt(2)) True """ return Z3_algebraic_eq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __ne__(self, other): """ Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False """ return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __str__(self): if Z3_is_numeral_ast(self.ctx_ref(), self.ast): return str(RatNumRef(self.ast, self.ctx)) else: return str(AlgebraicNumRef(self.ast, self.ctx)) def __repr__(self): return self.__str__() def sexpr(self): return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): return self.ast def ctx_ref(self): return self.ctx.ref() def eval_sign_at(p, vs): """ Evaluate the sign of the polynomial `p` at `vs`. `p` is a Z3 Expression containing arithmetic operators: +, -, *, ^k where k is an integer; and free variables x that is_var(x) is True. Moreover, all variables must be real. The result is 1 if the polynomial is positive at the given point, -1 if negative, and 0 if zero. >>> x0, x1, x2 = RealVarVector(3) >>> eval_sign_at(x0**2 + x1*x2 + 1, (Numeral(0), Numeral(1), Numeral(2))) 1 >>> eval_sign_at(x0**2 - 2, [ Numeral(Sqrt(2)) ]) 0 >>> eval_sign_at((x0 + x1)*(x0 + x2), (Numeral(0), Numeral(Sqrt(2)), Numeral(Sqrt(3)))) 1 """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast return Z3_algebraic_eval(p.ctx_ref(), p.as_ast(), num, _vs) def isolate_roots(p, vs=[]): """ Given a multivariate polynomial p(x_0, ..., x_{n-1}, x_n), returns the roots of the univariate polynomial p(vs[0], ..., vs[len(vs)-1], x_n). Remarks: * p is a Z3 expression that contains only arithmetic terms and free variables. * forall i in [0, n) vs is a numeral. The result is a list of numerals >>> x0 = RealVar(0) >>> isolate_roots(x0**5 - x0 - 1) [1.1673039782?] >>> x1 = RealVar(1) >>> isolate_roots(x0**2 - x1**4 - 1, [ Numeral(Sqrt(3)) ]) [-1.1892071150?, 1.1892071150?] >>> x2 = RealVar(2) >>> isolate_roots(x2**2 + x0 - x1, [ Numeral(Sqrt(3)), Numeral(Sqrt(2)) ]) [] """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast _roots = AstVector(Z3_algebraic_roots(p.ctx_ref(), p.as_ast(), num, _vs), p.ctx) return [Numeral(r) for r in _roots]
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3num.py
z3num.py
import ctypes from .z3 import * def vset(seq, idfun=None, as_list=True): # This functions preserves the order of arguments while removing duplicates. # This function is from https://code.google.com/p/common-python-vu/source/browse/vu_common.py # (Thanhu's personal code). It has been copied here to avoid a dependency on vu_common.py. """ order preserving >>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr) [[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]] """ def _uniq_normal(seq): d_ = {} for s in seq: if s not in d_: d_[s] = None yield s def _uniq_idfun(seq, idfun): d_ = {} for s in seq: h_ = idfun(s) if h_ not in d_: d_[h_] = None yield s if idfun is None: res = _uniq_normal(seq) else: res = _uniq_idfun(seq, idfun) return list(res) if as_list else res def get_z3_version(as_str=False): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) rs = map(int, (major.value, minor.value, build.value, rev.value)) if as_str: return "{}.{}.{}.{}".format(*rs) else: return rs def ehash(v): """ Returns a 'stronger' hash value than the default hash() method. The result from hash() is not enough to distinguish between 2 z3 expressions in some cases. Note: the following doctests will fail with Python 2.x as the default formatting doesn't match that of 3.x. >>> x1 = Bool('x'); x2 = Bool('x'); x3 = Int('x') >>> print(x1.hash(), x2.hash(), x3.hash()) #BAD: all same hash values 783810685 783810685 783810685 >>> print(ehash(x1), ehash(x2), ehash(x3)) x_783810685_1 x_783810685_1 x_783810685_2 """ if z3_debug(): assert is_expr(v) return "{}_{}_{}".format(str(v), v.hash(), v.sort_kind()) """ In Z3, variables are called *uninterpreted* consts and variables are *interpreted* consts. """ def is_expr_var(v): """ EXAMPLES: >>> is_expr_var(Int('7')) True >>> is_expr_var(IntVal('7')) False >>> is_expr_var(Bool('y')) True >>> is_expr_var(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_var(LOnOff) False >>> is_expr_var(On) False >>> is_expr_var(Block) True >>> is_expr_var(SafetyInjection) True """ return is_const(v) and v.decl().kind() == Z3_OP_UNINTERPRETED def is_expr_val(v): """ EXAMPLES: >>> is_expr_val(Int('7')) False >>> is_expr_val(IntVal('7')) True >>> is_expr_val(Bool('y')) False >>> is_expr_val(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_val(LOnOff) False >>> is_expr_val(On) True >>> is_expr_val(Block) False >>> is_expr_val(SafetyInjection) False """ return is_const(v) and v.decl().kind() != Z3_OP_UNINTERPRETED def get_vars(f, rs=None): """ >>> x,y = Ints('x y') >>> a,b = Bools('a b') >>> get_vars(Implies(And(x+y==0,x*2==10),Or(a,Implies(a,b==False)))) [x, y, a, b] """ if rs is None: rs = [] if z3_debug(): assert is_expr(f) if is_const(f): if is_expr_val(f): return rs else: # variable return vset(rs + [f], str) else: for f_ in f.children(): rs = get_vars(f_, rs) return vset(rs, str) def mk_var(name, vsort): if vsort.kind() == Z3_INT_SORT: v = Int(name) elif vsort.kind() == Z3_REAL_SORT: v = Real(name) elif vsort.kind() == Z3_BOOL_SORT: v = Bool(name) elif vsort.kind() == Z3_DATATYPE_SORT: v = Const(name, vsort) else: raise TypeError("Cannot handle this sort (s: %sid: %d)" % (vsort, vsort.kind())) return v def prove(claim, assume=None, verbose=0): """ >>> r,m = prove(BoolVal(True),verbose=0); r,model_str(m,as_str=False) (True, None) #infinite counter example when proving contradiction >>> r,m = prove(BoolVal(False)); r,model_str(m,as_str=False) (False, []) >>> x,y,z=Bools('x y z') >>> r,m = prove(And(x,Not(x))); r,model_str(m,as_str=True) (False, '[]') >>> r,m = prove(True,assume=And(x,Not(x)),verbose=0) Traceback (most recent call last): ... AssertionError: Assumption is always False! >>> r,m = prove(Implies(x,x),assume=y,verbose=2); r,model_str(m,as_str=False) assume: y claim: Implies(x, x) to_prove: Implies(y, Implies(x, x)) (True, None) >>> r,m = prove(And(x,True),assume=y,verbose=0); r,model_str(m,as_str=False) (False, [(x, False), (y, True)]) >>> r,m = prove(And(x,y),assume=y,verbose=0) >>> print(r) False >>> print(model_str(m,as_str=True)) x = False y = True >>> a,b = Ints('a b') >>> r,m = prove(a**b == b**a,assume=None,verbose=0) E: cannot solve ! >>> r is None and m is None True """ if z3_debug(): assert not assume or is_expr(assume) to_prove = claim if assume: if z3_debug(): is_proved, _ = prove(Not(assume)) def _f(): emsg = "Assumption is always False!" if verbose >= 2: emsg = "{}\n{}".format(assume, emsg) return emsg assert is_proved is False, _f() to_prove = Implies(assume, to_prove) if verbose >= 2: print("assume: ") print(assume) print("claim: ") print(claim) print("to_prove: ") print(to_prove) f = Not(to_prove) models = get_models(f, k=1) if models is None: # unknown print("E: cannot solve !") return None, None elif models is False: # unsat return True, None else: # sat if z3_debug(): assert isinstance(models, list) if models: return False, models[0] # the first counterexample else: return False, [] # infinite counterexample,models def get_models(f, k): """ Returns the first k models satisfiying f. If f is not satisfiable, returns False. If f cannot be solved, returns None If f is satisfiable, returns the first k models Note that if f is a tautology, e.g.\\ True, then the result is [] Based on http://stackoverflow.com/questions/11867611/z3py-checking-all-solutions-for-equation EXAMPLES: >>> x, y = Ints('x y') >>> len(get_models(And(0<=x,x <= 4),k=11)) 5 >>> get_models(And(0<=x**y,x <= 1),k=2) is None True >>> get_models(And(0<=x,x <= -1),k=2) False >>> len(get_models(x+y==7,5)) 5 >>> len(get_models(And(x<=5,x>=1),7)) 5 >>> get_models(And(x<=0,x>=5),7) False >>> x = Bool('x') >>> get_models(And(x,Not(x)),k=1) False >>> get_models(Implies(x,x),k=1) [] >>> get_models(BoolVal(True),k=1) [] """ if z3_debug(): assert is_expr(f) assert k >= 1 s = Solver() s.add(f) models = [] i = 0 while s.check() == sat and i < k: i = i + 1 m = s.model() if not m: # if m == [] break models.append(m) # create new constraint to block the current model block = Not(And([v() == m[v] for v in m])) s.add(block) if s.check() == unknown: return None elif s.check() == unsat and i == 0: return False else: return models def is_tautology(claim, verbose=0): """ >>> is_tautology(Implies(Bool('x'),Bool('x'))) True >>> is_tautology(Implies(Bool('x'),Bool('y'))) False >>> is_tautology(BoolVal(True)) True >>> is_tautology(BoolVal(False)) False """ return prove(claim=claim, assume=None, verbose=verbose)[0] def is_contradiction(claim, verbose=0): """ >>> x,y=Bools('x y') >>> is_contradiction(BoolVal(False)) True >>> is_contradiction(BoolVal(True)) False >>> is_contradiction(x) False >>> is_contradiction(Implies(x,y)) False >>> is_contradiction(Implies(x,x)) False >>> is_contradiction(And(x,Not(x))) True """ return prove(claim=Not(claim), assume=None, verbose=verbose)[0] def exact_one_model(f): """ return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False """ models = get_models(f, k=2) if isinstance(models, list): return len(models) == 1 else: return False def myBinOp(op, *L): """ >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd(*[Bool('x'),None]) x >>> myAnd(*[Bool('x')]) x >>> myAnd(*[]) >>> myAnd(Bool('x'),Bool('y')) And(x, y) >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd([Bool('x'),Bool('y')]) And(x, y) >>> myAnd((Bool('x'),Bool('y'))) And(x, y) >>> myAnd(*[Bool('x'),Bool('y'),True]) Traceback (most recent call last): ... AssertionError """ if z3_debug(): assert op == Z3_OP_OR or op == Z3_OP_AND or op == Z3_OP_IMPLIES if len(L) == 1 and (isinstance(L[0], list) or isinstance(L[0], tuple)): L = L[0] if z3_debug(): assert all(not isinstance(val, bool) for val in L) L = [val for val in L if is_expr(val)] if L: if len(L) == 1: return L[0] if op == Z3_OP_OR: return Or(L) if op == Z3_OP_AND: return And(L) return Implies(L[0], L[1]) else: return None def myAnd(*L): return myBinOp(Z3_OP_AND, *L) def myOr(*L): return myBinOp(Z3_OP_OR, *L) def myImplies(a, b): return myBinOp(Z3_OP_IMPLIES, [a, b]) def Iff(f): return And(Implies(f[0], f[1]), Implies(f[1], f[0])) def model_str(m, as_str=True): """ Returned a 'sorted' model (so that it's easier to see) The model is sorted by its key, e.g. if the model is y = 3 , x = 10, then the result is x = 10, y = 3 EXAMPLES: see doctest exampels from function prove() """ if z3_debug(): assert m is None or m == [] or isinstance(m, ModelRef) if m: vs = [(v, m[v]) for v in m] vs = sorted(vs, key=lambda a, _: str(a)) if as_str: return "\n".join(["{} = {}".format(k, v) for (k, v) in vs]) else: return vs else: return str(m) if as_str else m
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3util.py
z3util.py
import ctypes class Z3Exception(Exception): def __init__(self, value): self.value = value def __str__(self): return str(self.value) class ContextObj(ctypes.c_void_p): def __init__(self, context): self._as_parameter_ = context def from_param(obj): return obj class Config(ctypes.c_void_p): def __init__(self, config): self._as_parameter_ = config def from_param(obj): return obj class Symbol(ctypes.c_void_p): def __init__(self, symbol): self._as_parameter_ = symbol def from_param(obj): return obj class Sort(ctypes.c_void_p): def __init__(self, sort): self._as_parameter_ = sort def from_param(obj): return obj class FuncDecl(ctypes.c_void_p): def __init__(self, decl): self._as_parameter_ = decl def from_param(obj): return obj class Ast(ctypes.c_void_p): def __init__(self, ast): self._as_parameter_ = ast def from_param(obj): return obj class Pattern(ctypes.c_void_p): def __init__(self, pattern): self._as_parameter_ = pattern def from_param(obj): return obj class Model(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class Literals(ctypes.c_void_p): def __init__(self, literals): self._as_parameter_ = literals def from_param(obj): return obj class Constructor(ctypes.c_void_p): def __init__(self, constructor): self._as_parameter_ = constructor def from_param(obj): return obj class ConstructorList(ctypes.c_void_p): def __init__(self, constructor_list): self._as_parameter_ = constructor_list def from_param(obj): return obj class GoalObj(ctypes.c_void_p): def __init__(self, goal): self._as_parameter_ = goal def from_param(obj): return obj class TacticObj(ctypes.c_void_p): def __init__(self, tactic): self._as_parameter_ = tactic def from_param(obj): return obj class SimplifierObj(ctypes.c_void_p): def __init__(self, simplifier): self._as_parameter_ = simplifier def from_param(obj): return obj class ProbeObj(ctypes.c_void_p): def __init__(self, probe): self._as_parameter_ = probe def from_param(obj): return obj class ApplyResultObj(ctypes.c_void_p): def __init__(self, obj): self._as_parameter_ = obj def from_param(obj): return obj class StatsObj(ctypes.c_void_p): def __init__(self, statistics): self._as_parameter_ = statistics def from_param(obj): return obj class SolverObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class SolverCallbackObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class FixedpointObj(ctypes.c_void_p): def __init__(self, fixedpoint): self._as_parameter_ = fixedpoint def from_param(obj): return obj class OptimizeObj(ctypes.c_void_p): def __init__(self, optimize): self._as_parameter_ = optimize def from_param(obj): return obj class ModelObj(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class AstVectorObj(ctypes.c_void_p): def __init__(self, vector): self._as_parameter_ = vector def from_param(obj): return obj class AstMapObj(ctypes.c_void_p): def __init__(self, ast_map): self._as_parameter_ = ast_map def from_param(obj): return obj class Params(ctypes.c_void_p): def __init__(self, params): self._as_parameter_ = params def from_param(obj): return obj class ParamDescrs(ctypes.c_void_p): def __init__(self, paramdescrs): self._as_parameter_ = paramdescrs def from_param(obj): return obj class ParserContextObj(ctypes.c_void_p): def __init__(self, pc): self._as_parameter_ = pc def from_param(obj): return obj class FuncInterpObj(ctypes.c_void_p): def __init__(self, f): self._as_parameter_ = f def from_param(obj): return obj class FuncEntryObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj class RCFNumObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/z3/z3types.py
z3types.py
On Windows, to build Z3, you should executed the following command in the Z3 root directory at the Visual Studio Command Prompt msbuild /p:configuration=external If you are using a 64-bit Python interpreter, you should use msbuild /p:configuration=external /p:platform=x64 On Linux and macOS, you must install python bindings, before trying example.py. To install python on Linux and macOS, you should execute the following command in the Z3 root directory sudo make install-z3py
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/README.txt
README.txt
from .z3 import * from .z3core import * from .z3printer import * def _to_rcfnum(num, ctx=None): if isinstance(num, RCFNum): return num else: return RCFNum(num, ctx) def Pi(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_pi(ctx.ref()), ctx) def E(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_e(ctx.ref()), ctx) def MkInfinitesimal(name="eps", ctx=None): # Todo: remove parameter name. # For now, we keep it for backward compatibility. ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_infinitesimal(ctx.ref()), ctx) def MkRoots(p, ctx=None): ctx = z3.get_ctx(ctx) num = len(p) _tmp = [] _as = (RCFNumObj * num)() _rs = (RCFNumObj * num)() for i in range(num): _a = _to_rcfnum(p[i], ctx) _tmp.append(_a) # prevent GC _as[i] = _a.num nr = Z3_rcf_mk_roots(ctx.ref(), num, _as, _rs) r = [] for i in range(nr): r.append(RCFNum(_rs[i], ctx)) return r class RCFNum: def __init__(self, num, ctx=None): # TODO: add support for converting AST numeral values into RCFNum if isinstance(num, RCFNumObj): self.num = num self.ctx = z3.get_ctx(ctx) else: self.ctx = z3.get_ctx(ctx) self.num = Z3_rcf_mk_rational(self.ctx_ref(), str(num)) def __del__(self): Z3_rcf_del(self.ctx_ref(), self.num) def ctx_ref(self): return self.ctx.ref() def __repr__(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, False, in_html_mode()) def compact_str(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, True, in_html_mode()) def __add__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), self.num, v.num), self.ctx) def __radd__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), v.num, self.num), self.ctx) def __mul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), self.num, v.num), self.ctx) def __rmul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), v.num, self.num), self.ctx) def __sub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), self.num, v.num), self.ctx) def __rsub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), v.num, self.num), self.ctx) def __div__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), self.num, v.num), self.ctx) def __rdiv__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), v.num, self.num), self.ctx) def __neg__(self): return self.__rsub__(0) def power(self, k): return RCFNum(Z3_rcf_power(self.ctx_ref(), self.num, k), self.ctx) def __pow__(self, k): return self.power(k) def decimal(self, prec=5): return Z3_rcf_num_to_decimal_string(self.ctx_ref(), self.num, prec) def __lt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), self.num, v.num) def __rlt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), v.num, self.num) def __gt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), self.num, v.num) def __rgt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), v.num, self.num) def __le__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), self.num, v.num) def __rle__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), v.num, self.num) def __ge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), self.num, v.num) def __rge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), v.num, self.num) def __eq__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_eq(self.ctx_ref(), self.num, v.num) def __ne__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_neq(self.ctx_ref(), self.num, v.num) def split(self): n = (RCFNumObj * 1)() d = (RCFNumObj * 1)() Z3_rcf_get_numerator_denominator(self.ctx_ref(), self.num, n, d) return (RCFNum(n[0], self.ctx), RCFNum(d[0], self.ctx))
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3rcf.py
z3rcf.py
from . import z3core from .z3core import * from .z3types import * from .z3consts import * from .z3printer import * from fractions import Fraction import sys import io import math import copy if sys.version_info.major >= 3: from typing import Iterable Z3_DEBUG = __debug__ def z3_debug(): global Z3_DEBUG return Z3_DEBUG if sys.version_info.major < 3: def _is_int(v): return isinstance(v, (int, long)) else: def _is_int(v): return isinstance(v, int) def enable_trace(msg): Z3_enable_trace(msg) def disable_trace(msg): Z3_disable_trace(msg) def get_version_string(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return "%s.%s.%s" % (major.value, minor.value, build.value) def get_version(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return (major.value, minor.value, build.value, rev.value) def get_full_version(): return Z3_get_full_version() def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) def _z3_check_cint_overflow(n, name): _z3_assert(ctypes.c_int(n).value == n, name + " is too large") def open_log(fname): """Log interaction to a file. This function must be invoked immediately after init(). """ Z3_open_log(fname) def append_log(s): """Append user-defined string to interaction log. """ Z3_append_log(s) def to_symbol(s, ctx=None): """Convert an integer or string into a Z3 symbol.""" if _is_int(s): return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s) else: return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s) def _symbol2py(ctx, s): """Convert a Z3 symbol back into a Python object. """ if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL: return "k!%s" % Z3_get_symbol_int(ctx.ref(), s) else: return Z3_get_symbol_string(ctx.ref(), s) # Hack for having nary functions that can receive one argument that is the # list of arguments. # Use this when function takes a single list of arguments def _get_args(args): try: if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): return args[0] elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)): return [arg for arg in args[0]] else: return args except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?) return args # Use this when function takes multiple arguments def _get_args_ast_list(args): try: if isinstance(args, (set, AstVector, tuple)): return [arg for arg in args] else: return args except Exception: return args def _to_param_value(val): if isinstance(val, bool): return "true" if val else "false" return str(val) def z3_error_handler(c, e): # Do nothing error handler, just avoid exit(0) # The wrappers in z3core.py will raise a Z3Exception if an error is detected return class Context: """A Context manages all other Z3 objects, global configuration options, etc. Z3Py uses a default global context. For most applications this is sufficient. An application may use multiple Z3 contexts. Objects created in one context cannot be used in another one. However, several objects may be "translated" from one context to another. It is not safe to access Z3 objects from multiple threads. The only exception is the method `interrupt()` that can be used to interrupt() a long computation. The initialization method receives global configuration options for the new context. """ def __init__(self, *args, **kws): if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") conf = Z3_mk_config() for key in kws: value = kws[key] Z3_set_param_value(conf, str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_set_param_value(conf, str(prev), _to_param_value(a)) prev = None self.ctx = Z3_mk_context_rc(conf) self.owner = True self.eh = Z3_set_error_handler(self.ctx, z3_error_handler) Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT) Z3_del_config(conf) def __del__(self): if Z3_del_context is not None and self.owner: Z3_del_context(self.ctx) self.ctx = None self.eh = None def ref(self): """Return a reference to the actual C pointer to the Z3 context.""" return self.ctx def interrupt(self): """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions. This method can be invoked from a thread different from the one executing the interruptible procedure. """ Z3_interrupt(self.ref()) def param_descrs(self): """Return the global parameter description set.""" return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self) # Global Z3 context _main_ctx = None def main_ctx(): """Return a reference to the global Z3 context. >>> x = Real('x') >>> x.ctx == main_ctx() True >>> c = Context() >>> c == main_ctx() False >>> x2 = Real('x', c) >>> x2.ctx == c True >>> eq(x, x2) False """ global _main_ctx if _main_ctx is None: _main_ctx = Context() return _main_ctx def _get_ctx(ctx): if ctx is None: return main_ctx() else: return ctx def get_ctx(ctx): return _get_ctx(ctx) def set_param(*args, **kws): """Set Z3 global (or module) parameters. >>> set_param(precision=10) """ if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") new_kws = {} for k in kws: v = kws[k] if not set_pp_option(k, v): new_kws[k] = v for key in new_kws: value = new_kws[key] Z3_global_param_set(str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_global_param_set(str(prev), _to_param_value(a)) prev = None def reset_params(): """Reset all global (or module) parameters. """ Z3_global_param_reset_all() def set_option(*args, **kws): """Alias for 'set_param' for backward compatibility. """ return set_param(*args, **kws) def get_param(name): """Return the value of a Z3 global (or module) parameter >>> get_param('nlsat.reorder') 'true' """ ptr = (ctypes.c_char_p * 1)() if Z3_global_param_get(str(name), ptr): r = z3core._to_pystr(ptr[0]) return r raise Z3Exception("failed to retrieve value for '%s'" % name) ######################################### # # ASTs base class # ######################################### # Mark objects that use pretty printer class Z3PPObject: """Superclass for all Z3 objects that have support for pretty printing.""" def use_pp(self): return True def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res class AstRef(Z3PPObject): """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions.""" def __init__(self, ast, ctx=None): self.ast = ast self.ctx = _get_ctx(ctx) Z3_inc_ref(self.ctx.ref(), self.as_ast()) def __del__(self): if self.ctx.ref() is not None and self.ast is not None and Z3_dec_ref is not None: Z3_dec_ref(self.ctx.ref(), self.as_ast()) self.ast = None def __deepcopy__(self, memo={}): return _to_ast_ref(self.ast, self.ctx) def __str__(self): return obj_to_string(self) def __repr__(self): return obj_to_string(self) def __eq__(self, other): return self.eq(other) def __hash__(self): return self.hash() def __nonzero__(self): return self.__bool__() def __bool__(self): if is_true(self): return True elif is_false(self): return False elif is_eq(self) and self.num_args() == 2: return self.arg(0).eq(self.arg(1)) else: raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.") def sexpr(self): """Return a string representing the AST node in s-expression notation. >>> x = Int('x') >>> ((x + 1)*x).sexpr() '(* (+ x 1) x)' """ return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): """Return a pointer to the corresponding C Z3_ast object.""" return self.ast def get_id(self): """Return unique identifier for object. It can be used for hash-tables and maps.""" return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def ctx_ref(self): """Return a reference to the C context where this AST node is stored.""" return self.ctx.ref() def eq(self, other): """Return `True` if `self` and `other` are structurally identical. >>> x = Int('x') >>> n1 = x + 1 >>> n2 = 1 + x >>> n1.eq(n2) False >>> n1 = simplify(n1) >>> n2 = simplify(n2) >>> n1.eq(n2) True """ if z3_debug(): _z3_assert(is_ast(other), "Z3 AST expected") return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast()) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> x = Int('x', c1) >>> y = Int('y', c2) >>> # Nodes in different contexts can't be mixed. >>> # However, we can translate nodes from one context to another. >>> x.translate(c2) + y x + y """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target) def __copy__(self): return self.translate(self.ctx) def hash(self): """Return a hashcode for the `self`. >>> n1 = simplify(Int('x') + 1) >>> n2 = simplify(2 + Int('x') - 1) >>> n1.hash() == n2.hash() True """ return Z3_get_ast_hash(self.ctx_ref(), self.as_ast()) def is_ast(a): """Return `True` if `a` is an AST node. >>> is_ast(10) False >>> is_ast(IntVal(10)) True >>> is_ast(Int('x')) True >>> is_ast(BoolSort()) True >>> is_ast(Function('f', IntSort(), IntSort())) True >>> is_ast("x") False >>> is_ast(Solver()) False """ return isinstance(a, AstRef) def eq(a, b): """Return `True` if `a` and `b` are structurally identical AST nodes. >>> x = Int('x') >>> y = Int('y') >>> eq(x, y) False >>> eq(x + 1, x + 1) True >>> eq(x + 1, 1 + x) False >>> eq(simplify(x + 1), simplify(1 + x)) True """ if z3_debug(): _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected") return a.eq(b) def _ast_kind(ctx, a): if is_ast(a): a = a.as_ast() return Z3_get_ast_kind(ctx.ref(), a) def _ctx_from_ast_arg_list(args, default_ctx=None): ctx = None for a in args: if is_ast(a) or is_probe(a): if ctx is None: ctx = a.ctx else: if z3_debug(): _z3_assert(ctx == a.ctx, "Context mismatch") if ctx is None: ctx = default_ctx return ctx def _ctx_from_ast_args(*args): return _ctx_from_ast_arg_list(args) def _to_func_decl_array(args): sz = len(args) _args = (FuncDecl * sz)() for i in range(sz): _args[i] = args[i].as_func_decl() return _args, sz def _to_ast_array(args): sz = len(args) _args = (Ast * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ref_array(ref, args): sz = len(args) _args = (ref * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ast_ref(a, ctx): k = _ast_kind(ctx, a) if k == Z3_SORT_AST: return _to_sort_ref(a, ctx) elif k == Z3_FUNC_DECL_AST: return _to_func_decl_ref(a, ctx) else: return _to_expr_ref(a, ctx) ######################################### # # Sorts # ######################################### def _sort_kind(ctx, s): return Z3_get_sort_kind(ctx.ref(), s) class SortRef(AstRef): """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node.""" def as_ast(self): return Z3_sort_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def kind(self): """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts. >>> b = BoolSort() >>> b.kind() == Z3_BOOL_SORT True >>> b.kind() == Z3_INT_SORT False >>> A = ArraySort(IntSort(), IntSort()) >>> A.kind() == Z3_ARRAY_SORT True >>> A.kind() == Z3_INT_SORT False """ return _sort_kind(self.ctx, self.ast) def subsort(self, other): """Return `True` if `self` is a subsort of `other`. >>> IntSort().subsort(RealSort()) True """ return False def cast(self, val): """Try to cast `val` as an element of sort `self`. This method is used in Z3Py to convert Python objects such as integers, floats, longs and strings into Z3 expressions. >>> x = Int('x') >>> RealSort().cast(x) ToReal(x) """ if z3_debug(): _z3_assert(is_expr(val), "Z3 expression expected") _z3_assert(self.eq(val.sort()), "Sort mismatch") return val def name(self): """Return the name (string) of sort `self`. >>> BoolSort().name() 'Bool' >>> ArraySort(IntSort(), IntSort()).name() 'Array' """ return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast)) def __eq__(self, other): """Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False """ if other is None: return False return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __ne__(self, other): """Return `True` if `self` and `other` are not the same Z3 sort. >>> p = Bool('p') >>> p.sort() != BoolSort() False >>> p.sort() != IntSort() True """ return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def is_sort(s): """Return `True` if `s` is a Z3 sort. >>> is_sort(IntSort()) True >>> is_sort(Int('x')) False >>> is_expr(Int('x')) True """ return isinstance(s, SortRef) def _to_sort_ref(s, ctx): if z3_debug(): _z3_assert(isinstance(s, Sort), "Z3 Sort expected") k = _sort_kind(ctx, s) if k == Z3_BOOL_SORT: return BoolSortRef(s, ctx) elif k == Z3_INT_SORT or k == Z3_REAL_SORT: return ArithSortRef(s, ctx) elif k == Z3_BV_SORT: return BitVecSortRef(s, ctx) elif k == Z3_ARRAY_SORT: return ArraySortRef(s, ctx) elif k == Z3_DATATYPE_SORT: return DatatypeSortRef(s, ctx) elif k == Z3_FINITE_DOMAIN_SORT: return FiniteDomainSortRef(s, ctx) elif k == Z3_FLOATING_POINT_SORT: return FPSortRef(s, ctx) elif k == Z3_ROUNDING_MODE_SORT: return FPRMSortRef(s, ctx) elif k == Z3_RE_SORT: return ReSortRef(s, ctx) elif k == Z3_SEQ_SORT: return SeqSortRef(s, ctx) elif k == Z3_CHAR_SORT: return CharSortRef(s, ctx) return SortRef(s, ctx) def _sort(ctx, a): return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx) def DeclareSort(name, ctx=None): """Create a new uninterpreted sort named `name`. If `ctx=None`, then the new sort is declared in the global Z3Py context. >>> A = DeclareSort('A') >>> a = Const('a', A) >>> b = Const('b', A) >>> a.sort() == A True >>> b.sort() == A True >>> a == b a == b """ ctx = _get_ctx(ctx) return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx) ######################################### # # Function Declarations # ######################################### class FuncDeclRef(AstRef): """Function declaration. Every constant and function have an associated declaration. The declaration assigns a name, a sort (i.e., type), and for function the sort (i.e., type) of each of its arguments. Note that, in Z3, a constant is a function with 0 arguments. """ def as_ast(self): return Z3_func_decl_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def as_func_decl(self): return self.ast def name(self): """Return the name of the function declaration `self`. >>> f = Function('f', IntSort(), IntSort()) >>> f.name() 'f' >>> isinstance(f.name(), str) True """ return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast)) def arity(self): """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.arity() 2 """ return int(Z3_get_arity(self.ctx_ref(), self.ast)) def domain(self, i): """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.domain(0) Int >>> f.domain(1) Real """ return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the sort of the range of a function declaration. For constants, this is the sort of the constant. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.range() Bool """ return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx) def kind(self): """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc. >>> x = Int('x') >>> d = (x + 1).decl() >>> d.kind() == Z3_OP_ADD True >>> d.kind() == Z3_OP_MUL False """ return Z3_get_decl_kind(self.ctx_ref(), self.ast) def params(self): ctx = self.ctx n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast) result = [None for i in range(n)] for i in range(n): k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i) if k == Z3_PARAMETER_INT: result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_DOUBLE: result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_RATIONAL: result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SYMBOL: result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SORT: result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_AST: result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_FUNC_DECL: result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx) else: assert(False) return result def __call__(self, *args): """Create a Z3 application expression using the function `self`, and the given arguments. The arguments must be Z3 expressions. This method assumes that the sorts of the elements in `args` match the sorts of the domain. Limited coercion is supported. For example, if args[0] is a Python integer, and the function expects a Z3 integer, then the argument is automatically converted into a Z3 integer. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> x = Int('x') >>> y = Real('y') >>> f(x, y) f(x, y) >>> f(x, x) f(x, ToReal(x)) """ args = _get_args(args) num = len(args) _args = (Ast * num)() saved = [] for i in range(num): # self.domain(i).cast(args[i]) may create a new Z3 expression, # then we must save in 'saved' to prevent it from being garbage collected. tmp = self.domain(i).cast(args[i]) saved.append(tmp) _args[i] = tmp.as_ast() return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx) def is_func_decl(a): """Return `True` if `a` is a Z3 function declaration. >>> f = Function('f', IntSort(), IntSort()) >>> is_func_decl(f) True >>> x = Real('x') >>> is_func_decl(x) False """ return isinstance(a, FuncDeclRef) def Function(name, *sig): """Create a new Z3 uninterpreted function with the given sorts. >>> f = Function('f', IntSort(), IntSort()) >>> f(f(0)) f(f(0)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def FreshFunction(*sig): """Create a new fresh Z3 uninterpreted function with the given sorts. """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (z3.Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx) def _to_func_decl_ref(a, ctx): return FuncDeclRef(a, ctx) def RecFunction(name, *sig): """Create a new Z3 recursive with the given sorts.""" sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def RecAddDefinition(f, args, body): """Set the body of a recursive function. Recursive definitions can be simplified if they are applied to ground arguments. >>> ctx = Context() >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx)) >>> n = Int('n', ctx) >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1))) >>> simplify(fac(5)) 120 >>> s = Solver(ctx=ctx) >>> s.add(fac(n) < 3) >>> s.check() sat >>> s.model().eval(fac(5)) 120 """ if is_app(args): args = [args] ctx = body.ctx args = _get_args(args) n = len(args) _args = (Ast * n)() for i in range(n): _args[i] = args[i].ast Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast) ######################################### # # Expressions # ######################################### class ExprRef(AstRef): """Constraints, formulas and terms are expressions in Z3. Expressions are ASTs. Every expression has a sort. There are three main kinds of expressions: function applications, quantifiers and bounded variables. A constant is a function application with 0 arguments. For quantifier free problems, all expressions are function applications. """ def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the sort of expression `self`. >>> x = Int('x') >>> (x + 1).sort() Int >>> y = Real('y') >>> (x + y).sort() Real """ return _sort(self.ctx, self.as_ast()) def sort_kind(self): """Shorthand for `self.sort().kind()`. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort_kind() == Z3_ARRAY_SORT True >>> a.sort_kind() == Z3_INT_SORT False """ return self.sort().kind() def __eq__(self, other): """Return a Z3 expression that represents the constraint `self == other`. If `other` is `None`, then this method simply returns `False`. >>> a = Int('a') >>> b = Int('b') >>> a == b a == b >>> a is None False """ if other is None: return False a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def __ne__(self, other): """Return a Z3 expression that represents the constraint `self != other`. If `other` is `None`, then this method simply returns `True`. >>> a = Int('a') >>> b = Int('b') >>> a != b a != b >>> a is not None True """ if other is None: return True a, b = _coerce_exprs(self, other) _args, sz = _to_ast_array((a, b)) return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx) def params(self): return self.decl().params() def decl(self): """Return the Z3 function declaration associated with a Z3 application. >>> f = Function('f', IntSort(), IntSort()) >>> a = Int('a') >>> t = f(a) >>> eq(t.decl(), f) True >>> (a + 1).decl() + """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx) def num_args(self): """Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast())) def arg(self, idx): """Return argument `idx` of the application `self`. This method assumes that `self` is a function application with at least `idx+1` arguments. >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.arg(0) a >>> t.arg(1) b >>> t.arg(2) 0 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") _z3_assert(idx < self.num_args(), "Invalid argument index") return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx) def children(self): """Return a list containing the children of the given expression >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.children() [a, b, 0] """ if is_app(self): return [self.arg(i) for i in range(self.num_args())] else: return [] def from_string(self, s): pass def serialize(self): s = Solver() f = Function('F', self.sort(), BoolSort(self.ctx)) s.add(f(self)) return s.sexpr() def deserialize(st): """inverse function to the serialize method on ExprRef. It is made available to make it easier for users to serialize expressions back and forth between strings. Solvers can be serialized using the 'sexpr()' method. """ s = Solver() s.from_string(st) if len(s.assertions()) != 1: raise Z3Exception("single assertion expected") fml = s.assertions()[0] if fml.num_args() != 1: raise Z3Exception("dummy function 'F' expected") return fml.arg(0) def _to_expr_ref(a, ctx): if isinstance(a, Pattern): return PatternRef(a, ctx) ctx_ref = ctx.ref() k = Z3_get_ast_kind(ctx_ref, a) if k == Z3_QUANTIFIER_AST: return QuantifierRef(a, ctx) sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a)) if sk == Z3_BOOL_SORT: return BoolRef(a, ctx) if sk == Z3_INT_SORT: if k == Z3_NUMERAL_AST: return IntNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_REAL_SORT: if k == Z3_NUMERAL_AST: return RatNumRef(a, ctx) if _is_algebraic(ctx, a): return AlgebraicNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_BV_SORT: if k == Z3_NUMERAL_AST: return BitVecNumRef(a, ctx) else: return BitVecRef(a, ctx) if sk == Z3_ARRAY_SORT: return ArrayRef(a, ctx) if sk == Z3_DATATYPE_SORT: return DatatypeRef(a, ctx) if sk == Z3_FLOATING_POINT_SORT: if k == Z3_APP_AST and _is_numeral(ctx, a): return FPNumRef(a, ctx) else: return FPRef(a, ctx) if sk == Z3_FINITE_DOMAIN_SORT: if k == Z3_NUMERAL_AST: return FiniteDomainNumRef(a, ctx) else: return FiniteDomainRef(a, ctx) if sk == Z3_ROUNDING_MODE_SORT: return FPRMRef(a, ctx) if sk == Z3_SEQ_SORT: return SeqRef(a, ctx) if sk == Z3_CHAR_SORT: return CharRef(a, ctx) if sk == Z3_RE_SORT: return ReRef(a, ctx) return ExprRef(a, ctx) def _coerce_expr_merge(s, a): if is_expr(a): s1 = a.sort() if s is None: return s1 if s1.eq(s): return s elif s.subsort(s1): return s1 elif s1.subsort(s): return s else: if z3_debug(): _z3_assert(s1.ctx == s.ctx, "context mismatch") _z3_assert(False, "sort mismatch") else: return s def _coerce_exprs(a, b, ctx=None): if not is_expr(a) and not is_expr(b): a = _py2expr(a, ctx) b = _py2expr(b, ctx) if isinstance(a, str) and isinstance(b, SeqRef): a = StringVal(a, b.ctx) if isinstance(b, str) and isinstance(a, SeqRef): b = StringVal(b, a.ctx) if isinstance(a, float) and isinstance(b, ArithRef): a = RealVal(a, b.ctx) if isinstance(b, float) and isinstance(a, ArithRef): b = RealVal(b, a.ctx) s = None s = _coerce_expr_merge(s, a) s = _coerce_expr_merge(s, b) a = s.cast(a) b = s.cast(b) return (a, b) def _reduce(func, sequence, initial): result = initial for element in sequence: result = func(result, element) return result def _coerce_expr_list(alist, ctx=None): has_expr = False for a in alist: if is_expr(a): has_expr = True break if not has_expr: alist = [_py2expr(a, ctx) for a in alist] s = _reduce(_coerce_expr_merge, alist, None) return [s.cast(a) for a in alist] def is_expr(a): """Return `True` if `a` is a Z3 expression. >>> a = Int('a') >>> is_expr(a) True >>> is_expr(a + 1) True >>> is_expr(IntSort()) False >>> is_expr(1) False >>> is_expr(IntVal(1)) True >>> x = Int('x') >>> is_expr(ForAll(x, x >= 0)) True >>> is_expr(FPVal(1.0)) True """ return isinstance(a, ExprRef) def is_app(a): """Return `True` if `a` is a Z3 function application. Note that, constants are function applications with 0 arguments. >>> a = Int('a') >>> is_app(a) True >>> is_app(a + 1) True >>> is_app(IntSort()) False >>> is_app(1) False >>> is_app(IntVal(1)) True >>> x = Int('x') >>> is_app(ForAll(x, x >= 0)) False """ if not isinstance(a, ExprRef): return False k = _ast_kind(a.ctx, a) return k == Z3_NUMERAL_AST or k == Z3_APP_AST def is_const(a): """Return `True` if `a` is Z3 constant/variable expression. >>> a = Int('a') >>> is_const(a) True >>> is_const(a + 1) False >>> is_const(1) False >>> is_const(IntVal(1)) True >>> x = Int('x') >>> is_const(ForAll(x, x >= 0)) False """ return is_app(a) and a.num_args() == 0 def is_var(a): """Return `True` if `a` is variable. Z3 uses de-Bruijn indices for representing bound variables in quantifiers. >>> x = Int('x') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort()) >>> # Z3 replaces x with bound variables when ForAll is executed. >>> q = ForAll(x, f(x) == x) >>> b = q.body() >>> b f(Var(0)) == Var(0) >>> b.arg(1) Var(0) >>> is_var(b.arg(1)) True """ return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST def get_var_index(a): """Return the de-Bruijn index of the Z3 bounded variable `a`. >>> x = Int('x') >>> y = Int('y') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # Z3 replaces x and y with bound variables when ForAll is executed. >>> q = ForAll([x, y], f(x, y) == x + y) >>> q.body() f(Var(1), Var(0)) == Var(1) + Var(0) >>> b = q.body() >>> b.arg(0) f(Var(1), Var(0)) >>> v1 = b.arg(0).arg(0) >>> v2 = b.arg(0).arg(1) >>> v1 Var(1) >>> v2 Var(0) >>> get_var_index(v1) 1 >>> get_var_index(v2) 0 """ if z3_debug(): _z3_assert(is_var(a), "Z3 bound variable expected") return int(Z3_get_index_value(a.ctx.ref(), a.as_ast())) def is_app_of(a, k): """Return `True` if `a` is an application of the given kind `k`. >>> x = Int('x') >>> n = x + 1 >>> is_app_of(n, Z3_OP_ADD) True >>> is_app_of(n, Z3_OP_MUL) False """ return is_app(a) and a.decl().kind() == k def If(a, b, c, ctx=None): """Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x) """ if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic): return Cond(a, b, c, ctx) else: ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx)) s = BoolSort(ctx) a = s.cast(a) b, c = _coerce_exprs(b, c, ctx) if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def Distinct(*args): """Create a Z3 distinct expression. >>> x = Int('x') >>> y = Int('y') >>> Distinct(x, y) x != y >>> z = Int('z') >>> Distinct(x, y, z) Distinct(x, y, z) >>> simplify(Distinct(x, y, z)) Distinct(x, y, z) >>> simplify(Distinct(x, y, z), blast_distinct=True) And(Not(x == y), Not(x == z), Not(y == z)) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx) def _mk_bin(f, a, b): args = (Ast * 2)() if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") args[0] = a.as_ast() args[1] = b.as_ast() return f(a.ctx.ref(), 2, args) def Const(name, sort): """Create a constant of the given sort. >>> Const('x', IntSort()) x """ if z3_debug(): _z3_assert(isinstance(sort, SortRef), "Z3 sort expected") ctx = sort.ctx return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx) def Consts(names, sort): """Create several constants of the given sort. `names` is a string containing the names of all constants to be created. Blank spaces separate the names of different constants. >>> x, y, z = Consts('x y z', IntSort()) >>> x + y + z x + y + z """ if isinstance(names, str): names = names.split(" ") return [Const(name, sort) for name in names] def FreshConst(sort, prefix="c"): """Create a fresh constant of a specified sort""" ctx = _get_ctx(sort.ctx) return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx) def Var(idx, s): """Create a Z3 free variable. Free variables are used to create quantified formulas. A free variable with index n is bound when it occurs within the scope of n+1 quantified declarations. >>> Var(0, IntSort()) Var(0) >>> eq(Var(0, IntSort()), Var(0, BoolSort())) False """ if z3_debug(): _z3_assert(is_sort(s), "Z3 sort expected") return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx) def RealVar(idx, ctx=None): """ Create a real free variable. Free variables are used to create quantified formulas. They are also used to create polynomials. >>> RealVar(0) Var(0) """ return Var(idx, RealSort(ctx)) def RealVarVector(n, ctx=None): """ Create a list of Real free variables. The variables have ids: 0, 1, ..., n-1 >>> x0, x1, x2, x3 = RealVarVector(4) >>> x2 Var(2) """ return [RealVar(i, ctx) for i in range(n)] ######################################### # # Booleans # ######################################### class BoolSortRef(SortRef): """Boolean sort.""" def cast(self, val): """Try to cast `val` as a Boolean. >>> x = BoolSort().cast(True) >>> x True >>> is_expr(x) True >>> is_expr(True) False >>> x.sort() Bool """ if isinstance(val, bool): return BoolVal(val, self.ctx) if z3_debug(): if not is_expr(val): msg = "True, False or Z3 Boolean expression expected. Received %s of type %s" _z3_assert(is_expr(val), msg % (val, type(val))) if not self.eq(val.sort()): _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value") return val def subsort(self, other): return isinstance(other, ArithSortRef) def is_int(self): return True def is_bool(self): return True class BoolRef(ExprRef): """All Boolean expressions are instances of this class.""" def sort(self): return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __rmul__(self, other): return self * other def __mul__(self, other): """Create the Z3 expression `self * other`. """ if isinstance(other, int) and other == 1: return If(self, 1, 0) if isinstance(other, int) and other == 0: return IntVal(0, self.ctx) if isinstance(other, BoolRef): other = If(other, 1, 0) return If(self, other, 0) def is_bool(a): """Return `True` if `a` is a Z3 Boolean expression. >>> p = Bool('p') >>> is_bool(p) True >>> q = Bool('q') >>> is_bool(And(p, q)) True >>> x = Real('x') >>> is_bool(x) False >>> is_bool(x == 0) True """ return isinstance(a, BoolRef) def is_true(a): """Return `True` if `a` is the Z3 true expression. >>> p = Bool('p') >>> is_true(p) False >>> is_true(simplify(p == p)) True >>> x = Real('x') >>> is_true(x == 0) False >>> # True is a Python Boolean expression >>> is_true(True) False """ return is_app_of(a, Z3_OP_TRUE) def is_false(a): """Return `True` if `a` is the Z3 false expression. >>> p = Bool('p') >>> is_false(p) False >>> is_false(False) False >>> is_false(BoolVal(False)) True """ return is_app_of(a, Z3_OP_FALSE) def is_and(a): """Return `True` if `a` is a Z3 and expression. >>> p, q = Bools('p q') >>> is_and(And(p, q)) True >>> is_and(Or(p, q)) False """ return is_app_of(a, Z3_OP_AND) def is_or(a): """Return `True` if `a` is a Z3 or expression. >>> p, q = Bools('p q') >>> is_or(Or(p, q)) True >>> is_or(And(p, q)) False """ return is_app_of(a, Z3_OP_OR) def is_implies(a): """Return `True` if `a` is a Z3 implication expression. >>> p, q = Bools('p q') >>> is_implies(Implies(p, q)) True >>> is_implies(And(p, q)) False """ return is_app_of(a, Z3_OP_IMPLIES) def is_not(a): """Return `True` if `a` is a Z3 not expression. >>> p = Bool('p') >>> is_not(p) False >>> is_not(Not(p)) True """ return is_app_of(a, Z3_OP_NOT) def is_eq(a): """Return `True` if `a` is a Z3 equality expression. >>> x, y = Ints('x y') >>> is_eq(x == y) True """ return is_app_of(a, Z3_OP_EQ) def is_distinct(a): """Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True """ return is_app_of(a, Z3_OP_DISTINCT) def BoolSort(ctx=None): """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used. >>> BoolSort() Bool >>> p = Const('p', BoolSort()) >>> is_bool(p) True >>> r = Function('r', IntSort(), IntSort(), BoolSort()) >>> r(0, 1) r(0, 1) >>> is_bool(r(0, 1)) True """ ctx = _get_ctx(ctx) return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx) def BoolVal(val, ctx=None): """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used. >>> BoolVal(True) True >>> is_true(BoolVal(True)) True >>> is_true(True) False >>> is_false(BoolVal(False)) True """ ctx = _get_ctx(ctx) if val: return BoolRef(Z3_mk_true(ctx.ref()), ctx) else: return BoolRef(Z3_mk_false(ctx.ref()), ctx) def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) def Bools(names, ctx=None): """Return a tuple of Boolean constants. `names` is a single string containing all names separated by blank spaces. If `ctx=None`, then the global context is used. >>> p, q, r = Bools('p q r') >>> And(p, Or(q, r)) And(p, Or(q, r)) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Bool(name, ctx) for name in names] def BoolVector(prefix, sz, ctx=None): """Return a list of Boolean constants of size `sz`. The constants are named using the given prefix. If `ctx=None`, then the global context is used. >>> P = BoolVector('p', 3) >>> P [p__0, p__1, p__2] >>> And(P) And(p__0, p__1, p__2) """ return [Bool("%s__%s" % (prefix, i)) for i in range(sz)] def FreshBool(prefix="b", ctx=None): """Return a fresh Boolean constant in the given context using the given prefix. If `ctx=None`, then the global context is used. >>> b1 = FreshBool() >>> b2 = FreshBool() >>> eq(b1, b2) False """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx) def Implies(a, b, ctx=None): """Create a Z3 implies expression. >>> p, q = Bools('p q') >>> Implies(p, q) Implies(p, q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Xor(a, b, ctx=None): """Create a Z3 Xor expression. >>> p, q = Bools('p q') >>> Xor(p, q) Xor(p, q) >>> simplify(Xor(p, q)) Not(p == q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Not(a, ctx=None): """Create a Z3 not expression or probe. >>> p = Bool('p') >>> Not(Not(p)) Not(Not(p)) >>> simplify(Not(Not(p))) p """ ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) if is_probe(a): # Not is also used to build probes return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx) else: s = BoolSort(ctx) a = s.cast(a) return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx) def mk_not(a): if is_not(a): return a.arg(0) else: return Not(a) def _has_probe(args): """Return `True` if one of the elements of the given collection is a Z3 probe.""" for arg in args: if is_probe(arg): return True return False def And(*args): """Create a Z3 and-expression or and-probe. >>> p, q, r = Bools('p q r') >>> And(p, q, r) And(p, q, r) >>> P = BoolVector('p', 5) >>> And(P) And(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args) - 1] if isinstance(last_arg, Context): ctx = args[len(args) - 1] args = args[:len(args) - 1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_and(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx) def Or(*args): """Create a Z3 or-expression or or-probe. >>> p, q, r = Bools('p q r') >>> Or(p, q, r) Or(p, q, r) >>> P = BoolVector('p', 5) >>> Or(P) Or(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args) - 1] if isinstance(last_arg, Context): ctx = args[len(args) - 1] args = args[:len(args) - 1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_or(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx) ######################################### # # Patterns # ######################################### class PatternRef(ExprRef): """Patterns are hints for quantifier instantiation. """ def as_ast(self): return Z3_pattern_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def is_pattern(a): """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ]) >>> q ForAll(x, f(x) == 0) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) f(Var(0)) """ return isinstance(a, PatternRef) def MultiPattern(*args): """Create a Z3 multi-pattern using the given expressions `*args` >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ]) >>> q ForAll(x, f(x) != g(x)) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) MultiPattern(f(Var(0)), g(Var(0))) """ if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected") ctx = args[0].ctx args, sz = _to_ast_array(args) return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx) def _to_pattern(arg): if is_pattern(arg): return arg else: return MultiPattern(arg) ######################################### # # Quantifiers # ######################################### class QuantifierRef(BoolRef): """Universally and Existentially quantified formulas.""" def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the Boolean sort or sort of Lambda.""" if self.is_lambda(): return _sort(self.ctx, self.as_ast()) return BoolSort(self.ctx) def is_forall(self): """Return `True` if `self` is a universal quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_forall() True >>> q = Exists(x, f(x) != 0) >>> q.is_forall() False """ return Z3_is_quantifier_forall(self.ctx_ref(), self.ast) def is_exists(self): """Return `True` if `self` is an existential quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_exists() False >>> q = Exists(x, f(x) != 0) >>> q.is_exists() True """ return Z3_is_quantifier_exists(self.ctx_ref(), self.ast) def is_lambda(self): """Return `True` if `self` is a lambda expression. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = Lambda(x, f(x)) >>> q.is_lambda() True >>> q = Exists(x, f(x) != 0) >>> q.is_lambda() False """ return Z3_is_lambda(self.ctx_ref(), self.ast) def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. """ if z3_debug(): _z3_assert(self.is_lambda(), "quantifier should be a lambda expression") return _array_select(self, arg) def weight(self): """Return the weight annotation of `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.weight() 1 >>> q = ForAll(x, f(x) == 0, weight=10) >>> q.weight() 10 """ return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast)) def num_patterns(self): """Return the number of patterns (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 """ return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast)) def pattern(self, idx): """Return a pattern (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 >>> q.pattern(0) f(Var(0)) >>> q.pattern(1) g(Var(0)) """ if z3_debug(): _z3_assert(idx < self.num_patterns(), "Invalid pattern idx") return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def num_no_patterns(self): """Return the number of no-patterns.""" return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast) def no_pattern(self, idx): """Return a no-pattern.""" if z3_debug(): _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx") return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def body(self): """Return the expression being quantified. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.body() f(Var(0)) == 0 """ return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx) def num_vars(self): """Return the number of variables bounded by this quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.num_vars() 2 """ return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast)) def var_name(self, idx): """Return a string representing a name used when displaying the quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_name(0) 'x' >>> q.var_name(1) 'y' """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx)) def var_sort(self, idx): """Return the sort of a bound variable. >>> f = Function('f', IntSort(), RealSort(), IntSort()) >>> x = Int('x') >>> y = Real('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_sort(0) Int >>> q.var_sort(1) Real """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx) def children(self): """Return a list containing a single element self.body() >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.children() [f(Var(0)) == 0] """ return [self.body()] def is_quantifier(a): """Return `True` if `a` is a Z3 quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> is_quantifier(q) True >>> is_quantifier(f(x)) False """ return isinstance(a, QuantifierRef) def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): if z3_debug(): _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected") _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)") _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected") _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions") if is_app(vs): ctx = vs.ctx vs = [vs] else: ctx = vs[0].ctx if not is_expr(body): body = BoolVal(body, ctx) num_vars = len(vs) if num_vars == 0: return body _vs = (Ast * num_vars)() for i in range(num_vars): # TODO: Check if is constant _vs[i] = vs[i].as_ast() patterns = [_to_pattern(p) for p in patterns] num_pats = len(patterns) _pats = (Pattern * num_pats)() for i in range(num_pats): _pats[i] = patterns[i].ast _no_pats, num_no_pats = _to_ast_array(no_patterns) qid = to_symbol(qid, ctx) skid = to_symbol(skid, ctx) return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid, num_vars, _vs, num_pats, _pats, num_no_pats, _no_pats, body.as_ast()), ctx) def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 forall formula. The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> ForAll([x, y], f(x, y) >= x) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ]) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, weight=10) ForAll([x, y], f(x, y) >= x) """ return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns) def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 exists formula. The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = Exists([x, y], f(x, y) >= x, skid="foo") >>> q Exists([x, y], f(x, y) >= x) >>> is_quantifier(q) True >>> r = Tactic('nnf')(q).as_expr() >>> is_quantifier(r) False """ return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns) def Lambda(vs, body): """Create a Z3 lambda expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> mem0 = Array('mem0', IntSort(), IntSort()) >>> lo, hi, e, i = Ints('lo hi e i') >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i])) >>> mem1 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i])) """ ctx = body.ctx if is_app(vs): vs = [vs] num_vars = len(vs) _vs = (Ast * num_vars)() for i in range(num_vars): # TODO: Check if is constant _vs[i] = vs[i].as_ast() return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) ######################################### # # Arithmetic # ######################################### class ArithSortRef(SortRef): """Real and Integer sorts.""" def is_real(self): """Return `True` if `self` is of the sort Real. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True >>> x = Int('x') >>> x.is_real() False """ return self.kind() == Z3_REAL_SORT def is_int(self): """Return `True` if `self` is of the sort Integer. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> x = Real('x') >>> x.is_int() False """ return self.kind() == Z3_INT_SORT def is_bool(self): return False def subsort(self, other): """Return `True` if `self` is a subsort of `other`.""" return self.is_int() and is_arith_sort(other) and other.is_real() def cast(self, val): """Try to cast `val` as an Integer or Real. >>> IntSort().cast(10) 10 >>> is_int(IntSort().cast(10)) True >>> is_int(10) False >>> RealSort().cast(10) 10 >>> is_real(RealSort().cast(10)) True """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") val_s = val.sort() if self.eq(val_s): return val if val_s.is_int() and self.is_real(): return ToReal(val) if val_s.is_bool() and self.is_int(): return If(val, 1, 0) if val_s.is_bool() and self.is_real(): return ToReal(If(val, 1, 0)) if z3_debug(): _z3_assert(False, "Z3 Integer/Real expression expected") else: if self.is_int(): return IntVal(val, self.ctx) if self.is_real(): return RealVal(val, self.ctx) if z3_debug(): msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" _z3_assert(False, msg % self) def is_arith_sort(s): """Return `True` if s is an arithmetical sort (type). >>> is_arith_sort(IntSort()) True >>> is_arith_sort(RealSort()) True >>> is_arith_sort(BoolSort()) False >>> n = Int('x') + 1 >>> is_arith_sort(n.sort()) True """ return isinstance(s, ArithSortRef) class ArithRef(ExprRef): """Integer and Real expressions.""" def sort(self): """Return the sort (type) of the arithmetical expression `self`. >>> Int('x').sort() Int >>> (Real('x') + 1).sort() Real """ return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def is_int(self): """Return `True` if `self` is an integer expression. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> y = Real('y') >>> (x + y).is_int() False """ return self.sort().is_int() def is_real(self): """Return `True` if `self` is an real expression. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True """ return self.sort().is_real() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = Int('x') >>> y = Int('y') >>> x + y x + y >>> (x + y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = Int('x') >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = Real('x') >>> y = Real('y') >>> x * y x*y >>> (x * y).sort() Real """ if isinstance(other, BoolRef): return If(other, self, 0) a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = Real('x') >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = Int('x') >>> y = Int('y') >>> x - y x - y >>> (x - y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = Int('x') >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx) def __pow__(self, other): """Create the Z3 expression `self**other` (** is the power operator). >>> x = Real('x') >>> x**3 x**3 >>> (x**3).sort() Real >>> simplify(IntVal(2)**8) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rpow__(self, other): """Create the Z3 expression `other**self` (** is the power operator). >>> x = Real('x') >>> 2**x 2**x >>> (2**x).sort() Real >>> simplify(2**IntVal(8)) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> y = Int('y') >>> x/y x/y >>> (x/y).sort() Int >>> (x/y).sexpr() '(div x y)' >>> x = Real('x') >>> y = Real('y') >>> x/y x/y >>> (x/y).sort() Real >>> (x/y).sexpr() '(/ x y)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> 10/x 10/x >>> (10/x).sexpr() '(div 10 x)' >>> x = Real('x') >>> 10/x 10/x >>> (10/x).sexpr() '(/ 10.0 x)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> y = Int('y') >>> x % y x%y >>> simplify(IntVal(10) % IntVal(3)) 1 """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> 10 % x 10%x """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __neg__(self): """Return an expression representing `-self`. >>> x = Int('x') >>> -x -x >>> simplify(-(-x)) x """ return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = Int('x') >>> +x x """ return self def __le__(self, other): """Create the Z3 expression `other <= self`. >>> x, y = Ints('x y') >>> x <= y x <= y >>> y = Real('y') >>> x <= y ToReal(x) <= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression `other < self`. >>> x, y = Ints('x y') >>> x < y x < y >>> y = Real('y') >>> x < y ToReal(x) < y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression `other > self`. >>> x, y = Ints('x y') >>> x > y x > y >>> y = Real('y') >>> x > y ToReal(x) > y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression `other >= self`. >>> x, y = Ints('x y') >>> x >= y x >= y >>> y = Real('y') >>> x >= y ToReal(x) >= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def is_arith(a): """Return `True` if `a` is an arithmetical expression. >>> x = Int('x') >>> is_arith(x) True >>> is_arith(x + 1) True >>> is_arith(1) False >>> is_arith(IntVal(1)) True >>> y = Real('y') >>> is_arith(y) True >>> is_arith(y + 1) True """ return isinstance(a, ArithRef) def is_int(a): """Return `True` if `a` is an integer expression. >>> x = Int('x') >>> is_int(x + 1) True >>> is_int(1) False >>> is_int(IntVal(1)) True >>> y = Real('y') >>> is_int(y) False >>> is_int(y + 1) False """ return is_arith(a) and a.is_int() def is_real(a): """Return `True` if `a` is a real expression. >>> x = Int('x') >>> is_real(x + 1) False >>> y = Real('y') >>> is_real(y) True >>> is_real(y + 1) True >>> is_real(1) False >>> is_real(RealVal(1)) True """ return is_arith(a) and a.is_real() def _is_numeral(ctx, a): return Z3_is_numeral_ast(ctx.ref(), a) def _is_algebraic(ctx, a): return Z3_is_algebraic_number(ctx.ref(), a) def is_int_value(a): """Return `True` if `a` is an integer value of sort Int. >>> is_int_value(IntVal(1)) True >>> is_int_value(1) False >>> is_int_value(Int('x')) False >>> n = Int('x') + 1 >>> n x + 1 >>> n.arg(1) 1 >>> is_int_value(n.arg(1)) True >>> is_int_value(RealVal("1/3")) False >>> is_int_value(RealVal(1)) False """ return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast()) def is_rational_value(a): """Return `True` if `a` is rational value of sort Real. >>> is_rational_value(RealVal(1)) True >>> is_rational_value(RealVal("3/5")) True >>> is_rational_value(IntVal(1)) False >>> is_rational_value(1) False >>> n = Real('x') + 1 >>> n.arg(1) 1 >>> is_rational_value(n.arg(1)) True >>> is_rational_value(Real('x')) False """ return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast()) def is_algebraic_value(a): """Return `True` if `a` is an algebraic value of sort Real. >>> is_algebraic_value(RealVal("3/5")) False >>> n = simplify(Sqrt(2)) >>> n 1.4142135623? >>> is_algebraic_value(n) True """ return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast()) def is_add(a): """Return `True` if `a` is an expression of the form b + c. >>> x, y = Ints('x y') >>> is_add(x + y) True >>> is_add(x - y) False """ return is_app_of(a, Z3_OP_ADD) def is_mul(a): """Return `True` if `a` is an expression of the form b * c. >>> x, y = Ints('x y') >>> is_mul(x * y) True >>> is_mul(x - y) False """ return is_app_of(a, Z3_OP_MUL) def is_sub(a): """Return `True` if `a` is an expression of the form b - c. >>> x, y = Ints('x y') >>> is_sub(x - y) True >>> is_sub(x + y) False """ return is_app_of(a, Z3_OP_SUB) def is_div(a): """Return `True` if `a` is an expression of the form b / c. >>> x, y = Reals('x y') >>> is_div(x / y) True >>> is_div(x + y) False >>> x, y = Ints('x y') >>> is_div(x / y) False >>> is_idiv(x / y) True """ return is_app_of(a, Z3_OP_DIV) def is_idiv(a): """Return `True` if `a` is an expression of the form b div c. >>> x, y = Ints('x y') >>> is_idiv(x / y) True >>> is_idiv(x + y) False """ return is_app_of(a, Z3_OP_IDIV) def is_mod(a): """Return `True` if `a` is an expression of the form b % c. >>> x, y = Ints('x y') >>> is_mod(x % y) True >>> is_mod(x + y) False """ return is_app_of(a, Z3_OP_MOD) def is_le(a): """Return `True` if `a` is an expression of the form b <= c. >>> x, y = Ints('x y') >>> is_le(x <= y) True >>> is_le(x < y) False """ return is_app_of(a, Z3_OP_LE) def is_lt(a): """Return `True` if `a` is an expression of the form b < c. >>> x, y = Ints('x y') >>> is_lt(x < y) True >>> is_lt(x == y) False """ return is_app_of(a, Z3_OP_LT) def is_ge(a): """Return `True` if `a` is an expression of the form b >= c. >>> x, y = Ints('x y') >>> is_ge(x >= y) True >>> is_ge(x == y) False """ return is_app_of(a, Z3_OP_GE) def is_gt(a): """Return `True` if `a` is an expression of the form b > c. >>> x, y = Ints('x y') >>> is_gt(x > y) True >>> is_gt(x == y) False """ return is_app_of(a, Z3_OP_GT) def is_is_int(a): """Return `True` if `a` is an expression of the form IsInt(b). >>> x = Real('x') >>> is_is_int(IsInt(x)) True >>> is_is_int(x) False """ return is_app_of(a, Z3_OP_IS_INT) def is_to_real(a): """Return `True` if `a` is an expression of the form ToReal(b). >>> x = Int('x') >>> n = ToReal(x) >>> n ToReal(x) >>> is_to_real(n) True >>> is_to_real(x) False """ return is_app_of(a, Z3_OP_TO_REAL) def is_to_int(a): """Return `True` if `a` is an expression of the form ToInt(b). >>> x = Real('x') >>> n = ToInt(x) >>> n ToInt(x) >>> is_to_int(n) True >>> is_to_int(x) False """ return is_app_of(a, Z3_OP_TO_INT) class IntNumRef(ArithRef): """Integer values.""" def as_long(self): """Return a Z3 integer numeral as a Python long (bignum) numeral. >>> v = IntVal(1) >>> v + 1 1 + 1 >>> v.as_long() + 1 2 """ if z3_debug(): _z3_assert(self.is_int(), "Integer value expected") return int(self.as_string()) def as_string(self): """Return a Z3 integer numeral as a Python string. >>> v = IntVal(100) >>> v.as_string() '100' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_binary_string(self): """Return a Z3 integer numeral as a Python binary string. >>> v = IntVal(10) >>> v.as_binary_string() '1010' """ return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast()) class RatNumRef(ArithRef): """Rational values.""" def numerator(self): """ Return the numerator of a Z3 rational numeral. >>> is_rational_value(RealVal("3/5")) True >>> n = RealVal("3/5") >>> n.numerator() 3 >>> is_rational_value(Q(3,5)) True >>> Q(3,5).numerator() 3 """ return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def denominator(self): """ Return the denominator of a Z3 rational numeral. >>> is_rational_value(Q(3,5)) True >>> n = Q(3,5) >>> n.denominator() 5 """ return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator_as_long(self): """ Return the numerator as a Python long. >>> v = RealVal(10000000000) >>> v 10000000000 >>> v + 1 10000000000 + 1 >>> v.numerator_as_long() + 1 == 10000000001 True """ return self.numerator().as_long() def denominator_as_long(self): """ Return the denominator as a Python long. >>> v = RealVal("1/3") >>> v 1/3 >>> v.denominator_as_long() 3 """ return self.denominator().as_long() def is_int(self): return False def is_real(self): return True def is_int_value(self): return self.denominator().is_int() and self.denominator_as_long() == 1 def as_long(self): _z3_assert(self.is_int_value(), "Expected integer fraction") return self.numerator_as_long() def as_decimal(self, prec): """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places. >>> v = RealVal("1/5") >>> v.as_decimal(3) '0.2' >>> v = RealVal("1/3") >>> v.as_decimal(3) '0.333?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def as_string(self): """Return a Z3 rational numeral as a Python string. >>> v = Q(3,6) >>> v.as_string() '1/2' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_fraction(self): """Return a Z3 rational as a Python Fraction object. >>> v = RealVal("1/5") >>> v.as_fraction() Fraction(1, 5) """ return Fraction(self.numerator_as_long(), self.denominator_as_long()) class AlgebraicNumRef(ArithRef): """Algebraic irrational values.""" def approx(self, precision=10): """Return a Z3 rational number that approximates the algebraic number `self`. The result `r` is such that |r - self| <= 1/10^precision >>> x = simplify(Sqrt(2)) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 """ return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def as_decimal(self, prec): """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places. >>> x = simplify(Sqrt(2)) >>> x.as_decimal(10) '1.4142135623?' >>> x.as_decimal(20) '1.41421356237309504880?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def poly(self): return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_ast()), self.ctx) def index(self): return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast()) def _py2expr(a, ctx=None): if isinstance(a, bool): return BoolVal(a, ctx) if _is_int(a): return IntVal(a, ctx) if isinstance(a, float): return RealVal(a, ctx) if isinstance(a, str): return StringVal(a, ctx) if is_expr(a): return a if z3_debug(): _z3_assert(False, "Python bool, int, long or float expected") def IntSort(ctx=None): """Return the integer sort in the given context. If `ctx=None`, then the global context is used. >>> IntSort() Int >>> x = Const('x', IntSort()) >>> is_int(x) True >>> x.sort() == IntSort() True >>> x.sort() == BoolSort() False """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx) def RealSort(ctx=None): """Return the real sort in the given context. If `ctx=None`, then the global context is used. >>> RealSort() Real >>> x = Const('x', RealSort()) >>> is_real(x) True >>> is_int(x) False >>> x.sort() == RealSort() True """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx) def _to_int_str(val): if isinstance(val, float): return str(int(val)) elif isinstance(val, bool): if val: return "1" else: return "0" else: return str(val) def IntVal(val, ctx=None): """Return a Z3 integer value. If `ctx=None`, then the global context is used. >>> IntVal(1) 1 >>> IntVal("100") 100 """ ctx = _get_ctx(ctx) return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx) def RealVal(val, ctx=None): """Return a Z3 real value. `val` may be a Python int, long, float or string representing a number in decimal or rational notation. If `ctx=None`, then the global context is used. >>> RealVal(1) 1 >>> RealVal(1).sort() Real >>> RealVal("3/5") 3/5 >>> RealVal("1.5") 3/2 """ ctx = _get_ctx(ctx) return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx) def RatVal(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> RatVal(3,5) 3/5 >>> RatVal(3,5).sort() Real """ if z3_debug(): _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer") _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer") return simplify(RealVal(a, ctx) / RealVal(b, ctx)) def Q(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> Q(3,5) 3/5 >>> Q(3,5).sort() Real """ return simplify(RatVal(a, b, ctx=ctx)) def Int(name, ctx=None): """Return an integer constant named `name`. If `ctx=None`, then the global context is used. >>> x = Int('x') >>> is_int(x) True >>> is_int(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx) def Ints(names, ctx=None): """Return a tuple of Integer constants. >>> x, y, z = Ints('x y z') >>> Sum(x, y, z) x + y + z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Int(name, ctx) for name in names] def IntVector(prefix, sz, ctx=None): """Return a list of integer constants of size `sz`. >>> X = IntVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 """ ctx = _get_ctx(ctx) return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)] def FreshInt(prefix="x", ctx=None): """Return a fresh integer constant in the given context using the given prefix. >>> x = FreshInt() >>> y = FreshInt() >>> eq(x, y) False >>> x.sort() Int """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx) def Real(name, ctx=None): """Return a real constant named `name`. If `ctx=None`, then the global context is used. >>> x = Real('x') >>> is_real(x) True >>> is_real(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx) def Reals(names, ctx=None): """Return a tuple of real constants. >>> x, y, z = Reals('x y z') >>> Sum(x, y, z) x + y + z >>> Sum(x, y, z).sort() Real """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Real(name, ctx) for name in names] def RealVector(prefix, sz, ctx=None): """Return a list of real constants of size `sz`. >>> X = RealVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 >>> Sum(X).sort() Real """ ctx = _get_ctx(ctx) return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)] def FreshReal(prefix="b", ctx=None): """Return a fresh real constant in the given context using the given prefix. >>> x = FreshReal() >>> y = FreshReal() >>> eq(x, y) False >>> x.sort() Real """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx) def ToReal(a): """ Return the Z3 expression ToReal(a). >>> x = Int('x') >>> x.sort() Int >>> n = ToReal(x) >>> n ToReal(x) >>> n.sort() Real """ if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected.") ctx = a.ctx return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx) def ToInt(a): """ Return the Z3 expression ToInt(a). >>> x = Real('x') >>> x.sort() Real >>> n = ToInt(x) >>> n ToInt(x) >>> n.sort() Int """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx) def IsInt(a): """ Return the Z3 predicate IsInt(a). >>> x = Real('x') >>> IsInt(x + "1/2") IsInt(x + 1/2) >>> solve(IsInt(x + "1/2"), x > 0, x < 1) [x = 1/2] >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2") no solution """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx) def Sqrt(a, ctx=None): """ Return a Z3 expression which represents the square root of a. >>> x = Real('x') >>> Sqrt(x) x**(1/2) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/2" def Cbrt(a, ctx=None): """ Return a Z3 expression which represents the cubic root of a. >>> x = Real('x') >>> Cbrt(x) x**(1/3) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/3" ######################################### # # Bit-Vectors # ######################################### class BitVecSortRef(SortRef): """Bit-vector sort.""" def size(self): """Return the size (number of bits) of the bit-vector sort `self`. >>> b = BitVecSort(32) >>> b.size() 32 """ return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast)) def subsort(self, other): return is_bv_sort(other) and self.size() < other.size() def cast(self, val): """Try to cast `val` as a Bit-Vector. >>> b = BitVecSort(32) >>> b.cast(10) 10 >>> b.cast(10).sexpr() '#x0000000a' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") # Idea: use sign_extend if sort of val is a bitvector of smaller size return val else: return BitVecVal(val, self) def is_bv_sort(s): """Return True if `s` is a Z3 bit-vector sort. >>> is_bv_sort(BitVecSort(32)) True >>> is_bv_sort(IntSort()) False """ return isinstance(s, BitVecSortRef) class BitVecRef(ExprRef): """Bit-vector expressions.""" def sort(self): """Return the sort of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> x.sort() BitVec(32) >>> x.sort() == BitVecSort(32) True """ return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def size(self): """Return the number of bits of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> (x + 1).size() 32 >>> Concat(x, x).size() 64 """ return self.sort().size() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x + y x + y >>> (x + y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = BitVec('x', 32) >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x * y x*y >>> (x * y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = BitVec('x', 32) >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x - y x - y >>> (x - y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = BitVec('x', 32) >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __or__(self, other): """Create the Z3 expression bitwise-or `self | other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x | y x | y >>> (x | y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ror__(self, other): """Create the Z3 expression bitwise-or `other | self`. >>> x = BitVec('x', 32) >>> 10 | x 10 | x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __and__(self, other): """Create the Z3 expression bitwise-and `self & other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x & y x & y >>> (x & y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rand__(self, other): """Create the Z3 expression bitwise-or `other & self`. >>> x = BitVec('x', 32) >>> 10 & x 10 & x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __xor__(self, other): """Create the Z3 expression bitwise-xor `self ^ other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x ^ y x ^ y >>> (x ^ y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rxor__(self, other): """Create the Z3 expression bitwise-xor `other ^ self`. >>> x = BitVec('x', 32) >>> 10 ^ x 10 ^ x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = BitVec('x', 32) >>> +x x """ return self def __neg__(self): """Return an expression representing `-self`. >>> x = BitVec('x', 32) >>> -x -x >>> simplify(-(-x)) x """ return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx) def __invert__(self): """Create the Z3 expression bitwise-not `~self`. >>> x = BitVec('x', 32) >>> ~x ~x >>> simplify(~(~x)) x """ return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression (signed) division `self / other`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression (signed) division `other / self`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> 10 / x 10/x >>> (10 / x).sexpr() '(bvsdiv #x0000000a x)' >>> UDiv(10, x).sexpr() '(bvudiv #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression (signed) division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression (signed) mod `self % other`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x % y x%y >>> (x % y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression (signed) mod `other % self`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> 10 % x 10%x >>> (10 % x).sexpr() '(bvsmod #x0000000a x)' >>> URem(10, x).sexpr() '(bvurem #x0000000a x)' >>> SRem(10, x).sexpr() '(bvsrem #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __le__(self, other): """Create the Z3 expression (signed) `other <= self`. Use the function ULE() for unsigned less than or equal to. >>> x, y = BitVecs('x y', 32) >>> x <= y x <= y >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression (signed) `other < self`. Use the function ULT() for unsigned less than. >>> x, y = BitVecs('x y', 32) >>> x < y x < y >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression (signed) `other > self`. Use the function UGT() for unsigned greater than. >>> x, y = BitVecs('x y', 32) >>> x > y x > y >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression (signed) `other >= self`. Use the function UGE() for unsigned greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> x >= y x >= y >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rshift__(self, other): """Create the Z3 expression (arithmetical) right shift `self >> other` Use the function LShR() for the right logical shift >>> x, y = BitVecs('x y', 32) >>> x >> y x >> y >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lshift__(self, other): """Create the Z3 expression left shift `self << other` >>> x, y = BitVecs('x y', 32) >>> x << y x << y >>> (x << y).sexpr() '(bvshl x y)' >>> simplify(BitVecVal(2, 3) << 1) 4 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rrshift__(self, other): """Create the Z3 expression (arithmetical) right shift `other` >> `self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 >> x 10 >> x >>> (10 >> x).sexpr() '(bvashr #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rlshift__(self, other): """Create the Z3 expression left shift `other << self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 << x 10 << x >>> (10 << x).sexpr() '(bvshl #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) class BitVecNumRef(BitVecRef): """Bit-vector values.""" def as_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. >>> v = BitVecVal(0xbadc0de, 32) >>> v 195936478 >>> print("0x%.8x" % v.as_long()) 0x0badc0de """ return int(self.as_string()) def as_signed_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign. >>> BitVecVal(4, 3).as_signed_long() -4 >>> BitVecVal(7, 3).as_signed_long() -1 >>> BitVecVal(3, 3).as_signed_long() 3 >>> BitVecVal(2**32 - 1, 32).as_signed_long() -1 >>> BitVecVal(2**64 - 1, 64).as_signed_long() -1 """ sz = self.size() val = self.as_long() if val >= 2**(sz - 1): val = val - 2**sz if val < -2**(sz - 1): val = val + 2**sz return int(val) def as_string(self): return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_binary_string(self): return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast()) def is_bv(a): """Return `True` if `a` is a Z3 bit-vector expression. >>> b = BitVec('b', 32) >>> is_bv(b) True >>> is_bv(b + 10) True >>> is_bv(Int('x')) False """ return isinstance(a, BitVecRef) def is_bv_value(a): """Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True """ return is_bv(a) and _is_numeral(a.ctx, a.as_ast()) def BV2Int(a, is_signed=False): """Return the Z3 expression BV2Int(a). >>> b = BitVec('b', 3) >>> BV2Int(b).sort() Int >>> x = Int('x') >>> x > BV2Int(b) x > BV2Int(b) >>> x > BV2Int(b, is_signed=False) x > BV2Int(b) >>> x > BV2Int(b, is_signed=True) x > If(b < 0, BV2Int(b) - 8, BV2Int(b)) >>> solve(x > BV2Int(b), b == 1, x < 3) [x = 2, b = 1] """ if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") ctx = a.ctx # investigate problem with bv2int return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx) def Int2BV(a, num_bits): """Return the z3 expression Int2BV(a, num_bits). It is a bit-vector of width num_bits and represents the modulo of a by 2^num_bits """ ctx = a.ctx return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx) def BitVecSort(sz, ctx=None): """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used. >>> Byte = BitVecSort(8) >>> Word = BitVecSort(16) >>> Byte BitVec(8) >>> x = Const('x', Byte) >>> eq(x, BitVec('x', 8)) True """ ctx = _get_ctx(ctx) return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx) def BitVecVal(val, bv, ctx=None): """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used. >>> v = BitVecVal(10, 32) >>> v 10 >>> print("0x%.8x" % v.as_long()) 0x0000000a """ if is_bv_sort(bv): ctx = bv.ctx return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx) else: ctx = _get_ctx(ctx) return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx) def BitVec(name, bv, ctx=None): """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort. If `ctx=None`, then the global context is used. >>> x = BitVec('x', 16) >>> is_bv(x) True >>> x.size() 16 >>> x.sort() BitVec(16) >>> word = BitVecSort(16) >>> x2 = BitVec('x', word) >>> eq(x, x2) True """ if isinstance(bv, BitVecSortRef): ctx = bv.ctx else: ctx = _get_ctx(ctx) bv = BitVecSort(bv, ctx) return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) def BitVecs(names, bv, ctx=None): """Return a tuple of bit-vector constants of size bv. >>> x, y, z = BitVecs('x y z', 16) >>> x.size() 16 >>> x.sort() BitVec(16) >>> Sum(x, y, z) 0 + x + y + z >>> Product(x, y, z) 1*x*y*z >>> simplify(Product(x, y, z)) x*y*z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [BitVec(name, bv, ctx) for name in names] def Concat(*args): """Create a Z3 bit-vector concatenation expression. >>> v = BitVecVal(1, 4) >>> Concat(v, v+1, v) Concat(Concat(1, 1 + 1), 1) >>> simplify(Concat(v, v+1, v)) 289 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long()) 121 """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz >= 2, "At least two arguments expected.") ctx = None for a in args: if is_expr(a): ctx = a.ctx break if is_seq(args[0]) or isinstance(args[0], str): args = [_coerce_seq(s, ctx) for s in args] if z3_debug(): _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx) if is_re(args[0]): if z3_debug(): _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx) if z3_debug(): _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.") r = args[0] for i in range(sz - 1): r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx) return r def Extract(high, low, a): """Create a Z3 bit-vector extraction expression. Extract is overloaded to also work on sequence extraction. The functions SubString and SubSeq are redirected to Extract. For this case, the arguments are reinterpreted as: high - is a sequence (string) low - is an offset a - is the length to be extracted >>> x = BitVec('x', 8) >>> Extract(6, 2, x) Extract(6, 2, x) >>> Extract(6, 2, x).sort() BitVec(5) >>> simplify(Extract(StringVal("abcd"),2,1)) "c" """ if isinstance(high, str): high = StringVal(high) if is_seq(high): s = high offset, length = _coerce_exprs(low, a, s.ctx) return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx) if z3_debug(): _z3_assert(low <= high, "First argument must be greater than or equal to second argument") _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers") _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx) def _check_bv_args(a, b): if z3_debug(): _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression") def ULE(a, b): """Create the Z3 expression (unsigned) `other <= self`. Use the operator <= for signed less than or equal to. >>> x, y = BitVecs('x y', 32) >>> ULE(x, y) ULE(x, y) >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def ULT(a, b): """Create the Z3 expression (unsigned) `other < self`. Use the operator < for signed less than. >>> x, y = BitVecs('x y', 32) >>> ULT(x, y) ULT(x, y) >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGE(a, b): """Create the Z3 expression (unsigned) `other >= self`. Use the operator >= for signed greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> UGE(x, y) UGE(x, y) >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGT(a, b): """Create the Z3 expression (unsigned) `other > self`. Use the operator > for signed greater than. >>> x, y = BitVecs('x y', 32) >>> UGT(x, y) UGT(x, y) >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UDiv(a, b): """Create the Z3 expression (unsigned) division `self / other`. Use the operator / for signed division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> UDiv(x, y) UDiv(x, y) >>> UDiv(x, y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def URem(a, b): """Create the Z3 expression (unsigned) remainder `self % other`. Use the operator % for signed modulus, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> URem(x, y) URem(x, y) >>> URem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SRem(a, b): """Create the Z3 expression signed remainder. Use the operator % for signed modulus, and URem() for unsigned remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> SRem(x, y) SRem(x, y) >>> SRem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def LShR(a, b): """Create the Z3 expression logical right shift. Use the operator >> for the arithmetical right shift. >>> x, y = BitVecs('x y', 32) >>> LShR(x, y) LShR(x, y) >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateLeft(a, b): """Return an expression representing `a` rotated to the left `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateLeft(a, b) RotateLeft(a, b) >>> simplify(RotateLeft(a, 0)) a >>> simplify(RotateLeft(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateRight(a, b): """Return an expression representing `a` rotated to the right `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateRight(a, b) RotateRight(a, b) >>> simplify(RotateRight(a, 0)) a >>> simplify(RotateRight(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SignExt(n, a): """Return a bit-vector expression with `n` extra sign-bits. >>> x = BitVec('x', 16) >>> n = SignExt(8, x) >>> n.size() 24 >>> n SignExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(SignExt(6, v0)) >>> v 254 >>> v.size() 8 >>> print("%.x" % v.as_long()) fe """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def ZeroExt(n, a): """Return a bit-vector expression with `n` extra zero-bits. >>> x = BitVec('x', 16) >>> n = ZeroExt(8, x) >>> n.size() 24 >>> n ZeroExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(ZeroExt(6, v0)) >>> v 2 >>> v.size() 8 """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def RepeatBitVec(n, a): """Return an expression representing `n` copies of `a`. >>> x = BitVec('x', 8) >>> n = RepeatBitVec(4, x) >>> n RepeatBitVec(4, x) >>> n.size() 32 >>> v0 = BitVecVal(10, 4) >>> print("%.x" % v0.as_long()) a >>> v = simplify(RepeatBitVec(4, v0)) >>> v.size() 16 >>> print("%.x" % v.as_long()) aaaa """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx) def BVRedAnd(a): """Return the reduction-and expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx) def BVRedOr(a): """Return the reduction-or expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx) def BVAddNoOverflow(a, b, signed): """A predicate the determines that bit-vector addition does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVAddNoUnderflow(a, b): """A predicate the determines that signed bit-vector addition does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoOverflow(a, b): """A predicate the determines that bit-vector subtraction does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoUnderflow(a, b, signed): """A predicate the determines that bit-vector subtraction does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVSDivNoOverflow(a, b): """A predicate the determines that bit-vector signed division does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSNegNoOverflow(a): """A predicate the determines that bit-vector unary negation does not overflow""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx) def BVMulNoOverflow(a, b, signed): """A predicate the determines that bit-vector multiplication does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVMulNoUnderflow(a, b): """A predicate the determines that bit-vector signed multiplication does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) ######################################### # # Arrays # ######################################### class ArraySortRef(SortRef): """Array sorts.""" def domain(self): """Return the domain of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.domain() Int """ return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx) def domain_n(self, i): """Return the domain of the array sort `self`. """ return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the range of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.range() Bool """ return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx) class ArrayRef(ExprRef): """Array expressions. """ def sort(self): """Return the array sort of the array expression `self`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.sort() Array(Int, Bool) """ return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def domain(self): """Shorthand for `self.sort().domain()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.domain() Int """ return self.sort().domain() def domain_n(self, i): """Shorthand for self.sort().domain_n(i)`.""" return self.sort().domain_n(i) def range(self): """Shorthand for `self.sort().range()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.range() Bool """ return self.sort().range() def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. >>> a = Array('a', IntSort(), BoolSort()) >>> i = Int('i') >>> a[i] a[i] >>> a[i].sexpr() '(select a i)' """ return _array_select(self, arg) def default(self): return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) def _array_select(ar, arg): if isinstance(arg, tuple): args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))] _args, sz = _to_ast_array(args) return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx) arg = ar.sort().domain().cast(arg) return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx) def is_array_sort(a): return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT def is_array(a): """Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False """ return isinstance(a, ArrayRef) def is_const_array(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_const_array(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_const_array(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_K(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_K(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_K(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_map(a): """Return `True` if `a` is a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> a Map(f, b) >>> is_map(a) True >>> is_map(b) False """ return is_app_of(a, Z3_OP_ARRAY_MAP) def is_default(a): """Return `True` if `a` is a Z3 default array expression. >>> d = Default(K(IntSort(), 10)) >>> is_default(d) True """ return is_app_of(a, Z3_OP_ARRAY_DEFAULT) def get_map_func(a): """Return the function declaration associated with a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> eq(f, get_map_func(a)) True >>> get_map_func(a) f >>> get_map_func(a)(0) f(0) """ if z3_debug(): _z3_assert(is_map(a), "Z3 array map expression expected.") return FuncDeclRef( Z3_to_func_decl( a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0), ), ctx=a.ctx, ) def ArraySort(*sig): """Return the Z3 array sort with the given domain and range sorts. >>> A = ArraySort(IntSort(), BoolSort()) >>> A Array(Int, Bool) >>> A.domain() Int >>> A.range() Bool >>> AA = ArraySort(IntSort(), A) >>> AA Array(Int, Array(Int, Bool)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 1, "At least two arguments expected") arity = len(sig) - 1 r = sig[arity] d = sig[0] if z3_debug(): for s in sig: _z3_assert(is_sort(s), "Z3 sort expected") _z3_assert(s.ctx == r.ctx, "Context mismatch") ctx = d.ctx if len(sig) == 2: return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx) dom = (Sort * arity)() for i in range(arity): dom[i] = sig[i].ast return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx) def Array(name, *sorts): """Return an array constant named `name` with the given domain and range sorts. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort() Array(Int, Int) >>> a[0] a[0] """ s = ArraySort(sorts) ctx = s.ctx return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) def Update(a, *args): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Update(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") args = _get_args(args) ctx = a.ctx if len(args) <= 1: raise Z3Exception("array update requires index and value arguments") if len(args) == 2: i = args[0] v = args[1] i = a.sort().domain().cast(i) v = a.sort().range().cast(v) return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) v = a.sort().range().cast(args[-1]) idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)] _args, sz = _to_ast_array(idxs) return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx) def Default(a): """ Return a default value for array expression. >>> b = K(IntSort(), 1) >>> prove(Default(b) == 1) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a.default() def Store(a, *args): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Store(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ return Update(a, args) def Select(a, *args): """Return a Z3 select array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i = Int('i') >>> Select(a, i) a[i] >>> eq(Select(a, i), a[i]) True """ args = _get_args(args) if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a[args] def Map(f, *args): """Return a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> a1 = Array('a1', IntSort(), IntSort()) >>> a2 = Array('a2', IntSort(), IntSort()) >>> b = Map(f, a1, a2) >>> b Map(f, a1, a2) >>> prove(b[0] == f(a1[0], a2[0])) proved """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 0, "At least one Z3 array expression expected") _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration") _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected") _z3_assert(len(args) == f.arity(), "Number of arguments mismatch") _args, sz = _to_ast_array(args) ctx = f.ctx return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx) def K(dom, v): """Return a Z3 constant array expression. >>> a = K(IntSort(), 10) >>> a K(Int, 10) >>> a.sort() Array(Int, Int) >>> i = Int('i') >>> a[i] K(Int, 10)[i] >>> simplify(a[i]) 10 """ if z3_debug(): _z3_assert(is_sort(dom), "Z3 sort expected") ctx = dom.ctx if not is_expr(v): v = _py2expr(v, ctx) return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx) def Ext(a, b): """Return extensionality index for one-dimensional arrays. >> a, b = Consts('a b', SetSort(IntSort())) >> Ext(a, b) Ext(a, b) """ ctx = a.ctx if z3_debug(): _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays") return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def SetHasSize(a, k): ctx = a.ctx k = _py2expr(k, ctx) return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx) def is_select(a): """Return `True` if `a` is a Z3 array select application. >>> a = Array('a', IntSort(), IntSort()) >>> is_select(a) False >>> i = Int('i') >>> is_select(a[i]) True """ return is_app_of(a, Z3_OP_SELECT) def is_store(a): """Return `True` if `a` is a Z3 array store application. >>> a = Array('a', IntSort(), IntSort()) >>> is_store(a) False >>> is_store(Store(a, 0, 1)) True """ return is_app_of(a, Z3_OP_STORE) ######################################### # # Sets # ######################################### def SetSort(s): """ Create a set sort over element sort s""" return ArraySort(s, BoolSort()) def EmptySet(s): """Create the empty set >>> EmptySet(IntSort()) K(Int, False) """ ctx = s.ctx return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx) def FullSet(s): """Create the full set >>> FullSet(IntSort()) K(Int, True) """ ctx = s.ctx return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx) def SetUnion(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetUnion(a, b) union(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx) def SetIntersect(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetIntersect(a, b) intersection(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx) def SetAdd(s, e): """ Add element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetAdd(a, 1) Store(a, 1, True) """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetDel(s, e): """ Remove element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetDel(a, 1) Store(a, 1, False) """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetComplement(s): """ The complement of set s >>> a = Const('a', SetSort(IntSort())) >>> SetComplement(a) complement(a) """ ctx = s.ctx return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx) def SetDifference(a, b): """ The set difference of a and b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetDifference(a, b) setminus(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def IsMember(e, s): """ Check if e is a member of set s >>> a = Const('a', SetSort(IntSort())) >>> IsMember(1, a) a[1] """ ctx = _ctx_from_ast_arg_list([s, e]) e = _py2expr(e, ctx) return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx) def IsSubset(a, b): """ Check if a is a subset of b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> IsSubset(a, b) subset(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx) ######################################### # # Datatypes # ######################################### def _valid_accessor(acc): """Return `True` if acc is pair of the form (String, Datatype or Sort). """ if not isinstance(acc, tuple): return False if len(acc) != 2: return False return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])) class Datatype: """Helper class for declaring Z3 datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) >>> List.cons(10, List.nil).sort() List >>> cons = List.cons >>> nil = List.nil >>> car = List.car >>> cdr = List.cdr >>> n = cons(1, cons(0, nil)) >>> n cons(1, cons(0, nil)) >>> simplify(cdr(n)) cons(0, nil) >>> simplify(car(n)) 1 """ def __init__(self, name, ctx=None): self.ctx = _get_ctx(ctx) self.name = name self.constructors = [] def __deepcopy__(self, memo={}): r = Datatype(self.name, self.ctx) r.constructors = copy.deepcopy(self.constructors) return r def declare_core(self, name, rec_name, *args): if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(isinstance(rec_name, str), "String expected") _z3_assert( all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)", ) self.constructors.append((name, rec_name, args)) def declare(self, name, *args): """Declare constructor named `name` with the given accessors `args`. Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared. In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))` declares the constructor named `cons` that builds a new List using an integer and a List. It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() """ if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(name != "", "Constructor name cannot be empty") return self.declare_core(name, "is-" + name, *args) def __repr__(self): return "Datatype(%s, %s)" % (self.name, self.constructors) def create(self): """Create a Z3 datatype based on the constructors declared using the method `declare()`. The function `CreateDatatypes()` must be used to define mutually recursive datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) """ return CreateDatatypes([self])[0] class ScopedConstructor: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None and Z3_del_constructor is not None: Z3_del_constructor(self.ctx.ref(), self.c) class ScopedConstructorList: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None and Z3_del_constructor_list is not None: Z3_del_constructor_list(self.ctx.ref(), self.c) def CreateDatatypes(*ds): """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects. In the following example we define a Tree-List using two mutually recursive datatypes. >>> TreeList = Datatype('TreeList') >>> Tree = Datatype('Tree') >>> # Tree has two constructors: leaf and node >>> Tree.declare('leaf', ('val', IntSort())) >>> # a node contains a list of trees >>> Tree.declare('node', ('children', TreeList)) >>> TreeList.declare('nil') >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList)) >>> Tree, TreeList = CreateDatatypes(Tree, TreeList) >>> Tree.val(Tree.leaf(10)) val(leaf(10)) >>> simplify(Tree.val(Tree.leaf(10))) 10 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil))) >>> n1 node(cons(leaf(10), cons(leaf(20), nil))) >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil)) >>> simplify(n2 == n1) False >>> simplify(TreeList.car(Tree.children(n2)) == n1) True """ ds = _get_args(ds) if z3_debug(): _z3_assert(len(ds) > 0, "At least one Datatype must be specified") _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes") _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch") _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected") ctx = ds[0].ctx num = len(ds) names = (Symbol * num)() out = (Sort * num)() clists = (ConstructorList * num)() to_delete = [] for i in range(num): d = ds[i] names[i] = to_symbol(d.name, ctx) num_cs = len(d.constructors) cs = (Constructor * num_cs)() for j in range(num_cs): c = d.constructors[j] cname = to_symbol(c[0], ctx) rname = to_symbol(c[1], ctx) fs = c[2] num_fs = len(fs) fnames = (Symbol * num_fs)() sorts = (Sort * num_fs)() refs = (ctypes.c_uint * num_fs)() for k in range(num_fs): fname = fs[k][0] ftype = fs[k][1] fnames[k] = to_symbol(fname, ctx) if isinstance(ftype, Datatype): if z3_debug(): _z3_assert( ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected", ) sorts[k] = None refs[k] = ds.index(ftype) else: if z3_debug(): _z3_assert(is_sort(ftype), "Z3 sort expected") sorts[k] = ftype.ast refs[k] = 0 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs) to_delete.append(ScopedConstructor(cs[j], ctx)) clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs) to_delete.append(ScopedConstructorList(clists[i], ctx)) Z3_mk_datatypes(ctx.ref(), num, names, out, clists) result = [] # Create a field for every constructor, recognizer and accessor for i in range(num): dref = DatatypeSortRef(out[i], ctx) num_cs = dref.num_constructors() for j in range(num_cs): cref = dref.constructor(j) cref_name = cref.name() cref_arity = cref.arity() if cref.arity() == 0: cref = cref() setattr(dref, cref_name, cref) rref = dref.recognizer(j) setattr(dref, "is_" + cref_name, rref) for k in range(cref_arity): aref = dref.accessor(j, k) setattr(dref, aref.name(), aref) result.append(dref) return tuple(result) class DatatypeSortRef(SortRef): """Datatype sorts.""" def num_constructors(self): """Return the number of constructors in the given Z3 datatype. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 """ return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast)) def constructor(self, idx): """Return a constructor of the datatype `self`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> List.constructor(1) nil """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid constructor index") return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx) def recognizer(self, idx): """In Z3, each constructor has an associated recognizer predicate. If the constructor is named `name`, then the recognizer `is_name`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.recognizer(0) is(cons) >>> List.recognizer(1) is(nil) >>> simplify(List.is_nil(List.cons(10, List.nil))) False >>> simplify(List.is_cons(List.cons(10, List.nil))) True >>> l = Const('l', List) >>> simplify(List.is_cons(l)) is(cons, l) """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid recognizer index") return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx) def accessor(self, i, j): """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> num_accs = List.constructor(0).arity() >>> num_accs 2 >>> List.accessor(0, 0) car >>> List.accessor(0, 1) cdr >>> List.constructor(1) nil >>> num_accs = List.constructor(1).arity() >>> num_accs 0 """ if z3_debug(): _z3_assert(i < self.num_constructors(), "Invalid constructor index") _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index") return FuncDeclRef( Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), ctx=self.ctx, ) class DatatypeRef(ExprRef): """Datatype expressions.""" def sort(self): """Return the datatype sort of the datatype expression `self`.""" return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def DatatypeSort(name, ctx = None): """Create a reference to a sort that was declared, or will be declared, as a recursive datatype""" ctx = _get_ctx(ctx) return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), ctx) def TupleSort(name, sorts, ctx=None): """Create a named tuple sort base on a set of underlying sorts Example: >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()]) """ tuple = Datatype(name, ctx) projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))] tuple.declare(name, *projects) tuple = tuple.create() return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))] def DisjointSum(name, sorts, ctx=None): """Create a named tagged union sort base on a set of underlying sorts Example: >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()]) """ sum = Datatype(name, ctx) for i in range(len(sorts)): sum.declare("inject%d" % i, ("project%d" % i, sorts[i])) sum = sum.create() return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))] def EnumSort(name, values, ctx=None): """Return a new enumeration sort named `name` containing the given values. The result is a pair (sort, list of constants). Example: >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue']) """ if z3_debug(): _z3_assert(isinstance(name, str), "Name must be a string") _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings") _z3_assert(len(values) > 0, "At least one value expected") ctx = _get_ctx(ctx) num = len(values) _val_names = (Symbol * num)() for i in range(num): _val_names[i] = to_symbol(values[i]) _values = (FuncDecl * num)() _testers = (FuncDecl * num)() name = to_symbol(name) S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx) V = [] for i in range(num): V.append(FuncDeclRef(_values[i], ctx)) V = [a() for a in V] return S, V ######################################### # # Parameter Sets # ######################################### class ParamsRef: """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3. Consider using the function `args2params` to create instances of this object. """ def __init__(self, ctx=None, params=None): self.ctx = _get_ctx(ctx) if params is None: self.params = Z3_mk_params(self.ctx.ref()) else: self.params = params Z3_params_inc_ref(self.ctx.ref(), self.params) def __deepcopy__(self, memo={}): return ParamsRef(self.ctx, self.params) def __del__(self): if self.ctx.ref() is not None and Z3_params_dec_ref is not None: Z3_params_dec_ref(self.ctx.ref(), self.params) def set(self, name, val): """Set parameter name with value val.""" if z3_debug(): _z3_assert(isinstance(name, str), "parameter name must be a string") name_sym = to_symbol(name, self.ctx) if isinstance(val, bool): Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val) elif _is_int(val): Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, float): Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, str): Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx)) else: if z3_debug(): _z3_assert(False, "invalid parameter value") def __repr__(self): return Z3_params_to_string(self.ctx.ref(), self.params) def validate(self, ds): _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected") Z3_params_validate(self.ctx.ref(), self.params, ds.descr) def args2params(arguments, keywords, ctx=None): """Convert python arguments into a Z3_params object. A ':' is added to the keywords, and '_' is replaced with '-' >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True}) (params model true relevancy 2 elim_and true) """ if z3_debug(): _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.") prev = None r = ParamsRef(ctx) for a in arguments: if prev is None: prev = a else: r.set(prev, a) prev = None for k in keywords: v = keywords[k] r.set(k, v) return r class ParamDescrsRef: """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3. """ def __init__(self, descr, ctx=None): _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected") self.ctx = _get_ctx(ctx) self.descr = descr Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr) def __deepcopy__(self, memo={}): return ParamsDescrsRef(self.descr, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None: Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr) def size(self): """Return the size of in the parameter description `self`. """ return int(Z3_param_descrs_size(self.ctx.ref(), self.descr)) def __len__(self): """Return the size of in the parameter description `self`. """ return self.size() def get_name(self, i): """Return the i-th parameter name in the parameter description `self`. """ return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i)) def get_kind(self, n): """Return the kind of the parameter named `n`. """ return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def get_documentation(self, n): """Return the documentation string of the parameter named `n`. """ return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def __getitem__(self, arg): if _is_int(arg): return self.get_name(arg) else: return self.get_kind(arg) def __repr__(self): return Z3_param_descrs_to_string(self.ctx.ref(), self.descr) ######################################### # # Goals # ######################################### class Goal(Z3PPObject): """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible). Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals. A goal has a solution if one of its subgoals has a solution. A goal is unsatisfiable if all subgoals are unsatisfiable. """ def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None): if z3_debug(): _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None") self.ctx = _get_ctx(ctx) self.goal = goal if self.goal is None: self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs) Z3_goal_inc_ref(self.ctx.ref(), self.goal) def __del__(self): if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None: Z3_goal_dec_ref(self.ctx.ref(), self.goal) def depth(self): """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`. >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x == 0, y >= x + 1) >>> g.depth() 0 >>> r = Then('simplify', 'solve-eqs')(g) >>> # r has 1 subgoal >>> len(r) 1 >>> r[0].depth() 2 """ return int(Z3_goal_depth(self.ctx.ref(), self.goal)) def inconsistent(self): """Return `True` if `self` contains the `False` constraints. >>> x, y = Ints('x y') >>> g = Goal() >>> g.inconsistent() False >>> g.add(x == 0, x == 1) >>> g [x == 0, x == 1] >>> g.inconsistent() False >>> g2 = Tactic('propagate-values')(g)[0] >>> g2.inconsistent() True """ return Z3_goal_inconsistent(self.ctx.ref(), self.goal) def prec(self): """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`. >>> g = Goal() >>> g.prec() == Z3_GOAL_PRECISE True >>> x, y = Ints('x y') >>> g.add(x == y + 1) >>> g.prec() == Z3_GOAL_PRECISE True >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10) >>> g2 = t(g)[0] >>> g2 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0] >>> g2.prec() == Z3_GOAL_PRECISE False >>> g2.prec() == Z3_GOAL_UNDER True """ return Z3_goal_precision(self.ctx.ref(), self.goal) def precision(self): """Alias for `prec()`. >>> g = Goal() >>> g.precision() == Z3_GOAL_PRECISE True """ return self.prec() def size(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> g.size() 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.size() 2 """ return int(Z3_goal_size(self.ctx.ref(), self.goal)) def __len__(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> len(g) 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> len(g) 2 """ return self.size() def get(self, i): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.get(0) x == 0 >>> g.get(1) y > x """ return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx) def __getitem__(self, arg): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g[0] x == 0 >>> g[1] y > x """ if arg >= len(self): raise IndexError return self.get(arg) def assert_exprs(self, *args): """Assert constraints into the goal. >>> x = Int('x') >>> g = Goal() >>> g.assert_exprs(x > 0, x < 2) >>> g [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: arg = s.cast(arg) Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast()) def append(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.append(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.insert(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def add(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def convert_model(self, model): """Retrieve model from a satisfiable goal >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs')) >>> r = t(g) >>> r[0] [Or(b == 0, b == 1), Not(0 <= b)] >>> r[1] [Or(b == 0, b == 1), Not(1 <= b)] >>> # Remark: the subgoal r[0] is unsatisfiable >>> # Creating a solver for solving the second subgoal >>> s = Solver() >>> s.add(r[1]) >>> s.check() sat >>> s.model() [b = 0] >>> # Model s.model() does not assign a value to `a` >>> # It is a model for subgoal `r[1]`, but not for goal `g` >>> # The method convert_model creates a model for `g` from a model for `r[1]`. >>> r[1].convert_model(s.model()) [b = 0, a = 1] """ if z3_debug(): _z3_assert(isinstance(model, ModelRef), "Z3 Model expected") return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the goal.""" return Z3_goal_to_string(self.ctx.ref(), self.goal) def dimacs(self, include_names=True): """Return a textual representation of the goal in DIMACS format.""" return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names) def translate(self, target): """Copy goal `self` to context `target`. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 10) >>> g [x > 10] >>> c2 = Context() >>> g2 = g.translate(c2) >>> g2 [x > 10] >>> g.ctx == main_ctx() True >>> g2.ctx == c2 True >>> g2.ctx == main_ctx() False """ if z3_debug(): _z3_assert(isinstance(target, Context), "target must be a context") return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def simplify(self, *arguments, **keywords): """Return a new simplified goal. This method is essentially invoking the simplify tactic. >>> g = Goal() >>> x = Int('x') >>> g.add(x + 1 >= 2) >>> g [x + 1 >= 2] >>> g2 = g.simplify() >>> g2 [x >= 1] >>> # g was not modified >>> g [x + 1 >= 2] """ t = Tactic("simplify") return t.apply(self, *arguments, **keywords)[0] def as_expr(self): """Return goal `self` as a single Z3 expression. >>> x = Int('x') >>> g = Goal() >>> g.as_expr() True >>> g.add(x > 1) >>> g.as_expr() x > 1 >>> g.add(x < 10) >>> g.as_expr() And(x > 1, x < 10) """ sz = len(self) if sz == 0: return BoolVal(True, self.ctx) elif sz == 1: return self.get(0) else: return And([self.get(i) for i in range(len(self))], self.ctx) ######################################### # # AST Vector # ######################################### class AstVector(Z3PPObject): """A collection (vector) of ASTs.""" def __init__(self, v=None, ctx=None): self.vector = None if v is None: self.ctx = _get_ctx(ctx) self.vector = Z3_mk_ast_vector(self.ctx.ref()) else: self.vector = v assert ctx is not None self.ctx = ctx Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector) def __del__(self): if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None: Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector) def __len__(self): """Return the size of the vector `self`. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> A.push(Int('x')) >>> len(A) 2 """ return int(Z3_ast_vector_size(self.ctx.ref(), self.vector)) def __getitem__(self, i): """Return the AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[1] y """ if isinstance(i, int): if i < 0: i += self.__len__() if i >= self.__len__(): raise IndexError return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx) elif isinstance(i, slice): result = [] for ii in range(*i.indices(self.__len__())): result.append(_to_ast_ref( Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx, )) return result def __setitem__(self, i, v): """Update AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[0] = Int('x') >>> A[0] x """ if i >= self.__len__(): raise IndexError Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast()) def push(self, v): """Add `v` in the end of the vector. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> len(A) 1 """ Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast()) def resize(self, sz): """Resize the vector to `sz` elements. >>> A = AstVector() >>> A.resize(10) >>> len(A) 10 >>> for i in range(10): A[i] = Int('x') >>> A[5] x """ Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz) def __contains__(self, item): """Return `True` if the vector contains `item`. >>> x = Int('x') >>> A = AstVector() >>> x in A False >>> A.push(x) >>> x in A True >>> (x+1) in A False >>> A.push(x+1) >>> (x+1) in A True >>> A [x, x + 1] """ for elem in self: if elem.eq(item): return True return False def translate(self, other_ctx): """Copy vector `self` to context `other_ctx`. >>> x = Int('x') >>> A = AstVector() >>> A.push(x) >>> c2 = Context() >>> B = A.translate(c2) >>> B [x] """ return AstVector( Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), ctx=other_ctx, ) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the vector.""" return Z3_ast_vector_to_string(self.ctx.ref(), self.vector) ######################################### # # AST Map # ######################################### class AstMap: """A mapping from ASTs to ASTs.""" def __init__(self, m=None, ctx=None): self.map = None if m is None: self.ctx = _get_ctx(ctx) self.map = Z3_mk_ast_map(self.ctx.ref()) else: self.map = m assert ctx is not None self.ctx = ctx Z3_ast_map_inc_ref(self.ctx.ref(), self.map) def __deepcopy__(self, memo={}): return AstMap(self.map, self.ctx) def __del__(self): if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None: Z3_ast_map_dec_ref(self.ctx.ref(), self.map) def __len__(self): """Return the size of the map. >>> M = AstMap() >>> len(M) 0 >>> x = Int('x') >>> M[x] = IntVal(1) >>> len(M) 1 """ return int(Z3_ast_map_size(self.ctx.ref(), self.map)) def __contains__(self, key): """Return `True` if the map contains key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> x in M True >>> x+1 in M False """ return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast()) def __getitem__(self, key): """Retrieve the value associated with key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x] x + 1 """ return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx) def __setitem__(self, k, v): """Add/Update key `k` with value `v`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M[x] x + 1 >>> M[x] = IntVal(1) >>> M[x] 1 """ Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast()) def __repr__(self): return Z3_ast_map_to_string(self.ctx.ref(), self.map) def erase(self, k): """Remove the entry associated with key `k`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M.erase(x) >>> len(M) 0 """ Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast()) def reset(self): """Remove all entries from the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> len(M) 2 >>> M.reset() >>> len(M) 0 """ Z3_ast_map_reset(self.ctx.ref(), self.map) def keys(self): """Return an AstVector containing all keys in the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> M.keys() [x, x + x] """ return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx) ######################################### # # Model # ######################################### class FuncEntry: """Store the value of the interpretation of a function in a particular point.""" def __init__(self, entry, ctx): self.entry = entry self.ctx = ctx Z3_func_entry_inc_ref(self.ctx.ref(), self.entry) def __deepcopy__(self, memo={}): return FuncEntry(self.entry, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None: Z3_func_entry_dec_ref(self.ctx.ref(), self.entry) def num_args(self): """Return the number of arguments in the given entry. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.num_args() 2 """ return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry)) def arg_value(self, idx): """Return the value of argument `idx`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.arg_value(0) 1 >>> e.arg_value(1) 2 >>> try: ... e.arg_value(2) ... except IndexError: ... print("index error") index error """ if idx >= self.num_args(): raise IndexError return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx) def value(self): """Return the value of the function at point `self`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.value() 20 """ return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx) def as_list(self): """Return entry `self` as a Python list. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.as_list() [1, 2, 20] """ args = [self.arg_value(i) for i in range(self.num_args())] args.append(self.value()) return args def __repr__(self): return repr(self.as_list()) class FuncInterp(Z3PPObject): """Stores the interpretation of a function in a Z3 model.""" def __init__(self, f, ctx): self.f = f self.ctx = ctx if self.f is not None: Z3_func_interp_inc_ref(self.ctx.ref(), self.f) def __del__(self): if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None: Z3_func_interp_dec_ref(self.ctx.ref(), self.f) def else_value(self): """ Return the `else` value for a function interpretation. Return None if Z3 did not specify the `else` value for this object. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].else_value() 1 """ r = Z3_func_interp_get_else(self.ctx.ref(), self.f) if r: return _to_expr_ref(r, self.ctx) else: return None def num_entries(self): """Return the number of entries/points in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 """ return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f)) def arity(self): """Return the number of arguments for each entry in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f].arity() 1 """ return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f)) def entry(self, idx): """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 >>> m[f].entry(0) [2, 0] """ if idx >= self.num_entries(): raise IndexError return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx) def translate(self, other_ctx): """Copy model 'self' to context 'other_ctx'. """ return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def as_list(self): """Return the function interpretation as a Python list. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].as_list() [[2, 0], 1] """ r = [self.entry(i).as_list() for i in range(self.num_entries())] r.append(self.else_value()) return r def __repr__(self): return obj_to_string(self) class ModelRef(Z3PPObject): """Model/Solution of a satisfiability problem (aka system of constraints).""" def __init__(self, m, ctx): assert ctx is not None self.model = m self.ctx = ctx Z3_model_inc_ref(self.ctx.ref(), self.model) def __del__(self): if self.ctx.ref() is not None and Z3_model_dec_ref is not None: Z3_model_dec_ref(self.ctx.ref(), self.model) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the model.""" return Z3_model_to_string(self.ctx.ref(), self.model) def eval(self, t, model_completion=False): """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.eval(x + 1) 2 >>> m.eval(x == 1) True >>> y = Int('y') >>> m.eval(y + x) 1 + y >>> m.eval(y) y >>> m.eval(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.eval(y + x) 1 """ r = (Ast * 1)() if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r): return _to_expr_ref(r[0], self.ctx) raise Z3Exception("failed to evaluate expression in the model") def evaluate(self, t, model_completion=False): """Alias for `eval`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.evaluate(x + 1) 2 >>> m.evaluate(x == 1) True >>> y = Int('y') >>> m.evaluate(y + x) 1 + y >>> m.evaluate(y) y >>> m.evaluate(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.evaluate(y + x) 1 """ return self.eval(t, model_completion) def __len__(self): """Return the number of constant and function declarations in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, f(x) != x) >>> s.check() sat >>> m = s.model() >>> len(m) 2 """ num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) return num_consts + num_funcs def get_interp(self, decl): """Return the interpretation for a given declaration or constant. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1 >>> m[f] [else -> 0] """ if z3_debug(): _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected") if is_const(decl): decl = decl.decl() try: if decl.arity() == 0: _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast) if _r.value is None: return None r = _to_expr_ref(_r, self.ctx) if is_as_array(r): fi = self.get_interp(get_as_array_func(r)) if fi is None: return fi e = fi.else_value() if e is None: return fi if fi.arity() != 1: return fi srt = decl.range() dom = srt.domain() e = K(dom, e) i = 0 sz = fi.num_entries() n = fi.arity() while i < sz: fe = fi.entry(i) e = Store(e, fe.arg_value(0), fe.value()) i += 1 return e else: return r else: return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) except Z3Exception: return None def num_sorts(self): """Return the number of uninterpreted sorts that contain an interpretation in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 1 """ return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model)) def get_sort(self, idx): """Return the uninterpreted sort at position `idx` < self.num_sorts(). >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 2 >>> m.get_sort(0) A >>> m.get_sort(1) B """ if idx >= self.num_sorts(): raise IndexError return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx) def sorts(self): """Return all uninterpreted sorts that have an interpretation in the model `self`. >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.sorts() [A, B] """ return [self.get_sort(i) for i in range(self.num_sorts())] def get_universe(self, s): """Return the interpretation for the uninterpreted sort `s` in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.get_universe(A) [A!val!1, A!val!0] """ if z3_debug(): _z3_assert(isinstance(s, SortRef), "Z3 sort expected") try: return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx) except Z3Exception: return None def __getitem__(self, idx): """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned. The elements can be retrieved using position or the actual declaration. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> len(m) 2 >>> m[0] x >>> m[1] f >>> m[x] 1 >>> m[f] [else -> 0] >>> for d in m: print("%s -> %s" % (d, m[d])) x -> 1 f -> [else -> 0] """ if _is_int(idx): if idx >= len(self): raise IndexError num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model) if (idx < num_consts): return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx) else: return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx) if isinstance(idx, FuncDeclRef): return self.get_interp(idx) if is_const(idx): return self.get_interp(idx.decl()) if isinstance(idx, SortRef): return self.get_universe(idx) if z3_debug(): _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected") return None def decls(self): """Return a list with all symbols that have an interpretation in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m.decls() [x, f] """ r = [] for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx)) for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx)) return r def update_value(self, x, value): """Update the interpretation of a constant""" if is_expr(x): x = x.decl() if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp): fi1 = value.f fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast); fi2 = FuncInterp(fi2, x.ctx) for i in range(value.num_entries()): e = value.entry(i) n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry) v = AstVector() for j in range(n): v.push(e.arg_value(j)) val = Z3_func_entry_get_value(x.ctx_ref(), e.entry) Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val) return if not is_func_decl(x) or x.arity() != 0: raise Z3Exception("Expecting 0-ary function or constant expression") value = _py2expr(value) Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") model = Z3_model_translate(self.ctx.ref(), self.model, target.ref()) return ModelRef(model, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def Model(ctx=None): ctx = _get_ctx(ctx) return ModelRef(Z3_mk_model(ctx.ref()), ctx) def is_as_array(n): """Return true if n is a Z3 expression of the form (_ as-array f).""" return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast()) def get_as_array_func(n): """Return the function declaration f associated with a Z3 expression of the form (_ as-array f).""" if z3_debug(): _z3_assert(is_as_array(n), "as-array Z3 expression expected.") return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx) ######################################### # # Statistics # ######################################### class Statistics: """Statistics for `Solver.check()`.""" def __init__(self, stats, ctx): self.stats = stats self.ctx = ctx Z3_stats_inc_ref(self.ctx.ref(), self.stats) def __deepcopy__(self, memo={}): return Statistics(self.stats, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_stats_dec_ref is not None: Z3_stats_dec_ref(self.ctx.ref(), self.stats) def __repr__(self): if in_html_mode(): out = io.StringIO() even = True out.write(u('<table border="1" cellpadding="2" cellspacing="0">')) for k, v in self: if even: out.write(u('<tr style="background-color:#CFCFCF">')) even = False else: out.write(u("<tr>")) even = True out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v))) out.write(u("</table>")) return out.getvalue() else: return Z3_stats_to_string(self.ctx.ref(), self.stats) def __len__(self): """Return the number of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 """ return int(Z3_stats_size(self.ctx.ref(), self.stats)) def __getitem__(self, idx): """Return the value of statistical counter at position `idx`. The result is a pair (key, value). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 >>> st[0] ('nlsat propagations', 2) >>> st[1] ('nlsat stages', 2) """ if idx >= len(self): raise IndexError if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val) def keys(self): """Return the list of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() """ return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))] def get_key_value(self, key): """Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2 """ for idx in range(len(self)): if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) raise Z3Exception("unknown key") def __getattr__(self, name): """Access the value of statistical using attributes. Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'), we should use '_' (e.g., 'nlsat_propagations'). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.nlsat_propagations 2 >>> st.nlsat_stages 2 """ key = name.replace("_", " ") try: return self.get_key_value(key) except Z3Exception: raise AttributeError ######################################### # # Solver # ######################################### class CheckSatResult: """Represents the result of a satisfiability check: sat, unsat, unknown. >>> s = Solver() >>> s.check() sat >>> r = s.check() >>> isinstance(r, CheckSatResult) True """ def __init__(self, r): self.r = r def __deepcopy__(self, memo={}): return CheckSatResult(self.r) def __eq__(self, other): return isinstance(other, CheckSatResult) and self.r == other.r def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if in_html_mode(): if self.r == Z3_L_TRUE: return "<b>sat</b>" elif self.r == Z3_L_FALSE: return "<b>unsat</b>" else: return "<b>unknown</b>" else: if self.r == Z3_L_TRUE: return "sat" elif self.r == Z3_L_FALSE: return "unsat" else: return "unknown" def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res sat = CheckSatResult(Z3_L_TRUE) unsat = CheckSatResult(Z3_L_FALSE) unknown = CheckSatResult(Z3_L_UNDEF) class Solver(Z3PPObject): """ Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc. """ def __init__(self, solver=None, ctx=None, logFile=None): assert solver is None or ctx is not None self.ctx = _get_ctx(ctx) self.backtrack_level = 4000000000 self.solver = None if solver is None: self.solver = Z3_mk_solver(self.ctx.ref()) else: self.solver = solver Z3_solver_inc_ref(self.ctx.ref(), self.solver) if logFile is not None: self.set("smtlib2_log", logFile) def __del__(self): if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None: Z3_solver_dec_ref(self.ctx.ref(), self.solver) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. >>> s = Solver() >>> # The option MBQI can be set using three different approaches. >>> s.set(mbqi=True) >>> s.set('MBQI', True) >>> s.set(':mbqi', True) """ p = args2params(args, keys, self.ctx) Z3_solver_set_params(self.ctx.ref(), self.solver, p.params) def push(self): """Create a backtracking point. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_push(self.ctx.ref(), self.solver) def pop(self, num=1): """Backtrack \\c num backtracking points. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_pop(self.ctx.ref(), self.solver, num) def num_scopes(self): """Return the current number of backtracking points. >>> s = Solver() >>> s.num_scopes() 0 >>> s.push() >>> s.num_scopes() 1 >>> s.push() >>> s.num_scopes() 2 >>> s.pop() >>> s.num_scopes() 1 """ return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver) def reset(self): """Remove all asserted constraints and backtracking points created using `push()`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.reset() >>> s [] """ Z3_solver_reset(self.ctx.ref(), self.solver) def assert_exprs(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.assert_exprs(x > 0, x < 2) >>> s [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast()) else: arg = s.cast(arg) Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast()) def add(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.append(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.insert(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Solver() >>> s.set(unsat_core=True) >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast()) def check(self, *assumptions): """Check whether the assertions in the given solver plus the optional assumptions are consistent or not. >>> x = Int('x') >>> s = Solver() >>> s.check() sat >>> s.add(x > 0, x < 2) >>> s.check() sat >>> s.model().eval(x) 1 >>> s.add(x < 1) >>> s.check() unsat >>> s.reset() >>> s.add(2**x == 4) >>> s.check() unknown """ s = BoolSort(self.ctx) assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = s.cast(assumptions[i]).as_ast() r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions) return CheckSatResult(r) def model(self): """Return a model for the last `check()`. This function raises an exception if a model is not available (e.g., last `check()` returned unsat). >>> s = Solver() >>> a = Int('a') >>> s.add(a + 2 == 0) >>> s.check() sat >>> s.model() [a = -2] """ try: return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def import_model_converter(self, other): """Import model converter from other into the current solver""" Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver) def unsat_core(self): """Return a subset (as an AST vector) of the assumptions provided to the last check(). These are the assumptions Z3 used in the unsatisfiability proof. Assumptions are available in Z3. They are used to extract unsatisfiable cores. They may be also used to "retract" assumptions. Note that, assumptions are not really "soft constraints", but they can be used to implement them. >>> p1, p2, p3 = Bools('p1 p2 p3') >>> x, y = Ints('x y') >>> s = Solver() >>> s.add(Implies(p1, x > 0)) >>> s.add(Implies(p2, y > x)) >>> s.add(Implies(p2, y < 1)) >>> s.add(Implies(p3, y > -3)) >>> s.check(p1, p2, p3) unsat >>> core = s.unsat_core() >>> len(core) 2 >>> p1 in core True >>> p2 in core True >>> p3 in core False >>> # "Retracting" p2 >>> s.check(p1, p3) sat """ return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx) def consequences(self, assumptions, variables): """Determine fixed values for the variables based on the solver state and assumptions. >>> s = Solver() >>> a, b, c, d = Bools('a b c d') >>> s.add(Implies(a,b), Implies(b, c)) >>> s.consequences([a],[b,c,d]) (sat, [Implies(a, b), Implies(a, c)]) >>> s.consequences([Not(c),d],[a,b,c,d]) (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))]) """ if isinstance(assumptions, list): _asms = AstVector(None, self.ctx) for a in assumptions: _asms.push(a) assumptions = _asms if isinstance(variables, list): _vars = AstVector(None, self.ctx) for a in variables: _vars.push(a) variables = _vars _z3_assert(isinstance(assumptions, AstVector), "ast vector expected") _z3_assert(isinstance(variables, AstVector), "ast vector expected") consequences = AstVector(None, self.ctx) r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector) sz = len(consequences) consequences = [consequences[i] for i in range(sz)] return CheckSatResult(r), consequences def from_file(self, filename): """Parse assertions from a file""" Z3_solver_from_file(self.ctx.ref(), self.solver, filename) def from_string(self, s): """Parse assertions from a string""" Z3_solver_from_string(self.ctx.ref(), self.solver, s) def cube(self, vars=None): """Get set of cubes The method takes an optional set of variables that restrict which variables may be used as a starting point for cubing. If vars is not None, then the first case split is based on a variable in this set. """ self.cube_vs = AstVector(None, self.ctx) if vars is not None: for v in vars: self.cube_vs.push(v) while True: lvl = self.backtrack_level self.backtrack_level = 4000000000 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx) if (len(r) == 1 and is_false(r[0])): return yield r if (len(r) == 0): return def cube_vars(self): """Access the set of variables that were touched by the most recently generated cube. This set of variables can be used as a starting point for additional cubes. The idea is that variables that appear in clauses that are reduced by the most recent cube are likely more useful to cube on.""" return self.cube_vs def root(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure root of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx) def next(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure sibling of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx) def proof(self): """Return a proof for the last `check()`. Proof construction must be enabled.""" return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx) def assertions(self): """Return an AST vector containing all added constraints. >>> s = Solver() >>> s.assertions() [] >>> a = Int('a') >>> s.add(a > 0) >>> s.add(a < 10) >>> s.assertions() [a > 0, a < 10] """ return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx) def units(self): """Return an AST vector containing all currently inferred units. """ return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx) def non_units(self): """Return an AST vector containing all atomic formulas in solver state that are not units. """ return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx) def trail_levels(self): """Return trail and decision levels of the solver state after a check() call. """ trail = self.trail() levels = (ctypes.c_uint * len(trail))() Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels) return trail, levels def trail(self): """Return trail of the solver state after a check() call. """ return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx) def statistics(self): """Return statistics for the last `check()`. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('final checks') 1 >>> len(st) > 0 True >>> st[0] != 0 True """ return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx) def reason_unknown(self): """Return a string describing why the last `check()` returned `unknown`. >>> x = Int('x') >>> s = SimpleSolver() >>> s.add(2**x == 4) >>> s.check() unknown >>> s.reason_unknown() '(incomplete (theory arithmetic))' """ return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver) def help(self): """Display a string describing all available options.""" print(Z3_solver_get_help(self.ctx.ref(), self.solver)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx) def __repr__(self): """Return a formatted string with all added constraints.""" return obj_to_string(self) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> s1 = Solver(ctx=c1) >>> s2 = s1.translate(c2) """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref()) return Solver(solver, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s.add(x < 2) >>> r = s.sexpr() """ return Z3_solver_to_string(self.ctx.ref(), self.solver) def dimacs(self, include_names=True): """Return a textual representation of the solver in DIMACS format.""" return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names) def to_smt2(self): """return SMTLIB2 formatted benchmark for solver's assertions""" es = self.assertions() sz = len(es) sz1 = sz if sz1 > 0: sz1 -= 1 v = (Ast * sz1)() for i in range(sz1): v[i] = es[i].as_ast() if sz > 0: e = es[sz1].as_ast() else: e = BoolVal(True, self.ctx).as_ast() return Z3_benchmark_to_smtlib_string( self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e, ) def SolverFor(logic, ctx=None, logFile=None): """Create a solver customized for the given logic. The parameter `logic` is a string. It should be contains the name of a SMT-LIB logic. See http://www.smtlib.org/ for the name of all available logics. >>> s = SolverFor("QF_LIA") >>> x = Int('x') >>> s.add(x > 0) >>> s.add(x < 2) >>> s.check() sat >>> s.model() [x = 1] """ ctx = _get_ctx(ctx) logic = to_symbol(logic) return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile) def SimpleSolver(ctx=None, logFile=None): """Return a simple general purpose solver with limited amount of preprocessing. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat """ ctx = _get_ctx(ctx) return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile) ######################################### # # Fixedpoint # ######################################### class Fixedpoint(Z3PPObject): """Fixedpoint API provides methods for solving with recursive predicates""" def __init__(self, fixedpoint=None, ctx=None): assert fixedpoint is None or ctx is not None self.ctx = _get_ctx(ctx) self.fixedpoint = None if fixedpoint is None: self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref()) else: self.fixedpoint = fixedpoint Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint) self.vars = [] def __deepcopy__(self, memo={}): return FixedPoint(self.fixedpoint, self.ctx) def __del__(self): if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None: Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params) def help(self): """Display a string describing all available options.""" print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the fixedpoint solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: f = self.abstract(f) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast()) else: arg = s.cast(arg) arg = self.abstract(arg) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def insert(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def add_rule(self, head, body=None, name=None): """Assert rules defining recursive predicates to the fixedpoint solver. >>> a = Bool('a') >>> b = Bool('b') >>> s = Fixedpoint() >>> s.register_relation(a.decl()) >>> s.register_relation(b.decl()) >>> s.fact(a) >>> s.rule(b, a) >>> s.query(b) sat """ if name is None: name = "" name = to_symbol(name, self.ctx) if body is None: head = self.abstract(head) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name) else: body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx), head)) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def rule(self, head, body=None, name=None): """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, body, name) def fact(self, head, name=None): """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, None, name) def query(self, *query): """Query the fixedpoint engine whether formula is derivable. You can also pass an tuple or list of recursive predicates. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDeclRef): _decls = (FuncDecl * sz)() i = 0 for q in query: _decls[i] = q.ast i = i + 1 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls) else: if sz == 1: query = query[0] else: query = And(query, self.ctx) query = self.abstract(query, False) r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast()) return CheckSatResult(r) def query_from_lvl(self, lvl, *query): """Query the fixedpoint engine whether formula is derivable starting at the given query level. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDecl): _z3_assert(False, "unsupported") else: if sz == 1: query = query[0] else: query = And(query) query = self.abstract(query, False) r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl) return CheckSatResult(r) def update_rule(self, head, body, name): """update rule""" if name is None: name = "" name = to_symbol(name, self.ctx) body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx), head)) Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def get_answer(self): """Retrieve answer from last query call.""" r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_ground_sat_answer(self): """Retrieve a ground cex from last query call.""" r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_rules_along_trace(self): """retrieve rules along the counterexample trace""" return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx) def get_rule_names_along_trace(self): """retrieve rule names along the counterexample trace""" # this is a hack as I don't know how to return a list of symbols from C++; # obtain names as a single string separated by semicolons names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint)) # split into individual names return names.split(";") def get_num_levels(self, predicate): """Retrieve number of levels used for predicate in PDR engine""" return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast) def get_cover_delta(self, level, predicate): """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity) """ r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast) return _to_expr_ref(r, self.ctx) def add_cover(self, level, predicate, property): """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity) """ Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast) def register_relation(self, *relations): """Register relation as recursive""" relations = _get_args(relations) for f in relations: Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast) def set_predicate_representation(self, f, *representations): """Control how relation is represented""" representations = _get_args(representations) representations = [to_symbol(s) for s in representations] sz = len(representations) args = (Symbol * sz)() for i in range(sz): args[i] = representations[i] Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args) def parse_string(self, s): """Parse rules and queries from a string""" return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx) def parse_file(self, f): """Parse rules and queries from a file""" return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx) def get_rules(self): """retrieve rules that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx) def get_assertions(self): """retrieve assertions that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)()) def to_string(self, queries): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. Include also queries. """ args, len = _to_ast_array(queries) return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args) def statistics(self): """Return statistics for the last `query()`. """ return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx) def reason_unknown(self): """Return a string describing why the last `query()` returned `unknown`. """ return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint) def declare_var(self, *vars): """Add variable or several variables. The added variable or variables will be bound in the rules and queries """ vars = _get_args(vars) for v in vars: self.vars += [v] def abstract(self, fml, is_forall=True): if self.vars == []: return fml if is_forall: return ForAll(self.vars, fml) else: return Exists(self.vars, fml) ######################################### # # Finite domains # ######################################### class FiniteDomainSortRef(SortRef): """Finite domain sort.""" def size(self): """Return the size of the finite domain sort""" r = (ctypes.c_ulonglong * 1)() if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r): return r[0] else: raise Z3Exception("Failed to retrieve finite domain sort size") def FiniteDomainSort(name, sz, ctx=None): """Create a named finite domain sort of a given size sz""" if not isinstance(name, Symbol): name = to_symbol(name) ctx = _get_ctx(ctx) return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx) def is_finite_domain_sort(s): """Return True if `s` is a Z3 finite-domain sort. >>> is_finite_domain_sort(FiniteDomainSort('S', 100)) True >>> is_finite_domain_sort(IntSort()) False """ return isinstance(s, FiniteDomainSortRef) class FiniteDomainRef(ExprRef): """Finite-domain expressions.""" def sort(self): """Return the sort of the finite-domain expression `self`.""" return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def is_finite_domain(a): """Return `True` if `a` is a Z3 finite-domain expression. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain(b) True >>> is_finite_domain(Int('x')) False """ return isinstance(a, FiniteDomainRef) class FiniteDomainNumRef(FiniteDomainRef): """Integer values.""" def as_long(self): """Return a Z3 finite-domain numeral as a Python long (bignum) numeral. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(3, s) >>> v 3 >>> v.as_long() + 1 4 """ return int(self.as_string()) def as_string(self): """Return a Z3 finite-domain numeral as a Python string. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(42, s) >>> v.as_string() '42' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def FiniteDomainVal(val, sort, ctx=None): """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used. >>> s = FiniteDomainSort('S', 256) >>> FiniteDomainVal(255, s) 255 >>> FiniteDomainVal('100', s) 100 """ if z3_debug(): _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort") ctx = sort.ctx return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx) def is_finite_domain_value(a): """Return `True` if `a` is a Z3 finite-domain value. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain_value(b) False >>> b = FiniteDomainVal(10, s) >>> b 10 >>> is_finite_domain_value(b) True """ return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast()) ######################################### # # Optimize # ######################################### class OptimizeObjective: def __init__(self, opt, value, is_max): self._opt = opt self._value = value self._is_max = is_max def lower(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def lower_values(self): opt = self._opt return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper_values(self): opt = self._opt return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def value(self): if self._is_max: return self.upper() else: return self.lower() def __str__(self): return "%s:%s" % (self._value, self._is_max) _on_models = {} def _global_on_model(ctx): (fn, mdl) = _on_models[ctx] fn(mdl) _on_model_eh = on_model_eh_type(_global_on_model) class Optimize(Z3PPObject): """Optimize API provides methods for solving using objective functions and weighted soft constraints""" def __init__(self, ctx=None): self.ctx = _get_ctx(ctx) self.optimize = Z3_mk_optimize(self.ctx.ref()) self._on_models_id = None Z3_optimize_inc_ref(self.ctx.ref(), self.optimize) def __deepcopy__(self, memo={}): return Optimize(self.optimize, self.ctx) def __del__(self): if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None: Z3_optimize_dec_ref(self.ctx.ref(), self.optimize) if self._on_models_id is not None: del _on_models[self._on_models_id] def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params) def help(self): """Display a string describing all available options.""" print(Z3_optimize_get_help(self.ctx.ref(), self.optimize)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the optimize solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast()) else: arg = s.cast(arg) Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the optimize solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Optimize() >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast()) def add_soft(self, arg, weight="1", id=None): """Add soft constraint with optional weight and optional identifier. If no weight is supplied, then the penalty for violating the soft constraint is 1. Soft constraints are grouped by identifiers. Soft constraints that are added without identifiers are grouped by default. """ if _is_int(weight): weight = "%d" % weight elif isinstance(weight, float): weight = "%f" % weight if not isinstance(weight, str): raise Z3Exception("weight should be a string or an integer") if id is None: id = "" id = to_symbol(id, self.ctx) def asoft(a): v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id) return OptimizeObjective(self, v, False) if sys.version_info.major >= 3 and isinstance(arg, Iterable): return [asoft(a) for a in arg] return asoft(arg) def maximize(self, arg): """Add objective function to maximize.""" return OptimizeObjective( self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=True, ) def minimize(self, arg): """Add objective function to minimize.""" return OptimizeObjective( self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=False, ) def push(self): """create a backtracking point for added rules, facts and assertions""" Z3_optimize_push(self.ctx.ref(), self.optimize) def pop(self): """restore to previously created backtracking point""" Z3_optimize_pop(self.ctx.ref(), self.optimize) def check(self, *assumptions): """Check satisfiability while optimizing objective functions.""" assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions)) def reason_unknown(self): """Return a string that describes why the last `check()` returned `unknown`.""" return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize) def model(self): """Return a model for the last check().""" try: return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def unsat_core(self): return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx) def lower(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower() def upper(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper() def lower_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower_values() def upper_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper_values() def from_file(self, filename): """Parse assertions and objectives from a file""" Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename) def from_string(self, s): """Parse assertions and objectives from a string""" Z3_optimize_from_string(self.ctx.ref(), self.optimize, s) def assertions(self): """Return an AST vector containing all added constraints.""" return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx) def objectives(self): """returns set of objective functions""" return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_optimize_to_string(self.ctx.ref(), self.optimize) def statistics(self): """Return statistics for the last check`. """ return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx) def set_on_model(self, on_model): """Register a callback that is invoked with every incremental improvement to objective values. The callback takes a model as argument. The life-time of the model is limited to the callback so the model has to be (deep) copied if it is to be used after the callback """ id = len(_on_models) + 41 mdl = Model(self.ctx) _on_models[id] = (on_model, mdl) self._on_models_id = id Z3_optimize_register_model_eh( self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh, ) ######################################### # # ApplyResult # ######################################### class ApplyResult(Z3PPObject): """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters. """ def __init__(self, result, ctx): self.result = result self.ctx = ctx Z3_apply_result_inc_ref(self.ctx.ref(), self.result) def __deepcopy__(self, memo={}): return ApplyResult(self.result, self.ctx) def __del__(self): if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None: Z3_apply_result_dec_ref(self.ctx.ref(), self.result) def __len__(self): """Return the number of subgoals in `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> len(r) 2 >>> t = Then(Tactic('split-clause'), Tactic('split-clause')) >>> len(t(g)) 4 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values')) >>> len(t(g)) 1 """ return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result)) def __getitem__(self, idx): """Return one of the subgoals stored in ApplyResult object `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> r[0] [a == 0, Or(b == 0, b == 1), a > b] >>> r[1] [a == 1, Or(b == 0, b == 1), a > b] """ if idx >= len(self): raise IndexError return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the set of subgoals in `self`.""" return Z3_apply_result_to_string(self.ctx.ref(), self.result) def as_expr(self): """Return a Z3 expression consisting of all subgoals. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 1) >>> g.add(Or(x == 2, x == 3)) >>> r = Tactic('simplify')(g) >>> r [[Not(x <= 1), Or(x == 2, x == 3)]] >>> r.as_expr() And(Not(x <= 1), Or(x == 2, x == 3)) >>> r = Tactic('split-clause')(g) >>> r [[x > 1, x == 2], [x > 1, x == 3]] >>> r.as_expr() Or(And(x > 1, x == 2), And(x > 1, x == 3)) """ sz = len(self) if sz == 0: return BoolVal(False, self.ctx) elif sz == 1: return self[0].as_expr() else: return Or([self[i].as_expr() for i in range(len(self))]) ######################################### # # Simplifiers # ######################################### class Simplifier: """Simplifiers act as pre-processing utilities for solvers. Build a custom simplifier and add it to a solver""" def __init__(self, simplifier, ctx=None): self.ctx = _get_ctx(ctx) self.simplifier = None if isinstance(simplifier, SimplifierObj): self.simplifier = simplifier elif isinstance(simplifier, list): simps = [Simplifier(s, ctx) for s in simplifier] self.simplifier = simps[0].simplifier for i in range(1, len(simps)): self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) return else: if z3_debug(): _z3_assert(isinstance(simplifier, str), "simplifier name expected") try: self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier)) except Z3Exception: raise Z3Exception("unknown simplifier '%s'" % simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) def __deepcopy__(self, memo={}): return Simplifier(self.simplifier, self.ctx) def __del__(self): if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None: Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier) def using_params(self, *args, **keys): """Return a simplifier that uses the given configuration options""" p = args2params(args, keys, self.ctx) return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx) def add(self, solver): """Return a solver that applies the simplification pre-processing specified by the simplifier""" return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx) def help(self): """Display a string containing a description of the available options for the `self` simplifier.""" print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx) ######################################### # # Tactics # ######################################### class Tactic: """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver(). Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond(). """ def __init__(self, tactic, ctx=None): self.ctx = _get_ctx(ctx) self.tactic = None if isinstance(tactic, TacticObj): self.tactic = tactic else: if z3_debug(): _z3_assert(isinstance(tactic, str), "tactic name expected") try: self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic)) except Z3Exception: raise Z3Exception("unknown tactic '%s'" % tactic) Z3_tactic_inc_ref(self.ctx.ref(), self.tactic) def __deepcopy__(self, memo={}): return Tactic(self.tactic, self.ctx) def __del__(self): if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None: Z3_tactic_dec_ref(self.ctx.ref(), self.tactic) def solver(self, logFile=None): """Create a solver using the tactic `self`. The solver supports the methods `push()` and `pop()`, but it will always solve each `check()` from scratch. >>> t = Then('simplify', 'nlsat') >>> s = t.solver() >>> x = Real('x') >>> s.add(x**2 == 2, x > 0) >>> s.check() sat >>> s.model() [x = 1.4142135623?] """ return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile) def apply(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t.apply(And(x == 0, y >= x + 1)) [[y >= 1]] """ if z3_debug(): _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected") goal = _to_goal(goal) if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, self.ctx) return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx) else: return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx) def __call__(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t(And(x == 0, y >= x + 1)) [[y >= 1]] """ return self.apply(goal, *arguments, **keywords) def help(self): """Display a string containing a description of the available options for the `self` tactic.""" print(Z3_tactic_get_help(self.ctx.ref(), self.tactic)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx) def _to_goal(a): if isinstance(a, BoolRef): goal = Goal(ctx=a.ctx) goal.add(a) return goal else: return a def _to_tactic(t, ctx=None): if isinstance(t, Tactic): return t else: return Tactic(t, ctx) def _and_then(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def _or_else(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def AndThen(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. >>> x, y = Ints('x y') >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get("ctx", None) num = len(ts) r = ts[0] for i in range(num - 1): r = _and_then(r, ts[i + 1], ctx) return r def Then(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks). >>> x, y = Ints('x y') >>> t = Then(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ return AndThen(*ts, **ks) def OrElse(*ts, **ks): """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = OrElse(Tactic('split-clause'), Tactic('skip')) >>> # Tactic split-clause fails if there is no clause in the given goal. >>> t(x == 0) [[x == 0]] >>> t(Or(x == 0, x == 1)) [[x == 0], [x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get("ctx", None) num = len(ts) r = ts[0] for i in range(num - 1): r = _or_else(r, ts[i + 1], ctx) return r def ParOr(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = ParOr(Tactic('simplify'), Tactic('fail')) >>> t(x + 1 == 2) [[x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = _get_ctx(ks.get("ctx", None)) ts = [_to_tactic(t, ctx) for t in ts] sz = len(ts) _args = (TacticObj * sz)() for i in range(sz): _args[i] = ts[i].tactic return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx) def ParThen(t1, t2, ctx=None): """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel. >>> x, y = Ints('x y') >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values')) >>> t(And(Or(x == 1, x == 2), y == x + 1)) [[x == 1, y == 2], [x == 2, y == 3]] """ t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def ParAndThen(t1, t2, ctx=None): """Alias for ParThen(t1, t2, ctx).""" return ParThen(t1, t2, ctx) def With(t, *args, **keys): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> t = With(Tactic('simplify'), som=True) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ ctx = keys.pop("ctx", None) t = _to_tactic(t, ctx) p = args2params(args, keys, t.ctx) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def WithParams(t, p): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> p = ParamsRef() >>> p.set("som", True) >>> t = WithParams(Tactic('simplify'), p) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ t = _to_tactic(t, None) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def Repeat(t, max=4294967295, ctx=None): """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached. >>> x, y = Ints('x y') >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y) >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) >>> r = t(c) >>> for subgoal in r: print(subgoal) [x == 0, y == 0, x > y] [x == 0, y == 1, x > y] [x == 1, y == 0, x > y] [x == 1, y == 1, x > y] >>> t = Then(t, Tactic('propagate-values')) >>> t(c) [[x == 1, y == 0]] """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx) def TryFor(t, ms, ctx=None): """Return a tactic that applies `t` to a given goal for `ms` milliseconds. If `t` does not terminate in `ms` milliseconds, then it fails. """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx) def tactics(ctx=None): """Return a list of all available tactics in Z3. >>> l = tactics() >>> l.count('simplify') == 1 True """ ctx = _get_ctx(ctx) return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))] def tactic_description(name, ctx=None): """Return a short description for the tactic named `name`. >>> d = tactic_description('simplify') """ ctx = _get_ctx(ctx) return Z3_tactic_get_descr(ctx.ref(), name) def describe_tactics(): """Display a (tabular) description of all available tactics in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for t in tactics(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print("<tr>") even = True print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40))) print("</table>") else: for t in tactics(): print("%s : %s" % (t, tactic_description(t))) class Probe: """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used. """ def __init__(self, probe, ctx=None): self.ctx = _get_ctx(ctx) self.probe = None if isinstance(probe, ProbeObj): self.probe = probe elif isinstance(probe, float): self.probe = Z3_probe_const(self.ctx.ref(), probe) elif _is_int(probe): self.probe = Z3_probe_const(self.ctx.ref(), float(probe)) elif isinstance(probe, bool): if probe: self.probe = Z3_probe_const(self.ctx.ref(), 1.0) else: self.probe = Z3_probe_const(self.ctx.ref(), 0.0) else: if z3_debug(): _z3_assert(isinstance(probe, str), "probe name expected") try: self.probe = Z3_mk_probe(self.ctx.ref(), probe) except Z3Exception: raise Z3Exception("unknown probe '%s'" % probe) Z3_probe_inc_ref(self.ctx.ref(), self.probe) def __deepcopy__(self, memo={}): return Probe(self.probe, self.ctx) def __del__(self): if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None: Z3_probe_dec_ref(self.ctx.ref(), self.probe) def __lt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`. >>> p = Probe('size') < 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __gt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`. >>> p = Probe('size') > 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __le__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`. >>> p = Probe('size') <= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ge__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`. >>> p = Probe('size') >= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __eq__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`. >>> p = Probe('size') == 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ne__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`. >>> p = Probe('size') != 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ p = self.__eq__(other) return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx) def __call__(self, goal): """Evaluate the probe `self` in the given goal. >>> p = Probe('size') >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 2.0 >>> g.add(x < 20) >>> p(g) 3.0 >>> p = Probe('num-consts') >>> p(g) 1.0 >>> p = Probe('is-propositional') >>> p(g) 0.0 >>> p = Probe('is-qflia') >>> p(g) 1.0 """ if z3_debug(): _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected") goal = _to_goal(goal) return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal) def is_probe(p): """Return `True` if `p` is a Z3 probe. >>> is_probe(Int('x')) False >>> is_probe(Probe('memory')) True """ return isinstance(p, Probe) def _to_probe(p, ctx=None): if is_probe(p): return p else: return Probe(p, ctx) def probes(ctx=None): """Return a list of all available probes in Z3. >>> l = probes() >>> l.count('memory') == 1 True """ ctx = _get_ctx(ctx) return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))] def probe_description(name, ctx=None): """Return a short description for the probe named `name`. >>> d = probe_description('memory') """ ctx = _get_ctx(ctx) return Z3_probe_get_descr(ctx.ref(), name) def describe_probes(): """Display a (tabular) description of all available probes in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for p in probes(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print("<tr>") even = True print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40))) print("</table>") else: for p in probes(): print("%s : %s" % (p, probe_description(p))) def _probe_nary(f, args, ctx): if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") num = len(args) r = _to_probe(args[0], ctx) for i in range(num - 1): r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx) return r def _probe_and(args, ctx): return _probe_nary(Z3_probe_and, args, ctx) def _probe_or(args, ctx): return _probe_nary(Z3_probe_or, args, ctx) def FailIf(p, ctx=None): """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal. >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx) def When(p, t, ctx=None): """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. >>> t = When(Probe('size') > 2, Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) t = _to_tactic(t, ctx) return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx) def Cond(p, t1, t2, ctx=None): """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise. >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt')) """ p = _to_probe(p, ctx) t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx) ######################################### # # Utils # ######################################### def simplify(a, *arguments, **keywords): """Simplify the expression `a` using the given options. This function has many options. Use `help_simplify` to obtain the complete list. >>> x = Int('x') >>> y = Int('y') >>> simplify(x + 1 + y + x + 1) 2 + 2*x + y >>> simplify((x + 1)*(y + 1), som=True) 1 + x + y + x*y >>> simplify(Distinct(x, y, 1), blast_distinct=True) And(Not(x == y), Not(x == 1), Not(y == 1)) >>> simplify(And(x == 0, y == 1), elim_and=True) Not(Or(Not(x == 0), Not(y == 1))) """ if z3_debug(): _z3_assert(is_expr(a), "Z3 expression expected") if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, a.ctx) return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx) else: return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx) def help_simplify(): """Return a string describing all options available for Z3 `simplify` procedure.""" print(Z3_simplify_get_help(main_ctx().ref())) def simplify_param_descrs(): """Return the set of parameter descriptions for Z3 `simplify` procedure.""" return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx()) def substitute(t, *m): """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to. >>> x = Int('x') >>> y = Int('y') >>> substitute(x + 1, (x, y + 1)) y + 1 + 1 >>> f = Function('f', IntSort(), IntSort()) >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1))) 1 + 1 """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert( all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, expression pairs expected.") _z3_assert( all([p[0].sort().eq(p[1].sort()) for p in m]), 'Z3 invalid substitution, mismatching "from" and "to" sorts.') num = len(m) _from = (Ast * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_ast() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def substitute_vars(t, *m): """Substitute the free variables in t with the expression in m. >>> v0 = Var(0, IntSort()) >>> v1 = Var(1, IntSort()) >>> x = Int('x') >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # replace v0 with x+1 and v1 with x >>> substitute_vars(f(v0, v1), x + 1, x) f(x + 1, x) """ if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.") num = len(m) _to = (Ast * num)() for i in range(num): _to[i] = m[i].as_ast() return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx) def substitute_funs(t, *m): """Apply substitution m on t, m is a list of pairs of a function and expression (from, to) Every occurrence in to of the function from is replaced with the expression to. The expression to can have free variables, that refer to the arguments of from. For examples, see """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, funcion pairs expected.") num = len(m) _from = (FuncDecl * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_func_decl() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def Sum(*args): """Create the sum of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Sum(a, b, c) a + b + c >>> Sum([a, b, c]) a + b + c >>> A = IntVector('a', 5) >>> Sum(A) a__0 + a__1 + a__2 + a__3 + a__4 """ args = _get_args(args) if len(args) == 0: return 0 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a + b, args, 0) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a + b, args, 0) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx) def Product(*args): """Create the product of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Product(a, b, c) a*b*c >>> Product([a, b, c]) a*b*c >>> A = IntVector('a', 5) >>> Product(A) a__0*a__1*a__2*a__3*a__4 """ args = _get_args(args) if len(args) == 0: return 1 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a * b, args, 1) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a * b, args, 1) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx) def Abs(arg): """Create the absolute value of an arithmetic expression""" return If(arg > 0, arg, -arg) def AtMost(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtMost(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx) def AtLeast(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtLeast(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx) def _reorder_pb_arg(arg): a, b = arg if not _is_int(b) and _is_int(a): return b, a return arg def _pb_args_coeffs(args, default_ctx=None): args = _get_args_ast_list(args) if len(args) == 0: return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)() args = [_reorder_pb_arg(arg) for arg in args] args, coeffs = zip(*args) if z3_debug(): _z3_assert(len(args) > 0, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) _coeffs = (ctypes.c_int * len(coeffs))() for i in range(len(coeffs)): _z3_check_cint_overflow(coeffs[i], "coefficient") _coeffs[i] = coeffs[i] return ctx, sz, _args, _coeffs, args def PbLe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbLe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbGe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbGe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbEq(args, k, ctx=None): """Create a Pseudo-Boolean equality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbEq(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx) def solve(*args, **keywords): """Solve the constraints `*args`. This is a simple function for creating demonstrations. It creates a solver, configure it using the options in `keywords`, adds the constraints in `args`, and invokes check. >>> a = Int('a') >>> solve(a > 0, a < 2) [a = 1] """ show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: print(s.model()) def solve_using(s, *args, **keywords): """Solve the constraints `*args` using solver `s`. This is a simple function for creating demonstrations. It is similar to `solve`, but it uses the given solver `s`. It configures solver `s` using the options in `keywords`, adds the constraints in `args`, and invokes check. """ show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: print("Problem:") print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: if show: print("Solution:") print(s.model()) def prove(claim, show=False, **keywords): """Try to prove the given claim. This is a simple function for creating demonstrations. It tries to prove `claim` by showing the negation is unsatisfiable. >>> p, q = Bools('p q') >>> prove(Not(And(p, q)) == Or(Not(p), Not(q))) proved """ if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if show: print(s) r = s.check() if r == unsat: print("proved") elif r == unknown: print("failed to prove") print(s.model()) else: print("counterexample") print(s.model()) def _solve_html(*args, **keywords): """Version of function `solve` that renders HTML output.""" show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if show: print("<b>Solution:</b>") print(s.model()) def _solve_using_html(s, *args, **keywords): """Version of function `solve_using` that renders HTML.""" show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if show: print("<b>Solution:</b>") print(s.model()) def _prove_html(claim, show=False, **keywords): """Version of function `prove` that renders HTML.""" if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if show: print(s) r = s.check() if r == unsat: print("<b>proved</b>") elif r == unknown: print("<b>failed to prove</b>") print(s.model()) else: print("<b>counterexample</b>") print(s.model()) def _dict2sarray(sorts, ctx): sz = len(sorts) _names = (Symbol * sz)() _sorts = (Sort * sz)() i = 0 for k in sorts: v = sorts[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_sort(v), "Z3 sort expected") _names[i] = to_symbol(k, ctx) _sorts[i] = v.ast i = i + 1 return sz, _names, _sorts def _dict2darray(decls, ctx): sz = len(decls) _names = (Symbol * sz)() _decls = (FuncDecl * sz)() i = 0 for k in decls: v = decls[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected") _names[i] = to_symbol(k, ctx) if is_const(v): _decls[i] = v.decl().ast else: _decls[i] = v.ast i = i + 1 return sz, _names, _decls class ParserContext: def __init__(self, ctx= None): self.ctx = _get_ctx(ctx) self.pctx = Z3_mk_parser_context(self.ctx.ref()) Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx) def __del__(self): if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None: Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx) self.pctx = None def add_sort(self, sort): Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast()) def add_decl(self, decl): Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast()) def from_string(self, s): return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx) def parse_smt2_string(s, sorts={}, decls={}, ctx=None): """Parse a string in SMT 2.0 format using the given sorts and decls. The arguments sorts and decls are Python dictionaries used to initialize the symbol table used for the SMT 2.0 parser. >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))') [x > 0, x < 10] >>> x, y = Ints('x y') >>> f = Function('f', IntSort(), IntSort()) >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f}) [x + f(y) > 0] >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() }) [a > 0] """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) def parse_smt2_file(f, sorts={}, decls={}, ctx=None): """Parse a file in SMT 2.0 format using the given sorts and decls. This function is similar to parse_smt2_string(). """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) ######################################### # # Floating-Point Arithmetic # ######################################### # Global default rounding mode _dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN _dflt_fpsort_ebits = 11 _dflt_fpsort_sbits = 53 def get_default_rounding_mode(ctx=None): """Retrieves the global default rounding mode.""" global _dflt_rounding_mode if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO: return RTZ(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE: return RTN(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE: return RTP(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: return RNE(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: return RNA(ctx) _ROUNDING_MODES = frozenset({ Z3_OP_FPA_RM_TOWARD_ZERO, Z3_OP_FPA_RM_TOWARD_NEGATIVE, Z3_OP_FPA_RM_TOWARD_POSITIVE, Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN, Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY }) def set_default_rounding_mode(rm, ctx=None): global _dflt_rounding_mode if is_fprm_value(rm): _dflt_rounding_mode = rm.decl().kind() else: _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode") _dflt_rounding_mode = rm def get_default_fp_sort(ctx=None): return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx) def set_default_fp_sort(ebits, sbits, ctx=None): global _dflt_fpsort_ebits global _dflt_fpsort_sbits _dflt_fpsort_ebits = ebits _dflt_fpsort_sbits = sbits def _dflt_rm(ctx=None): return get_default_rounding_mode(ctx) def _dflt_fps(ctx=None): return get_default_fp_sort(ctx) def _coerce_fp_expr_list(alist, ctx): first_fp_sort = None for a in alist: if is_fp(a): if first_fp_sort is None: first_fp_sort = a.sort() elif first_fp_sort == a.sort(): pass # OK, same as before else: # we saw at least 2 different float sorts; something will # throw a sort mismatch later, for now assume None. first_fp_sort = None break r = [] for i in range(len(alist)): a = alist[i] is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")") if is_repr or _is_int(a) or isinstance(a, (float, bool)): r.append(FPVal(a, None, first_fp_sort, ctx)) else: r.append(a) return _coerce_expr_list(r, ctx) # FP Sorts class FPSortRef(SortRef): """Floating-point sort.""" def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast)) def sbits(self): """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast)) def cast(self, val): """Try to cast `val` as a floating-point expression. >>> b = FPSort(8, 24) >>> b.cast(1.0) 1 >>> b.cast(1.0).sexpr() '(fp #b0 #x7f #b00000000000000000000000)' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") return val else: return FPVal(val, None, self, self.ctx) def Float16(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx) def FloatHalf(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx) def Float32(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx) def FloatSingle(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) def Float64(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx) def FloatDouble(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) def Float128(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx) def FloatQuadruple(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx) class FPRMSortRef(SortRef): """"Floating-point rounding mode sort.""" def is_fp_sort(s): """Return True if `s` is a Z3 floating-point sort. >>> is_fp_sort(FPSort(8, 24)) True >>> is_fp_sort(IntSort()) False """ return isinstance(s, FPSortRef) def is_fprm_sort(s): """Return True if `s` is a Z3 floating-point rounding mode sort. >>> is_fprm_sort(FPSort(8, 24)) False >>> is_fprm_sort(RNE().sort()) True """ return isinstance(s, FPRMSortRef) # FP Expressions class FPRef(ExprRef): """Floating-point expressions.""" def sort(self): """Return the sort of the floating-point expression `self`. >>> x = FP('1.0', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sort() == FPSort(8, 24) True """ return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return self.sort().ebits() def sbits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return self.sort().sbits() def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return fpLEQ(self, other, self.ctx) def __lt__(self, other): return fpLT(self, other, self.ctx) def __ge__(self, other): return fpGEQ(self, other, self.ctx) def __gt__(self, other): return fpGT(self, other, self.ctx) def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x + y x + y >>> (x + y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 + x 1.25*(2**3) + x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x - y x - y >>> (x - y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 - x 1.25*(2**3) - x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> (x * y).sort() FPSort(8, 24) >>> 10 * y 1.25*(2**3) * y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> x * 10 x * 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __pos__(self): """Create the Z3 expression `+self`.""" return self def __neg__(self): """Create the Z3 expression `-self`. >>> x = FP('x', Float32()) >>> -x -x """ return fpNeg(self) def __div__(self, other): """Create the Z3 expression `self / other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> (x / y).sort() FPSort(8, 24) >>> 10 / y 1.25*(2**3) / y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __rdiv__(self, other): """Create the Z3 expression `other / self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> x / 10 x / 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __truediv__(self, other): """Create the Z3 expression division `self / other`.""" return self.__div__(other) def __rtruediv__(self, other): """Create the Z3 expression division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression mod `self % other`.""" return fpRem(self, other) def __rmod__(self, other): """Create the Z3 expression mod `other % self`.""" return fpRem(other, self) class FPRMRef(ExprRef): """Floating-point rounding mode expressions""" def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def RoundNearestTiesToEven(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RNE(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RoundNearestTiesToAway(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RNA(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RoundTowardPositive(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RTP(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RoundTowardNegative(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RTN(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RoundTowardZero(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def RTZ(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def is_fprm(a): """Return `True` if `a` is a Z3 floating-point rounding mode expression. >>> rm = RNE() >>> is_fprm(rm) True >>> rm = 1.0 >>> is_fprm(rm) False """ return isinstance(a, FPRMRef) def is_fprm_value(a): """Return `True` if `a` is a Z3 floating-point rounding mode numeral value.""" return is_fprm(a) and _is_numeral(a.ctx, a.ast) # FP Numerals class FPNumRef(FPRef): """The sign of the numeral. >>> x = FPVal(+1.0, FPSort(8, 24)) >>> x.sign() False >>> x = FPVal(-1.0, FPSort(8, 24)) >>> x.sign() True """ def sign(self): num = (ctypes.c_int)() nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num)) if nsign is False: raise Z3Exception("error retrieving the sign of a numeral.") return num.value != 0 """The sign of a floating-point numeral as a bit-vector expression. Remark: NaN's are invalid arguments. """ def sign_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The significand of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand() 1.25 """ def significand(self): return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast()) """The significand of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand_as_long() 1.25 """ def significand_as_long(self): ptr = (ctypes.c_ulonglong * 1)() if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr): raise Z3Exception("error retrieving the significand of a numeral.") return ptr[0] """The significand of the numeral as a bit-vector expression. Remark: NaN are invalid arguments. """ def significand_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The exponent of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent() 1 """ def exponent(self, biased=True): return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased) """The exponent of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent_as_long() 1 """ def exponent_as_long(self, biased=True): ptr = (ctypes.c_longlong * 1)() if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased): raise Z3Exception("error retrieving the exponent of a numeral.") return ptr[0] """The exponent of the numeral as a bit-vector expression. Remark: NaNs are invalid arguments. """ def exponent_as_bv(self, biased=True): return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx) """Indicates whether the numeral is a NaN.""" def isNaN(self): return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +oo or -oo.""" def isInf(self): return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +zero or -zero.""" def isZero(self): return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is normal.""" def isNormal(self): return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is subnormal.""" def isSubnormal(self): return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is positive.""" def isPositive(self): return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is negative.""" def isNegative(self): return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast()) """ The string representation of the numeral. >>> x = FPVal(20, FPSort(8, 24)) >>> x.as_string() 1.25*(2**4) """ def as_string(self): s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast()) return ("FPVal(%s, %s)" % (s, self.sort())) def is_fp(a): """Return `True` if `a` is a Z3 floating-point expression. >>> b = FP('b', FPSort(8, 24)) >>> is_fp(b) True >>> is_fp(b + 1.0) True >>> is_fp(Int('x')) False """ return isinstance(a, FPRef) def is_fp_value(a): """Return `True` if `a` is a Z3 floating-point numeral value. >>> b = FP('b', FPSort(8, 24)) >>> is_fp_value(b) False >>> b = FPVal(1.0, FPSort(8, 24)) >>> b 1 >>> is_fp_value(b) True """ return is_fp(a) and _is_numeral(a.ctx, a.ast) def FPSort(ebits, sbits, ctx=None): """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used. >>> Single = FPSort(8, 24) >>> Double = FPSort(11, 53) >>> Single FPSort(8, 24) >>> x = Const('x', Single) >>> eq(x, FP('x', FPSort(8, 24))) True """ ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx) def _to_float_str(val, exp=0): if isinstance(val, float): if math.isnan(val): res = "NaN" elif val == 0.0: sone = math.copysign(1.0, val) if sone < 0.0: return "-0.0" else: return "+0.0" elif val == float("+inf"): res = "+oo" elif val == float("-inf"): res = "-oo" else: v = val.as_integer_ratio() num = v[0] den = v[1] rvs = str(num) + "/" + str(den) res = rvs + "p" + _to_int_str(exp) elif isinstance(val, bool): if val: res = "1.0" else: res = "0.0" elif _is_int(val): res = str(val) elif isinstance(val, str): inx = val.find("*(2**") if inx == -1: res = val elif val[-1] == ")": res = val[0:inx] exp = str(int(val[inx + 5:-1]) + int(exp)) else: _z3_assert(False, "String does not have floating-point numeral form.") elif z3_debug(): _z3_assert(False, "Python value cannot be used to create floating-point numerals.") if exp == 0: return res else: return res + "p" + exp def fpNaN(s): """Create a Z3 floating-point NaN term. >>> s = FPSort(8, 24) >>> set_fpa_pretty(True) >>> fpNaN(s) NaN >>> pb = get_fpa_pretty() >>> set_fpa_pretty(False) >>> fpNaN(s) fpNaN(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx) def fpPlusInfinity(s): """Create a Z3 floating-point +oo term. >>> s = FPSort(8, 24) >>> pb = get_fpa_pretty() >>> set_fpa_pretty(True) >>> fpPlusInfinity(s) +oo >>> set_fpa_pretty(False) >>> fpPlusInfinity(s) fpPlusInfinity(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusInfinity(s): """Create a Z3 floating-point -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx) def fpInfinity(s, negative): """Create a Z3 floating-point +oo or -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) def fpPlusZero(s): """Create a Z3 floating-point +0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusZero(s): """Create a Z3 floating-point -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx) def fpZero(s, negative): """Create a Z3 floating-point +0.0 or -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx) def FPVal(sig, exp=None, fps=None, ctx=None): """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used. >>> v = FPVal(20.0, FPSort(8, 24)) >>> v 1.25*(2**4) >>> print("0x%.8x" % v.exponent_as_long(False)) 0x00000004 >>> v = FPVal(2.25, FPSort(8, 24)) >>> v 1.125*(2**1) >>> v = FPVal(-2.25, FPSort(8, 24)) >>> v -1.125*(2**1) >>> FPVal(-0.0, FPSort(8, 24)) -0.0 >>> FPVal(0.0, FPSort(8, 24)) +0.0 >>> FPVal(+0.0, FPSort(8, 24)) +0.0 """ ctx = _get_ctx(ctx) if is_fp_sort(exp): fps = exp exp = None elif fps is None: fps = _dflt_fps(ctx) _z3_assert(is_fp_sort(fps), "sort mismatch") if exp is None: exp = 0 val = _to_float_str(sig) if val == "NaN" or val == "nan": return fpNaN(fps) elif val == "-0.0": return fpMinusZero(fps) elif val == "0.0" or val == "+0.0": return fpPlusZero(fps) elif val == "+oo" or val == "+inf" or val == "+Inf": return fpPlusInfinity(fps) elif val == "-oo" or val == "-inf" or val == "-Inf": return fpMinusInfinity(fps) else: return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx) def FP(name, fpsort, ctx=None): """Return a floating-point constant named `name`. `fpsort` is the floating-point sort. If `ctx=None`, then the global context is used. >>> x = FP('x', FPSort(8, 24)) >>> is_fp(x) True >>> x.ebits() 8 >>> x.sort() FPSort(8, 24) >>> word = FPSort(8, 24) >>> x2 = FP('x', word) >>> eq(x, x2) True """ if isinstance(fpsort, FPSortRef) and ctx is None: ctx = fpsort.ctx else: ctx = _get_ctx(ctx) return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx) def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) x + y * z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [FP(name, fpsort, ctx) for name in names] def fpAbs(a, ctx=None): """Create a Z3 floating-point absolute value expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FPVal(1.0, s) >>> fpAbs(x) fpAbs(1) >>> y = FPVal(-20.0, s) >>> y -1.25*(2**4) >>> fpAbs(y) fpAbs(-1.25*(2**4)) >>> fpAbs(-1.25*(2**4)) fpAbs(-1.25*(2**4)) >>> fpAbs(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx) def fpNeg(a, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx) def _mk_fp_unary(f, rm, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx) def _mk_fp_unary_pred(f, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast()), ctx) def _mk_fp_bin(f, rm, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_norm(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_pred(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_tern(f, rm, a, b, c, ctx): ctx = _get_ctx(ctx) [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b) or is_fp( c), "Second, third or fourth argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def fpAdd(rm, a, b, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpAdd(rm, x, y) x + y >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ fpAdd(RTZ(), x, y) >>> fpAdd(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx) def fpSub(rm, a, b, ctx=None): """Create a Z3 floating-point subtraction expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpSub(rm, x, y) x - y >>> fpSub(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx) def fpMul(rm, a, b, ctx=None): """Create a Z3 floating-point multiplication expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMul(rm, x, y) x * y >>> fpMul(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx) def fpDiv(rm, a, b, ctx=None): """Create a Z3 floating-point division expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpDiv(rm, x, y) x / y >>> fpDiv(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx) def fpRem(a, b, ctx=None): """Create a Z3 floating-point remainder expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpRem(x, y) fpRem(x, y) >>> fpRem(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx) def fpMin(a, b, ctx=None): """Create a Z3 floating-point minimum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMin(x, y) fpMin(x, y) >>> fpMin(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx) def fpMax(a, b, ctx=None): """Create a Z3 floating-point maximum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMax(x, y) fpMax(x, y) >>> fpMax(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx) def fpFMA(rm, a, b, c, ctx=None): """Create a Z3 floating-point fused multiply-add expression. """ return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx) def fpSqrt(rm, a, ctx=None): """Create a Z3 floating-point square root expression. """ return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx) def fpRoundToIntegral(rm, a, ctx=None): """Create a Z3 floating-point roundToIntegral expression. """ return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx) def fpIsNaN(a, ctx=None): """Create a Z3 floating-point isNaN expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpIsNaN(x) fpIsNaN(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx) def fpIsInf(a, ctx=None): """Create a Z3 floating-point isInfinite expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> fpIsInf(x) fpIsInf(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx) def fpIsZero(a, ctx=None): """Create a Z3 floating-point isZero expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx) def fpIsNormal(a, ctx=None): """Create a Z3 floating-point isNormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) def fpIsSubnormal(a, ctx=None): """Create a Z3 floating-point isSubnormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx) def fpIsNegative(a, ctx=None): """Create a Z3 floating-point isNegative expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx) def fpIsPositive(a, ctx=None): """Create a Z3 floating-point isPositive expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx) def _check_fp_args(a, b): if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") def fpLT(a, b, ctx=None): """Create the Z3 floating-point expression `other < self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLT(x, y) x < y >>> (x < y).sexpr() '(fp.lt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx) def fpLEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other <= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLEQ(x, y) x <= y >>> (x <= y).sexpr() '(fp.leq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx) def fpGT(a, b, ctx=None): """Create the Z3 floating-point expression `other > self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGT(x, y) x > y >>> (x > y).sexpr() '(fp.gt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx) def fpGEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other >= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGEQ(x, y) x >= y >>> (x >= y).sexpr() '(fp.geq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx) def fpEQ(a, b, ctx=None): """Create the Z3 floating-point expression `fpEQ(other, self)`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpEQ(x, y) fpEQ(x, y) >>> fpEQ(x, y).sexpr() '(fp.eq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx) def fpNEQ(a, b, ctx=None): """Create the Z3 floating-point expression `Not(fpEQ(other, self))`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpNEQ(x, y) Not(fpEQ(x, y)) >>> (x != y).sexpr() '(distinct x y)' """ return Not(fpEQ(a, b, ctx)) def fpFP(sgn, exp, sig, ctx=None): """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp. >>> s = FPSort(8, 24) >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23)) >>> print(x) fpFP(1, 127, 4194304) >>> xv = FPVal(-1.5, s) >>> print(xv) -1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() sat >>> xv = FPVal(+1.5, s) >>> print(xv) 1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() unsat """ _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch") _z3_assert(sgn.sort().size() == 1, "sort mismatch") ctx = _get_ctx(ctx) _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch") return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx) def fpToFP(a1, a2=None, a3=None, ctx=None): """Create a Z3 floating-point conversion expression from other term sorts to floating-point. From a bit-vector term in IEEE 754-2008 format: >>> x = FPVal(1.0, Float32()) >>> x_bv = fpToIEEEBV(x) >>> simplify(fpToFP(x_bv, Float32())) 1 From a floating-point term with different precision: >>> x = FPVal(1.0, Float32()) >>> x_db = fpToFP(RNE(), x, Float64()) >>> x_db.sort() FPSort(11, 53) From a real term: >>> x_r = RealVal(1.5) >>> simplify(fpToFP(RNE(), x_r, Float32())) 1.5 From a signed bit-vector term: >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> simplify(fpToFP(RNE(), x_signed, Float32())) -1.25*(2**2) """ ctx = _get_ctx(ctx) if is_bv(a1) and is_fp_sort(a2): return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx) elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) else: raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.") def fpBVToFP(v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a bit-vector term to a floating-point term. >>> x_bv = BitVecVal(0x3F800000, 32) >>> x_fp = fpBVToFP(x_bv, Float32()) >>> x_fp fpToFP(1065353216) >>> simplify(x_fp) 1 """ _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx) def fpFPToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a floating-point term to a floating-point term of different precision. >>> x_sgl = FPVal(1.0, Float32()) >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64()) >>> x_dbl fpToFP(RNE(), 1) >>> simplify(x_dbl) 1 >>> x_dbl.sort() FPSort(11, 53) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpRealToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a real term to a floating-point term. >>> x_r = RealVal(1.5) >>> x_fp = fpRealToFP(RNE(), x_r, Float32()) >>> x_fp fpToFP(RNE(), 3/2) >>> simplify(x_fp) 1.5 """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpSignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a signed bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFP(RNE(), 4294967291) >>> simplify(x_fp) -1.25*(2**2) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpUnsignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFPUnsigned(RNE(), 4294967291) >>> simplify(x_fp) 1*(2**32) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpToFPUnsigned(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression.""" if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx) def fpToSBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToSBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToUBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToUBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToReal(x, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to real. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToReal(x) >>> print(is_fp(x)) True >>> print(is_real(y)) True >>> print(is_fp(y)) False >>> print(is_real(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx) def fpToIEEEBV(x, ctx=None): """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format. The size of the resulting bit-vector is automatically determined. Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion knows only one NaN and it will always produce the same bit-vector representation of that NaN. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToIEEEBV(x) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx) ######################################### # # Strings, Sequences and Regular expressions # ######################################### class SeqSortRef(SortRef): """Sequence sort.""" def is_string(self): """Determine if sort is a string >>> s = StringSort() >>> s.is_string() True >>> s = SeqSort(IntSort()) >>> s.is_string() False """ return Z3_is_string_sort(self.ctx_ref(), self.ast) def basis(self): return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx) class CharSortRef(SortRef): """Character sort.""" def StringSort(ctx=None): """Create a string sort >>> s = StringSort() >>> print(s) String """ ctx = _get_ctx(ctx) return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx) def CharSort(ctx=None): """Create a character sort >>> ch = CharSort() >>> print(ch) Char """ ctx = _get_ctx(ctx) return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx) def SeqSort(s): """Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True """ return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx) class SeqRef(ExprRef): """Sequence expression.""" def sort(self): return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __add__(self, other): return Concat(self, other) def __radd__(self, other): return Concat(other, self) def __getitem__(self, i): if _is_int(i): i = IntVal(i, self.ctx) return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def at(self, i): if _is_int(i): i = IntVal(i, self.ctx) return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def is_string(self): return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast())) def is_string_value(self): return Z3_is_string(self.ctx_ref(), self.as_ast()) def as_string(self): """Return a string representation of sequence expression.""" if self.is_string_value(): string_length = ctypes.c_uint() chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length)) return string_at(chars, size=string_length.value).decode("latin-1") return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __lt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __ge__(self, other): return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def __gt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def _coerce_char(ch, ctx=None): if isinstance(ch, str): ctx = _get_ctx(ctx) ch = CharVal(ch, ctx) if not is_expr(ch): raise Z3Exception("Character expression expected") return ch class CharRef(ExprRef): """Character expression.""" def __le__(self, other): other = _coerce_char(other, self.ctx) return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def to_int(self): return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx) def to_bv(self): return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx) def is_digit(self): return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx) def CharVal(ch, ctx=None): ctx = _get_ctx(ctx) if isinstance(ch, str): ch = ord(ch) if not isinstance(ch, int): raise Z3Exception("character value should be an ordinal") return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx) def CharFromBv(ch, ctx=None): if not is_expr(ch): raise Z3Expression("Bit-vector expression needed") return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx) def CharToBv(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_bv() def CharToInt(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_int() def CharIsDigit(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.is_digit() def _coerce_seq(s, ctx=None): if isinstance(s, str): ctx = _get_ctx(ctx) s = StringVal(s, ctx) if not is_expr(s): raise Z3Exception("Non-expression passed as a sequence") if not is_seq(s): raise Z3Exception("Non-sequence passed as a sequence") return s def _get_ctx2(a, b, ctx=None): if is_expr(a): return a.ctx if is_expr(b): return b.ctx if ctx is None: ctx = main_ctx() return ctx def is_seq(a): """Return `True` if `a` is a Z3 sequence expression. >>> print (is_seq(Unit(IntVal(0)))) True >>> print (is_seq(StringVal("abc"))) True """ return isinstance(a, SeqRef) def is_string(a): """Return `True` if `a` is a Z3 string expression. >>> print (is_string(StringVal("ab"))) True """ return isinstance(a, SeqRef) and a.is_string() def is_string_value(a): """return 'True' if 'a' is a Z3 string constant expression. >>> print (is_string_value(StringVal("a"))) True >>> print (is_string_value(StringVal("a") + StringVal("b"))) False """ return isinstance(a, SeqRef) and a.is_string_value() def StringVal(s, ctx=None): """create a string expression""" s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s) ctx = _get_ctx(ctx) return SeqRef(Z3_mk_string(ctx.ref(), s), ctx) def String(name, ctx=None): """Return a string constant named `name`. If `ctx=None`, then the global context is used. >>> x = String('x') """ ctx = _get_ctx(ctx) return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx) def Strings(names, ctx=None): """Return a tuple of String constants. """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [String(name, ctx) for name in names] def SubString(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def SubSeq(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def Empty(s): """Create the empty sequence of the given sort >>> e = Empty(StringSort()) >>> e2 = StringVal("") >>> print(e.eq(e2)) True >>> e3 = Empty(SeqSort(IntSort())) >>> print(e3) Empty(Seq(Int)) >>> e4 = Empty(ReSort(SeqSort(IntSort()))) >>> print(e4) Empty(ReSort(Seq(Int))) """ if isinstance(s, SeqSortRef): return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx) if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty") def Full(s): """Create the regular expression that accepts the universal language >>> e = Full(ReSort(SeqSort(IntSort()))) >>> print(e) Full(ReSort(Seq(Int))) >>> e1 = Full(ReSort(StringSort())) >>> print(e1) Full(ReSort(String)) """ if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Full") def Unit(a): """Create a singleton sequence""" return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx) def PrefixOf(a, b): """Check if 'a' is a prefix of 'b' >>> s1 = PrefixOf("ab", "abc") >>> simplify(s1) True >>> s2 = PrefixOf("bc", "abc") >>> simplify(s2) False """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SuffixOf(a, b): """Check if 'a' is a suffix of 'b' >>> s1 = SuffixOf("ab", "abc") >>> simplify(s1) False >>> s2 = SuffixOf("bc", "abc") >>> simplify(s2) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Contains(a, b): """Check if 'a' contains 'b' >>> s1 = Contains("abc", "ab") >>> simplify(s1) True >>> s2 = Contains("abc", "bc") >>> simplify(s2) True >>> x, y, z = Strings('x y z') >>> s3 = Contains(Concat(x,y,z), y) >>> simplify(s3) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Replace(s, src, dst): """Replace the first occurrence of 'src' by 'dst' in 's' >>> r = Replace("aaa", "a", "b") >>> simplify(r) "baa" """ ctx = _get_ctx2(dst, s) if ctx is None and is_expr(src): ctx = src.ctx src = _coerce_seq(src, ctx) dst = _coerce_seq(dst, ctx) s = _coerce_seq(s, ctx) return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx) def IndexOf(s, substr, offset=None): """Retrieve the index of substring within a string starting at a specified offset. >>> simplify(IndexOf("abcabc", "bc", 0)) 1 >>> simplify(IndexOf("abcabc", "bc", 2)) 4 """ if offset is None: offset = IntVal(0) ctx = None if is_expr(offset): ctx = offset.ctx ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) if _is_int(offset): offset = IntVal(offset, ctx) return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) def LastIndexOf(s, substr): """Retrieve the last index of substring within a string""" ctx = None ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx) def Length(s): """Obtain the length of a sequence 's' >>> l = Length(StringVal("abc")) >>> simplify(l) 3 """ s = _coerce_seq(s) return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx) def StrToInt(s): """Convert string expression to integer >>> a = StrToInt("1") >>> simplify(1 == a) True >>> b = StrToInt("2") >>> simplify(1 == b) False >>> c = StrToInt(IntToStr(2)) >>> simplify(1 == c) False """ s = _coerce_seq(s) return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx) def IntToStr(s): """Convert integer expression to string""" if not is_expr(s): s = _py2expr(s) return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx) def StrToCode(s): """Convert a unit length string to integer code""" if not is_expr(s): s = _py2expr(s) return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx) def StrFromCode(c): """Convert code to a string""" if not is_expr(c): c = _py2expr(c) return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx) def Re(s, ctx=None): """The regular expression that accepts sequence 's' >>> s1 = Re("ab") >>> s2 = Re(StringVal("ab")) >>> s3 = Re(Unit(BoolVal(True))) """ s = _coerce_seq(s, ctx) return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx) # Regular expressions class ReSortRef(SortRef): """Regular expression sort.""" def basis(self): return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx) def ReSort(s): if is_ast(s): return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx) if s is None or isinstance(s, Context): ctx = _get_ctx(s) return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx) raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument") class ReRef(ExprRef): """Regular expressions.""" def __add__(self, other): return Union(self, other) def is_re(s): return isinstance(s, ReRef) def InRe(s, re): """Create regular expression membership test >>> re = Union(Re("a"),Re("b")) >>> print (simplify(InRe("a", re))) True >>> print (simplify(InRe("b", re))) True >>> print (simplify(InRe("c", re))) False """ s = _coerce_seq(s, re.ctx) return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx) def Union(*args): """Create union of regular expressions. >>> re = Union(Re("a"), Re("b"), Re("c")) >>> print (simplify(InRe("d", re))) False """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx) def Intersect(*args): """Create intersection of regular expressions. >>> re = Intersect(Re("a"), Re("b"), Re("c")) """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx) def Plus(re): """Create the regular expression accepting one or more repetitions of argument. >>> re = Plus(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx) def Option(re): """Create the regular expression that optionally accepts the argument. >>> re = Option(Re("a")) >>> print(simplify(InRe("a", re))) True >>> print(simplify(InRe("", re))) True >>> print(simplify(InRe("aa", re))) False """ return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx) def Complement(re): """Create the complement regular expression.""" return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx) def Star(re): """Create the regular expression accepting zero or more repetitions of argument. >>> re = Star(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) True """ return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx) def Loop(re, lo, hi=0): """Create the regular expression accepting between a lower and upper bound repetitions >>> re = Loop(Re("a"), 1, 3) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("aaaa", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx) def Range(lo, hi, ctx=None): """Create the range regular expression over two sequences of length 1 >>> range = Range("a","z") >>> print(simplify(InRe("b", range))) True >>> print(simplify(InRe("bb", range))) False """ lo = _coerce_seq(lo, ctx) hi = _coerce_seq(hi, ctx) return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx) def Diff(a, b, ctx=None): """Create the difference regular expression """ return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx) def AllChar(regex_sort, ctx=None): """Create a regular expression that accepts all single character strings """ return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx) # Special Relations def PartialOrder(a, index): return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx) def LinearOrder(a, index): return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx) def TreeOrder(a, index): return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx) def PiecewiseLinearOrder(a, index): return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx) def TransitiveClosure(f): """Given a binary relation R, such that the two arguments have the same sort create the transitive closure relation R+. The transitive closure R+ is a new relation. """ return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx) def to_Ast(ptr,): ast = Ast(ptr) super(ctypes.c_void_p, ast).__init__(ptr) return ast def to_ContextObj(ptr,): ctx = ContextObj(ptr) super(ctypes.c_void_p, ctx).__init__(ptr) return ctx def to_AstVectorObj(ptr,): v = AstVectorObj(ptr) super(ctypes.c_void_p, v).__init__(ptr) return v # NB. my-hacky-class only works for a single instance of OnClause # it should be replaced with a proper correlation between OnClause # and object references that can be passed over the FFI. # for UserPropagator we use a global dictionary, which isn't great code. _my_hacky_class = None def on_clause_eh(ctx, p, clause): onc = _my_hacky_class p = _to_expr_ref(to_Ast(p), onc.ctx) clause = AstVector(to_AstVectorObj(clause), onc.ctx) onc.on_clause(p, clause) _on_clause_eh = Z3_on_clause_eh(on_clause_eh) class OnClause: def __init__(self, s, on_clause): self.s = s self.ctx = s.ctx self.on_clause = on_clause self.idx = 22 global _my_hacky_class _my_hacky_class = self Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh) class PropClosures: def __init__(self): self.bases = {} self.lock = None def set_threaded(self): if self.lock is None: import threading self.lock = threading.Lock() def get(self, ctx): if self.lock: with self.lock: r = self.bases[ctx] else: r = self.bases[ctx] return r def set(self, ctx, r): if self.lock: with self.lock: self.bases[ctx] = r else: self.bases[ctx] = r def insert(self, r): if self.lock: with self.lock: id = len(self.bases) + 3 self.bases[id] = r else: id = len(self.bases) + 3 self.bases[id] = r return id _prop_closures = None def ensure_prop_closures(): global _prop_closures if _prop_closures is None: _prop_closures = PropClosures() def user_prop_push(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.push() def user_prop_pop(ctx, cb, num_scopes): prop = _prop_closures.get(ctx) prop.cb = cb prop.pop(num_scopes) def user_prop_fresh(ctx, _new_ctx): _prop_closures.set_threaded() prop = _prop_closures.get(ctx) nctx = Context() Z3_del_context(nctx.ctx) new_ctx = to_ContextObj(_new_ctx) nctx.ctx = new_ctx nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler) nctx.owner = False new_prop = prop.fresh(nctx) _prop_closures.set(new_prop.id, new_prop) return new_prop.id def user_prop_fixed(ctx, cb, id, value): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) value = _to_expr_ref(to_Ast(value), prop.ctx()) prop.fixed(id, value) prop.cb = None def user_prop_created(ctx, cb, id): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) prop.created(id) prop.cb = None def user_prop_final(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.final() prop.cb = None def user_prop_eq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.eq(x, y) prop.cb = None def user_prop_diseq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.diseq(x, y) prop.cb = None # TODO The decision callback is not fully implemented. # It needs to handle the ast*, unsigned* idx, and Z3_lbool* def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref): prop = _prop_closures.get(ctx) prop.cb = cb t = _to_expr_ref(to_Ast(t_ref), prop.ctx()) t, idx, phase = prop.decide(t, idx, phase) t_ref = t idx_ref = idx phase_ref = phase prop.cb = None _user_prop_push = Z3_push_eh(user_prop_push) _user_prop_pop = Z3_pop_eh(user_prop_pop) _user_prop_fresh = Z3_fresh_eh(user_prop_fresh) _user_prop_fixed = Z3_fixed_eh(user_prop_fixed) _user_prop_created = Z3_created_eh(user_prop_created) _user_prop_final = Z3_final_eh(user_prop_final) _user_prop_eq = Z3_eq_eh(user_prop_eq) _user_prop_diseq = Z3_eq_eh(user_prop_diseq) _user_prop_decide = Z3_decide_eh(user_prop_decide) def PropagateFunction(name, *sig): """Create a function that gets tracked by user propagator. Every term headed by this function symbol is tracked. If a term is fixed and the fixed callback is registered a callback is invoked that the term headed by this function is fixed. """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) class UserPropagateBase: # # Either solver is set or ctx is set. # Propagators that are created throuh callbacks # to "fresh" inherit the context of that is supplied # as argument to the callback. # This context should not be deleted. It is owned by the solver. # def __init__(self, s, ctx=None): assert s is None or ctx is None ensure_prop_closures() self.solver = s self._ctx = None self.fresh_ctx = None self.cb = None self.id = _prop_closures.insert(self) self.fixed = None self.final = None self.eq = None self.diseq = None self.created = None if ctx: self.fresh_ctx = ctx if s: Z3_solver_propagate_init(self.ctx_ref(), s.solver, ctypes.c_void_p(self.id), _user_prop_push, _user_prop_pop, _user_prop_fresh) def __del__(self): if self._ctx: self._ctx.ctx = None def ctx(self): if self.fresh_ctx: return self.fresh_ctx else: return self.solver.ctx def ctx_ref(self): return self.ctx().ref() def add_fixed(self, fixed): assert not self.fixed assert not self._ctx if self.solver: Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed) self.fixed = fixed def add_created(self, created): assert not self.created assert not self._ctx if self.solver: Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created) self.created = created def add_final(self, final): assert not self.final assert not self._ctx if self.solver: Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final) self.final = final def add_eq(self, eq): assert not self.eq assert not self._ctx if self.solver: Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq) self.eq = eq def add_diseq(self, diseq): assert not self.diseq assert not self._ctx if self.solver: Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq) self.diseq = diseq def add_decide(self, decide): assert not self.decide assert not self._ctx if self.solver: Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide) self.decide = decide def push(self): raise Z3Exception("push needs to be overwritten") def pop(self, num_scopes): raise Z3Exception("pop needs to be overwritten") def fresh(self, new_ctx): raise Z3Exception("fresh needs to be overwritten") def add(self, e): assert not self._ctx if self.solver: Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast) else: Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast) # # Tell the solver to perform the next split on a given term # If the term is a bit-vector the index idx specifies the index of the Boolean variable being # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument. # def next_split(self, t, idx, phase): Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase) # # Propagation can only be invoked as during a fixed or final callback. # def propagate(self, e, ids, eqs=[]): _ids, num_fixed = _to_ast_array(ids) num_eqs = len(eqs) _lhs, _num_lhs = _to_ast_array([x for x, y in eqs]) _rhs, _num_rhs = _to_ast_array([y for x, y in eqs]) Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p( self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast) def conflict(self, deps = [], eqs = []): self.propagate(BoolVal(False, self.ctx()), deps, eqs)
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3.py
z3.py
import sys import io # We want to import submodule z3 here, but there's no way # to do that that works correctly on both Python 2 and 3. if sys.version_info.major < 3: # In Python 2: an implicit-relative import of submodule z3. # In Python 3: an undesirable import of global package z3. import z3 else: # In Python 2: an illegal circular import. # In Python 3: an explicit-relative import of submodule z3. from . import z3 from .z3consts import * from .z3core import * from ctypes import * def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) ############################## # # Configuration # ############################## # Z3 operator names to Z3Py _z3_op_to_str = { Z3_OP_TRUE: "True", Z3_OP_FALSE: "False", Z3_OP_EQ: "==", Z3_OP_DISTINCT: "Distinct", Z3_OP_ITE: "If", Z3_OP_AND: "And", Z3_OP_OR: "Or", Z3_OP_IFF: "==", Z3_OP_XOR: "Xor", Z3_OP_NOT: "Not", Z3_OP_IMPLIES: "Implies", Z3_OP_IDIV: "/", Z3_OP_MOD: "%", Z3_OP_TO_REAL: "ToReal", Z3_OP_TO_INT: "ToInt", Z3_OP_POWER: "**", Z3_OP_IS_INT: "IsInt", Z3_OP_BADD: "+", Z3_OP_BSUB: "-", Z3_OP_BMUL: "*", Z3_OP_BOR: "|", Z3_OP_BAND: "&", Z3_OP_BNOT: "~", Z3_OP_BXOR: "^", Z3_OP_BNEG: "-", Z3_OP_BUDIV: "UDiv", Z3_OP_BSDIV: "/", Z3_OP_BSMOD: "%", Z3_OP_BSREM: "SRem", Z3_OP_BUREM: "URem", Z3_OP_EXT_ROTATE_LEFT: "RotateLeft", Z3_OP_EXT_ROTATE_RIGHT: "RotateRight", Z3_OP_SLEQ: "<=", Z3_OP_SLT: "<", Z3_OP_SGEQ: ">=", Z3_OP_SGT: ">", Z3_OP_ULEQ: "ULE", Z3_OP_ULT: "ULT", Z3_OP_UGEQ: "UGE", Z3_OP_UGT: "UGT", Z3_OP_SIGN_EXT: "SignExt", Z3_OP_ZERO_EXT: "ZeroExt", Z3_OP_REPEAT: "RepeatBitVec", Z3_OP_BASHR: ">>", Z3_OP_BSHL: "<<", Z3_OP_BLSHR: "LShR", Z3_OP_CONCAT: "Concat", Z3_OP_EXTRACT: "Extract", Z3_OP_BV2INT: "BV2Int", Z3_OP_ARRAY_MAP: "Map", Z3_OP_SELECT: "Select", Z3_OP_STORE: "Store", Z3_OP_CONST_ARRAY: "K", Z3_OP_ARRAY_EXT: "Ext", Z3_OP_PB_AT_MOST: "AtMost", Z3_OP_PB_LE: "PbLe", Z3_OP_PB_GE: "PbGe", Z3_OP_PB_EQ: "PbEq", Z3_OP_SEQ_CONCAT: "Concat", Z3_OP_SEQ_PREFIX: "PrefixOf", Z3_OP_SEQ_SUFFIX: "SuffixOf", Z3_OP_SEQ_UNIT: "Unit", Z3_OP_SEQ_CONTAINS: "Contains", Z3_OP_SEQ_REPLACE: "Replace", Z3_OP_SEQ_AT: "At", Z3_OP_SEQ_NTH: "Nth", Z3_OP_SEQ_INDEX: "IndexOf", Z3_OP_SEQ_LAST_INDEX: "LastIndexOf", Z3_OP_SEQ_LENGTH: "Length", Z3_OP_STR_TO_INT: "StrToInt", Z3_OP_INT_TO_STR: "IntToStr", Z3_OP_SEQ_IN_RE: "InRe", Z3_OP_SEQ_TO_RE: "Re", Z3_OP_RE_PLUS: "Plus", Z3_OP_RE_STAR: "Star", Z3_OP_RE_OPTION: "Option", Z3_OP_RE_UNION: "Union", Z3_OP_RE_RANGE: "Range", Z3_OP_RE_INTERSECT: "Intersect", Z3_OP_RE_COMPLEMENT: "Complement", Z3_OP_FPA_IS_NAN: "fpIsNaN", Z3_OP_FPA_IS_INF: "fpIsInf", Z3_OP_FPA_IS_ZERO: "fpIsZero", Z3_OP_FPA_IS_NORMAL: "fpIsNormal", Z3_OP_FPA_IS_SUBNORMAL: "fpIsSubnormal", Z3_OP_FPA_IS_NEGATIVE: "fpIsNegative", Z3_OP_FPA_IS_POSITIVE: "fpIsPositive", } # List of infix operators _z3_infix = [ Z3_OP_EQ, Z3_OP_IFF, Z3_OP_ADD, Z3_OP_SUB, Z3_OP_MUL, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_POWER, Z3_OP_LE, Z3_OP_LT, Z3_OP_GE, Z3_OP_GT, Z3_OP_BADD, Z3_OP_BSUB, Z3_OP_BMUL, Z3_OP_BSDIV, Z3_OP_BSMOD, Z3_OP_BOR, Z3_OP_BAND, Z3_OP_BXOR, Z3_OP_BSDIV, Z3_OP_SLEQ, Z3_OP_SLT, Z3_OP_SGEQ, Z3_OP_SGT, Z3_OP_BASHR, Z3_OP_BSHL, ] _z3_unary = [Z3_OP_UMINUS, Z3_OP_BNOT, Z3_OP_BNEG] # Precedence _z3_precedence = { Z3_OP_POWER: 0, Z3_OP_UMINUS: 1, Z3_OP_BNEG: 1, Z3_OP_BNOT: 1, Z3_OP_MUL: 2, Z3_OP_DIV: 2, Z3_OP_IDIV: 2, Z3_OP_MOD: 2, Z3_OP_BMUL: 2, Z3_OP_BSDIV: 2, Z3_OP_BSMOD: 2, Z3_OP_ADD: 3, Z3_OP_SUB: 3, Z3_OP_BADD: 3, Z3_OP_BSUB: 3, Z3_OP_BASHR: 4, Z3_OP_BSHL: 4, Z3_OP_BAND: 5, Z3_OP_BXOR: 6, Z3_OP_BOR: 7, Z3_OP_LE: 8, Z3_OP_LT: 8, Z3_OP_GE: 8, Z3_OP_GT: 8, Z3_OP_EQ: 8, Z3_OP_SLEQ: 8, Z3_OP_SLT: 8, Z3_OP_SGEQ: 8, Z3_OP_SGT: 8, Z3_OP_IFF: 8, Z3_OP_FPA_NEG: 1, Z3_OP_FPA_MUL: 2, Z3_OP_FPA_DIV: 2, Z3_OP_FPA_REM: 2, Z3_OP_FPA_FMA: 2, Z3_OP_FPA_ADD: 3, Z3_OP_FPA_SUB: 3, Z3_OP_FPA_LE: 8, Z3_OP_FPA_LT: 8, Z3_OP_FPA_GE: 8, Z3_OP_FPA_GT: 8, Z3_OP_FPA_EQ: 8, } # FPA operators _z3_op_to_fpa_normal_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: "RoundNearestTiesToEven()", Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: "RoundNearestTiesToAway()", Z3_OP_FPA_RM_TOWARD_POSITIVE: "RoundTowardPositive()", Z3_OP_FPA_RM_TOWARD_NEGATIVE: "RoundTowardNegative()", Z3_OP_FPA_RM_TOWARD_ZERO: "RoundTowardZero()", Z3_OP_FPA_PLUS_INF: "fpPlusInfinity", Z3_OP_FPA_MINUS_INF: "fpMinusInfinity", Z3_OP_FPA_NAN: "fpNaN", Z3_OP_FPA_PLUS_ZERO: "fpPZero", Z3_OP_FPA_MINUS_ZERO: "fpNZero", Z3_OP_FPA_ADD: "fpAdd", Z3_OP_FPA_SUB: "fpSub", Z3_OP_FPA_NEG: "fpNeg", Z3_OP_FPA_MUL: "fpMul", Z3_OP_FPA_DIV: "fpDiv", Z3_OP_FPA_REM: "fpRem", Z3_OP_FPA_ABS: "fpAbs", Z3_OP_FPA_MIN: "fpMin", Z3_OP_FPA_MAX: "fpMax", Z3_OP_FPA_FMA: "fpFMA", Z3_OP_FPA_SQRT: "fpSqrt", Z3_OP_FPA_ROUND_TO_INTEGRAL: "fpRoundToIntegral", Z3_OP_FPA_EQ: "fpEQ", Z3_OP_FPA_LT: "fpLT", Z3_OP_FPA_GT: "fpGT", Z3_OP_FPA_LE: "fpLEQ", Z3_OP_FPA_GE: "fpGEQ", Z3_OP_FPA_FP: "fpFP", Z3_OP_FPA_TO_FP: "fpToFP", Z3_OP_FPA_TO_FP_UNSIGNED: "fpToFPUnsigned", Z3_OP_FPA_TO_UBV: "fpToUBV", Z3_OP_FPA_TO_SBV: "fpToSBV", Z3_OP_FPA_TO_REAL: "fpToReal", Z3_OP_FPA_TO_IEEE_BV: "fpToIEEEBV", } _z3_op_to_fpa_pretty_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: "RNE()", Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: "RNA()", Z3_OP_FPA_RM_TOWARD_POSITIVE: "RTP()", Z3_OP_FPA_RM_TOWARD_NEGATIVE: "RTN()", Z3_OP_FPA_RM_TOWARD_ZERO: "RTZ()", Z3_OP_FPA_PLUS_INF: "+oo", Z3_OP_FPA_MINUS_INF: "-oo", Z3_OP_FPA_NAN: "NaN", Z3_OP_FPA_PLUS_ZERO: "+0.0", Z3_OP_FPA_MINUS_ZERO: "-0.0", Z3_OP_FPA_ADD: "+", Z3_OP_FPA_SUB: "-", Z3_OP_FPA_MUL: "*", Z3_OP_FPA_DIV: "/", Z3_OP_FPA_REM: "%", Z3_OP_FPA_NEG: "-", Z3_OP_FPA_EQ: "fpEQ", Z3_OP_FPA_LT: "<", Z3_OP_FPA_GT: ">", Z3_OP_FPA_LE: "<=", Z3_OP_FPA_GE: ">=" } _z3_fpa_infix = [ Z3_OP_FPA_ADD, Z3_OP_FPA_SUB, Z3_OP_FPA_MUL, Z3_OP_FPA_DIV, Z3_OP_FPA_REM, Z3_OP_FPA_LT, Z3_OP_FPA_GT, Z3_OP_FPA_LE, Z3_OP_FPA_GE ] _ASSOC_OPS = frozenset({ Z3_OP_BOR, Z3_OP_BXOR, Z3_OP_BAND, Z3_OP_ADD, Z3_OP_BADD, Z3_OP_MUL, Z3_OP_BMUL, }) def _is_assoc(k): return k in _ASSOC_OPS def _is_left_assoc(k): return _is_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_html_assoc(k): return k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IFF or _is_assoc(k) def _is_html_left_assoc(k): return _is_html_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_add(k): return k == Z3_OP_ADD or k == Z3_OP_BADD def _is_sub(k): return k == Z3_OP_SUB or k == Z3_OP_BSUB if sys.version_info.major < 3: import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x _z3_infix_compact = [Z3_OP_MUL, Z3_OP_BMUL, Z3_OP_POWER, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_BSDIV, Z3_OP_BSMOD] _ellipses = "..." _html_ellipses = "&hellip;" # Overwrite some of the operators for HTML _z3_pre_html_op_to_str = {Z3_OP_EQ: "=", Z3_OP_IFF: "=", Z3_OP_NOT: "&not;", Z3_OP_AND: "&and;", Z3_OP_OR: "&or;", Z3_OP_IMPLIES: "&rArr;", Z3_OP_LT: "&lt;", Z3_OP_GT: "&gt;", Z3_OP_LE: "&le;", Z3_OP_GE: "&ge;", Z3_OP_MUL: "&middot;", Z3_OP_SLEQ: "&le;", Z3_OP_SLT: "&lt;", Z3_OP_SGEQ: "&ge;", Z3_OP_SGT: "&gt;", Z3_OP_ULEQ: "&le;<sub>u</sub>", Z3_OP_ULT: "&lt;<sub>u</sub>", Z3_OP_UGEQ: "&ge;<sub>u</sub>", Z3_OP_UGT: "&gt;<sub>u</sub>", Z3_OP_BMUL: "&middot;", Z3_OP_BUDIV: "/<sub>u</sub>", Z3_OP_BUREM: "%<sub>u</sub>", Z3_OP_BASHR: "&gt;&gt;", Z3_OP_BSHL: "&lt;&lt;", Z3_OP_BLSHR: "&gt;&gt;<sub>u</sub>" } # Extra operators that are infix/unary for HTML _z3_html_infix = [Z3_OP_AND, Z3_OP_OR, Z3_OP_IMPLIES, Z3_OP_ULEQ, Z3_OP_ULT, Z3_OP_UGEQ, Z3_OP_UGT, Z3_OP_BUDIV, Z3_OP_BUREM, Z3_OP_BLSHR ] _z3_html_unary = [Z3_OP_NOT] # Extra Precedence for HTML _z3_pre_html_precedence = {Z3_OP_BUDIV: 2, Z3_OP_BUREM: 2, Z3_OP_BLSHR: 4, Z3_OP_ULEQ: 8, Z3_OP_ULT: 8, Z3_OP_UGEQ: 8, Z3_OP_UGT: 8, Z3_OP_ULEQ: 8, Z3_OP_ULT: 8, Z3_OP_UGEQ: 8, Z3_OP_UGT: 8, Z3_OP_NOT: 1, Z3_OP_AND: 10, Z3_OP_OR: 11, Z3_OP_IMPLIES: 12} ############################## # # End of Configuration # ############################## def _support_pp(a): return isinstance(a, z3.Z3PPObject) or isinstance(a, list) or isinstance(a, tuple) _infix_map = {} _unary_map = {} _infix_compact_map = {} for _k in _z3_infix: _infix_map[_k] = True for _k in _z3_unary: _unary_map[_k] = True for _k in _z3_infix_compact: _infix_compact_map[_k] = True def _is_infix(k): global _infix_map return _infix_map.get(k, False) def _is_infix_compact(k): global _infix_compact_map return _infix_compact_map.get(k, False) def _is_unary(k): global _unary_map return _unary_map.get(k, False) def _op_name(a): if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_op_to_str.get(k, None) if n is None: return f.name() else: return n def _get_precedence(k): global _z3_precedence return _z3_precedence.get(k, 100000) _z3_html_op_to_str = {} for _k in _z3_op_to_str: _v = _z3_op_to_str[_k] _z3_html_op_to_str[_k] = _v for _k in _z3_pre_html_op_to_str: _v = _z3_pre_html_op_to_str[_k] _z3_html_op_to_str[_k] = _v _z3_html_precedence = {} for _k in _z3_precedence: _v = _z3_precedence[_k] _z3_html_precedence[_k] = _v for _k in _z3_pre_html_precedence: _v = _z3_pre_html_precedence[_k] _z3_html_precedence[_k] = _v _html_infix_map = {} _html_unary_map = {} for _k in _z3_infix: _html_infix_map[_k] = True for _k in _z3_html_infix: _html_infix_map[_k] = True for _k in _z3_unary: _html_unary_map[_k] = True for _k in _z3_html_unary: _html_unary_map[_k] = True def _is_html_infix(k): global _html_infix_map return _html_infix_map.get(k, False) def _is_html_unary(k): global _html_unary_map return _html_unary_map.get(k, False) def _html_op_name(a): global _z3_html_op_to_str if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_html_op_to_str.get(k, None) if n is None: sym = Z3_get_decl_name(f.ctx_ref(), f.ast) if Z3_get_symbol_kind(f.ctx_ref(), sym) == Z3_INT_SYMBOL: return "&#950;<sub>%s</sub>" % Z3_get_symbol_int(f.ctx_ref(), sym) else: # Sanitize the string return f.name() else: return n def _get_html_precedence(k): global _z3_html_predence return _z3_html_precedence.get(k, 100000) class FormatObject: def is_compose(self): return False def is_choice(self): return False def is_indent(self): return False def is_string(self): return False def is_linebreak(self): return False def is_nil(self): return True def children(self): return [] def as_tuple(self): return None def space_upto_nl(self): return (0, False) def flat(self): return self class NAryFormatObject(FormatObject): def __init__(self, fs): assert all([isinstance(a, FormatObject) for a in fs]) self.children = fs def children(self): return self.children class ComposeFormatObject(NAryFormatObject): def is_compose(sef): return True def as_tuple(self): return ("compose", [a.as_tuple() for a in self.children]) def space_upto_nl(self): r = 0 for child in self.children: s, nl = child.space_upto_nl() r = r + s if nl: return (r, True) return (r, False) def flat(self): return compose([a.flat() for a in self.children]) class ChoiceFormatObject(NAryFormatObject): def is_choice(sef): return True def as_tuple(self): return ("choice", [a.as_tuple() for a in self.children]) def space_upto_nl(self): return self.children[0].space_upto_nl() def flat(self): return self.children[0].flat() class IndentFormatObject(FormatObject): def __init__(self, indent, child): assert isinstance(child, FormatObject) self.indent = indent self.child = child def children(self): return [self.child] def as_tuple(self): return ("indent", self.indent, self.child.as_tuple()) def space_upto_nl(self): return self.child.space_upto_nl() def flat(self): return indent(self.indent, self.child.flat()) def is_indent(self): return True class LineBreakFormatObject(FormatObject): def __init__(self): self.space = " " def is_linebreak(self): return True def as_tuple(self): return "<line-break>" def space_upto_nl(self): return (0, True) def flat(self): return to_format(self.space) class StringFormatObject(FormatObject): def __init__(self, string): assert isinstance(string, str) self.string = string def is_string(self): return True def as_tuple(self): return self.string def space_upto_nl(self): return (getattr(self, "size", len(self.string)), False) def fits(f, space_left): s, nl = f.space_upto_nl() return s <= space_left def to_format(arg, size=None): if isinstance(arg, FormatObject): return arg else: r = StringFormatObject(str(arg)) if size is not None: r.size = size return r def compose(*args): if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): args = args[0] return ComposeFormatObject(args) def indent(i, arg): return IndentFormatObject(i, arg) def group(arg): return ChoiceFormatObject([arg.flat(), arg]) def line_break(): return LineBreakFormatObject() def _len(a): if isinstance(a, StringFormatObject): return getattr(a, "size", len(a.string)) else: return len(a) def seq(args, sep=",", space=True): nl = line_break() if not space: nl.space = "" r = [] r.append(args[0]) num = len(args) for i in range(num - 1): r.append(to_format(sep)) r.append(nl) r.append(args[i + 1]) return compose(r) def seq1(header, args, lp="(", rp=")"): return group(compose(to_format(header), to_format(lp), indent(len(lp) + _len(header), seq(args)), to_format(rp))) def seq2(header, args, i=4, lp="(", rp=")"): if len(args) == 0: return compose(to_format(header), to_format(lp), to_format(rp)) else: return group(compose(indent(len(lp), compose(to_format(lp), to_format(header))), indent(i, compose(seq(args), to_format(rp))))) def seq3(args, lp="(", rp=")"): if len(args) == 0: return compose(to_format(lp), to_format(rp)) else: return group(indent(len(lp), compose(to_format(lp), seq(args), to_format(rp)))) class StopPPException(Exception): def __str__(self): return "pp-interrupted" class PP: def __init__(self): self.max_lines = 200 self.max_width = 60 self.bounded = False self.max_indent = 40 def pp_string(self, f, indent): if not self.bounded or self.pos <= self.max_width: sz = _len(f) if self.bounded and self.pos + sz > self.max_width: self.out.write(u(_ellipses)) else: self.pos = self.pos + sz self.ribbon_pos = self.ribbon_pos + sz self.out.write(u(f.string)) def pp_compose(self, f, indent): for c in f.children: self.pp(c, indent) def pp_choice(self, f, indent): space_left = self.max_width - self.pos if space_left > 0 and fits(f.children[0], space_left): self.pp(f.children[0], indent) else: self.pp(f.children[1], indent) def pp_line_break(self, f, indent): self.pos = indent self.ribbon_pos = 0 self.line = self.line + 1 if self.line < self.max_lines: self.out.write(u("\n")) for i in range(indent): self.out.write(u(" ")) else: self.out.write(u("\n...")) raise StopPPException() def pp(self, f, indent): if isinstance(f, str): self.pp_string(f, indent) elif f.is_string(): self.pp_string(f, indent) elif f.is_indent(): self.pp(f.child, min(indent + f.indent, self.max_indent)) elif f.is_compose(): self.pp_compose(f, indent) elif f.is_choice(): self.pp_choice(f, indent) elif f.is_linebreak(): self.pp_line_break(f, indent) else: return def __call__(self, out, f): try: self.pos = 0 self.ribbon_pos = 0 self.line = 0 self.out = out self.pp(f, 0) except StopPPException: return class Formatter: def __init__(self): global _ellipses self.max_depth = 20 self.max_args = 128 self.rational_to_decimal = False self.precision = 10 self.ellipses = to_format(_ellipses) self.max_visited = 10000 self.fpa_pretty = True def pp_ellipses(self): return self.ellipses def pp_arrow(self): return " ->" def pp_unknown(self): return "<unknown>" def pp_name(self, a): return to_format(_op_name(a)) def is_infix(self, a): return _is_infix(a) def is_unary(self, a): return _is_unary(a) def get_precedence(self, a): return _get_precedence(a) def is_infix_compact(self, a): return _is_infix_compact(a) def is_infix_unary(self, a): return self.is_infix(a) or self.is_unary(a) def add_paren(self, a): return compose(to_format("("), indent(1, a), to_format(")")) def pp_sort(self, s): if isinstance(s, z3.ArraySortRef): return seq1("Array", (self.pp_sort(s.domain()), self.pp_sort(s.range()))) elif isinstance(s, z3.BitVecSortRef): return seq1("BitVec", (to_format(s.size()), )) elif isinstance(s, z3.FPSortRef): return seq1("FPSort", (to_format(s.ebits()), to_format(s.sbits()))) elif isinstance(s, z3.ReSortRef): return seq1("ReSort", (self.pp_sort(s.basis()), )) elif isinstance(s, z3.SeqSortRef): if s.is_string(): return to_format("String") return seq1("Seq", (self.pp_sort(s.basis()), )) elif isinstance(s, z3.CharSortRef): return to_format("Char") else: return to_format(s.name()) def pp_const(self, a): k = a.decl().kind() if k == Z3_OP_RE_EMPTY_SET: return self.pp_set("Empty", a) elif k == Z3_OP_SEQ_EMPTY: return self.pp_set("Empty", a) elif k == Z3_OP_RE_FULL_SET: return self.pp_set("Full", a) elif k == Z3_OP_CHAR_CONST: return self.pp_char(a) return self.pp_name(a) def pp_int(self, a): return to_format(a.as_string()) def pp_rational(self, a): if not self.rational_to_decimal: return to_format(a.as_string()) else: return to_format(a.as_decimal(self.precision)) def pp_algebraic(self, a): return to_format(a.as_decimal(self.precision)) def pp_string(self, a): return to_format("\"" + a.as_string() + "\"") def pp_bv(self, a): return to_format(a.as_string()) def pp_fd(self, a): return to_format(a.as_string()) def pp_fprm_value(self, a): _z3_assert(z3.is_fprm_value(a), "expected FPRMNumRef") if self.fpa_pretty and (a.decl().kind() in _z3_op_to_fpa_pretty_str): return to_format(_z3_op_to_fpa_pretty_str.get(a.decl().kind())) else: return to_format(_z3_op_to_fpa_normal_str.get(a.decl().kind())) def pp_fp_value(self, a): _z3_assert(isinstance(a, z3.FPNumRef), "type mismatch") if not self.fpa_pretty: r = [] if (a.isNaN()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_NAN])) r.append(to_format("(")) r.append(to_format(a.sort())) r.append(to_format(")")) return compose(r) elif (a.isInf()): if (a.isNegative()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_MINUS_INF])) else: r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_PLUS_INF])) r.append(to_format("(")) r.append(to_format(a.sort())) r.append(to_format(")")) return compose(r) elif (a.isZero()): if (a.isNegative()): return to_format("-zero") else: return to_format("+zero") else: _z3_assert(z3.is_fp_value(a), "expecting FP num ast") r = [] sgn = c_int(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) r.append(to_format("FPVal(")) if sgnb and sgn.value != 0: r.append(to_format("-")) r.append(to_format(sig)) r.append(to_format("*(2**")) r.append(to_format(exp)) r.append(to_format(", ")) r.append(to_format(a.sort())) r.append(to_format("))")) return compose(r) else: if (a.isNaN()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_NAN]) elif (a.isInf()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_INF]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_INF]) elif (a.isZero()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_ZERO]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_ZERO]) else: _z3_assert(z3.is_fp_value(a), "expecting FP num ast") r = [] sgn = (ctypes.c_int)(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) if sgnb and sgn.value != 0: r.append(to_format("-")) r.append(to_format(sig)) if (exp != "0"): r.append(to_format("*(2**")) r.append(to_format(exp)) r.append(to_format(")")) return compose(r) def pp_fp(self, a, d, xs): _z3_assert(isinstance(a, z3.FPRef), "type mismatch") k = a.decl().kind() op = "?" if (self.fpa_pretty and k in _z3_op_to_fpa_pretty_str): op = _z3_op_to_fpa_pretty_str[k] elif k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] elif k in _z3_op_to_str: op = _z3_op_to_str[k] n = a.num_args() if self.fpa_pretty: if self.is_infix(k) and n >= 3: rm = a.arg(0) if z3.is_fprm_value(rm) and z3.get_default_rounding_mode(a.ctx).eq(rm): arg1 = to_format(self.pp_expr(a.arg(1), d + 1, xs)) arg2 = to_format(self.pp_expr(a.arg(2), d + 1, xs)) r = [] r.append(arg1) r.append(to_format(" ")) r.append(to_format(op)) r.append(to_format(" ")) r.append(arg2) return compose(r) elif k == Z3_OP_FPA_NEG: return compose([to_format("-"), to_format(self.pp_expr(a.arg(0), d + 1, xs))]) if k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] r = [] r.append(to_format(op)) if not z3.is_const(a): r.append(to_format("(")) first = True for c in a.children(): if first: first = False else: r.append(to_format(", ")) r.append(self.pp_expr(c, d + 1, xs)) r.append(to_format(")")) return compose(r) else: return to_format(a.as_string()) def pp_prefix(self, a, d, xs): r = [] sz = 0 for child in a.children(): r.append(self.pp_expr(child, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def is_assoc(self, k): return _is_assoc(k) def is_left_assoc(self, k): return _is_left_assoc(k) def infix_args_core(self, a, d, xs, r): sz = len(r) k = a.decl().kind() p = self.get_precedence(k) first = True for child in a.children(): child_pp = self.pp_expr(child, d + 1, xs) child_k = None if z3.is_app(child): child_k = child.decl().kind() if k == child_k and (self.is_assoc(k) or (first and self.is_left_assoc(k))): self.infix_args_core(child, d, xs, r) sz = len(r) if sz > self.max_args: return elif self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p > child_p or (_is_add(k) and _is_sub(child_k)) or (_is_sub(k) and first and _is_add(child_k)): r.append(child_pp) else: r.append(self.add_paren(child_pp)) sz = sz + 1 elif z3.is_quantifier(child): r.append(self.add_paren(child_pp)) else: r.append(child_pp) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) return first = False def infix_args(self, a, d, xs): r = [] self.infix_args_core(a, d, xs, r) return r def pp_infix(self, a, d, xs): k = a.decl().kind() if self.is_infix_compact(k): op = self.pp_name(a) return group(seq(self.infix_args(a, d, xs), op, False)) else: op = self.pp_name(a) sz = _len(op) op.string = " " + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) def pp_unary(self, a, d, xs): k = a.decl().kind() p = self.get_precedence(k) child = a.children()[0] child_k = None if z3.is_app(child): child_k = child.decl().kind() child_pp = self.pp_expr(child, d + 1, xs) if k != child_k and self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p <= child_p: child_pp = self.add_paren(child_pp) if z3.is_quantifier(child): child_pp = self.add_paren(child_pp) name = self.pp_name(a) return compose(to_format(name), indent(_len(name), child_pp)) def pp_power_arg(self, arg, d, xs): r = self.pp_expr(arg, d + 1, xs) k = None if z3.is_app(arg): k = arg.decl().kind() if self.is_infix_unary(k) or (z3.is_rational_value(arg) and arg.denominator_as_long() != 1): return self.add_paren(r) else: return r def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d + 1, xs) arg2_pp = self.pp_power_arg(a.arg(1), d + 1, xs) return group(seq((arg1_pp, arg2_pp), "**", False)) def pp_neq(self): return to_format("!=") def pp_distinct(self, a, d, xs): if a.num_args() == 2: op = self.pp_neq() sz = _len(op) op.string = " " + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) else: return self.pp_prefix(a, d, xs) def pp_select(self, a, d, xs): if a.num_args() != 2: return self.pp_prefix(a, d, xs) else: arg1_pp = self.pp_expr(a.arg(0), d + 1, xs) arg2_pp = self.pp_expr(a.arg(1), d + 1, xs) return compose(arg1_pp, indent(2, compose(to_format("["), arg2_pp, to_format("]")))) def pp_unary_param(self, a, d, xs): p = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d + 1, xs) return seq1(self.pp_name(a), [to_format(p), arg]) def pp_extract(self, a, d, xs): high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) low = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) arg = self.pp_expr(a.arg(0), d + 1, xs) return seq1(self.pp_name(a), [to_format(high), to_format(low), arg]) def pp_loop(self, a, d, xs): low = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d + 1, xs) if Z3_get_decl_num_parameters(a.ctx_ref(), a.decl().ast) > 1: high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) return seq1("Loop", [arg, to_format(low), to_format(high)]) return seq1("Loop", [arg, to_format(low)]) def pp_set(self, id, a): return seq1(id, [self.pp_sort(a.sort())]) def pp_char(self, a): n = a.params()[0] return to_format(str(n)) def pp_pattern(self, a, d, xs): if a.num_args() == 1: return self.pp_expr(a.arg(0), d, xs) else: return seq1("MultiPattern", [self.pp_expr(arg, d + 1, xs) for arg in a.children()]) def pp_is(self, a, d, xs): f = a.params()[0] return self.pp_fdecl(f, a, d, xs) def pp_map(self, a, d, xs): f = z3.get_map_func(a) return self.pp_fdecl(f, a, d, xs) def pp_fdecl(self, f, a, d, xs): r = [] sz = 0 r.append(to_format(f.name())) for child in a.children(): r.append(self.pp_expr(child, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def pp_K(self, a, d, xs): return seq1(self.pp_name(a), [self.pp_sort(a.domain()), self.pp_expr(a.arg(0), d + 1, xs)]) def pp_atmost(self, a, d, f, xs): k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) return seq1(self.pp_name(a), [seq3([self.pp_expr(ch, d + 1, xs) for ch in a.children()]), to_format(k)]) def pp_pbcmp(self, a, d, f, xs): chs = a.children() rchs = range(len(chs)) k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) ks = [Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, i + 1) for i in rchs] ls = [seq3([self.pp_expr(chs[i], d + 1, xs), to_format(ks[i])]) for i in rchs] return seq1(self.pp_name(a), [seq3(ls), to_format(k)]) def pp_app(self, a, d, xs): if z3.is_int_value(a): return self.pp_int(a) elif z3.is_rational_value(a): return self.pp_rational(a) elif z3.is_algebraic_value(a): return self.pp_algebraic(a) elif z3.is_bv_value(a): return self.pp_bv(a) elif z3.is_finite_domain_value(a): return self.pp_fd(a) elif z3.is_fprm_value(a): return self.pp_fprm_value(a) elif z3.is_fp_value(a): return self.pp_fp_value(a) elif z3.is_fp(a): return self.pp_fp(a, d, xs) elif z3.is_string_value(a): return self.pp_string(a) elif z3.is_const(a): return self.pp_const(a) else: f = a.decl() k = f.kind() if k == Z3_OP_POWER: return self.pp_power(a, d, xs) elif k == Z3_OP_DISTINCT: return self.pp_distinct(a, d, xs) elif k == Z3_OP_SELECT: return self.pp_select(a, d, xs) elif k == Z3_OP_SIGN_EXT or k == Z3_OP_ZERO_EXT or k == Z3_OP_REPEAT: return self.pp_unary_param(a, d, xs) elif k == Z3_OP_EXTRACT: return self.pp_extract(a, d, xs) elif k == Z3_OP_RE_LOOP: return self.pp_loop(a, d, xs) elif k == Z3_OP_DT_IS: return self.pp_is(a, d, xs) elif k == Z3_OP_ARRAY_MAP: return self.pp_map(a, d, xs) elif k == Z3_OP_CONST_ARRAY: return self.pp_K(a, d, xs) elif k == Z3_OP_PB_AT_MOST: return self.pp_atmost(a, d, f, xs) elif k == Z3_OP_PB_LE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_GE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_EQ: return self.pp_pbcmp(a, d, f, xs) elif z3.is_pattern(a): return self.pp_pattern(a, d, xs) elif self.is_infix(k): return self.pp_infix(a, d, xs) elif self.is_unary(k): return self.pp_unary(a, d, xs) else: return self.pp_prefix(a, d, xs) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: return seq1("Var", (to_format(idx),)) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [to_format(a.var_name(i)) for i in range(a.num_vars())] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d + 1, new_xs) if len(ys) == 1: ys_pp = ys[0] else: ys_pp = seq3(ys, "[", "]") if a.is_forall(): header = "ForAll" elif a.is_exists(): header = "Exists" else: header = "Lambda" return seq1(header, (ys_pp, body_pp)) def pp_expr(self, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() if z3.is_app(a): return self.pp_app(a, d, xs) elif z3.is_quantifier(a): return self.pp_quantifier(a, d, xs) elif z3.is_var(a): return self.pp_var(a, d, xs) else: return to_format(self.pp_unknown()) def pp_decl(self, f): k = f.kind() if k == Z3_OP_DT_IS or k == Z3_OP_ARRAY_MAP: g = f.params()[0] r = [to_format(g.name())] return seq1(self.pp_name(f), r) return self.pp_name(f) def pp_seq_core(self, f, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() r = [] sz = 0 for elem in a: r.append(f(elem, d + 1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, "[", "]") def pp_seq(self, a, d, xs): return self.pp_seq_core(self.pp_expr, a, d, xs) def pp_seq_seq(self, a, d, xs): return self.pp_seq_core(self.pp_seq, a, d, xs) def pp_model(self, m): r = [] sz = 0 for d in m: i = m[d] if isinstance(i, z3.FuncInterp): i_pp = self.pp_func_interp(i) else: i_pp = self.pp_expr(i, 0, []) name = self.pp_name(d) r.append(compose(name, to_format(" = "), indent(_len(name) + 3, i_pp))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, "[", "]") def pp_func_entry(self, e): num = e.num_args() if num > 1: args = [] for i in range(num): args.append(self.pp_expr(e.arg_value(i), 0, [])) args_pp = group(seq3(args)) else: args_pp = self.pp_expr(e.arg_value(0), 0, []) value_pp = self.pp_expr(e.value(), 0, []) return group(seq((args_pp, value_pp), self.pp_arrow())) def pp_func_interp(self, f): r = [] sz = 0 num = f.num_entries() for i in range(num): r.append(self.pp_func_entry(f.entry(i))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if sz <= self.max_args: else_val = f.else_value() if else_val is None: else_pp = to_format("#unspecified") else: else_pp = self.pp_expr(else_val, 0, []) r.append(group(seq((to_format("else"), else_pp), self.pp_arrow()))) return seq3(r, "[", "]") def pp_list(self, a): r = [] sz = 0 for elem in a: if _support_pp(elem): r.append(self.main(elem)) else: r.append(to_format(str(elem))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if isinstance(a, tuple): return seq3(r) else: return seq3(r, "[", "]") def main(self, a): if z3.is_expr(a): return self.pp_expr(a, 0, []) elif z3.is_sort(a): return self.pp_sort(a) elif z3.is_func_decl(a): return self.pp_decl(a) elif isinstance(a, z3.Goal) or isinstance(a, z3.AstVector): return self.pp_seq(a, 0, []) elif isinstance(a, z3.Solver): return self.pp_seq(a.assertions(), 0, []) elif isinstance(a, z3.Fixedpoint): return a.sexpr() elif isinstance(a, z3.Optimize): return a.sexpr() elif isinstance(a, z3.ApplyResult): return self.pp_seq_seq(a, 0, []) elif isinstance(a, z3.ModelRef): return self.pp_model(a) elif isinstance(a, z3.FuncInterp): return self.pp_func_interp(a) elif isinstance(a, list) or isinstance(a, tuple): return self.pp_list(a) else: return to_format(self.pp_unknown()) def __call__(self, a): self.visited = 0 return self.main(a) class HTMLFormatter(Formatter): def __init__(self): Formatter.__init__(self) global _html_ellipses self.ellipses = to_format(_html_ellipses) def pp_arrow(self): return to_format(" &rarr;", 1) def pp_unknown(self): return "<b>unknown</b>" def pp_name(self, a): r = _html_op_name(a) if r[0] == "&" or r[0] == "/" or r[0] == "%": return to_format(r, 1) else: pos = r.find("__") if pos == -1 or pos == 0: return to_format(r) else: sz = len(r) if pos + 2 == sz: return to_format(r) else: return to_format("%s<sub>%s</sub>" % (r[0:pos], r[pos + 2:sz]), sz - 2) def is_assoc(self, k): return _is_html_assoc(k) def is_left_assoc(self, k): return _is_html_left_assoc(k) def is_infix(self, a): return _is_html_infix(a) def is_unary(self, a): return _is_html_unary(a) def get_precedence(self, a): return _get_html_precedence(a) def pp_neq(self): return to_format("&ne;") def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d + 1, xs) arg2_pp = self.pp_expr(a.arg(1), d + 1, xs) return compose(arg1_pp, to_format("<sup>", 1), arg2_pp, to_format("</sup>", 1)) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: # 957 is the greek letter nu return to_format("&#957;<sub>%s</sub>" % idx, 1) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [to_format(a.var_name(i)) for i in range(a.num_vars())] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d + 1, new_xs) ys_pp = group(seq(ys)) if a.is_forall(): header = "&forall;" else: header = "&exist;" return group(compose(to_format(header, 1), indent(1, compose(ys_pp, to_format(" :"), line_break(), body_pp)))) _PP = PP() _Formatter = Formatter() def set_pp_option(k, v): if k == "html_mode": if v: set_html_mode(True) else: set_html_mode(False) return True if k == "fpa_pretty": if v: set_fpa_pretty(True) else: set_fpa_pretty(False) return True val = getattr(_PP, k, None) if val is not None: _z3_assert(isinstance(v, type(val)), "Invalid pretty print option value") setattr(_PP, k, v) return True val = getattr(_Formatter, k, None) if val is not None: _z3_assert(isinstance(v, type(val)), "Invalid pretty print option value") setattr(_Formatter, k, v) return True return False def obj_to_string(a): out = io.StringIO() _PP(out, _Formatter(a)) return out.getvalue() _html_out = None def set_html_mode(flag=True): global _Formatter if flag: _Formatter = HTMLFormatter() else: _Formatter = Formatter() def set_fpa_pretty(flag=True): global _Formatter global _z3_op_to_str _Formatter.fpa_pretty = flag if flag: for (_k, _v) in _z3_op_to_fpa_pretty_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = True else: for (_k, _v) in _z3_op_to_fpa_normal_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = False set_fpa_pretty(True) def get_fpa_pretty(): global Formatter return _Formatter.fpa_pretty def in_html_mode(): return isinstance(_Formatter, HTMLFormatter) def pp(a): if _support_pp(a): print(obj_to_string(a)) else: print(a) def print_matrix(m): _z3_assert(isinstance(m, list) or isinstance(m, tuple), "matrix expected") if not in_html_mode(): print(obj_to_string(m)) else: print('<table cellpadding="2", cellspacing="0", border="1">') for r in m: _z3_assert(isinstance(r, list) or isinstance(r, tuple), "matrix expected") print("<tr>") for c in r: print("<td>%s</td>" % c) print("</tr>") print("</table>") def insert_line_breaks(s, width): """Break s in lines of size width (approx)""" sz = len(s) if sz <= width: return s new_str = io.StringIO() w = 0 for i in range(sz): if w > width and s[i] == " ": new_str.write(u("<br />")) w = 0 else: new_str.write(u(s[i])) w = w + 1 return new_str.getvalue()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3printer.py
z3printer.py
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction from .z3 import _get_ctx def _to_numeral(num, ctx=None): if isinstance(num, Numeral): return num else: return Numeral(num, ctx) class Numeral: """ A Z3 numeral can be used to perform computations over arbitrary precision integers, rationals and real algebraic numbers. It also automatically converts python numeric values. >>> Numeral(2) 2 >>> Numeral("3/2") + 1 5/2 >>> Numeral(Sqrt(2)) 1.4142135623? >>> Numeral(Sqrt(2)) + 2 3.4142135623? >>> Numeral(Sqrt(2)) + Numeral(Sqrt(3)) 3.1462643699? Z3 numerals can be used to perform computations with values in a Z3 model. >>> s = Solver() >>> x = Real('x') >>> s.add(x*x == 2) >>> s.add(x > 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1.4142135623? >>> m[x] + 1 1.4142135623? + 1 The previous result is a Z3 expression. >>> (m[x] + 1).sexpr() '(+ (root-obj (+ (^ x 2) (- 2)) 2) 1.0)' >>> Numeral(m[x]) + 1 2.4142135623? >>> Numeral(m[x]).is_pos() True >>> Numeral(m[x])**2 2 We can also isolate the roots of polynomials. >>> x0, x1, x2 = RealVarVector(3) >>> r0 = isolate_roots(x0**5 - x0 - 1) >>> r0 [1.1673039782?] In the following example, we are isolating the roots of a univariate polynomial (on x1) obtained after substituting x0 -> r0[0] >>> r1 = isolate_roots(x1**2 - x0 + 1, [ r0[0] ]) >>> r1 [-0.4090280898?, 0.4090280898?] Similarly, in the next example we isolate the roots of a univariate polynomial (on x2) obtained after substituting x0 -> r0[0] and x1 -> r1[0] >>> isolate_roots(x1*x2 + x0, [ r0[0], r1[0] ]) [2.8538479564?] """ def __init__(self, num, ctx=None): if isinstance(num, Ast): self.ast = num self.ctx = _get_ctx(ctx) elif isinstance(num, RatNumRef) or isinstance(num, AlgebraicNumRef): self.ast = num.ast self.ctx = num.ctx elif isinstance(num, ArithRef): r = simplify(num) self.ast = r.ast self.ctx = r.ctx else: v = RealVal(num, ctx) self.ast = v.ast self.ctx = v.ctx Z3_inc_ref(self.ctx_ref(), self.as_ast()) assert Z3_algebraic_is_value(self.ctx_ref(), self.ast) def __del__(self): Z3_dec_ref(self.ctx_ref(), self.as_ast()) def is_integer(self): """ Return True if the numeral is integer. >>> Numeral(2).is_integer() True >>> (Numeral(Sqrt(2)) * Numeral(Sqrt(2))).is_integer() True >>> Numeral(Sqrt(2)).is_integer() False >>> Numeral("2/3").is_integer() False """ return self.is_rational() and self.denominator() == 1 def is_rational(self): """ Return True if the numeral is rational. >>> Numeral(2).is_rational() True >>> Numeral("2/3").is_rational() True >>> Numeral(Sqrt(2)).is_rational() False """ return Z3_get_ast_kind(self.ctx_ref(), self.as_ast()) == Z3_NUMERAL_AST def denominator(self): """ Return the denominator if `self` is rational. >>> Numeral("2/3").denominator() 3 """ assert(self.is_rational()) return Numeral(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator(self): """ Return the numerator if `self` is rational. >>> Numeral("2/3").numerator() 2 """ assert(self.is_rational()) return Numeral(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def is_irrational(self): """ Return True if the numeral is irrational. >>> Numeral(2).is_irrational() False >>> Numeral("2/3").is_irrational() False >>> Numeral(Sqrt(2)).is_irrational() True """ return not self.is_rational() def as_long(self): """ Return a numeral (that is an integer) as a Python long. """ assert(self.is_integer()) if sys.version_info.major >= 3: return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) else: return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) def as_fraction(self): """ Return a numeral (that is a rational) as a Python Fraction. >>> Numeral("1/5").as_fraction() Fraction(1, 5) """ assert(self.is_rational()) return Fraction(self.numerator().as_long(), self.denominator().as_long()) def approx(self, precision=10): """Return a numeral that approximates the numeral `self`. The result `r` is such that |r - self| <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 >>> Numeral(2).approx(10) 2 """ return self.upper(precision) def upper(self, precision=10): """Return a upper bound that approximates the numeral `self`. The result `r` is such that r - self <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.upper(20) 6838717160008073720548335/4835703278458516698824704 >>> x.upper(5) 2965821/2097152 >>> Numeral(2).upper(10) 2 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def lower(self, precision=10): """Return a lower bound that approximates the numeral `self`. The result `r` is such that self - r <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.lower(20) 1709679290002018430137083/1208925819614629174706176 >>> Numeral("2/3").lower(10) 2/3 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_lower(self.ctx_ref(), self.as_ast(), precision), self.ctx) def sign(self): """ Return the sign of the numeral. >>> Numeral(2).sign() 1 >>> Numeral(-3).sign() -1 >>> Numeral(0).sign() 0 """ return Z3_algebraic_sign(self.ctx_ref(), self.ast) def is_pos(self): """ Return True if the numeral is positive. >>> Numeral(2).is_pos() True >>> Numeral(-3).is_pos() False >>> Numeral(0).is_pos() False """ return Z3_algebraic_is_pos(self.ctx_ref(), self.ast) def is_neg(self): """ Return True if the numeral is negative. >>> Numeral(2).is_neg() False >>> Numeral(-3).is_neg() True >>> Numeral(0).is_neg() False """ return Z3_algebraic_is_neg(self.ctx_ref(), self.ast) def is_zero(self): """ Return True if the numeral is zero. >>> Numeral(2).is_zero() False >>> Numeral(-3).is_zero() False >>> Numeral(0).is_zero() True >>> sqrt2 = Numeral(2).root(2) >>> sqrt2.is_zero() False >>> (sqrt2 - sqrt2).is_zero() True """ return Z3_algebraic_is_zero(self.ctx_ref(), self.ast) def __add__(self, other): """ Return the numeral `self + other`. >>> Numeral(2) + 3 5 >>> Numeral(2) + Numeral(4) 6 >>> Numeral("2/3") + 1 5/3 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __radd__(self, other): """ Return the numeral `other + self`. >>> 3 + Numeral(2) 5 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __sub__(self, other): """ Return the numeral `self - other`. >>> Numeral(2) - 3 -1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rsub__(self, other): """ Return the numeral `other - self`. >>> 3 - Numeral(2) 1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __mul__(self, other): """ Return the numeral `self * other`. >>> Numeral(2) * 3 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rmul__(self, other): """ Return the numeral `other * mul`. >>> 3 * Numeral(2) 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __div__(self, other): """ Return the numeral `self / other`. >>> Numeral(2) / 3 2/3 >>> Numeral(2).root(2) / 3 0.4714045207? >>> Numeral(Sqrt(2)) / Numeral(Sqrt(3)) 0.8164965809? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): """ Return the numeral `other / self`. >>> 3 / Numeral(2) 3/2 >>> 3 / Numeral(2).root(2) 2.1213203435? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __rtruediv__(self, other): return self.__rdiv__(other) def root(self, k): """ Return the numeral `self^(1/k)`. >>> sqrt2 = Numeral(2).root(2) >>> sqrt2 1.4142135623? >>> sqrt2 * sqrt2 2 >>> sqrt2 * 2 + 1 3.8284271247? >>> (sqrt2 * 2 + 1).sexpr() '(root-obj (+ (^ x 2) (* (- 2) x) (- 7)) 2)' """ return Numeral(Z3_algebraic_root(self.ctx_ref(), self.ast, k), self.ctx) def power(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3 """ return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx) def __pow__(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3**2 3 """ return self.power(k) def __lt__(self, other): """ Return True if `self < other`. >>> Numeral(Sqrt(2)) < 2 True >>> Numeral(Sqrt(3)) < Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) < Numeral(Sqrt(2)) False """ return Z3_algebraic_lt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rlt__(self, other): """ Return True if `other < self`. >>> 2 < Numeral(Sqrt(2)) False """ return self > other def __gt__(self, other): """ Return True if `self > other`. >>> Numeral(Sqrt(2)) > 2 False >>> Numeral(Sqrt(3)) > Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) > Numeral(Sqrt(2)) False """ return Z3_algebraic_gt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rgt__(self, other): """ Return True if `other > self`. >>> 2 > Numeral(Sqrt(2)) True """ return self < other def __le__(self, other): """ Return True if `self <= other`. >>> Numeral(Sqrt(2)) <= 2 True >>> Numeral(Sqrt(3)) <= Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) <= Numeral(Sqrt(2)) True """ return Z3_algebraic_le(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rle__(self, other): """ Return True if `other <= self`. >>> 2 <= Numeral(Sqrt(2)) False """ return self >= other def __ge__(self, other): """ Return True if `self >= other`. >>> Numeral(Sqrt(2)) >= 2 False >>> Numeral(Sqrt(3)) >= Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) >= Numeral(Sqrt(2)) True """ return Z3_algebraic_ge(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rge__(self, other): """ Return True if `other >= self`. >>> 2 >= Numeral(Sqrt(2)) True """ return self <= other def __eq__(self, other): """ Return True if `self == other`. >>> Numeral(Sqrt(2)) == 2 False >>> Numeral(Sqrt(3)) == Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) == Numeral(Sqrt(2)) True """ return Z3_algebraic_eq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __ne__(self, other): """ Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False """ return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __str__(self): if Z3_is_numeral_ast(self.ctx_ref(), self.ast): return str(RatNumRef(self.ast, self.ctx)) else: return str(AlgebraicNumRef(self.ast, self.ctx)) def __repr__(self): return self.__str__() def sexpr(self): return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): return self.ast def ctx_ref(self): return self.ctx.ref() def eval_sign_at(p, vs): """ Evaluate the sign of the polynomial `p` at `vs`. `p` is a Z3 Expression containing arithmetic operators: +, -, *, ^k where k is an integer; and free variables x that is_var(x) is True. Moreover, all variables must be real. The result is 1 if the polynomial is positive at the given point, -1 if negative, and 0 if zero. >>> x0, x1, x2 = RealVarVector(3) >>> eval_sign_at(x0**2 + x1*x2 + 1, (Numeral(0), Numeral(1), Numeral(2))) 1 >>> eval_sign_at(x0**2 - 2, [ Numeral(Sqrt(2)) ]) 0 >>> eval_sign_at((x0 + x1)*(x0 + x2), (Numeral(0), Numeral(Sqrt(2)), Numeral(Sqrt(3)))) 1 """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast return Z3_algebraic_eval(p.ctx_ref(), p.as_ast(), num, _vs) def isolate_roots(p, vs=[]): """ Given a multivariate polynomial p(x_0, ..., x_{n-1}, x_n), returns the roots of the univariate polynomial p(vs[0], ..., vs[len(vs)-1], x_n). Remarks: * p is a Z3 expression that contains only arithmetic terms and free variables. * forall i in [0, n) vs is a numeral. The result is a list of numerals >>> x0 = RealVar(0) >>> isolate_roots(x0**5 - x0 - 1) [1.1673039782?] >>> x1 = RealVar(1) >>> isolate_roots(x0**2 - x1**4 - 1, [ Numeral(Sqrt(3)) ]) [-1.1892071150?, 1.1892071150?] >>> x2 = RealVar(2) >>> isolate_roots(x2**2 + x0 - x1, [ Numeral(Sqrt(3)), Numeral(Sqrt(2)) ]) [] """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast _roots = AstVector(Z3_algebraic_roots(p.ctx_ref(), p.as_ast(), num, _vs), p.ctx) return [Numeral(r) for r in _roots]
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3num.py
z3num.py
import ctypes from .z3 import * def vset(seq, idfun=None, as_list=True): # This functions preserves the order of arguments while removing duplicates. # This function is from https://code.google.com/p/common-python-vu/source/browse/vu_common.py # (Thanhu's personal code). It has been copied here to avoid a dependency on vu_common.py. """ order preserving >>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr) [[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]] """ def _uniq_normal(seq): d_ = {} for s in seq: if s not in d_: d_[s] = None yield s def _uniq_idfun(seq, idfun): d_ = {} for s in seq: h_ = idfun(s) if h_ not in d_: d_[h_] = None yield s if idfun is None: res = _uniq_normal(seq) else: res = _uniq_idfun(seq, idfun) return list(res) if as_list else res def get_z3_version(as_str=False): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) rs = map(int, (major.value, minor.value, build.value, rev.value)) if as_str: return "{}.{}.{}.{}".format(*rs) else: return rs def ehash(v): """ Returns a 'stronger' hash value than the default hash() method. The result from hash() is not enough to distinguish between 2 z3 expressions in some cases. Note: the following doctests will fail with Python 2.x as the default formatting doesn't match that of 3.x. >>> x1 = Bool('x'); x2 = Bool('x'); x3 = Int('x') >>> print(x1.hash(), x2.hash(), x3.hash()) #BAD: all same hash values 783810685 783810685 783810685 >>> print(ehash(x1), ehash(x2), ehash(x3)) x_783810685_1 x_783810685_1 x_783810685_2 """ if z3_debug(): assert is_expr(v) return "{}_{}_{}".format(str(v), v.hash(), v.sort_kind()) """ In Z3, variables are called *uninterpreted* consts and variables are *interpreted* consts. """ def is_expr_var(v): """ EXAMPLES: >>> is_expr_var(Int('7')) True >>> is_expr_var(IntVal('7')) False >>> is_expr_var(Bool('y')) True >>> is_expr_var(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_var(LOnOff) False >>> is_expr_var(On) False >>> is_expr_var(Block) True >>> is_expr_var(SafetyInjection) True """ return is_const(v) and v.decl().kind() == Z3_OP_UNINTERPRETED def is_expr_val(v): """ EXAMPLES: >>> is_expr_val(Int('7')) False >>> is_expr_val(IntVal('7')) True >>> is_expr_val(Bool('y')) False >>> is_expr_val(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_val(LOnOff) False >>> is_expr_val(On) True >>> is_expr_val(Block) False >>> is_expr_val(SafetyInjection) False """ return is_const(v) and v.decl().kind() != Z3_OP_UNINTERPRETED def get_vars(f, rs=None): """ >>> x,y = Ints('x y') >>> a,b = Bools('a b') >>> get_vars(Implies(And(x+y==0,x*2==10),Or(a,Implies(a,b==False)))) [x, y, a, b] """ if rs is None: rs = [] if z3_debug(): assert is_expr(f) if is_const(f): if is_expr_val(f): return rs else: # variable return vset(rs + [f], str) else: for f_ in f.children(): rs = get_vars(f_, rs) return vset(rs, str) def mk_var(name, vsort): if vsort.kind() == Z3_INT_SORT: v = Int(name) elif vsort.kind() == Z3_REAL_SORT: v = Real(name) elif vsort.kind() == Z3_BOOL_SORT: v = Bool(name) elif vsort.kind() == Z3_DATATYPE_SORT: v = Const(name, vsort) else: raise TypeError("Cannot handle this sort (s: %sid: %d)" % (vsort, vsort.kind())) return v def prove(claim, assume=None, verbose=0): """ >>> r,m = prove(BoolVal(True),verbose=0); r,model_str(m,as_str=False) (True, None) #infinite counter example when proving contradiction >>> r,m = prove(BoolVal(False)); r,model_str(m,as_str=False) (False, []) >>> x,y,z=Bools('x y z') >>> r,m = prove(And(x,Not(x))); r,model_str(m,as_str=True) (False, '[]') >>> r,m = prove(True,assume=And(x,Not(x)),verbose=0) Traceback (most recent call last): ... AssertionError: Assumption is always False! >>> r,m = prove(Implies(x,x),assume=y,verbose=2); r,model_str(m,as_str=False) assume: y claim: Implies(x, x) to_prove: Implies(y, Implies(x, x)) (True, None) >>> r,m = prove(And(x,True),assume=y,verbose=0); r,model_str(m,as_str=False) (False, [(x, False), (y, True)]) >>> r,m = prove(And(x,y),assume=y,verbose=0) >>> print(r) False >>> print(model_str(m,as_str=True)) x = False y = True >>> a,b = Ints('a b') >>> r,m = prove(a**b == b**a,assume=None,verbose=0) E: cannot solve ! >>> r is None and m is None True """ if z3_debug(): assert not assume or is_expr(assume) to_prove = claim if assume: if z3_debug(): is_proved, _ = prove(Not(assume)) def _f(): emsg = "Assumption is always False!" if verbose >= 2: emsg = "{}\n{}".format(assume, emsg) return emsg assert is_proved is False, _f() to_prove = Implies(assume, to_prove) if verbose >= 2: print("assume: ") print(assume) print("claim: ") print(claim) print("to_prove: ") print(to_prove) f = Not(to_prove) models = get_models(f, k=1) if models is None: # unknown print("E: cannot solve !") return None, None elif models is False: # unsat return True, None else: # sat if z3_debug(): assert isinstance(models, list) if models: return False, models[0] # the first counterexample else: return False, [] # infinite counterexample,models def get_models(f, k): """ Returns the first k models satisfiying f. If f is not satisfiable, returns False. If f cannot be solved, returns None If f is satisfiable, returns the first k models Note that if f is a tautology, e.g.\\ True, then the result is [] Based on http://stackoverflow.com/questions/11867611/z3py-checking-all-solutions-for-equation EXAMPLES: >>> x, y = Ints('x y') >>> len(get_models(And(0<=x,x <= 4),k=11)) 5 >>> get_models(And(0<=x**y,x <= 1),k=2) is None True >>> get_models(And(0<=x,x <= -1),k=2) False >>> len(get_models(x+y==7,5)) 5 >>> len(get_models(And(x<=5,x>=1),7)) 5 >>> get_models(And(x<=0,x>=5),7) False >>> x = Bool('x') >>> get_models(And(x,Not(x)),k=1) False >>> get_models(Implies(x,x),k=1) [] >>> get_models(BoolVal(True),k=1) [] """ if z3_debug(): assert is_expr(f) assert k >= 1 s = Solver() s.add(f) models = [] i = 0 while s.check() == sat and i < k: i = i + 1 m = s.model() if not m: # if m == [] break models.append(m) # create new constraint to block the current model block = Not(And([v() == m[v] for v in m])) s.add(block) if s.check() == unknown: return None elif s.check() == unsat and i == 0: return False else: return models def is_tautology(claim, verbose=0): """ >>> is_tautology(Implies(Bool('x'),Bool('x'))) True >>> is_tautology(Implies(Bool('x'),Bool('y'))) False >>> is_tautology(BoolVal(True)) True >>> is_tautology(BoolVal(False)) False """ return prove(claim=claim, assume=None, verbose=verbose)[0] def is_contradiction(claim, verbose=0): """ >>> x,y=Bools('x y') >>> is_contradiction(BoolVal(False)) True >>> is_contradiction(BoolVal(True)) False >>> is_contradiction(x) False >>> is_contradiction(Implies(x,y)) False >>> is_contradiction(Implies(x,x)) False >>> is_contradiction(And(x,Not(x))) True """ return prove(claim=Not(claim), assume=None, verbose=verbose)[0] def exact_one_model(f): """ return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False """ models = get_models(f, k=2) if isinstance(models, list): return len(models) == 1 else: return False def myBinOp(op, *L): """ >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd(*[Bool('x'),None]) x >>> myAnd(*[Bool('x')]) x >>> myAnd(*[]) >>> myAnd(Bool('x'),Bool('y')) And(x, y) >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd([Bool('x'),Bool('y')]) And(x, y) >>> myAnd((Bool('x'),Bool('y'))) And(x, y) >>> myAnd(*[Bool('x'),Bool('y'),True]) Traceback (most recent call last): ... AssertionError """ if z3_debug(): assert op == Z3_OP_OR or op == Z3_OP_AND or op == Z3_OP_IMPLIES if len(L) == 1 and (isinstance(L[0], list) or isinstance(L[0], tuple)): L = L[0] if z3_debug(): assert all(not isinstance(val, bool) for val in L) L = [val for val in L if is_expr(val)] if L: if len(L) == 1: return L[0] if op == Z3_OP_OR: return Or(L) if op == Z3_OP_AND: return And(L) return Implies(L[0], L[1]) else: return None def myAnd(*L): return myBinOp(Z3_OP_AND, *L) def myOr(*L): return myBinOp(Z3_OP_OR, *L) def myImplies(a, b): return myBinOp(Z3_OP_IMPLIES, [a, b]) def Iff(f): return And(Implies(f[0], f[1]), Implies(f[1], f[0])) def model_str(m, as_str=True): """ Returned a 'sorted' model (so that it's easier to see) The model is sorted by its key, e.g. if the model is y = 3 , x = 10, then the result is x = 10, y = 3 EXAMPLES: see doctest exampels from function prove() """ if z3_debug(): assert m is None or m == [] or isinstance(m, ModelRef) if m: vs = [(v, m[v]) for v in m] vs = sorted(vs, key=lambda a, _: str(a)) if as_str: return "\n".join(["{} = {}".format(k, v) for (k, v) in vs]) else: return vs else: return str(m) if as_str else m
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3util.py
z3util.py
import ctypes class Z3Exception(Exception): def __init__(self, value): self.value = value def __str__(self): return str(self.value) class ContextObj(ctypes.c_void_p): def __init__(self, context): self._as_parameter_ = context def from_param(obj): return obj class Config(ctypes.c_void_p): def __init__(self, config): self._as_parameter_ = config def from_param(obj): return obj class Symbol(ctypes.c_void_p): def __init__(self, symbol): self._as_parameter_ = symbol def from_param(obj): return obj class Sort(ctypes.c_void_p): def __init__(self, sort): self._as_parameter_ = sort def from_param(obj): return obj class FuncDecl(ctypes.c_void_p): def __init__(self, decl): self._as_parameter_ = decl def from_param(obj): return obj class Ast(ctypes.c_void_p): def __init__(self, ast): self._as_parameter_ = ast def from_param(obj): return obj class Pattern(ctypes.c_void_p): def __init__(self, pattern): self._as_parameter_ = pattern def from_param(obj): return obj class Model(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class Literals(ctypes.c_void_p): def __init__(self, literals): self._as_parameter_ = literals def from_param(obj): return obj class Constructor(ctypes.c_void_p): def __init__(self, constructor): self._as_parameter_ = constructor def from_param(obj): return obj class ConstructorList(ctypes.c_void_p): def __init__(self, constructor_list): self._as_parameter_ = constructor_list def from_param(obj): return obj class GoalObj(ctypes.c_void_p): def __init__(self, goal): self._as_parameter_ = goal def from_param(obj): return obj class TacticObj(ctypes.c_void_p): def __init__(self, tactic): self._as_parameter_ = tactic def from_param(obj): return obj class SimplifierObj(ctypes.c_void_p): def __init__(self, simplifier): self._as_parameter_ = simplifier def from_param(obj): return obj class ProbeObj(ctypes.c_void_p): def __init__(self, probe): self._as_parameter_ = probe def from_param(obj): return obj class ApplyResultObj(ctypes.c_void_p): def __init__(self, obj): self._as_parameter_ = obj def from_param(obj): return obj class StatsObj(ctypes.c_void_p): def __init__(self, statistics): self._as_parameter_ = statistics def from_param(obj): return obj class SolverObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class SolverCallbackObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class FixedpointObj(ctypes.c_void_p): def __init__(self, fixedpoint): self._as_parameter_ = fixedpoint def from_param(obj): return obj class OptimizeObj(ctypes.c_void_p): def __init__(self, optimize): self._as_parameter_ = optimize def from_param(obj): return obj class ModelObj(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class AstVectorObj(ctypes.c_void_p): def __init__(self, vector): self._as_parameter_ = vector def from_param(obj): return obj class AstMapObj(ctypes.c_void_p): def __init__(self, ast_map): self._as_parameter_ = ast_map def from_param(obj): return obj class Params(ctypes.c_void_p): def __init__(self, params): self._as_parameter_ = params def from_param(obj): return obj class ParamDescrs(ctypes.c_void_p): def __init__(self, paramdescrs): self._as_parameter_ = paramdescrs def from_param(obj): return obj class ParserContextObj(ctypes.c_void_p): def __init__(self, pc): self._as_parameter_ = pc def from_param(obj): return obj class FuncInterpObj(ctypes.c_void_p): def __init__(self, f): self._as_parameter_ = f def from_param(obj): return obj class FuncEntryObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj class RCFNumObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/python/z3/z3types.py
z3types.py
# Julia bindings The Julia package [Z3.jl](https://github.com/ahumenberger/Z3.jl) provides and interface to Z3 by exposing its C++ API via [CxxWrap.jl](https://github.com/JuliaInterop/CxxWrap.jl). The bindings therefore consist of a [C++ part](z3jl.cpp) and a [Julia part](https://github.com/ahumenberger/Z3.jl). The C++ part defines the Z3 types/methods which are exposed. The resulting library is loaded in the Julia part via CxxWrap.jl which creates the corresponding Julia types/methods. ## Building the C++ part In order to build the Julia bindings the build option `Z3_BUILD_JULIA_BINDINGS` has to be enabled via CMake and [libcxxwrap-julia](https://github.com/JuliaInterop/libcxxwrap-julia) has to be present. Infos about obtaining the libcxxwrap prefix can be found [here](https://github.com/JuliaInterop/CxxWrap.jl#compiling-the-c-code). ``` mkdir build && cd build cmake -DCMAKE_BUILD_TYPE=Release -DZ3_BUILD_JULIA_BINDINGS=True -DCMAKE_PREFIX_PATH=/path/to/libcxxwrap-julia-prefix .. make ``` ## Julia part The Z3 binaries are provided to [Z3.jl](https://github.com/ahumenberger/Z3.jl) via [z3_jll.jl](https://github.com/JuliaBinaryWrappers/z3_jll.jl). That is, in order to release a new Z3 version one has to update the corresponding [build script](https://github.com/JuliaPackaging/Yggdrasil/tree/master/Z/z3) which triggers a new version of z3_jll.jl. ### Using the compiled version of Z3 The binaries are managed via the JLL package z3_jll. To use your own binaries, you need to set up an overrides file, by default at `~/.julia/artifacts/Overrides.toml` with the following content: ```toml [1bc4e1ec-7839-5212-8f2f-0d16b7bd09bc] z3 = "/path/to/z3/build" ```
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/julia/README.md
README.md
Summary ======= The OCaml z3 bindings now work both in dynamic and static mode and the compiled libraries can be used by all linkers in the OCaml system, without any specific instructions other than specifying the dependency on the z3 library. Using the libraries =================== Compiling binaries ------------------ The libraries can be linked statically with both ocamlc and ocamlopt compilers, e.g., ``` ocamlfind ocamlc -thread -package z3 -linkpkg run.ml -o run ``` or ``` ocamlfind ocamlopt -thread -package z3 -linkpkg run.ml -o run ``` When bindings compiled with the `--staticlib` the produced binary will not have any dependencies on z3 ``` $ ldd ./run linux-vdso.so.1 (0x00007fff9c9ed000) libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb56f09c000) libgmp.so.10 => /usr/lib/x86_64-linux-gnu/libgmp.so.10 (0x00007fb56ee1b000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fb56ebfc000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb56e85e000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fb56e65a000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb56e442000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb56e051000) /lib64/ld-linux-x86-64.so.2 (0x00007fb570de9000) ``` The bytecode version will have a dependency on z3 and other external libraries (packed as dlls and usually installed in opam switch): ``` $ ocamlobjinfo run | grep 'Used DLL' -A5 Used DLLs: dllz3ml dllzarith dllthreads dllunix ``` But it is possible to compile a portable self-contained version of the bytecode executable using the `-custom` switch: ``` ocamlfind ocamlc -custom -thread -package z3 -linkpkg run.ml -o run ``` The build binary is now quite large but doesn't have any external dependencies (modulo the system dependencies): ``` $ du -h run 27M run $ ocamlobjinfo run | grep 'Used DLL' | wc -l 0 $ ldd run linux-vdso.so.1 (0x00007ffee42c2000) libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fdbdc415000) libgmp.so.10 => /usr/lib/x86_64-linux-gnu/libgmp.so.10 (0x00007fdbdc194000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fdbdbf75000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fdbdbbd7000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fdbdb9d3000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fdbdb7bb000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fdbdb3ca000) /lib64/ld-linux-x86-64.so.2 (0x00007fdbde026000) ``` Loading in toplevel ------------------- It is also possible to use the built libraries in toplevel and use them in ocaml scripts, e.g., ``` $ ocaml OCaml version 4.09.0 # #use "topfind";; - : unit = () Findlib has been successfully loaded. Additional directives: #require "package";; to load a package #list;; to list the available packages #camlp4o;; to load camlp4 (standard syntax) #camlp4r;; to load camlp4 (revised syntax) #predicates "p,q,...";; to set these predicates Topfind.reset();; to force that packages will be reloaded #thread;; to enable threads - : unit = () # #require "z3";; /home/ivg/.opam/4.09.0/lib/zarith: added to search path /home/ivg/.opam/4.09.0/lib/zarith/zarith.cma: loaded /home/ivg/.opam/4.09.0/lib/z3: added to search path /home/ivg/.opam/4.09.0/lib/z3/z3ml.cma: loaded # ``` To use z3 in a script mode add the following preamble to a file with OCaml code: ``` #!/usr/bin/env ocaml #use "topfind";; #require "z3";; (* your OCaml code *) ``` Then it is possible to run it as `./script` (provided that the code is in a file named `script` and permissions are set with `chmod a+x script`). Of course, such scripts will depend on ocaml installation that shall have z3 dependencies installed. Using Dynlink ------------- The built z3ml.cmxs file is a self-contained shared library that doesn't have any dependencies on z3 (the z3 code is included in it) and could be loaded with `Dynlink.loadfile` in runtime. Installation ============ I did not touch the installation part in this PR, as I was using opam and installed artifacts as simple as: ``` ocamlfind install z3 build/api/ml/* build/libz3-static.a ``` assuming that the following configuration and building process ``` python2.7 scripts/mk_make.py --ml --staticlib make -C build ``` Though the default installation script in the make file shall work. Dynamic Library mode ==================== The dynamic library mode is also supported provided that libz3.so is installed in a search path of the dynamic loader (or the location is added via the LD_LIBRARY_PATH) or stored in rpaths of the built binary. Build Artifacts =============== In the static mode (--staticlib), the following files are built and installed: - `{z3,z3enums,z3native}.{cmi,cmo,cmx,o,mli}`: the three compilation units (modules) that comprise Z3 bindings. The `*.mli` files are not necessary but are installed for the user convenience and documentation purposes. The *.cmi files enables access to the unit definitions. Finally, `*.cmo` contain the bytecode and `*.cmx, *.o` contain the native code. Files with the code are necessary for cross-module optimization but are not strictly needed as the code is also duplicated in the libraries. - libz3-static.a (OR libz3.so if built not in the staticlib mode) contains the machine code of the Z3 library; - z3ml.{a,cma,cmxa,cmxs} - the OCaml code for the bindings. File z3ml.a and z3ml.cmxa are static libraries with OCaml native code, which will be included in the final binary when ocamlopt is used. The z3 library code itself is not included in those three artifacts, but the instructions where to find it are. The same is truce for `z3ml.a` which includes the bytecode of the bindings as well as instructions how to link the final product. Finally, `z3ml.cmxs` is a standalone shared library that could be loaded in runtime use `Dynlink.loadfile` (which used dlopen on posix machines underneath the hood). - libz3ml.a is the archived machine code for `z3native_stubs.c`, which is made by ocamlmklib: `ar rcs api/ml/libz3ml.a api/ml/z3native_stubs.o` it is needed to build statically linked binaries and libraries that use z3 bindings. - dllz3ml.so is the shared object that contains `z3native_stubs.o` as well as correct ldd entries for C++ and Z3 libraries to enable proper static and dynamic linking. The file is built with ocamlmklib on posix systems as ``` gcc -shared -o api/ml/dllz3ml.so api/ml/z3native_stubs.o -L. -lz3-static -lstdc++ ``` It is used by `ocaml`, `ocamlrun`, and `ocamlc` to link z3 and c++ code into the OCaml runtime and enables usage of z3 bindings in non-custom runtimes (default runtimes). The `dllz3ml.so` is usually installed in the stubs library in opam installation (`$(opam config var lib)/stublibs`), it is done automatically by `ocamlfind` so no special treatment is needed. Technical Details ================= The patch itself is rather small. First of all, we have to use `-l<lib>` instead of `-cclib -l<lib>` in ocamlmklib since the latter will pass the options only to the ocaml{c,opt} linker and will not use the passed libraries when shared and non-shared versions of the bindings are built (libz3ml.a and dllz3ml.so). They were both missing either z3 code itself and ldd entries for stdc++ (and z3 if built not in --staticlib mode). Having stdc++ entry streamlines the compilation process and makes dynamic loading more resistant to the inclusion order. Finally, we had to add `-L.` to make sure that the built artifacts are correctly found by gcc. I specifically left the cygwin part of the code intact as I have no idea what the original author meant by this, neither do I use or tested this patch in the cygwin or mingw environemt. I think that this code is rather outdated and shouldn't really work. E.g., in the --staticlib mode adding z3linkdep (which is libz3-static.a) as an argument to `ocamlmklib` will yield the following broken archive ``` ar rcs api/ml/libz3ml.a libz3-static.a api/ml/z3native_stubs.o ``` and it is not allowed (or supported) to have .a in archives (though it doesn't really hurt as most of the systems will just ignore it). But otherwise, cygwin, mingw shall behave as they did (the only change that affects them is `-L.` which I believe should be benign). [1]: https://stackoverflow.com/questions/56839246/installing-ocaml-api-for-z3-using-opam/58398704 [2]: https://stackoverflow.com/questions/57065191/linker-error-when-installing-z3-ocaml-bindings-in-local-opam-environment [3]: https://discuss.ocaml.org/t/trouble-with-z3-on-ocaml-4-10-on-linux-and-ocaml-4-x-on-macos/5418/9 [4]: https://github.com/ocaml/opam-repository/blob/master/packages/z3/z3.4.8.8/opam [5]: https://github.com/akabe/ocaml-jupyter Other notes ============== On Windows, there are no less than four different ports of OCaml. The Z3 build system assumes that either the win32 or the win64 port is installed. This means that OCaml will use `cl' as the underlying C compiler and not the cygwin or mingw compilers. OCamlfind: When ocamlfind is found, the `install' target will install the Z3 OCaml bindings into the ocamlfind site-lib directory. The installed package is linked against the (dynamic) libz3 and it adds $(PREFIX)/lib to the library include paths. On Windows, there is no $(PREFIX), so the build directory is used instead (see META.in).
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/ml/README.md
README.md
# TypeScript Bindings This directory contains JavaScript code to automatically derive TypeScript bindings for the C API, which are published on npm as [z3-solver](https://www.npmjs.com/package/z3-solver). The readme for the bindings themselves is located in [`PUBLISHED_README.md`](./PUBLISHED_README.md). ## Building You'll need to have emscripten set up, along with all of its dependencies. The easiest way to do that is with [emsdk](https://github.com/emscripten-core/emsdk). Then run `npm i` to install dependencies, `npm run build:ts` to build the TypeScript wrapper, and `npm run build:wasm` to build the wasm artifact. ### Build on your own Consult the file [build-wasm.ts](https://github.com/Z3Prover/z3/blob/master/src/api/js/scripts/build-wasm.ts) for configurations used for building wasm. ## Tests Current tests are very minimal: [`test-ts-api.ts`](./test-ts-api.ts) contains a couple real cases translated very mechanically from [this file](https://github.com/Z3Prover/z3/blob/90fd3d82fce20d45ed2eececdf65545bab769503/examples/c/test_capi.c).
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/README.md
README.md
# Z3 TypeScript Bindings This project provides high-level and low-level TypeScript bindings for the [Z3 theorem prover](https://github.com/Z3Prover/z3). It is available on npm as [z3-solver](https://www.npmjs.com/package/z3-solver). Z3 itself is distributed as a wasm artifact as part of this package. ## Using ```javascript const { init } = require('z3-solver'); const { Z3, // Low-level C-like API Context, // High-level Z3Py-like API } = await init(); ``` This package has different initialization for browser and node. Your bundler and node should choose good version automatically, but you can import the one you need manually - `const { init } = require('z3-solver/node');` or `const { init } = require('z3-solver/browser');`. ### Limitations The package requires threads, which means you'll need to be running in an environment which supports `SharedArrayBuffer`. In browsers, in addition to ensuring the browser has implemented `SharedArrayBuffer`, you'll need to serve your page with [special headers](https://web.dev/coop-coep/). There's a [neat trick](https://github.com/gzuidhof/coi-serviceworker) for doing that client-side on e.g. Github Pages, though you shouldn't use that trick in more complex applications. The Emscripten worker model will spawn multiple instances of `z3-built.js` for long-running operations. When building for the web, you should include that file as its own script on the page - using a bundler like webpack will prevent it from loading correctly. ## High-level You can find the documentation for the high-level Z3 API [here](https://z3prover.github.io/api/html/js/index.html). There are some usage examples in `src/high-level/high-level.test.ts` Most of the API requires a context to run, and so you need to initialize one to access most functionality. ```javascript const { init } = require('z3-solver'); const { Context } = await init(); const { Solver, Int, And } = new Context('main'); const x = Int.const('x'); const solver = new Solver(); solver.add(And(x.ge(0), x.le(9))); console.log(await solver.check()); // sat ``` Typescript types try to catch errors concerning mixing of Contexts during compile time. Objects returned from `new Context('name')` have a type narrowed by the provided Context name and will fail to compile if you try to mix them. ```typescript const { Int: Int1 } = new Context('context1'); const { Int: Int2 } = new Context('context2'); const x = Int1.const('x'); const y = Int2.const('y'); // The below will fail to compile in Typescript x.ge(y); ``` ```typescript // Use templated functions to propagate narrowed types function add<Name extends string>(a: Arith<Name>, b: Arith<Name>): Arith<Name> { return a.add(b).add(5); } ``` Some long-running functions are promises and will run in a separate thread. Currently Z3-solver is not thread safe, and so, high-level APIs ensures that only one long-running function can run at a time, and all other long-running requests will queue up and be run one after another. ## Low-level You can find the documentation for the low-level Z3 API [here](https://z3prover.github.io/api/html/z3__api_8h.html), though note the differences below. `examples/low-level/` contains a couple real cases translated very mechanically from [this file](https://github.com/Z3Prover/z3/blob/90fd3d82fce20d45ed2eececdf65545bab769503/examples/c/test_capi.c). The bindings can be used exactly as you'd use the C library. Because this is a wrapper around a C library, most of the values you'll use are just numbers representing pointers. For this reason you are strongly encouraged to make use of the TypeScript types to differentiate among the different kinds of value. The module exports an `init` function, which is an async function which initializes the library and returns `{ em, Z3 }` - `em` contains the underlying emscripten module, which you can use to e.g. kill stray threads, and `Z3` contains the actual bindings. The other module exports are the enums defined in the Z3 API. ### Differences from the C API #### Integers JavaScript numbers are IEEE double-precisions floats. These can be used wherever the C API expects an `int`, `unsigned int`, `float`, or `double`. `int64_t` and `uint64_t` cannot be precisely represented by JS numbers, so in the TS bindings they are represented by [BigInts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type). #### Out parameters In C, to return multiple values a function will take an address to write to, conventionally referred to as an "out parameter". Sometimes the function returns a boolean to indicate success; other times it may return nothing or some other value. In JS the convention when returning multiple values is to return records containing the values of interest. The wrapper translates between the two conventions. For example, the C declaration ```c void Z3_rcf_get_numerator_denominator(Z3_context c, Z3_rcf_num a, Z3_rcf_num * n, Z3_rcf_num * d); ``` is represented in the TS bindings as ```ts function rcf_get_numerator_denominator(c: Z3_context, a: Z3_rcf_num): { n: Z3_rcf_num; d: Z3_rcf_num } { // ... } ``` When there is only a single out parameter, and the return value is not otherwise of interest, the parameter is not wrapped. For example, the C declaration ```c bool Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast * v); ``` is represented in the TS bindings as ```ts function model_eval(c: Z3_context, m: Z3_model, t: Z3_ast, model_completion: boolean): Z3_ast | null { // ... } ``` Note that the boolean return type of the C function is translated into a nullable return type for the TS binding. When the return value is of interest it is included in the returned record under the key `rv`. #### Arrays The when the C API takes an array as an argument it will also require a parameter which specifies the length of the array (since arrays do not carry their own lengths in C). In the TS bindings this is automatically inferred. For example, the C declaration ```js unsigned Z3_rcf_mk_roots(Z3_context c, unsigned n, Z3_rcf_num const a[], Z3_rcf_num roots[]); ``` is represented in the TS bindings as ```ts function rcf_mk_roots(c: Z3_context, a: Z3_rcf_num[]): { rv: number; roots: Z3_rcf_num[] } { // ... } ``` When there are multiple arrays which the C API expects to be of the same length, the TS bindings will enforce that this is the case. #### Null pointers Some of the C APIs accept or return null pointers (represented by types whose name end in `_opt`). These are represented in the TS bindings as `| null`. For example, the C declaration ```js Z3_ast_opt Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a); ``` is represented in the TS bindings as ```ts function model_get_const_interp(c: Z3_context, m: Z3_model, a: Z3_func_decl): Z3_ast | null { // ... } ``` #### Async functions Certain long-running APIs are not appropriate to call on the main thread. In the TS bindings those APIs are marked as `async` and are automatically called on a different thread. This includes the following APIs: - `Z3_simplify` - `Z3_simplify_ex` - `Z3_solver_check` - `Z3_solver_check_assumptions` - `Z3_solver_cube` - `Z3_solver_get_consequences` - `Z3_tactic_apply` - `Z3_tactic_apply_ex` - `Z3_optimize_check` - `Z3_algebraic_roots` - `Z3_algebraic_eval` - `Z3_fixedpoint_query` - `Z3_fixedpoint_query_relations` - `Z3_fixedpoint_query_from_lvl` - `Z3_polynomial_subresultants` Note that these are not thread-safe, and so only one call can be running at a time. In contrast to high-level APIs, trying to call a second async API before the first completes will throw.
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/PUBLISHED_README.md
PUBLISHED_README.md
import { Mutex } from 'async-mutex'; import { Z3Core, Z3_ast, Z3_ast_kind, Z3_ast_map, Z3_ast_print_mode, Z3_ast_vector, Z3_context, Z3_decl_kind, Z3_error_code, Z3_func_decl, Z3_func_interp, Z3_lbool, Z3_model, Z3_parameter_kind, Z3_probe, Z3_solver, Z3_sort, Z3_sort_kind, Z3_symbol, Z3_symbol_kind, Z3_tactic, Z3_pattern, Z3_app, Z3_params, Z3_func_entry, Z3_optimize, } from '../low-level'; import { AnyAst, AnyExpr, AnySort, Arith, ArithSort, ArrayIndexType, CoercibleToArrayIndexType, Ast, AstMap, AstMapCtor, AstVector, AstVectorCtor, BitVec, BitVecNum, BitVecSort, Bool, BoolSort, CheckSatResult, CoercibleToMap, CoercibleRational, CoercibleToBitVec, CoercibleToExpr, CoercibleFromMap, Context, ContextCtor, Expr, FuncDecl, FuncDeclSignature, FuncInterp, IntNum, Model, Optimize, Pattern, Probe, Quantifier, BodyT, RatNum, SMTArray, SMTArraySort, Solver, Sort, SortToExprMap, Tactic, Z3Error, Z3HighLevel, CoercibleToArith, NonEmptySortArray, FuncEntry, } from './types'; import { allSatisfy, assert, assertExhaustive } from './utils'; const FALLBACK_PRECISION = 17; const asyncMutex = new Mutex(); function isCoercibleRational(obj: any): obj is CoercibleRational { // prettier-ignore const r = ( (obj !== null && (typeof obj === 'object' || typeof obj === 'function')) && (obj.numerator !== null && (typeof obj.numerator === 'number' || typeof obj.numerator === 'bigint')) && (obj.denominator !== null && (typeof obj.denominator === 'number' || typeof obj.denominator === 'bigint')) ); r && assert( (typeof obj!.numerator !== 'number' || Number.isSafeInteger(obj!.numerator)) && (typeof obj!.denominator !== 'number' || Number.isSafeInteger(obj!.denominator)), 'Fraction numerator and denominator must be integers', ); return r; } export function createApi(Z3: Z3Core): Z3HighLevel { // TODO(ritave): Create a custom linting rule that checks if the provided callbacks to cleanup // Don't capture `this` const cleanup = new FinalizationRegistry<() => void>(callback => callback()); function enableTrace(tag: string) { Z3.enable_trace(tag); } function disableTrace(tag: string) { Z3.disable_trace(tag); } function getVersion() { return Z3.get_version(); } function getVersionString() { const { major, minor, build_number } = Z3.get_version(); return `${major}.${minor}.${build_number}`; } function getFullVersion() { return Z3.get_full_version(); } function openLog(filename: string) { return Z3.open_log(filename); } function appendLog(s: string) { Z3.append_log(s); } function setParam(key: string, value: any): void; function setParam(params: Record<string, any>): void; function setParam(key: string | Record<string, any>, value?: any) { if (typeof key === 'string') { Z3.global_param_set(key, value.toString()); } else { assert(value === undefined, "Can't provide a Record and second parameter to set_param at the same time"); Object.entries(key).forEach(([key, value]) => setParam(key, value)); } } function resetParams() { Z3.global_param_reset_all(); } function getParam(name: string) { return Z3.global_param_get(name); } function createContext<Name extends string>(name: Name, options?: Record<string, any>): Context<Name> { const cfg = Z3.mk_config(); if (options != null) { Object.entries(options).forEach(([key, value]) => check(Z3.set_param_value(cfg, key, value.toString()))); } const contextPtr = Z3.mk_context_rc(cfg); Z3.set_ast_print_mode(contextPtr, Z3_ast_print_mode.Z3_PRINT_SMTLIB2_COMPLIANT); Z3.del_config(cfg); function _assertContext(...ctxs: (Context<Name> | { ctx: Context<Name> })[]) { ctxs.forEach(other => assert('ctx' in other ? ctx === other.ctx : ctx === other, 'Context mismatch')); } // call this after every nontrivial call to the underlying API function throwIfError() { if (Z3.get_error_code(contextPtr) !== Z3_error_code.Z3_OK) { throw new Error(Z3.get_error_msg(ctx.ptr, Z3.get_error_code(ctx.ptr))); } } function check<T>(val: T): T { throwIfError(); return val; } ///////////// // Private // ///////////// function _toSymbol(s: string | number) { if (typeof s === 'number') { return check(Z3.mk_int_symbol(contextPtr, s)); } else { return check(Z3.mk_string_symbol(contextPtr, s)); } } function _fromSymbol(sym: Z3_symbol) { const kind = check(Z3.get_symbol_kind(contextPtr, sym)); switch (kind) { case Z3_symbol_kind.Z3_INT_SYMBOL: return Z3.get_symbol_int(contextPtr, sym); case Z3_symbol_kind.Z3_STRING_SYMBOL: return Z3.get_symbol_string(contextPtr, sym); default: assertExhaustive(kind); } } function _toParams(key: string, value: any): Z3_params { const params = Z3.mk_params(contextPtr); Z3.params_inc_ref(contextPtr, params); // If value is a boolean if (typeof value === 'boolean') { Z3.params_set_bool(contextPtr, params, _toSymbol(key), value); } else if (typeof value === 'number') { // If value is a uint if (Number.isInteger(value)) { check(Z3.params_set_uint(contextPtr, params, _toSymbol(key), value)); } else { // If value is a double check(Z3.params_set_double(contextPtr, params, _toSymbol(key), value)); } } else if (typeof value === 'string') { check(Z3.params_set_symbol(contextPtr, params, _toSymbol(key), _toSymbol(value))); } return params; } function _toAst(ast: Z3_ast): AnyAst<Name> { switch (check(Z3.get_ast_kind(contextPtr, ast))) { case Z3_ast_kind.Z3_SORT_AST: return _toSort(ast as Z3_sort); case Z3_ast_kind.Z3_FUNC_DECL_AST: return new FuncDeclImpl(ast as Z3_func_decl); default: return _toExpr(ast); } } function _toSort(ast: Z3_sort): AnySort<Name> { switch (check(Z3.get_sort_kind(contextPtr, ast))) { case Z3_sort_kind.Z3_BOOL_SORT: return new BoolSortImpl(ast); case Z3_sort_kind.Z3_INT_SORT: case Z3_sort_kind.Z3_REAL_SORT: return new ArithSortImpl(ast); case Z3_sort_kind.Z3_BV_SORT: return new BitVecSortImpl(ast); case Z3_sort_kind.Z3_ARRAY_SORT: return new ArraySortImpl(ast); default: return new SortImpl(ast); } } function _toExpr(ast: Z3_ast): AnyExpr<Name> { const kind = check(Z3.get_ast_kind(contextPtr, ast)); if (kind === Z3_ast_kind.Z3_QUANTIFIER_AST) { if (Z3.is_lambda(contextPtr, ast)) { return new LambdaImpl(ast); } return new NonLambdaQuantifierImpl(ast); } const sortKind = check(Z3.get_sort_kind(contextPtr, Z3.get_sort(contextPtr, ast))); switch (sortKind) { case Z3_sort_kind.Z3_BOOL_SORT: return new BoolImpl(ast); case Z3_sort_kind.Z3_INT_SORT: if (kind === Z3_ast_kind.Z3_NUMERAL_AST) { return new IntNumImpl(ast); } return new ArithImpl(ast); case Z3_sort_kind.Z3_REAL_SORT: if (kind === Z3_ast_kind.Z3_NUMERAL_AST) { return new RatNumImpl(ast); } return new ArithImpl(ast); case Z3_sort_kind.Z3_BV_SORT: if (kind === Z3_ast_kind.Z3_NUMERAL_AST) { return new BitVecNumImpl(ast); } return new BitVecImpl(ast); case Z3_sort_kind.Z3_ARRAY_SORT: return new ArrayImpl(ast); default: return new ExprImpl(ast); } } function _flattenArgs<T extends AnyAst<Name> = AnyAst<Name>>(args: (T | AstVector<Name, T>)[]): T[] { const result: T[] = []; for (const arg of args) { if (isAstVector(arg)) { result.push(...arg.values()); } else { result.push(arg); } } return result; } function _toProbe(p: Probe<Name> | Z3_probe): Probe<Name> { if (isProbe(p)) { return p; } return new ProbeImpl(p); } function _probeNary( f: (ctx: Z3_context, left: Z3_probe, right: Z3_probe) => Z3_probe, args: [Probe<Name> | Z3_probe, ...(Probe<Name> | Z3_probe)[]], ) { assert(args.length > 0, 'At least one argument expected'); let r = _toProbe(args[0]); for (let i = 1; i < args.length; i++) { r = new ProbeImpl(check(f(contextPtr, r.ptr, _toProbe(args[i]).ptr))); } return r; } /////////////// // Functions // /////////////// function interrupt(): void { check(Z3.interrupt(contextPtr)); } function isModel(obj: unknown): obj is Model<Name> { const r = obj instanceof ModelImpl; r && _assertContext(obj); return r; } function isAst(obj: unknown): obj is Ast<Name> { const r = obj instanceof AstImpl; r && _assertContext(obj); return r; } function isSort(obj: unknown): obj is Sort<Name> { const r = obj instanceof SortImpl; r && _assertContext(obj); return r; } function isFuncDecl(obj: unknown): obj is FuncDecl<Name> { const r = obj instanceof FuncDeclImpl; r && _assertContext(obj); return r; } function isFuncInterp(obj: unknown): obj is FuncInterp<Name> { const r = obj instanceof FuncInterpImpl; r && _assertContext(obj); return r; } function isApp(obj: unknown): boolean { if (!isExpr(obj)) { return false; } const kind = check(Z3.get_ast_kind(contextPtr, obj.ast)); return kind === Z3_ast_kind.Z3_NUMERAL_AST || kind === Z3_ast_kind.Z3_APP_AST; } function isConst(obj: unknown): boolean { return isExpr(obj) && isApp(obj) && obj.numArgs() === 0; } function isExpr(obj: unknown): obj is Expr<Name> { const r = obj instanceof ExprImpl; r && _assertContext(obj); return r; } function isVar(obj: unknown): boolean { return isExpr(obj) && check(Z3.get_ast_kind(contextPtr, obj.ast)) === Z3_ast_kind.Z3_VAR_AST; } function isAppOf(obj: unknown, kind: Z3_decl_kind): boolean { return isExpr(obj) && isApp(obj) && obj.decl().kind() === kind; } function isBool(obj: unknown): obj is Bool<Name> { const r = obj instanceof ExprImpl && obj.sort.kind() === Z3_sort_kind.Z3_BOOL_SORT; r && _assertContext(obj); return r; } function isTrue(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_TRUE); } function isFalse(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_FALSE); } function isAnd(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_AND); } function isOr(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_OR); } function isImplies(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_IMPLIES); } function isNot(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_NOT); } function isEq(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_EQ); } function isDistinct(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_DISTINCT); } function isQuantifier(obj: unknown): obj is Quantifier<Name> { const r = obj instanceof QuantifierImpl; r && _assertContext(obj); return r; } function isArith(obj: unknown): obj is Arith<Name> { const r = obj instanceof ArithImpl; r && _assertContext(obj); return r; } function isArithSort(obj: unknown): obj is ArithSort<Name> { const r = obj instanceof ArithSortImpl; r && _assertContext(obj); return r; } function isInt(obj: unknown): boolean { return isArith(obj) && isIntSort(obj.sort); } function isIntVal(obj: unknown): obj is IntNum<Name> { const r = obj instanceof IntNumImpl; r && _assertContext(obj); return r; } function isIntSort(obj: unknown): boolean { return isSort(obj) && obj.kind() === Z3_sort_kind.Z3_INT_SORT; } function isReal(obj: unknown): boolean { return isArith(obj) && isRealSort(obj.sort); } function isRealVal(obj: unknown): obj is RatNum<Name> { const r = obj instanceof RatNumImpl; r && _assertContext(obj); return r; } function isRealSort(obj: unknown): boolean { return isSort(obj) && obj.kind() === Z3_sort_kind.Z3_REAL_SORT; } function isBitVecSort(obj: unknown): obj is BitVecSort<number, Name> { const r = obj instanceof BitVecSortImpl; r && _assertContext(obj); return r; } function isBitVec(obj: unknown): obj is BitVec<number, Name> { const r = obj instanceof BitVecImpl; r && _assertContext(obj); return r; } function isBitVecVal(obj: unknown): obj is BitVecNum<number, Name> { const r = obj instanceof BitVecNumImpl; r && _assertContext(obj); return r; } function isArraySort(obj: unknown): obj is SMTArraySort<Name> { const r = obj instanceof ArraySortImpl; r && _assertContext(obj); return r; } function isArray(obj: unknown): obj is SMTArray<Name> { const r = obj instanceof ArrayImpl; r && _assertContext(obj); return r; } function isConstArray(obj: unknown): boolean { return isAppOf(obj, Z3_decl_kind.Z3_OP_CONST_ARRAY); } function isProbe(obj: unknown): obj is Probe<Name> { const r = obj instanceof ProbeImpl; r && _assertContext(obj); return r; } function isTactic(obj: unknown): obj is Tactic<Name> { const r = obj instanceof TacticImpl; r && _assertContext(obj); return r; } function isAstVector(obj: unknown): obj is AstVector<Name> { const r = obj instanceof AstVectorImpl; r && _assertContext(obj); return r; } function eqIdentity(a: Ast<Name>, b: Ast<Name>): boolean { return a.eqIdentity(b); } function getVarIndex(obj: Expr<Name>): number { assert(isVar(obj), 'Z3 bound variable expected'); return Z3.get_index_value(contextPtr, obj.ast); } function from(primitive: boolean): Bool<Name>; function from(primitive: number): IntNum<Name> | RatNum<Name>; function from(primitive: CoercibleRational): RatNum<Name>; function from(primitive: bigint): IntNum<Name>; function from<T extends Expr<Name>>(expr: T): T; function from(expr: CoercibleToExpr<Name>): AnyExpr<Name>; function from(value: CoercibleToExpr<Name>): AnyExpr<Name> { if (typeof value === 'boolean') { return Bool.val(value); } else if (typeof value === 'number') { if (!Number.isFinite(value)) { throw new Error(`cannot represent infinity/NaN (got ${value})`); } if (Math.floor(value) === value) { return Int.val(value); } return Real.val(value); } else if (isCoercibleRational(value)) { return Real.val(value); } else if (typeof value === 'bigint') { return Int.val(value); } else if (isExpr(value)) { return value; } assert(false); } async function solve(...assertions: Bool<Name>[]): Promise<Model<Name> | 'unsat' | 'unknown'> { const solver = new ctx.Solver(); solver.add(...assertions); const result = await solver.check(); if (result === 'sat') { return solver.model(); } return result; } /////////////////////////////// // expression simplification // /////////////////////////////// async function simplify(e: Expr<Name>): Promise<Expr<Name>> { const result = await Z3.simplify(contextPtr, e.ast); return _toExpr(check(result)); } ///////////// // Objects // ///////////// const Sort = { declare: (name: string) => new SortImpl(Z3.mk_uninterpreted_sort(contextPtr, _toSymbol(name))), }; const Function = { declare: <DomainSort extends Sort<Name>[], RangeSort extends Sort<Name>>( name: string, ...signature: [...DomainSort, RangeSort] ): FuncDecl<Name, DomainSort, RangeSort> => { const arity = signature.length - 1; const rng = signature[arity]; _assertContext(rng); const dom = []; for (let i = 0; i < arity; i++) { _assertContext(signature[i]); dom.push(signature[i].ptr); } return new FuncDeclImpl<DomainSort, RangeSort>(Z3.mk_func_decl(contextPtr, _toSymbol(name), dom, rng.ptr)); }, fresh: <DomainSort extends Sort<Name>[], RangeSort extends Sort<Name>>( ...signature: [...DomainSort, RangeSort] ): FuncDecl<Name, DomainSort, RangeSort> => { const arity = signature.length - 1; const rng = signature[arity]; _assertContext(rng); const dom = []; for (let i = 0; i < arity; i++) { _assertContext(signature[i]); dom.push(signature[i].ptr); } return new FuncDeclImpl<DomainSort, RangeSort>(Z3.mk_fresh_func_decl(contextPtr, 'f', dom, rng.ptr)); }, }; const RecFunc = { declare: (name: string, ...signature: FuncDeclSignature<Name>) => { const arity = signature.length - 1; const rng = signature[arity]; _assertContext(rng); const dom = []; for (let i = 0; i < arity; i++) { _assertContext(signature[i]); dom.push(signature[i].ptr); } return new FuncDeclImpl(Z3.mk_rec_func_decl(contextPtr, _toSymbol(name), dom, rng.ptr)); }, addDefinition: (f: FuncDecl<Name>, args: Expr<Name>[], body: Expr<Name>) => { _assertContext(f, ...args, body); check( Z3.add_rec_def( contextPtr, f.ptr, args.map(arg => arg.ast), body.ast, ), ); }, }; const Bool = { sort: () => new BoolSortImpl(Z3.mk_bool_sort(contextPtr)), const: (name: string) => new BoolImpl(Z3.mk_const(contextPtr, _toSymbol(name), Bool.sort().ptr)), consts: (names: string | string[]) => { if (typeof names === 'string') { names = names.split(' '); } return names.map(name => Bool.const(name)); }, vector: (prefix: string, count: number) => { const result = []; for (let i = 0; i < count; i++) { result.push(Bool.const(`${prefix}__${i}`)); } return result; }, fresh: (prefix = 'b') => new BoolImpl(Z3.mk_fresh_const(contextPtr, prefix, Bool.sort().ptr)), val: (value: boolean) => { if (value) { return new BoolImpl(Z3.mk_true(contextPtr)); } return new BoolImpl(Z3.mk_false(contextPtr)); }, }; const Int = { sort: () => new ArithSortImpl(Z3.mk_int_sort(contextPtr)), const: (name: string) => new ArithImpl(Z3.mk_const(contextPtr, _toSymbol(name), Int.sort().ptr)), consts: (names: string | string[]) => { if (typeof names === 'string') { names = names.split(' '); } return names.map(name => Int.const(name)); }, vector: (prefix: string, count: number) => { const result = []; for (let i = 0; i < count; i++) { result.push(Int.const(`${prefix}__${i}`)); } return result; }, fresh: (prefix = 'x') => new ArithImpl(Z3.mk_fresh_const(contextPtr, prefix, Int.sort().ptr)), val: (value: number | bigint | string) => { assert(typeof value === 'bigint' || typeof value === 'string' || Number.isSafeInteger(value)); return new IntNumImpl(check(Z3.mk_numeral(contextPtr, value.toString(), Int.sort().ptr))); }, }; const Real = { sort: () => new ArithSortImpl(Z3.mk_real_sort(contextPtr)), const: (name: string) => new ArithImpl(check(Z3.mk_const(contextPtr, _toSymbol(name), Real.sort().ptr))), consts: (names: string | string[]) => { if (typeof names === 'string') { names = names.split(' '); } return names.map(name => Real.const(name)); }, vector: (prefix: string, count: number) => { const result = []; for (let i = 0; i < count; i++) { result.push(Real.const(`${prefix}__${i}`)); } return result; }, fresh: (prefix = 'b') => new ArithImpl(Z3.mk_fresh_const(contextPtr, prefix, Real.sort().ptr)), val: (value: number | bigint | string | CoercibleRational) => { if (isCoercibleRational(value)) { value = `${value.numerator}/${value.denominator}`; } return new RatNumImpl(Z3.mk_numeral(contextPtr, value.toString(), Real.sort().ptr)); }, }; const BitVec = { sort<Bits extends number>(bits: Bits): BitVecSort<Bits, Name> { assert(Number.isSafeInteger(bits), 'number of bits must be an integer'); return new BitVecSortImpl(Z3.mk_bv_sort(contextPtr, bits)); }, const<Bits extends number>(name: string, bits: Bits | BitVecSort<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>( check(Z3.mk_const(contextPtr, _toSymbol(name), isBitVecSort(bits) ? bits.ptr : BitVec.sort(bits).ptr)), ); }, consts<Bits extends number>(names: string | string[], bits: Bits | BitVecSort<Bits, Name>): BitVec<Bits, Name>[] { if (typeof names === 'string') { names = names.split(' '); } return names.map(name => BitVec.const(name, bits)); }, val<Bits extends number>( value: bigint | number | boolean, bits: Bits | BitVecSort<Bits, Name>, ): BitVecNum<Bits, Name> { if (value === true) { return BitVec.val(1, bits); } else if (value === false) { return BitVec.val(0, bits); } return new BitVecNumImpl<Bits>( check(Z3.mk_numeral(contextPtr, value.toString(), isBitVecSort(bits) ? bits.ptr : BitVec.sort(bits).ptr)), ); }, }; const Array = { sort<DomainSort extends NonEmptySortArray<Name>, RangeSort extends AnySort<Name>>( ...sig: [...DomainSort, RangeSort] ): SMTArraySort<Name, DomainSort, RangeSort> { const arity = sig.length - 1; const r = sig[arity]; const d = sig[0]; if (arity === 1) { return new ArraySortImpl(Z3.mk_array_sort(contextPtr, d.ptr, r.ptr)); } const dom = sig.slice(0, arity); return new ArraySortImpl( Z3.mk_array_sort_n( contextPtr, dom.map(s => s.ptr), r.ptr, ), ); }, const<DomainSort extends NonEmptySortArray<Name>, RangeSort extends AnySort<Name>>( name: string, ...sig: [...DomainSort, RangeSort] ): SMTArray<Name, DomainSort, RangeSort> { return new ArrayImpl<DomainSort, RangeSort>( check(Z3.mk_const(contextPtr, _toSymbol(name), Array.sort(...sig).ptr)), ); }, consts<DomainSort extends NonEmptySortArray<Name>, RangeSort extends AnySort<Name>>( names: string | string[], ...sig: [...DomainSort, RangeSort] ): SMTArray<Name, DomainSort, RangeSort>[] { if (typeof names === 'string') { names = names.split(' '); } return names.map(name => Array.const(name, ...sig)); }, K<DomainSort extends AnySort<Name>, RangeSort extends AnySort<Name>>( domain: DomainSort, value: SortToExprMap<RangeSort, Name>, ): SMTArray<Name, [DomainSort], RangeSort> { return new ArrayImpl<[DomainSort], RangeSort>(check(Z3.mk_const_array(contextPtr, domain.ptr, value.ptr))); }, }; //////////////// // Operations // //////////////// function If(condition: Probe<Name>, onTrue: Tactic<Name>, onFalse: Tactic<Name>): Tactic<Name>; function If<OnTrueRef extends CoercibleToExpr<Name>, OnFalseRef extends CoercibleToExpr<Name>>( condition: Bool<Name> | boolean, onTrue: OnTrueRef, onFalse: OnFalseRef, ): CoercibleFromMap<OnTrueRef | OnFalseRef, Name>; function If( condition: Bool<Name> | Probe<Name> | boolean, onTrue: CoercibleToExpr<Name> | Tactic<Name>, onFalse: CoercibleToExpr<Name> | Tactic<Name>, ): Expr<Name> | Tactic<Name> { if (isProbe(condition) && isTactic(onTrue) && isTactic(onFalse)) { return Cond(condition, onTrue, onFalse); } assert(!isProbe(condition) && !isTactic(onTrue) && !isTactic(onFalse), 'Mixed expressions and goals'); if (typeof condition === 'boolean') { condition = Bool.val(condition); } onTrue = from(onTrue); onFalse = from(onFalse); return _toExpr(check(Z3.mk_ite(contextPtr, condition.ptr, onTrue.ast, onFalse.ast))); } function Distinct(...exprs: CoercibleToExpr<Name>[]): Bool<Name> { assert(exprs.length > 0, "Can't make Distinct ouf of nothing"); return new BoolImpl( check( Z3.mk_distinct( contextPtr, exprs.map(expr => { expr = from(expr); _assertContext(expr); return expr.ast; }), ), ), ); } function Const<S extends Sort<Name>>(name: string, sort: S): SortToExprMap<S, Name> { _assertContext(sort); return _toExpr(check(Z3.mk_const(contextPtr, _toSymbol(name), sort.ptr))) as SortToExprMap<S, Name>; } function Consts<S extends Sort<Name>>(names: string | string[], sort: S): SortToExprMap<S, Name>[] { _assertContext(sort); if (typeof names === 'string') { names = names.split(' '); } return names.map(name => Const(name, sort)); } function FreshConst<S extends Sort<Name>>(sort: S, prefix: string = 'c'): SortToExprMap<S, Name> { _assertContext(sort); return _toExpr(Z3.mk_fresh_const(sort.ctx.ptr, prefix, sort.ptr)) as SortToExprMap<S, Name>; } function Var<S extends Sort<Name>>(idx: number, sort: S): SortToExprMap<S, Name> { _assertContext(sort); return _toExpr(Z3.mk_bound(sort.ctx.ptr, idx, sort.ptr)) as SortToExprMap<S, Name>; } function Implies(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name> { a = from(a) as Bool<Name>; b = from(b) as Bool<Name>; _assertContext(a, b); return new BoolImpl(check(Z3.mk_implies(contextPtr, a.ptr, b.ptr))); } function Iff(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name> { a = from(a) as Bool<Name>; b = from(b) as Bool<Name>; _assertContext(a, b); return new BoolImpl(check(Z3.mk_iff(contextPtr, a.ptr, b.ptr))); } function Eq(a: CoercibleToExpr<Name>, b: CoercibleToExpr<Name>): Bool<Name> { a = from(a); b = from(b); _assertContext(a, b); return a.eq(b); } function Xor(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name> { a = from(a) as Bool<Name>; b = from(b) as Bool<Name>; _assertContext(a, b); return new BoolImpl(check(Z3.mk_xor(contextPtr, a.ptr, b.ptr))); } function Not(a: Probe<Name>): Probe<Name>; function Not(a: Bool<Name> | boolean): Bool<Name>; function Not(a: Bool<Name> | boolean | Probe<Name>): Bool<Name> | Probe<Name> { if (typeof a === 'boolean') { a = from(a); } _assertContext(a); if (isProbe(a)) { return new ProbeImpl(check(Z3.probe_not(contextPtr, a.ptr))); } return new BoolImpl(check(Z3.mk_not(contextPtr, a.ptr))); } function And(): Bool<Name>; function And(vector: AstVector<Name, Bool<Name>>): Bool<Name>; function And(...args: (Bool<Name> | boolean)[]): Bool<Name>; function And(...args: Probe<Name>[]): Probe<Name>; function And( ...args: (AstVector<Name, Bool<Name>> | Probe<Name> | Bool<Name> | boolean)[] ): Bool<Name> | Probe<Name> { if (args.length == 1 && args[0] instanceof ctx.AstVector) { args = [...args[0].values()]; assert(allSatisfy(args, isBool) ?? true, 'AstVector containing not bools'); } const allProbes = allSatisfy(args, isProbe) ?? false; if (allProbes) { return _probeNary(Z3.probe_and, args as [Probe<Name>, ...Probe<Name>[]]); } else { const castArgs = args.map(from) as Bool<Name>[]; _assertContext(...castArgs); return new BoolImpl( check( Z3.mk_and( contextPtr, castArgs.map(arg => arg.ptr), ), ), ); } } function Or(): Bool<Name>; function Or(vector: AstVector<Name, Bool<Name>>): Bool<Name>; function Or(...args: (Bool<Name> | boolean)[]): Bool<Name>; function Or(...args: Probe<Name>[]): Probe<Name>; function Or( ...args: (AstVector<Name, Bool<Name>> | Probe<Name> | Bool<Name> | boolean)[] ): Bool<Name> | Probe<Name> { if (args.length == 1 && args[0] instanceof ctx.AstVector) { args = [...args[0].values()]; assert(allSatisfy(args, isBool) ?? true, 'AstVector containing not bools'); } const allProbes = allSatisfy(args, isProbe) ?? false; if (allProbes) { return _probeNary(Z3.probe_or, args as [Probe<Name>, ...Probe<Name>[]]); } else { const castArgs = args.map(from) as Bool<Name>[]; _assertContext(...castArgs); return new BoolImpl( check( Z3.mk_or( contextPtr, castArgs.map(arg => arg.ptr), ), ), ); } } function ForAll<QVarSorts extends NonEmptySortArray<Name>>( quantifiers: ArrayIndexType<Name, QVarSorts>, body: Bool<Name>, weight: number = 1, ): NonLambdaQuantifierImpl<QVarSorts> { // Verify all quantifiers are constants if (!allSatisfy(quantifiers, isConst)) { throw new Error('Quantifier variables must be constants'); } return new NonLambdaQuantifierImpl<QVarSorts>( check( Z3.mk_quantifier_const_ex( contextPtr, true, weight, _toSymbol(''), _toSymbol(''), quantifiers.map(q => q.ptr as unknown as Z3_app), // The earlier check verifies these are all apps [], [], body.ptr, ), ), ); } function Exists<QVarSorts extends NonEmptySortArray<Name>>( quantifiers: ArrayIndexType<Name, QVarSorts>, body: Bool<Name>, weight: number = 1, ): NonLambdaQuantifierImpl<QVarSorts> { // Verify all quantifiers are constants if (!allSatisfy(quantifiers, isConst)) { throw new Error('Quantifier variables must be constants'); } return new NonLambdaQuantifierImpl<QVarSorts>( check( Z3.mk_quantifier_const_ex( contextPtr, false, weight, _toSymbol(''), _toSymbol(''), quantifiers.map(q => q.ptr as unknown as Z3_app), // The earlier check verifies these are all apps [], [], body.ptr, ), ), ); } function Lambda<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( quantifiers: ArrayIndexType<Name, DomainSort>, expr: SortToExprMap<RangeSort, Name>, ): LambdaImpl<any, RangeSort> { // TODO(walden): For some reason LambdaImpl<DomainSort, RangeSort> leads to type issues // and Typescript won't build. I'm not sure why since the types seem to all match // up. For now, we just use any for the domain sort // Verify all quantifiers are constants if (!allSatisfy(quantifiers, isConst)) { throw new Error('Quantifier variables must be constants'); } return new LambdaImpl<DomainSort, RangeSort>( check( Z3.mk_lambda_const( contextPtr, quantifiers.map(q => q.ptr as unknown as Z3_app), expr.ptr, ), ), ); } function ToReal(expr: Arith<Name> | bigint): Arith<Name> { expr = from(expr) as Arith<Name>; _assertContext(expr); assert(isInt(expr), 'Int expression expected'); return new ArithImpl(check(Z3.mk_int2real(contextPtr, expr.ast))); } function ToInt(expr: Arith<Name> | number | CoercibleRational | string): Arith<Name> { if (!isExpr(expr)) { expr = Real.val(expr); } _assertContext(expr); assert(isReal(expr), 'Real expression expected'); return new ArithImpl(check(Z3.mk_real2int(contextPtr, expr.ast))); } function IsInt(expr: Arith<Name> | number | CoercibleRational | string): Bool<Name> { if (!isExpr(expr)) { expr = Real.val(expr); } _assertContext(expr); assert(isReal(expr), 'Real expression expected'); return new BoolImpl(check(Z3.mk_is_int(contextPtr, expr.ast))); } function Sqrt(a: Arith<Name> | number | bigint | string | CoercibleRational): Arith<Name> { if (!isExpr(a)) { a = Real.val(a); } return a.pow('1/2'); } function Cbrt(a: Arith<Name> | number | bigint | string | CoercibleRational): Arith<Name> { if (!isExpr(a)) { a = Real.val(a); } return a.pow('1/3'); } function BV2Int<Bits extends number>(a: BitVec<Bits, Name>, isSigned: boolean): Arith<Name> { _assertContext(a); return new ArithImpl(check(Z3.mk_bv2int(contextPtr, a.ast, isSigned))); } function Int2BV<Bits extends number>(a: Arith<Name> | bigint | number, bits: Bits): BitVec<Bits, Name> { if (isArith(a)) { assert(isInt(a), 'parameter must be an integer'); } else { assert(typeof a !== 'number' || Number.isSafeInteger(a), 'parameter must not have decimal places'); a = Int.val(a); } return new BitVecImpl<Bits>(check(Z3.mk_int2bv(contextPtr, bits, a.ast))); } function Concat<Bits extends number>(...bitvecs: BitVec<Bits, Name>[]): BitVec<Bits, Name> { _assertContext(...bitvecs); return bitvecs.reduce((prev, curr) => new BitVecImpl<Bits>(check(Z3.mk_concat(contextPtr, prev.ast, curr.ast)))); } function Cond(probe: Probe<Name>, onTrue: Tactic<Name>, onFalse: Tactic<Name>): Tactic<Name> { _assertContext(probe, onTrue, onFalse); return new TacticImpl(check(Z3.tactic_cond(contextPtr, probe.ptr, onTrue.ptr, onFalse.ptr))); } function LT(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_lt(contextPtr, a.ast, a.sort.cast(b).ast))); } function GT(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_gt(contextPtr, a.ast, a.sort.cast(b).ast))); } function LE(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_le(contextPtr, a.ast, a.sort.cast(b).ast))); } function GE(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_ge(contextPtr, a.ast, a.sort.cast(b).ast))); } function ULT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvult(contextPtr, a.ast, a.sort.cast(b).ast))); } function UGT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvugt(contextPtr, a.ast, a.sort.cast(b).ast))); } function ULE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvule(contextPtr, a.ast, a.sort.cast(b).ast))); } function UGE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvuge(contextPtr, a.ast, a.sort.cast(b).ast))); } function SLT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvslt(contextPtr, a.ast, a.sort.cast(b).ast))); } function SGT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsgt(contextPtr, a.ast, a.sort.cast(b).ast))); } function SLE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsle(contextPtr, a.ast, a.sort.cast(b).ast))); } function SGE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsge(contextPtr, a.ast, a.sort.cast(b).ast))); } function Extract<Bits extends number>(hi: number, lo: number, val: BitVec<Bits, Name>): BitVec<number, Name> { return new BitVecImpl<number>(check(Z3.mk_extract(contextPtr, hi, lo, val.ast))); } function Select<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( array: SMTArray<Name, DomainSort, RangeSort>, ...indices: CoercibleToArrayIndexType<Name, DomainSort> ): SortToExprMap<RangeSort, Name> { const args = indices.map((arg, i) => array.domain_n(i).cast(arg as any)); if (args.length === 1) { return _toExpr(check(Z3.mk_select(contextPtr, array.ast, args[0].ast))) as SortToExprMap<RangeSort, Name>; } const _args = args.map(arg => arg.ast); return _toExpr(check(Z3.mk_select_n(contextPtr, array.ast, _args))) as SortToExprMap<RangeSort, Name>; } function Store<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( array: SMTArray<Name, DomainSort, RangeSort>, ...indicesAndValue: [ ...CoercibleToArrayIndexType<Name, DomainSort>, CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ] ): SMTArray<Name, DomainSort, RangeSort> { const args = indicesAndValue.map((arg, i) => { if (i === indicesAndValue.length - 1) { return array.range().cast(arg as any) as SortToExprMap<RangeSort, Name>; } return array.domain_n(i).cast(arg as any); }); if (args.length <= 1) { throw new Error('Array store requires both index and value arguments'); } if (args.length === 2) { return _toExpr(check(Z3.mk_store(contextPtr, array.ast, args[0].ast, args[1].ast))) as SMTArray< Name, DomainSort, RangeSort >; } const _idxs = args.slice(0, args.length - 1).map(arg => arg.ast); return _toExpr(check(Z3.mk_store_n(contextPtr, array.ast, _idxs, args[args.length - 1].ast))) as SMTArray< Name, DomainSort, RangeSort >; } class AstImpl<Ptr extends Z3_ast> implements Ast<Name, Ptr> { declare readonly __typename: Ast['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Ptr) { this.ctx = ctx; const myAst = this.ast; Z3.inc_ref(contextPtr, myAst); cleanup.register(this, () => Z3.dec_ref(contextPtr, myAst)); } get ast(): Z3_ast { return this.ptr; } id() { return Z3.get_ast_id(contextPtr, this.ast); } eqIdentity(other: Ast<Name>) { _assertContext(other); return check(Z3.is_eq_ast(contextPtr, this.ast, other.ast)); } neqIdentity(other: Ast<Name>) { _assertContext(other); return !this.eqIdentity(other); } sexpr() { return Z3.ast_to_string(contextPtr, this.ast); } hash() { return Z3.get_ast_hash(contextPtr, this.ast); } toString() { return this.sexpr(); } } class SolverImpl implements Solver<Name> { declare readonly __typename: Solver['__typename']; readonly ptr: Z3_solver; readonly ctx: Context<Name>; constructor(ptr: Z3_solver | string = Z3.mk_solver(contextPtr)) { this.ctx = ctx; let myPtr: Z3_solver; if (typeof ptr === 'string') { myPtr = check(Z3.mk_solver_for_logic(contextPtr, _toSymbol(ptr))); } else { myPtr = ptr; } this.ptr = myPtr; Z3.solver_inc_ref(contextPtr, myPtr); cleanup.register(this, () => Z3.solver_dec_ref(contextPtr, myPtr)); } set(key: string, value: any): void { Z3.solver_set_params(contextPtr, this.ptr, _toParams(key, value)); } push() { Z3.solver_push(contextPtr, this.ptr); } pop(num: number = 1) { Z3.solver_pop(contextPtr, this.ptr, num); } numScopes() { return Z3.solver_get_num_scopes(contextPtr, this.ptr); } reset() { Z3.solver_reset(contextPtr, this.ptr); } add(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]) { _flattenArgs(exprs).forEach(expr => { _assertContext(expr); check(Z3.solver_assert(contextPtr, this.ptr, expr.ast)); }); } addAndTrack(expr: Bool<Name>, constant: Bool<Name> | string) { if (typeof constant === 'string') { constant = Bool.const(constant); } assert(isConst(constant), 'Provided expression that is not a constant to addAndTrack'); check(Z3.solver_assert_and_track(contextPtr, this.ptr, expr.ast, constant.ast)); } assertions(): AstVector<Name, Bool<Name>> { return new AstVectorImpl(check(Z3.solver_get_assertions(contextPtr, this.ptr))); } async check(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): Promise<CheckSatResult> { const assumptions = _flattenArgs(exprs).map(expr => { _assertContext(expr); return expr.ast; }); const result = await asyncMutex.runExclusive(() => check(Z3.solver_check_assumptions(contextPtr, this.ptr, assumptions)), ); switch (result) { case Z3_lbool.Z3_L_FALSE: return 'unsat'; case Z3_lbool.Z3_L_TRUE: return 'sat'; case Z3_lbool.Z3_L_UNDEF: return 'unknown'; default: assertExhaustive(result); } } model() { return new ModelImpl(check(Z3.solver_get_model(contextPtr, this.ptr))); } toString() { return check(Z3.solver_to_string(contextPtr, this.ptr)); } fromString(s: string) { Z3.solver_from_string(contextPtr, this.ptr, s); throwIfError(); } } class OptimizeImpl implements Optimize<Name> { declare readonly __typename: Optimize['__typename']; readonly ptr: Z3_optimize; readonly ctx: Context<Name>; constructor(ptr: Z3_optimize = Z3.mk_optimize(contextPtr)) { this.ctx = ctx; let myPtr: Z3_optimize; myPtr = ptr; this.ptr = myPtr; Z3.optimize_inc_ref(contextPtr, myPtr); cleanup.register(this, () => Z3.optimize_dec_ref(contextPtr, myPtr)); } set(key: string, value: any): void { Z3.optimize_set_params(contextPtr, this.ptr, _toParams(key, value)); } push() { Z3.optimize_push(contextPtr, this.ptr); } pop() { Z3.optimize_pop(contextPtr, this.ptr); } add(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]) { _flattenArgs(exprs).forEach(expr => { _assertContext(expr); check(Z3.optimize_assert(contextPtr, this.ptr, expr.ast)); }); } addSoft(expr: Bool<Name>, weight: number | bigint | string | CoercibleRational, id: number | string = "") { if (isCoercibleRational(weight)) { weight = `${weight.numerator}/${weight.denominator}`; } check(Z3.optimize_assert_soft(contextPtr, this.ptr, expr.ast, weight.toString(), _toSymbol(id))) } addAndTrack(expr: Bool<Name>, constant: Bool<Name> | string) { if (typeof constant === 'string') { constant = Bool.const(constant); } assert(isConst(constant), 'Provided expression that is not a constant to addAndTrack'); check(Z3.optimize_assert_and_track(contextPtr, this.ptr, expr.ast, constant.ast)); } assertions(): AstVector<Name, Bool<Name>> { return new AstVectorImpl(check(Z3.optimize_get_assertions(contextPtr, this.ptr))); } maximize(expr: Arith<Name>) { check(Z3.optimize_maximize(contextPtr, this.ptr, expr.ast)); } minimize(expr: Arith<Name>) { check(Z3.optimize_minimize(contextPtr, this.ptr, expr.ast)); } async check(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): Promise<CheckSatResult> { const assumptions = _flattenArgs(exprs).map(expr => { _assertContext(expr); return expr.ast; }); const result = await asyncMutex.runExclusive(() => check(Z3.optimize_check(contextPtr, this.ptr, assumptions)), ); switch (result) { case Z3_lbool.Z3_L_FALSE: return 'unsat'; case Z3_lbool.Z3_L_TRUE: return 'sat'; case Z3_lbool.Z3_L_UNDEF: return 'unknown'; default: assertExhaustive(result); } } model() { return new ModelImpl(check(Z3.optimize_get_model(contextPtr, this.ptr))); } toString() { return check(Z3.optimize_to_string(contextPtr, this.ptr)); } fromString(s: string) { Z3.optimize_from_string(contextPtr, this.ptr, s); throwIfError(); } } class ModelImpl implements Model<Name> { declare readonly __typename: Model['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_model = Z3.mk_model(contextPtr)) { this.ctx = ctx; Z3.model_inc_ref(contextPtr, ptr); cleanup.register(this, () => Z3.model_dec_ref(contextPtr, ptr)); } length() { return Z3.model_get_num_consts(contextPtr, this.ptr) + Z3.model_get_num_funcs(contextPtr, this.ptr); } [Symbol.iterator](): Iterator<FuncDecl<Name>> { return this.values(); } *entries(): IterableIterator<[number, FuncDecl<Name>]> { const length = this.length(); for (let i = 0; i < length; i++) { yield [i, this.get(i)]; } } *keys(): IterableIterator<number> { for (const [key] of this.entries()) { yield key; } } *values(): IterableIterator<FuncDecl<Name>> { for (const [, value] of this.entries()) { yield value; } } decls() { return [...this.values()]; } sexpr() { return check(Z3.model_to_string(contextPtr, this.ptr)); } toString() { return this.sexpr(); } eval(expr: Bool<Name>, modelCompletion?: boolean): Bool<Name>; eval(expr: Arith<Name>, modelCompletion?: boolean): Arith<Name>; eval<Bits extends number = number>(expr: BitVec<Bits, Name>, modelCompletion?: boolean): BitVecNum<Bits, Name>; eval(expr: Expr<Name>, modelCompletion: boolean = false) { _assertContext(expr); const r = check(Z3.model_eval(contextPtr, this.ptr, expr.ast, modelCompletion)); if (r === null) { throw new Z3Error('Failed to evaluate expression in the model'); } return _toExpr(r); } get(i: number): FuncDecl<Name>; get(from: number, to: number): FuncDecl<Name>[]; get(declaration: FuncDecl<Name>): FuncInterp<Name> | Expr<Name>; get(constant: Expr<Name>): Expr<Name>; get(sort: Sort<Name>): AstVector<Name, AnyExpr<Name>>; get( i: number | FuncDecl<Name> | Expr<Name> | Sort<Name>, to?: number, ): FuncDecl<Name> | FuncInterp<Name> | Expr<Name> | AstVector<Name, AnyAst<Name>> | FuncDecl<Name>[] { assert(to === undefined || typeof i === 'number'); if (typeof i === 'number') { const length = this.length(); if (i >= length) { throw new RangeError(`expected index ${i} to be less than length ${length}`); } if (to === undefined) { const numConsts = check(Z3.model_get_num_consts(contextPtr, this.ptr)); if (i < numConsts) { return new FuncDeclImpl(check(Z3.model_get_const_decl(contextPtr, this.ptr, i))); } else { return new FuncDeclImpl(check(Z3.model_get_func_decl(contextPtr, this.ptr, i - numConsts))); } } if (to < 0) { to += length; } if (to >= length) { throw new RangeError(`expected index ${to} to be less than length ${length}`); } const result = []; for (let j = i; j < to; j++) { result.push(this.get(j)); } return result; } else if (isFuncDecl(i) || (isExpr(i) && isConst(i))) { const result = this.getInterp(i); assert(result !== null); return result; } else if (isSort(i)) { return this.getUniverse(i); } assert(false, 'Number, declaration or constant expected'); } updateValue(decl: FuncDecl<Name> | Expr<Name>, a: Ast<Name> | FuncInterp<Name>): void { _assertContext(decl); _assertContext(a); if (isExpr(decl)) { decl = decl.decl(); } if (isFuncDecl(decl) && decl.arity() !== 0 && isFuncInterp(a)) { const funcInterp = this.addFuncInterp(decl, a.elseValue() as Expr<Name>); for (let i = 0; i < a.numEntries(); i++) { const e = a.entry(i); const n = e.numArgs(); const args = global.Array(n).map((_, i) => e.argValue(i)); funcInterp.addEntry(args, e.value()); } return; } if (!isFuncDecl(decl) || decl.arity() !== 0) { throw new Z3Error('Expecting 0-ary function or constant expression'); } if (!isAst(a)) { throw new Z3Error('Only func declarations can be assigned to func interpretations'); } check(Z3.add_const_interp(contextPtr, this.ptr, decl.ptr, a.ast)); } addFuncInterp<DomainSort extends Sort<Name>[] = Sort<Name>[], RangeSort extends Sort<Name> = Sort<Name>>( decl: FuncDecl<Name, DomainSort, RangeSort>, defaultValue: CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ): FuncInterp<Name> { const fi = check( Z3.add_func_interp(contextPtr, this.ptr, decl.ptr, decl.range().cast(defaultValue).ptr as Z3_ast), ); return new FuncInterpImpl(fi); } private getInterp(expr: FuncDecl<Name> | Expr<Name>): Expr<Name> | FuncInterp<Name> | null { assert(isFuncDecl(expr) || isConst(expr), 'Declaration expected'); if (isConst(expr)) { assert(isExpr(expr)); expr = expr.decl(); } assert(isFuncDecl(expr)); if (expr.arity() === 0) { const result = check(Z3.model_get_const_interp(contextPtr, this.ptr, expr.ptr)); if (result === null) { return null; } return _toExpr(result); } else { const interp = check(Z3.model_get_func_interp(contextPtr, this.ptr, expr.ptr)); if (interp === null) { return null; } return new FuncInterpImpl(interp); } } private getUniverse(sort: Sort<Name>): AstVector<Name, AnyAst<Name>> { _assertContext(sort); return new AstVectorImpl(check(Z3.model_get_sort_universe(contextPtr, this.ptr, sort.ptr))); } } class FuncEntryImpl implements FuncEntry<Name> { declare readonly __typename: FuncEntry['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_func_entry) { this.ctx = ctx; Z3.func_entry_inc_ref(contextPtr, ptr); cleanup.register(this, () => Z3.func_entry_dec_ref(contextPtr, ptr)); } numArgs() { return check(Z3.func_entry_get_num_args(contextPtr, this.ptr)); } argValue(i: number): Expr<Name> { return _toExpr(check(Z3.func_entry_get_arg(contextPtr, this.ptr, i))); } value(): Expr<Name> { return _toExpr(check(Z3.func_entry_get_value(contextPtr, this.ptr))); } } class FuncInterpImpl implements FuncInterp<Name> { declare readonly __typename: FuncInterp['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_func_interp) { this.ctx = ctx; Z3.func_interp_inc_ref(contextPtr, ptr); cleanup.register(this, () => Z3.func_interp_dec_ref(contextPtr, ptr)); } elseValue(): Expr<Name> { return _toExpr(check(Z3.func_interp_get_else(contextPtr, this.ptr))); } numEntries(): number { return check(Z3.func_interp_get_num_entries(contextPtr, this.ptr)); } arity(): number { return check(Z3.func_interp_get_arity(contextPtr, this.ptr)); } entry(i: number): FuncEntry<Name> { return new FuncEntryImpl(check(Z3.func_interp_get_entry(contextPtr, this.ptr, i))); } addEntry(args: Expr<Name>[], value: Expr<Name>): void { const argsVec = new AstVectorImpl(); for (const arg of args) { argsVec.push(arg); } _assertContext(argsVec); _assertContext(value); assert(this.arity() === argsVec.length(), "Number of arguments in entry doesn't match function arity"); check(Z3.func_interp_add_entry(contextPtr, this.ptr, argsVec.ptr, value.ptr as Z3_ast)); } } class SortImpl extends AstImpl<Z3_sort> implements Sort<Name> { declare readonly __typename: Sort['__typename']; get ast(): Z3_ast { return Z3.sort_to_ast(contextPtr, this.ptr); } kind() { return Z3.get_sort_kind(contextPtr, this.ptr); } subsort(other: Sort<Name>) { _assertContext(other); return false; } cast(expr: Expr<Name>): Expr<Name> { _assertContext(expr); assert(expr.sort.eqIdentity(expr.sort), 'Sort mismatch'); return expr; } name() { return _fromSymbol(Z3.get_sort_name(contextPtr, this.ptr)); } eqIdentity(other: Sort<Name>) { _assertContext(other); return check(Z3.is_eq_sort(contextPtr, this.ptr, other.ptr)); } neqIdentity(other: Sort<Name>) { return !this.eqIdentity(other); } } class FuncDeclImpl<DomainSort extends Sort<Name>[], RangeSort extends Sort<Name>> extends AstImpl<Z3_func_decl> implements FuncDecl<Name> { declare readonly __typename: FuncDecl['__typename']; get ast(): Z3_ast { return Z3.func_decl_to_ast(contextPtr, this.ptr); } name() { return _fromSymbol(Z3.get_decl_name(contextPtr, this.ptr)); } arity() { return Z3.get_arity(contextPtr, this.ptr); } domain<T extends number>(i: T): DomainSort[T] { assert(i < this.arity(), 'Index out of bounds'); return _toSort(Z3.get_domain(contextPtr, this.ptr, i)); } range(): RangeSort { return _toSort(Z3.get_range(contextPtr, this.ptr)) as RangeSort; } kind() { return Z3.get_decl_kind(contextPtr, this.ptr); } params(): (number | string | Sort<Name> | Expr<Name> | FuncDecl<Name>)[] { const n = Z3.get_decl_num_parameters(contextPtr, this.ptr); const result = []; for (let i = 0; i < n; i++) { const kind = check(Z3.get_decl_parameter_kind(contextPtr, this.ptr, i)); switch (kind) { case Z3_parameter_kind.Z3_PARAMETER_INT: result.push(check(Z3.get_decl_int_parameter(contextPtr, this.ptr, i))); break; case Z3_parameter_kind.Z3_PARAMETER_DOUBLE: result.push(check(Z3.get_decl_double_parameter(contextPtr, this.ptr, i))); break; case Z3_parameter_kind.Z3_PARAMETER_RATIONAL: result.push(check(Z3.get_decl_rational_parameter(contextPtr, this.ptr, i))); break; case Z3_parameter_kind.Z3_PARAMETER_SYMBOL: result.push(_fromSymbol(check(Z3.get_decl_symbol_parameter(contextPtr, this.ptr, i)))); break; case Z3_parameter_kind.Z3_PARAMETER_SORT: result.push(new SortImpl(check(Z3.get_decl_sort_parameter(contextPtr, this.ptr, i)))); break; case Z3_parameter_kind.Z3_PARAMETER_AST: result.push(new ExprImpl(check(Z3.get_decl_ast_parameter(contextPtr, this.ptr, i)))); break; case Z3_parameter_kind.Z3_PARAMETER_FUNC_DECL: result.push(new FuncDeclImpl(check(Z3.get_decl_func_decl_parameter(contextPtr, this.ptr, i)))); break; default: assertExhaustive(kind); } } return result; } call(...args: CoercibleToArrayIndexType<Name, DomainSort>): SortToExprMap<RangeSort, Name> { assert(args.length === this.arity(), `Incorrect number of arguments to ${this}`); return _toExpr( check( Z3.mk_app( contextPtr, this.ptr, args.map((arg, i) => { return this.domain(i).cast(arg as any).ast; }), ), ), ) as SortToExprMap<RangeSort, Name>; } } class ExprImpl<Ptr extends Z3_ast, S extends Sort<Name> = AnySort<Name>> extends AstImpl<Ptr> implements Expr<Name> { declare readonly __typename: Expr['__typename']; get sort(): S { return _toSort(Z3.get_sort(contextPtr, this.ast)) as S; } eq(other: CoercibleToExpr<Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_eq(contextPtr, this.ast, from(other).ast))); } neq(other: CoercibleToExpr<Name>): Bool<Name> { return new BoolImpl( check( Z3.mk_distinct( contextPtr, [this, other].map(expr => from(expr).ast), ), ), ); } name() { return this.decl().name(); } params() { return this.decl().params(); } decl(): FuncDecl<Name> { assert(isApp(this), 'Z3 application expected'); return new FuncDeclImpl(check(Z3.get_app_decl(contextPtr, check(Z3.to_app(contextPtr, this.ast))))); } numArgs(): number { assert(isApp(this), 'Z3 applicaiton expected'); return check(Z3.get_app_num_args(contextPtr, check(Z3.to_app(contextPtr, this.ast)))); } arg(i: number): ReturnType<typeof _toExpr> { assert(isApp(this), 'Z3 applicaiton expected'); assert(i < this.numArgs(), `Invalid argument index - expected ${i} to be less than ${this.numArgs()}`); return _toExpr(check(Z3.get_app_arg(contextPtr, check(Z3.to_app(contextPtr, this.ast)), i))); } children(): ReturnType<typeof _toExpr>[] { const num_args = this.numArgs(); if (isApp(this)) { const result = []; for (let i = 0; i < num_args; i++) { result.push(this.arg(i)); } return result; } return []; } } class PatternImpl implements Pattern<Name> { declare readonly __typename: Pattern['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_pattern) { this.ctx = ctx; // TODO: implement rest of Pattern } } class BoolSortImpl extends SortImpl implements BoolSort<Name> { declare readonly __typename: BoolSort['__typename']; cast(other: Bool<Name> | boolean): Bool<Name>; cast(other: CoercibleToExpr<Name>): never; cast(other: CoercibleToExpr<Name> | Bool<Name>) { if (typeof other === 'boolean') { other = Bool.val(other); } assert(isExpr(other), 'true, false or Z3 Boolean expression expected.'); assert(this.eqIdentity(other.sort), 'Value cannot be converted into a Z3 Boolean value'); return other; } subsort(other: Sort<Name>) { _assertContext(other.ctx); return other instanceof ArithSortImpl; } } class BoolImpl extends ExprImpl<Z3_ast, BoolSort<Name>> implements Bool<Name> { declare readonly __typename: 'Bool' | 'NonLambdaQuantifier'; not(): Bool<Name> { return Not(this); } and(other: Bool<Name> | boolean): Bool<Name> { return And(this, other); } or(other: Bool<Name> | boolean): Bool<Name> { return Or(this, other); } xor(other: Bool<Name> | boolean): Bool<Name> { return Xor(this, other); } implies(other: Bool<Name> | boolean): Bool<Name> { return Implies(this, other); } iff(other: Bool<Name> | boolean): Bool<Name> { return Iff(this, other); } } class ProbeImpl implements Probe<Name> { declare readonly __typename: Probe['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_probe) { this.ctx = ctx; } } class TacticImpl implements Tactic<Name> { declare readonly __typename: Tactic['__typename']; readonly ptr: Z3_tactic; readonly ctx: Context<Name>; constructor(tactic: string | Z3_tactic) { this.ctx = ctx; let myPtr: Z3_tactic; if (typeof tactic === 'string') { myPtr = check(Z3.mk_tactic(contextPtr, tactic)); } else { myPtr = tactic; } this.ptr = myPtr; Z3.tactic_inc_ref(contextPtr, myPtr); cleanup.register(this, () => Z3.tactic_dec_ref(contextPtr, myPtr)); } } class ArithSortImpl extends SortImpl implements ArithSort<Name> { declare readonly __typename: ArithSort['__typename']; cast(other: bigint | number | string): IntNum<Name> | RatNum<Name>; cast(other: CoercibleRational | RatNum<Name>): RatNum<Name>; cast(other: IntNum<Name>): IntNum<Name>; cast(other: Bool<Name> | Arith<Name>): Arith<Name>; cast(other: CoercibleToExpr<Name>): never; cast(other: CoercibleToExpr<Name> | string): Arith<Name> | RatNum<Name> | IntNum<Name> { const sortTypeStr = isIntSort(this) ? 'IntSort' : 'RealSort'; if (isExpr(other)) { const otherS = other.sort; if (isArith(other)) { if (this.eqIdentity(otherS)) { return other; } else if (isIntSort(otherS) && isRealSort(this)) { return ToReal(other); } assert(false, "Can't cast Real to IntSort without loss"); } else if (isBool(other)) { if (isIntSort(this)) { return If(other, 1, 0); } else { return ToReal(If(other, 1, 0)); } } assert(false, `Can't cast expression to ${sortTypeStr}`); } else { if (typeof other !== 'boolean') { if (isIntSort(this)) { assert(!isCoercibleRational(other), "Can't cast fraction to IntSort"); return Int.val(other); } return Real.val(other); } assert(false, `Can't cast primitive to ${sortTypeStr}`); } } } function Sum(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; function Sum<Bits extends number>( arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[] ): BitVec<Bits, Name>; function Sum<T extends Expr<Name>>(arg0: T, ...args: CoercibleToMap<T, Name>[]): T { if (arg0 instanceof BitVecImpl) { // Assert only 2 if (args.length !== 1) { throw new Error('BitVec add only supports 2 arguments'); } return new BitVecImpl<number>( check(Z3.mk_bvadd(contextPtr, arg0.ast, arg0.sort.cast(args[0]).ast)), ) as unknown as T; } else { assert(arg0 instanceof ArithImpl); return new ArithImpl( check(Z3.mk_add(contextPtr, [arg0.ast].concat(args.map(arg => arg0.sort.cast(arg).ast)))), ) as unknown as T; } } function Sub(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; function Sub<Bits extends number>( arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[] ): BitVec<Bits, Name>; function Sub<T extends Expr<Name>>(arg0: T, ...args: CoercibleToMap<T, Name>[]): T { if (arg0 instanceof BitVecImpl) { // Assert only 2 if (args.length !== 1) { throw new Error('BitVec sub only supports 2 arguments'); } return new BitVecImpl<number>( check(Z3.mk_bvsub(contextPtr, arg0.ast, arg0.sort.cast(args[0]).ast)), ) as unknown as T; } else { assert(arg0 instanceof ArithImpl); return new ArithImpl( check(Z3.mk_sub(contextPtr, [arg0.ast].concat(args.map(arg => arg0.sort.cast(arg).ast)))), ) as unknown as T; } } function Product(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; function Product<Bits extends number>( arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[] ): BitVec<Bits, Name>; function Product<T extends Expr<Name>>(arg0: T, ...args: CoercibleToMap<T, Name>[]): T { if (arg0 instanceof BitVecImpl) { // Assert only 2 if (args.length !== 1) { throw new Error('BitVec mul only supports 2 arguments'); } return new BitVecImpl<number>( check(Z3.mk_bvmul(contextPtr, arg0.ast, arg0.sort.cast(args[0]).ast)), ) as unknown as T; } else { assert(arg0 instanceof ArithImpl); return new ArithImpl( check(Z3.mk_mul(contextPtr, [arg0.ast].concat(args.map(arg => arg0.sort.cast(arg).ast)))), ) as unknown as T; } } function Div(arg0: Arith<Name>, arg1: CoercibleToArith<Name>): Arith<Name>; function Div<Bits extends number>( arg0: BitVec<Bits, Name>, arg1: CoercibleToBitVec<Bits, Name>, ): BitVec<Bits, Name>; function Div<T extends Expr<Name>>(arg0: T, arg1: CoercibleToMap<T, Name>): T { if (arg0 instanceof BitVecImpl) { return new BitVecImpl<number>( check(Z3.mk_bvsdiv(contextPtr, arg0.ast, arg0.sort.cast(arg1).ast)), ) as unknown as T; } else { assert(arg0 instanceof ArithImpl); return new ArithImpl(check(Z3.mk_div(contextPtr, arg0.ast, arg0.sort.cast(arg1).ast))) as unknown as T; } } function BUDiv<Bits extends number>( arg0: BitVec<Bits, Name>, arg1: CoercibleToBitVec<Bits, Name>, ): BitVec<Bits, Name> { return new BitVecImpl<number>( check(Z3.mk_bvudiv(contextPtr, arg0.ast, arg0.sort.cast(arg1).ast)), ) as unknown as BitVec<Bits, Name>; } function Neg(a: Arith<Name>): Arith<Name>; function Neg<Bits extends number>(a: BitVec<Bits, Name>): BitVec<Bits, Name>; function Neg<T extends Expr<Name>>(a: T): T { if (a instanceof BitVecImpl) { return new BitVecImpl<number>(check(Z3.mk_bvneg(contextPtr, a.ast))) as unknown as T; } else { assert(a instanceof ArithImpl); return new ArithImpl(check(Z3.mk_unary_minus(contextPtr, a.ast))) as unknown as T; } } function Mod(a: Arith<Name>, b: CoercibleToArith<Name>): Arith<Name>; function Mod<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; function Mod<T extends Expr<Name>>(a: T, b: CoercibleToMap<T, Name>): T { if (a instanceof BitVecImpl) { return new BitVecImpl<number>(check(Z3.mk_bvsrem(contextPtr, a.ast, a.sort.cast(b).ast))) as unknown as T; } else { assert(a instanceof ArithImpl); return new ArithImpl(check(Z3.mk_mod(contextPtr, a.ast, a.sort.cast(b).ast))) as unknown as T; } } class ArithImpl extends ExprImpl<Z3_ast, ArithSort<Name>> implements Arith<Name> { declare readonly __typename: Arith['__typename']; add(other: CoercibleToArith<Name>) { return Sum(this, other); } mul(other: CoercibleToArith<Name>) { return Product(this, other); } sub(other: CoercibleToArith<Name>) { return Sub(this, other); } pow(exponent: CoercibleToArith<Name>) { return new ArithImpl(check(Z3.mk_power(contextPtr, this.ast, this.sort.cast(exponent).ast))); } div(other: CoercibleToArith<Name>) { return Div(this, other); } mod(other: CoercibleToArith<Name>) { return Mod(this, other); } neg() { return Neg(this); } le(other: CoercibleToArith<Name>) { return LE(this, other); } lt(other: CoercibleToArith<Name>) { return LT(this, other); } gt(other: CoercibleToArith<Name>) { return GT(this, other); } ge(other: CoercibleToArith<Name>) { return GE(this, other); } } class IntNumImpl extends ArithImpl implements IntNum<Name> { declare readonly __typename: IntNum['__typename']; value() { return BigInt(this.asString()); } asString() { return Z3.get_numeral_string(contextPtr, this.ast); } asBinary() { return Z3.get_numeral_binary_string(contextPtr, this.ast); } } class RatNumImpl extends ArithImpl implements RatNum<Name> { declare readonly __typename: RatNum['__typename']; value() { return { numerator: this.numerator().value(), denominator: this.denominator().value() }; } numerator() { return new IntNumImpl(Z3.get_numerator(contextPtr, this.ast)); } denominator() { return new IntNumImpl(Z3.get_denominator(contextPtr, this.ast)); } asNumber() { const { numerator, denominator } = this.value(); const div = numerator / denominator; return Number(div) + Number(numerator - div * denominator) / Number(denominator); } asDecimal(prec: number = Number.parseInt(getParam('precision') ?? FALLBACK_PRECISION.toString())) { return Z3.get_numeral_decimal_string(contextPtr, this.ast, prec); } asString() { return Z3.get_numeral_string(contextPtr, this.ast); } } class BitVecSortImpl<Bits extends number> extends SortImpl implements BitVecSort<Bits, Name> { declare readonly __typename: BitVecSort['__typename']; size() { return Z3.get_bv_sort_size(contextPtr, this.ptr) as Bits; } subsort(other: Sort<Name>): boolean { return isBitVecSort(other) && this.size() < other.size(); } cast(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; cast(other: CoercibleToExpr<Name>): Expr<Name>; cast(other: CoercibleToExpr<Name>): Expr<Name> { if (isExpr(other)) { _assertContext(other); return other; } assert(!isCoercibleRational(other), "Can't convert rational to BitVec"); return BitVec.val(other, this.size()); } } class BitVecImpl<Bits extends number> extends ExprImpl<Z3_ast, BitVecSortImpl<Bits>> implements BitVec<Bits, Name> { declare readonly __typename: BitVec['__typename']; size() { return this.sort.size(); } add(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return Sum(this, other); } mul(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return Product(this, other); } sub(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return Sub(this, other); } sdiv(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return Div(this, other); } udiv(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return BUDiv(this, other); } smod(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return Mod(this, other); } urem(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvurem(contextPtr, this.ast, this.sort.cast(other).ast))); } srem(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvsrem(contextPtr, this.ast, this.sort.cast(other).ast))); } neg(): BitVec<Bits, Name> { return Neg(this); } or(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvor(contextPtr, this.ast, this.sort.cast(other).ast))); } and(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvand(contextPtr, this.ast, this.sort.cast(other).ast))); } nand(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvnand(contextPtr, this.ast, this.sort.cast(other).ast))); } xor(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvxor(contextPtr, this.ast, this.sort.cast(other).ast))); } xnor(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvxnor(contextPtr, this.ast, this.sort.cast(other).ast))); } shr(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvashr(contextPtr, this.ast, this.sort.cast(count).ast))); } lshr(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvlshr(contextPtr, this.ast, this.sort.cast(count).ast))); } shl(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvshl(contextPtr, this.ast, this.sort.cast(count).ast))); } rotateRight(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_ext_rotate_right(contextPtr, this.ast, this.sort.cast(count).ast))); } rotateLeft(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_ext_rotate_left(contextPtr, this.ast, this.sort.cast(count).ast))); } not(): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvnot(contextPtr, this.ast))); } extract(high: number, low: number): BitVec<number, Name> { return Extract(high, low, this); } signExt(count: number): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_sign_ext(contextPtr, count, this.ast))); } zeroExt(count: number): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_zero_ext(contextPtr, count, this.ast))); } repeat(count: number): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_repeat(contextPtr, count, this.ast))); } sle(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return SLE(this, other); } ule(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return ULE(this, other); } slt(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return SLT(this, other); } ult(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return ULT(this, other); } sge(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return SGE(this, other); } uge(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return UGE(this, other); } sgt(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return SGT(this, other); } ugt(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return UGT(this, other); } redAnd(): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvredand(contextPtr, this.ast))); } redOr(): BitVec<Bits, Name> { return new BitVecImpl<Bits>(check(Z3.mk_bvredor(contextPtr, this.ast))); } addNoOverflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name> { return new BoolImpl(check(Z3.mk_bvadd_no_overflow(contextPtr, this.ast, this.sort.cast(other).ast, isSigned))); } addNoUnderflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvadd_no_underflow(contextPtr, this.ast, this.sort.cast(other).ast))); } subNoOverflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsub_no_overflow(contextPtr, this.ast, this.sort.cast(other).ast))); } subNoUndeflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsub_no_underflow(contextPtr, this.ast, this.sort.cast(other).ast, isSigned))); } sdivNoOverflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvsdiv_no_overflow(contextPtr, this.ast, this.sort.cast(other).ast))); } mulNoOverflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name> { return new BoolImpl(check(Z3.mk_bvmul_no_overflow(contextPtr, this.ast, this.sort.cast(other).ast, isSigned))); } mulNoUndeflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name> { return new BoolImpl(check(Z3.mk_bvmul_no_underflow(contextPtr, this.ast, this.sort.cast(other).ast))); } negNoOverflow(): Bool<Name> { return new BoolImpl(check(Z3.mk_bvneg_no_overflow(contextPtr, this.ast))); } } class BitVecNumImpl<Bits extends number> extends BitVecImpl<Bits> implements BitVecNum<Bits, Name> { declare readonly __typename: BitVecNum['__typename']; value() { return BigInt(this.asString()); } asSignedValue() { let val = this.value(); const size = BigInt(this.size()); if (val >= 2n ** (size - 1n)) { val = val - 2n ** size; } if (val < (-2n) ** (size - 1n)) { val = val + 2n ** size; } return val; } asString() { return Z3.get_numeral_string(contextPtr, this.ast); } asBinaryString() { return Z3.get_numeral_binary_string(contextPtr, this.ast); } } class ArraySortImpl<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>> extends SortImpl implements SMTArraySort<Name, DomainSort, RangeSort> { declare readonly __typename: SMTArraySort['__typename']; domain(): DomainSort[0] { return _toSort(check(Z3.get_array_sort_domain(contextPtr, this.ptr))); } domain_n<T extends number>(i: T): DomainSort[T] { return _toSort(check(Z3.get_array_sort_domain_n(contextPtr, this.ptr, i))); } range(): RangeSort { return _toSort(check(Z3.get_array_sort_range(contextPtr, this.ptr))) as RangeSort; } } class ArrayImpl<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>> extends ExprImpl<Z3_ast, ArraySortImpl<DomainSort, RangeSort>> implements SMTArray<Name, DomainSort, RangeSort> { declare readonly __typename: 'Array' | 'Lambda'; domain(): DomainSort[0] { return this.sort.domain(); } domain_n<T extends number>(i: T): DomainSort[T] { return this.sort.domain_n(i); } range(): RangeSort { return this.sort.range(); } select(...indices: CoercibleToArrayIndexType<Name, DomainSort>): SortToExprMap<RangeSort, Name> { return Select<DomainSort, RangeSort>(this, ...indices) as SortToExprMap<RangeSort, Name>; } store( ...indicesAndValue: [ ...CoercibleToArrayIndexType<Name, DomainSort>, CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ] ): SMTArray<Name, DomainSort, RangeSort> { return Store(this, ...indicesAndValue); } } class QuantifierImpl< QVarSorts extends NonEmptySortArray<Name>, QSort extends BoolSort<Name> | SMTArraySort<Name, QVarSorts>, > extends ExprImpl<Z3_ast, QSort> implements Quantifier<Name, QVarSorts, QSort> { declare readonly __typename: Quantifier['__typename']; is_forall(): boolean { return Z3.is_quantifier_forall(contextPtr, this.ast); } is_exists(): boolean { return Z3.is_quantifier_exists(contextPtr, this.ast); } is_lambda(): boolean { return Z3.is_lambda(contextPtr, this.ast); } weight(): number { return Z3.get_quantifier_weight(contextPtr, this.ast); } num_patterns(): number { return Z3.get_quantifier_num_patterns(contextPtr, this.ast); } pattern(i: number): Pattern<Name> { return new PatternImpl(check(Z3.get_quantifier_pattern_ast(contextPtr, this.ast, i))); } num_no_patterns(): number { return Z3.get_quantifier_num_no_patterns(contextPtr, this.ast); } no_pattern(i: number): Expr<Name> { return _toExpr(check(Z3.get_quantifier_no_pattern_ast(contextPtr, this.ast, i))); } body(): BodyT<Name, QVarSorts, QSort> { return _toExpr(check(Z3.get_quantifier_body(contextPtr, this.ast))) as any; } num_vars(): number { return Z3.get_quantifier_num_bound(contextPtr, this.ast); } var_name(i: number): string | number { return _fromSymbol(Z3.get_quantifier_bound_name(contextPtr, this.ast, i)); } var_sort<T extends number>(i: T): QVarSorts[T] { return _toSort(check(Z3.get_quantifier_bound_sort(contextPtr, this.ast, i))); } children(): [BodyT<Name, QVarSorts, QSort>] { return [this.body()]; } } class NonLambdaQuantifierImpl<QVarSorts extends NonEmptySortArray<Name>> extends QuantifierImpl<QVarSorts, BoolSort<Name>> implements Quantifier<Name, QVarSorts, BoolSort<Name>>, Bool<Name> { declare readonly __typename: 'NonLambdaQuantifier'; not(): Bool<Name> { return Not(this); } and(other: Bool<Name> | boolean): Bool<Name> { return And(this, other); } or(other: Bool<Name> | boolean): Bool<Name> { return Or(this, other); } xor(other: Bool<Name> | boolean): Bool<Name> { return Xor(this, other); } implies(other: Bool<Name> | boolean): Bool<Name> { return Implies(this, other); } iff(other: Bool<Name> | boolean): Bool<Name> { return Iff(this, other); } } // isBool will return false which is unlike the python API (but like the C API) class LambdaImpl<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>> extends QuantifierImpl<DomainSort, SMTArraySort<Name, DomainSort, RangeSort>> implements Quantifier<Name, DomainSort, SMTArraySort<Name, DomainSort, RangeSort>>, SMTArray<Name, DomainSort, RangeSort> { declare readonly __typename: 'Lambda'; domain(): DomainSort[0] { return this.sort.domain(); } domain_n<T extends number>(i: T): DomainSort[T] { return this.sort.domain_n(i); } range(): RangeSort { return this.sort.range(); } select(...indices: CoercibleToArrayIndexType<Name, DomainSort>): SortToExprMap<RangeSort, Name> { return Select<DomainSort, RangeSort>(this, ...indices); } store( ...indicesAndValue: [ ...CoercibleToArrayIndexType<Name, DomainSort>, CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ] ): SMTArray<Name, DomainSort, RangeSort> { return Store(this, ...indicesAndValue); } } class AstVectorImpl<Item extends AnyAst<Name>> { declare readonly __typename: AstVector['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_ast_vector = Z3.mk_ast_vector(contextPtr)) { this.ctx = ctx; Z3.ast_vector_inc_ref(contextPtr, ptr); cleanup.register(this, () => Z3.ast_vector_dec_ref(contextPtr, ptr)); } length(): number { return Z3.ast_vector_size(contextPtr, this.ptr); } [Symbol.iterator](): IterableIterator<Item> { return this.values(); } *entries(): IterableIterator<[number, Item]> { const length = this.length(); for (let i = 0; i < length; i++) { yield [i, this.get(i)]; } } *keys(): IterableIterator<number> { for (let [key] of this.entries()) { yield key; } } *values(): IterableIterator<Item> { for (let [, value] of this.entries()) { yield value; } } get(i: number): Item; get(from: number, to: number): Item[]; get(from: number, to?: number): Item | Item[] { const length = this.length(); if (from < 0) { from += length; } if (from >= length) { throw new RangeError(`expected from index ${from} to be less than length ${length}`); } if (to === undefined) { return _toAst(check(Z3.ast_vector_get(contextPtr, this.ptr, from))) as Item; } if (to < 0) { to += length; } if (to >= length) { throw new RangeError(`expected to index ${to} to be less than length ${length}`); } const result: Item[] = []; for (let i = from; i < to; i++) { result.push(_toAst(check(Z3.ast_vector_get(contextPtr, this.ptr, i))) as Item); } return result; } set(i: number, v: Item): void { _assertContext(v); if (i >= this.length()) { throw new RangeError(`expected index ${i} to be less than length ${this.length()}`); } check(Z3.ast_vector_set(contextPtr, this.ptr, i, v.ast)); } push(v: Item): void { _assertContext(v); check(Z3.ast_vector_push(contextPtr, this.ptr, v.ast)); } resize(size: number): void { check(Z3.ast_vector_resize(contextPtr, this.ptr, size)); } has(v: Item): boolean { _assertContext(v); for (const item of this.values()) { if (item.eqIdentity(v)) { return true; } } return false; } sexpr(): string { return check(Z3.ast_vector_to_string(contextPtr, this.ptr)); } } class AstMapImpl<Key extends AnyAst<Name>, Value extends AnyAst<Name>> implements AstMap<Name, Key, Value> { declare readonly __typename: AstMap['__typename']; readonly ctx: Context<Name>; constructor(readonly ptr: Z3_ast_map = Z3.mk_ast_map(contextPtr)) { this.ctx = ctx; Z3.ast_map_inc_ref(contextPtr, ptr); cleanup.register(this, () => Z3.ast_map_dec_ref(contextPtr, ptr)); } [Symbol.iterator](): Iterator<[Key, Value]> { return this.entries(); } get size(): number { return Z3.ast_map_size(contextPtr, this.ptr); } *entries(): IterableIterator<[Key, Value]> { for (const key of this.keys()) { yield [key, this.get(key)]; } } keys(): AstVector<Name, Key> { return new AstVectorImpl(Z3.ast_map_keys(contextPtr, this.ptr)); } *values(): IterableIterator<Value> { for (const [_, value] of this.entries()) { yield value; } } get(key: Key): Value { return _toAst(check(Z3.ast_map_find(contextPtr, this.ptr, key.ast))) as Value; } set(key: Key, value: Value): void { check(Z3.ast_map_insert(contextPtr, this.ptr, key.ast, value.ast)); } delete(key: Key): void { check(Z3.ast_map_erase(contextPtr, this.ptr, key.ast)); } clear(): void { check(Z3.ast_map_reset(contextPtr, this.ptr)); } has(key: Key): boolean { return check(Z3.ast_map_contains(contextPtr, this.ptr, key.ast)); } sexpr(): string { return check(Z3.ast_map_to_string(contextPtr, this.ptr)); } } function substitute(t: Expr<Name>, ...substitutions: [Expr<Name>, Expr<Name>][]): Expr<Name> { _assertContext(t); const from: Z3_ast[] = []; const to: Z3_ast[] = []; for (const [f, t] of substitutions) { _assertContext(f); _assertContext(t); from.push(f.ast); to.push(t.ast); } return _toExpr(check(Z3.substitute(contextPtr, t.ast, from, to))); } function ast_from_string(s: string): Ast<Name> { const sort_names: Z3_symbol[] = []; const sorts: Z3_sort[] = []; const decl_names: Z3_symbol[] = []; const decls: Z3_func_decl[] = []; const v = new AstVectorImpl(check(Z3.parse_smtlib2_string(contextPtr, s, sort_names, sorts, decl_names, decls))); if (v.length() !== 1) { throw new Error('Expected exactly one AST. Instead got ' + v.length() + ': ' + v.sexpr()); } return v.get(0); } const ctx: Context<Name> = { ptr: contextPtr, name, ///////////// // Classes // ///////////// Solver: SolverImpl, Optimize: OptimizeImpl, Model: ModelImpl, Tactic: TacticImpl, AstVector: AstVectorImpl as AstVectorCtor<Name>, AstMap: AstMapImpl as AstMapCtor<Name>, /////////////// // Functions // /////////////// interrupt, isModel, isAst, isSort, isFuncDecl, isFuncInterp, isApp, isConst, isExpr, isVar, isAppOf, isBool, isTrue, isFalse, isAnd, isOr, isImplies, isNot, isEq, isDistinct, isQuantifier, isArith, isArithSort, isInt, isIntVal, isIntSort, isReal, isRealVal, isRealSort, isBitVecSort, isBitVec, isBitVecVal, // TODO fix ordering isArraySort, isArray, isConstArray, isProbe, isTactic, isAstVector, eqIdentity, getVarIndex, from, solve, ///////////// // Objects // ///////////// Sort, Function, RecFunc, Bool, Int, Real, BitVec, Array, //////////////// // Operations // //////////////// If, Distinct, Const, Consts, FreshConst, Var, Implies, Iff, Eq, Xor, Not, And, Or, ForAll, Exists, Lambda, ToReal, ToInt, IsInt, Sqrt, Cbrt, BV2Int, Int2BV, Concat, Cond, LT, GT, LE, GE, ULT, UGT, ULE, UGE, SLT, SGT, SLE, SGE, Sum, Sub, Product, Div, BUDiv, Neg, Mod, Select, Store, Extract, substitute, simplify, ///////////// // Loading // ///////////// ast_from_string, }; cleanup.register(ctx, () => Z3.del_context(contextPtr)); return ctx; } return { enableTrace, disableTrace, getVersion, getVersionString, getFullVersion, openLog, appendLog, getParam, setParam, resetParams, Context: createContext, }; }
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/src/high-level/high-level.ts
high-level.ts
import { Z3_ast, Z3_ast_map, Z3_ast_vector, Z3_context, Z3_decl_kind, Z3_func_decl, Z3_func_entry, Z3_func_interp, Z3_model, Z3_probe, Z3_solver, Z3_optimize, Z3_sort, Z3_sort_kind, Z3_tactic, } from '../low-level'; /** @hidden */ export type AnySort<Name extends string = 'main'> = | Sort<Name> | BoolSort<Name> | ArithSort<Name> | BitVecSort<number, Name> | SMTArraySort<Name>; /** @hidden */ export type AnyExpr<Name extends string = 'main'> = | Expr<Name> | Bool<Name> | Arith<Name> | IntNum<Name> | RatNum<Name> | BitVec<number, Name> | BitVecNum<number, Name> | SMTArray<Name>; /** @hidden */ export type AnyAst<Name extends string = 'main'> = AnyExpr<Name> | AnySort<Name> | FuncDecl<Name>; /** @hidden */ export type SortToExprMap<S extends AnySort<Name>, Name extends string = 'main'> = S extends BoolSort ? Bool<Name> : S extends ArithSort<Name> ? Arith<Name> : S extends BitVecSort<infer Size, Name> ? BitVec<Size, Name> : S extends SMTArraySort<Name, infer DomainSort, infer RangeSort> ? SMTArray<Name, DomainSort, RangeSort> : S extends Sort<Name> ? Expr<Name, S, Z3_ast> : never; /** @hidden */ export type CoercibleFromMap<S extends CoercibleToExpr<Name>, Name extends string = 'main'> = S extends bigint ? Arith<Name> : S extends number | CoercibleRational ? RatNum<Name> : S extends boolean ? Bool<Name> : S extends Expr<Name> ? S : never; /** @hidden */ export type CoercibleToBitVec<Bits extends number = number, Name extends string = 'main'> = | bigint | number | BitVec<Bits, Name>; export type CoercibleRational = { numerator: bigint | number; denominator: bigint | number }; /** @hidden */ export type CoercibleToExpr<Name extends string = 'main'> = number | bigint | boolean | CoercibleRational | Expr<Name>; /** @hidden */ export type CoercibleToArith<Name extends string = 'main'> = number | string | bigint | CoercibleRational | Arith<Name>; /** @hidden */ export type CoercibleToMap<T extends AnyExpr<Name>, Name extends string = 'main'> = T extends Bool<Name> ? boolean | Bool<Name> : T extends IntNum<Name> ? bigint | number | IntNum<Name> : T extends RatNum<Name> ? bigint | number | CoercibleRational | RatNum<Name> : T extends Arith<Name> ? CoercibleToArith<Name> : T extends BitVec<infer Size, Name> ? CoercibleToBitVec<Size, Name> : T extends SMTArray<Name, infer DomainSort, infer RangeSort> ? SMTArray<Name, DomainSort, RangeSort> : T extends Expr<Name> ? Expr<Name> : never; /** * Used to create a Real constant * * ```typescript * const x = from({ numerator: 1, denominator: 3 }) * * x * // 1/3 * isReal(x) * // true * isRealVal(x) * // true * x.asNumber() * // 0.3333333333333333 * ``` * @see {@link Context.from} * @category Global */ export class Z3Error extends Error {} export class Z3AssertionError extends Z3Error {} /** @category Global */ export type CheckSatResult = 'sat' | 'unsat' | 'unknown'; /** @hidden */ export interface ContextCtor { <Name extends string>(name: Name, options?: Record<string, any>): Context<Name>; } export interface Context<Name extends string = 'main'> { /** @hidden */ readonly ptr: Z3_context; /** * Name of the current Context * * ```typescript * const c = new Context('main') * * c.name * // 'main' * ``` */ readonly name: Name; /////////////// // Functions // /////////////// /** @category Functions */ interrupt(): void; /** @category Functions */ isModel(obj: unknown): obj is Model<Name>; /** @category Functions */ isAst(obj: unknown): obj is Ast<Name>; /** @category Functions */ isSort(obj: unknown): obj is Sort<Name>; /** @category Functions */ isFuncDecl(obj: unknown): obj is FuncDecl<Name>; /** @category Functions */ isFuncInterp(obj: unknown): obj is FuncInterp<Name>; /** @category Functions */ isApp(obj: unknown): boolean; /** @category Functions */ isConst(obj: unknown): boolean; /** @category Functions */ isExpr(obj: unknown): obj is Expr<Name>; /** @category Functions */ isVar(obj: unknown): boolean; /** @category Functions */ isAppOf(obj: unknown, kind: Z3_decl_kind): boolean; /** @category Functions */ isBool(obj: unknown): obj is Bool<Name>; /** @category Functions */ isTrue(obj: unknown): boolean; /** @category Functions */ isFalse(obj: unknown): boolean; /** @category Functions */ isAnd(obj: unknown): boolean; /** @category Functions */ isOr(obj: unknown): boolean; /** @category Functions */ isImplies(obj: unknown): boolean; /** @category Functions */ isNot(obj: unknown): boolean; /** @category Functions */ isEq(obj: unknown): boolean; /** @category Functions */ isDistinct(obj: unknown): boolean; /** @category Functions */ isQuantifier(obj: unknown): obj is Quantifier<Name>; /** @category Functions */ isArith(obj: unknown): obj is Arith<Name>; /** @category Functions */ isArithSort(obj: unknown): obj is ArithSort<Name>; /** @category Functions */ isInt(obj: unknown): boolean; /** @category Functions */ isIntVal(obj: unknown): obj is IntNum<Name>; /** @category Functions */ isIntSort(obj: unknown): boolean; /** @category Functions */ isReal(obj: unknown): boolean; /** @category Functions */ isRealVal(obj: unknown): obj is RatNum<Name>; /** @category Functions */ isRealSort(obj: unknown): boolean; /** @category Functions */ isBitVecSort(obj: unknown): obj is BitVecSort<number, Name>; /** @category Functions */ isBitVec(obj: unknown): obj is BitVec<number, Name>; /** @category Functions */ isBitVecVal(obj: unknown): obj is BitVecNum<number, Name>; /** @category Functions */ isArraySort(obj: unknown): obj is SMTArraySort<Name>; /** @category Functions */ isArray(obj: unknown): obj is SMTArray<Name>; /** @category Functions */ isConstArray(obj: unknown): boolean; /** @category Functions */ isProbe(obj: unknown): obj is Probe<Name>; /** @category Functions */ isTactic(obj: unknown): obj is Tactic<Name>; /** @category Functions */ isAstVector(obj: unknown): obj is AstVector<Name, AnyAst<Name>>; /** * Returns whether two Asts are the same thing * @category Functions */ eqIdentity(a: Ast<Name>, b: Ast<Name>): boolean; /** @category Functions */ getVarIndex(obj: Expr<Name>): number; /** * Coerce a boolean into a Bool expression * @category Functions */ from(primitive: boolean): Bool<Name>; /** * Coerce a number to an Int or Real expression (integral numbers become Ints) * @category Functions */ from(primitive: number): IntNum<Name> | RatNum<Name>; /** * Coerce a rational into a Real expression * @category Functions */ from(primitive: CoercibleRational): RatNum<Name>; /** * Coerce a big number into a Integer expression * @category Functions */ from(primitive: bigint): IntNum<Name>; /** * Returns whatever expression was given * @category Functions */ from<E extends Expr<Name>>(expr: E): E; /** @hidden */ from(value: CoercibleToExpr<Name>): AnyExpr<Name>; /** * Sugar function for getting a model for given assertions * * ```typescript * const x = Int.const('x'); * const y = Int.const('y'); * const result = await solve(x.le(y)); * if (isModel(result)) { * console.log('Z3 found a solution'); * console.log(`x=${result.get(x)}, y=${result.get(y)}`); * } else { * console.error('No solution found'); * } * ``` * * @see {@link Solver} * @category Functions */ solve(...assertions: Bool<Name>[]): Promise<Model<Name> | 'unsat' | 'unknown'>; ///////////// // Classes // ///////////// /** * Creates a Solver * @param logic - Optional logic which the solver will use. Creates a general Solver otherwise * @category Classes */ readonly Solver: new (logic?: string) => Solver<Name>; readonly Optimize: new () => Optimize<Name>; /** * Creates an empty Model * @see {@link Solver.model} for common usage of Model * @category Classes */ readonly Model: new () => Model<Name>; /** @category Classes */ readonly AstVector: new <Item extends Ast<Name> = AnyAst<Name>>() => AstVector<Name, Item>; /** @category Classes */ readonly AstMap: new <Key extends Ast<Name> = AnyAst<Name>, Value extends Ast<Name> = AnyAst<Name>>() => AstMap< Name, Key, Value >; /** @category Classes */ readonly Tactic: new (name: string) => Tactic<Name>; ///////////// // Objects // ///////////// /** @category Expressions */ readonly Sort: SortCreation<Name>; /** @category Expressions */ readonly Function: FuncDeclCreation<Name>; /** @category Expressions */ readonly RecFunc: RecFuncCreation<Name>; /** @category Expressions */ readonly Bool: BoolCreation<Name>; /** @category Expressions */ readonly Int: IntCreation<Name>; /** @category Expressions */ readonly Real: RealCreation<Name>; /** @category Expressions */ readonly BitVec: BitVecCreation<Name>; /** @category Expressions */ readonly Array: SMTArrayCreation<Name>; //////////////// // Operations // //////////////// /** @category Operations */ Const<S extends Sort<Name>>(name: string, sort: S): SortToExprMap<S, Name>; /** @category Operations */ Consts<S extends Sort<Name>>(name: string | string[], sort: S): SortToExprMap<S, Name>[]; /** @category Operations */ FreshConst<S extends Sort<Name>>(sort: S, prefix?: string): SortToExprMap<S, Name>; /** @category Operations */ Var<S extends Sort<Name>>(idx: number, sort: S): SortToExprMap<S, Name>; // Booleans /** @category Operations */ If(condition: Probe<Name>, onTrue: Tactic<Name>, onFalse: Tactic<Name>): Tactic<Name>; /** @category Operations */ If<OnTrueRef extends CoercibleToExpr<Name>, OnFalseRef extends CoercibleToExpr<Name>>( condition: Bool<Name> | boolean, onTrue: OnTrueRef, onFalse: OnFalseRef, ): CoercibleFromMap<OnTrueRef | OnFalseRef, Name>; /** @category Operations */ Distinct(...args: CoercibleToExpr<Name>[]): Bool<Name>; /** @category Operations */ Implies(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name>; /** @category Operations */ Iff(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name>; /** @category Operations */ Eq(a: CoercibleToExpr<Name>, b: CoercibleToExpr<Name>): Bool<Name>; /** @category Operations */ Xor(a: Bool<Name> | boolean, b: Bool<Name> | boolean): Bool<Name>; /** @category Operations */ Not(a: Probe<Name>): Probe<Name>; /** @category Operations */ Not(a: Bool<Name> | boolean): Bool<Name>; /** @category Operations */ And(): Bool<Name>; /** @category Operations */ And(vector: AstVector<Name, Bool<Name>>): Bool<Name>; /** @category Operations */ And(...args: (Bool<Name> | boolean)[]): Bool<Name>; /** @category Operations */ And(...args: Probe<Name>[]): Probe<Name>; /** @category Operations */ Or(): Bool<Name>; /** @category Operations */ Or(vector: AstVector<Name, Bool<Name>>): Bool<Name>; /** @category Operations */ Or(...args: (Bool<Name> | boolean)[]): Bool<Name>; /** @category Operations */ Or(...args: Probe<Name>[]): Probe<Name>; // Quantifiers /** @category Operations */ ForAll<QVarSorts extends NonEmptySortArray<Name>>( quantifiers: ArrayIndexType<Name, QVarSorts>, body: Bool<Name>, weight?: number, ): Quantifier<Name, QVarSorts, BoolSort<Name>> & Bool<Name>; /** @category Operations */ Exists<QVarSorts extends NonEmptySortArray<Name>>( quantifiers: ArrayIndexType<Name, QVarSorts>, body: Bool<Name>, weight?: number, ): Quantifier<Name, QVarSorts, BoolSort<Name>> & Bool<Name>; /** @category Operations */ Lambda<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( quantifiers: ArrayIndexType<Name, DomainSort>, expr: SortToExprMap<RangeSort, Name>, ): Quantifier<Name, DomainSort, SMTArraySort<Name, DomainSort, RangeSort>> & SMTArray<Name, DomainSort, RangeSort>; // Arithmetic /** @category Operations */ ToReal(expr: Arith<Name> | bigint): Arith<Name>; /** @category Operations */ ToInt(expr: Arith<Name> | number | CoercibleRational | string): Arith<Name>; /** * Create an IsInt Z3 predicate * * ```typescript * const x = Real.const('x'); * await solve(IsInt(x.add("1/2")), x.gt(0), x.lt(1)) * // x = 1/2 * await solve(IsInt(x.add("1/2")), x.gt(0), x.lt(1), x.neq("1/2")) * // unsat * ``` * @category Operations */ IsInt(expr: Arith<Name> | number | CoercibleRational | string): Bool<Name>; /** * Returns a Z3 expression representing square root of a * * ```typescript * const a = Real.const('a'); * * Sqrt(a); * // a**(1/2) * ``` * @category Operations */ Sqrt(a: CoercibleToArith<Name>): Arith<Name>; /** * Returns a Z3 expression representing cubic root of a * * ```typescript * const a = Real.const('a'); * * Cbrt(a); * // a**(1/3) * ``` * @category Operations */ Cbrt(a: CoercibleToArith<Name>): Arith<Name>; // Bit Vectors /** @category Operations */ BV2Int(a: BitVec<number, Name>, isSigned: boolean): Arith<Name>; /** @category Operations */ Int2BV<Bits extends number>(a: Arith<Name> | bigint | number, bits: Bits): BitVec<Bits, Name>; /** @category Operations */ Concat(...bitvecs: BitVec<number, Name>[]): BitVec<number, Name>; /** @category Operations */ Cond(probe: Probe<Name>, onTrue: Tactic<Name>, onFalse: Tactic<Name>): Tactic<Name>; // Arith /** @category Operations */ LT(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name>; /** @category Operations */ GT(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name>; /** @category Operations */ LE(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name>; /** @category Operations */ GE(a: Arith<Name>, b: CoercibleToArith<Name>): Bool<Name>; // Bit Vectors /** @category Operations */ ULT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ UGT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ ULE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ UGE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ SLT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ SGT<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ SGE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ SLE<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Operations */ Sum(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; Sum<Bits extends number>(arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[]): BitVec<Bits, Name>; Sub(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; Sub<Bits extends number>(arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[]): BitVec<Bits, Name>; Product(arg0: Arith<Name>, ...args: CoercibleToArith<Name>[]): Arith<Name>; Product<Bits extends number>(arg0: BitVec<Bits, Name>, ...args: CoercibleToBitVec<Bits, Name>[]): BitVec<Bits, Name>; Div(arg0: Arith<Name>, arg1: CoercibleToArith<Name>): Arith<Name>; Div<Bits extends number>(arg0: BitVec<Bits, Name>, arg1: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; BUDiv<Bits extends number>(arg0: BitVec<Bits, Name>, arg1: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; Neg(a: Arith<Name>): Arith<Name>; Neg<Bits extends number>(a: BitVec<Bits, Name>): BitVec<Bits, Name>; Mod(a: Arith<Name>, b: CoercibleToArith<Name>): Arith<Name>; Mod<Bits extends number>(a: BitVec<Bits, Name>, b: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; // Arrays /** @category Operations */ Select<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name> = Sort<Name>>( array: SMTArray<Name, DomainSort, RangeSort>, ...indices: CoercibleToArrayIndexType<Name, DomainSort> ): SortToExprMap<RangeSort, Name>; /** @category Operations */ Store<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name> = Sort<Name>>( array: SMTArray<Name, DomainSort, RangeSort>, ...indicesAndValue: [ ...CoercibleToArrayIndexType<Name, DomainSort>, CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ] ): SMTArray<Name, DomainSort, RangeSort>; /** @category Operations */ Extract<Bits extends number>(hi: number, lo: number, val: BitVec<Bits, Name>): BitVec<number, Name>; /** @category Operations */ ast_from_string(s: string): Ast<Name>; /** @category Operations */ substitute(t: Expr<Name>, ...substitutions: [Expr<Name>, Expr<Name>][]): Expr<Name>; simplify(expr: Expr<Name>): Promise<Expr<Name>>; } export interface Ast<Name extends string = 'main', Ptr = unknown> { /** @hidden */ readonly __typename: 'Ast' | Sort['__typename'] | FuncDecl['__typename'] | Expr['__typename']; readonly ctx: Context<Name>; /** @hidden */ readonly ptr: Ptr; /** @virtual */ get ast(): Z3_ast; /** @virtual */ id(): number; eqIdentity(other: Ast<Name>): boolean; neqIdentity(other: Ast<Name>): boolean; sexpr(): string; hash(): number; } /** @hidden */ export interface SolverCtor<Name extends string> { new (): Solver<Name>; } export interface Solver<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'Solver'; readonly ctx: Context<Name>; readonly ptr: Z3_solver; set(key: string, value: any): void; /* TODO(ritave): Decide on how to discern between integer and float parameters set(params: Record<string, any>): void; */ push(): void; pop(num?: number): void; numScopes(): number; reset(): void; add(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): void; addAndTrack(expr: Bool<Name>, constant: Bool<Name> | string): void; assertions(): AstVector<Name, Bool<Name>>; fromString(s: string): void; check(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): Promise<CheckSatResult>; model(): Model<Name>; } export interface Optimize<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'Optimize'; readonly ctx: Context<Name>; readonly ptr: Z3_optimize; set(key: string, value: any): void; push(): void; pop(num?: number): void; add(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): void; addSoft(expr: Bool<Name>, weight: number | bigint | string | CoercibleRational, id?: number | string): void; addAndTrack(expr: Bool<Name>, constant: Bool<Name> | string): void; assertions(): AstVector<Name, Bool<Name>>; fromString(s: string): void; maximize(expr: Arith<Name>): void; minimize(expr: Arith<Name>): void; check(...exprs: (Bool<Name> | AstVector<Name, Bool<Name>>)[]): Promise<CheckSatResult>; model(): Model<Name>; } /** @hidden */ export interface ModelCtor<Name extends string> { new (): Model<Name>; } export interface Model<Name extends string = 'main'> extends Iterable<FuncDecl<Name>> { /** @hidden */ readonly __typename: 'Model'; readonly ctx: Context<Name>; readonly ptr: Z3_model; length(): number; entries(): IterableIterator<[number, FuncDecl<Name>]>; keys(): IterableIterator<number>; values(): IterableIterator<FuncDecl<Name>>; decls(): FuncDecl<Name>[]; sexpr(): string; eval(expr: Bool<Name>, modelCompletion?: boolean): Bool<Name>; eval(expr: Arith<Name>, modelCompletion?: boolean): Arith<Name>; eval<Bits extends number = number>(expr: BitVec<Bits, Name>, modelCompletion?: boolean): BitVecNum<Bits, Name>; eval(expr: Expr<Name>, modelCompletion?: boolean): Expr<Name>; get(i: number): FuncDecl<Name>; get(from: number, to: number): FuncDecl<Name>[]; get(declaration: FuncDecl<Name>): FuncInterp<Name> | Expr<Name>; get(constant: Expr<Name>): Expr<Name>; get(sort: Sort<Name>): AstVector<Name, AnyExpr<Name>>; updateValue(decl: FuncDecl<Name> | Expr<Name>, a: Ast<Name> | FuncInterp<Name>): void; addFuncInterp<DomainSort extends Sort<Name>[] = Sort<Name>[], RangeSort extends Sort<Name> = Sort<Name>>( decl: FuncDecl<Name, DomainSort, RangeSort>, defaultValue: CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ): FuncInterp<Name>; } /** * Part of {@link Context}. Used to declare uninterpreted sorts * * ```typescript * const A = context.Sort.declare('A'); * const a = context.Const('a', A); * const b = context.const('b', A); * * a.sort.eqIdentity(A) * // true * b.sort.eqIdentity(A) * // true * a.eq(b) * // a == b * ``` */ export interface SortCreation<Name extends string> { declare(name: string): Sort<Name>; } export interface Sort<Name extends string = 'main'> extends Ast<Name, Z3_sort> { /** @hidden */ readonly __typename: | 'Sort' | BoolSort['__typename'] | ArithSort['__typename'] | BitVecSort['__typename'] | SMTArraySort['__typename']; kind(): Z3_sort_kind; /** @virtual */ subsort(other: Sort<Name>): boolean; /** @virtual */ cast(expr: CoercibleToExpr<Name>): Expr<Name>; name(): string | number; } /** * @category Functions */ export interface FuncEntry<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'FuncEntry'; readonly ctx: Context<Name>; readonly ptr: Z3_func_entry; numArgs(): number; argValue(i: number): Expr<Name>; value(): Expr<Name>; } /** * @category Functions */ export interface FuncInterp<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'FuncInterp'; readonly ctx: Context<Name>; readonly ptr: Z3_func_interp; elseValue(): Expr<Name>; numEntries(): number; arity(): number; entry(i: number): FuncEntry<Name>; addEntry(args: Expr<Name>[], value: Expr<Name>): void; } /** @hidden */ export type FuncDeclSignature<Name extends string> = [Sort<Name>, Sort<Name>, ...Sort<Name>[]]; /** * Part of {@link Context}. Used to declare functions * @category Functions */ export interface FuncDeclCreation<Name extends string> { /** * Declare a new function * * ```typescript * const f = ctx.Function.declare('f', ctx.Bool.sort(), ctx.Real.sort(), ctx.Int.sort()) * * f.call(true, "1/3").eq(5) * // f(true, 1/3) == 5 * ``` * @param name Name of the function * @param signature The domains, and last parameter - the range of the function */ declare<DomainSort extends Sort<Name>[], RangeSort extends Sort<Name>>( name: string, ...signature: [...DomainSort, RangeSort] ): FuncDecl<Name, DomainSort, RangeSort>; fresh<DomainSort extends Sort<Name>[], RangeSort extends Sort<Name>>( ...signature: [...DomainSort, RangeSort] ): FuncDecl<Name, DomainSort, RangeSort>; } /** * @category Functions */ export interface RecFuncCreation<Name extends string> { declare(name: string, ...signature: FuncDeclSignature<Name>): FuncDecl<Name>; addDefinition(f: FuncDecl<Name>, args: Expr<Name>[], body: Expr<Name>): void; } /** * @category Functions */ export interface FuncDecl< Name extends string = 'main', DomainSort extends Sort<Name>[] = Sort<Name>[], RangeSort extends Sort<Name> = Sort<Name>, > extends Ast<Name, Z3_func_decl> { /** @hidden */ readonly __typename: 'FuncDecl'; name(): string | number; arity(): number; domain<T extends number>(i: T): DomainSort[T]; range(): RangeSort; kind(): Z3_decl_kind; params(): (number | string | Sort<Name> | Expr<Name> | FuncDecl<Name>)[]; call(...args: CoercibleToArrayIndexType<Name, DomainSort>): SortToExprMap<RangeSort, Name>; } export interface Expr<Name extends string = 'main', S extends Sort<Name> = AnySort<Name>, Ptr = unknown> extends Ast<Name, Ptr> { /** @hidden */ readonly __typename: | 'Expr' | Bool['__typename'] | Arith['__typename'] | BitVec['__typename'] | SMTArray['__typename']; get sort(): S; eq(other: CoercibleToExpr<Name>): Bool<Name>; neq(other: CoercibleToExpr<Name>): Bool<Name>; params(): ReturnType<FuncDecl<Name>['params']>; name(): ReturnType<FuncDecl<Name>['name']>; decl(): FuncDecl<Name>; numArgs(): number; arg(i: number): AnyExpr<Name>; children(): AnyExpr<Name>[]; } /** @category Booleans */ export interface BoolSort<Name extends string = 'main'> extends Sort<Name> { /** @hidden */ readonly __typename: 'BoolSort'; cast(expr: Bool<Name> | boolean): Bool<Name>; cast(expr: CoercibleToExpr<Name>): never; } /** @category Booleans */ export interface BoolCreation<Name extends string = 'main'> { sort(): BoolSort<Name>; const(name: string): Bool<Name>; consts(names: string | string[]): Bool<Name>[]; vector(prefix: string, count: number): Bool<Name>[]; fresh(prefix?: string): Bool<Name>; val(value: boolean): Bool<Name>; } /** @category Booleans */ export interface Bool<Name extends string = 'main'> extends Expr<Name, BoolSort<Name>, Z3_ast> { /** @hidden */ readonly __typename: 'Bool' | 'NonLambdaQuantifier'; not(): Bool<Name>; and(other: Bool<Name> | boolean): Bool<Name>; or(other: Bool<Name> | boolean): Bool<Name>; xor(other: Bool<Name> | boolean): Bool<Name>; implies(other: Bool<Name> | boolean): Bool<Name>; } // TODO: properly implement pattern /** @category Quantifiers */ export interface Pattern<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'Pattern'; } /** * A Sort that represents Integers or Real numbers * @category Arithmetic */ export interface ArithSort<Name extends string = 'main'> extends Sort<Name> { /** @hidden */ readonly __typename: 'ArithSort'; cast(other: bigint | number | string): IntNum<Name> | RatNum<Name>; cast(other: CoercibleRational | RatNum<Name>): RatNum<Name>; cast(other: IntNum<Name>): IntNum<Name>; cast(other: bigint | number | string | Bool<Name> | Arith<Name> | CoercibleRational): Arith<Name>; cast(other: CoercibleToExpr<Name> | string): never; } /** @category Arithmetic */ export interface IntCreation<Name extends string> { sort(): ArithSort<Name>; const(name: string): Arith<Name>; consts(names: string | string[]): Arith<Name>[]; vector(prefix: string, count: number): Arith<Name>[]; fresh(prefix?: string): Arith<Name>; val(value: bigint | number | string): IntNum<Name>; } /** @category Arithmetic */ export interface RealCreation<Name extends string> { sort(): ArithSort<Name>; const(name: string): Arith<Name>; consts(names: string | string[]): Arith<Name>[]; vector(prefix: string, count: number): Arith<Name>[]; fresh(prefix?: string): Arith<Name>; val(value: number | string | bigint | CoercibleRational): RatNum<Name>; } /** * Represents Integer or Real number expression * @category Arithmetic */ export interface Arith<Name extends string = 'main'> extends Expr<Name, ArithSort<Name>, Z3_ast> { /** @hidden */ readonly __typename: 'Arith' | IntNum['__typename'] | RatNum['__typename']; /** * Adds two numbers together */ add(other: CoercibleToArith<Name>): Arith<Name>; /** * Multiplies two numbers together */ mul(other: CoercibleToArith<Name>): Arith<Name>; /** * Subtract second number from the first one */ sub(other: CoercibleToArith<Name>): Arith<Name>; /** * Applies power to the number * * ```typescript * const x = Int.const('x'); * * await solve(x.pow(2).eq(4), x.lt(0)); // x**2 == 4, x < 0 * // x=-2 * ``` */ pow(exponent: CoercibleToArith<Name>): Arith<Name>; /** * Divides the number by the second one */ div(other: CoercibleToArith<Name>): Arith<Name>; /** * Returns a number modulo second one * * ```typescript * const x = Int.const('x'); * * await solve(x.mod(7).eq(1), x.gt(7)) // x % 7 == 1, x > 7 * // x=8 * ``` */ mod(other: CoercibleToArith<Name>): Arith<Name>; /** * Returns a negation of the number */ neg(): Arith<Name>; /** * Return whether the number is less or equal than the second one (`<=`) */ le(other: CoercibleToArith<Name>): Bool<Name>; /** * Returns whether the number is less than the second one (`<`) */ lt(other: CoercibleToArith<Name>): Bool<Name>; /** * Returns whether the number is greater than the second one (`>`) */ gt(other: CoercibleToArith<Name>): Bool<Name>; /** * Returns whether the number is greater or equal than the second one (`>=`) */ ge(other: CoercibleToArith<Name>): Bool<Name>; } /** * A constant Integer value expression * @category Arithmetic */ export interface IntNum<Name extends string = 'main'> extends Arith<Name> { /** @hidden */ readonly __typename: 'IntNum'; value(): bigint; asString(): string; asBinary(): string; } /** * A constant Rational value expression * * ```typescript * const num = Real.val('1/3'); * * num.asString() * // '1/3' * num.value * // { numerator: 1n, denominator: 3n } * num.asNumber() * // 0.3333333333333333 * ``` * @category Arithmetic */ export interface RatNum<Name extends string = 'main'> extends Arith<Name> { /** @hidden */ readonly __typename: 'RatNum'; value(): { numerator: bigint; denominator: bigint }; numerator(): IntNum<Name>; denominator(): IntNum<Name>; asNumber(): number; asDecimal(prec?: number): string; asString(): string; } /** * A Sort representing Bit Vector numbers of specified {@link BitVecSort.size size} * * @typeParam Bits - A number representing amount of bits for this sort * @category Bit Vectors */ export interface BitVecSort<Bits extends number = number, Name extends string = 'main'> extends Sort<Name> { /** @hidden */ readonly __typename: 'BitVecSort'; /** * The amount of bits inside the sort * * ```typescript * const x = BitVec.const('x', 32); * * console.log(x.sort.size) * // 32 * ``` */ size(): Bits; cast(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; cast(other: CoercibleToExpr<Name>): Expr<Name>; } /** @category Bit Vectors */ export interface BitVecCreation<Name extends string> { sort<Bits extends number = number>(bits: Bits): BitVecSort<Bits, Name>; const<Bits extends number = number>(name: string, bits: Bits | BitVecSort<Bits, Name>): BitVec<Bits, Name>; consts<Bits extends number = number>( names: string | string[], bits: Bits | BitVecSort<Bits, Name>, ): BitVec<Bits, Name>[]; val<Bits extends number = number>( value: bigint | number | boolean, bits: Bits | BitVecSort<Bits, Name>, ): BitVecNum<Bits, Name>; } /** * Represents Bit Vector expression * @category Bit Vectors */ export interface BitVec<Bits extends number = number, Name extends string = 'main'> extends Expr<Name, BitVecSort<Bits, Name>, Z3_ast> { /** @hidden */ readonly __typename: 'BitVec' | BitVecNum['__typename']; /** * The amount of bits of this BitVectors sort * * ```typescript * const x = BitVec.const('x', 32); * * x.size * // 32 * * const Y = BitVec.sort(8); * const y = BitVec.const('y', Y); * * y.size * // 8 * ``` */ size(): Bits; /** @category Arithmetic */ add(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ mul(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ sub(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ sdiv(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ udiv(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ smod(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ urem(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ srem(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** @category Arithmetic */ neg(): BitVec<Bits, Name>; /** * Creates a bitwise-or between two bitvectors * @category4 Bitwise */ or(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a bitwise-and between two bitvectors * @category Bitwise */ and(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a bitwise-not-and between two bitvectors * @category Bitwise */ nand(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a bitwise-exclusive-or between two bitvectors * @category Bitwise */ xor(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a bitwise-exclusive-not-or between two bitvectors * @category Bitwise */ xnor(other: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates an arithmetic shift right operation * @category Bitwise */ shr(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a logical shift right operation * @category Bitwise */ lshr(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a shift left operation * @category Bitwise */ shl(count: CoercibleToBitVec<Bits, Name>): BitVec<Bits, Name>; /** * Creates a rotate right operation * @category Bitwise */ rotateRight(count: CoercibleToBitVec<number, Name>): BitVec<Bits, Name>; /** * Creates a rotate left operation * @category Bitwise */ rotateLeft(count: CoercibleToBitVec<number, Name>): BitVec<Bits, Name>; /** * Creates a bitwise not operation * @category Bitwise */ not(): BitVec<Bits, Name>; /** * Creates an extraction operation. * Bits are indexed starting from 1 from the most right one (least significant) increasing to left (most significant) * * ```typescript * const x = BitVec.const('x', 8); * * x.extract(6, 2) * // Extract(6, 2, x) * x.extract(6, 2).sort * // BitVec(5) * ``` * @param high The most significant bit to be extracted * @param low The least significant bit to be extracted */ extract(high: number, low: number): BitVec<number, Name>; signExt(count: number): BitVec<number, Name>; zeroExt(count: number): BitVec<number, Name>; repeat(count: number): BitVec<number, Name>; /** * Creates a signed less-or-equal operation (`<=`) * @category Comparison */ sle(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates an unsigned less-or-equal operation (`<=`) * @category Comparison */ ule(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates a signed less-than operation (`<`) * @category Comparison */ slt(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates an unsigned less-than operation (`<`) * @category Comparison */ ult(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates a signed greater-or-equal operation (`>=`) * @category Comparison */ sge(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates an unsigned greater-or-equal operation (`>=`) * @category Comparison */ uge(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates a signed greater-than operation (`>`) * @category Comparison */ sgt(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates an unsigned greater-than operation (`>`) * @category Comparison */ ugt(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** * Creates a reduction-and operation */ redAnd(): BitVec<number, Name>; /** * Creates a reduction-or operation */ redOr(): BitVec<number, Name>; /** @category Boolean */ addNoOverflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name>; /** @category Boolean */ addNoUnderflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Boolean */ subNoOverflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Boolean */ subNoUndeflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name>; /** @category Boolean */ sdivNoOverflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Boolean */ mulNoOverflow(other: CoercibleToBitVec<Bits, Name>, isSigned: boolean): Bool<Name>; /** @category Boolean */ mulNoUndeflow(other: CoercibleToBitVec<Bits, Name>): Bool<Name>; /** @category Boolean */ negNoOverflow(): Bool<Name>; } /** * Represents Bit Vector constant value * @category Bit Vectors */ export interface BitVecNum<Bits extends number = number, Name extends string = 'main'> extends BitVec<Bits, Name> { /** @hidden */ readonly __typename: 'BitVecNum'; value(): bigint; asSignedValue(): bigint; asString(): string; asBinaryString(): string; } /** * A Sort representing a SMT Array with range of sort {@link SMTArraySort.range range} * and a domain of sort {@link SMTArraySort.domain domain} * * @typeParam DomainSort The sort of the domain of the array (provided as an array of sorts) * @typeParam RangeSort The sort of the array range * @category Arrays */ export interface SMTArraySort< Name extends string = 'main', DomainSort extends NonEmptySortArray<Name> = [Sort<Name>, ...Sort<Name>[]], RangeSort extends AnySort<Name> = AnySort<Name>, > extends Sort<Name> { /** @hidden */ readonly __typename: 'ArraySort'; /** * The sort of the first dimension of the domain */ domain(): DomainSort[0]; /** * The sort of the i-th (0-indexed) dimension of the domain * * @param i index of the dimension of the domain being requested */ domain_n<T extends number>(i: T): DomainSort[T]; /** * The sort of the range */ range(): RangeSort; } /** @category Arrays */ export interface SMTArrayCreation<Name extends string> { sort<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( ...sig: [...DomainSort, RangeSort] ): SMTArraySort<Name, DomainSort, RangeSort>; const<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( name: string, ...sig: [...DomainSort, RangeSort] ): SMTArray<Name, DomainSort, RangeSort>; consts<DomainSort extends NonEmptySortArray<Name>, RangeSort extends Sort<Name>>( names: string | string[], ...sig: [...DomainSort, RangeSort] ): SMTArray<Name, DomainSort, RangeSort>[]; K<DomainSort extends AnySort<Name>, RangeSort extends AnySort<Name>>( domain: DomainSort, value: SortToExprMap<RangeSort, Name>, ): SMTArray<Name, [DomainSort], RangeSort>; } export type NonEmptySortArray<Name extends string = 'main'> = [Sort<Name>, ...Array<Sort<Name>>]; export type ArrayIndexType<Name extends string, DomainSort extends Sort<Name>[]> = [ ...{ [Key in keyof DomainSort]: DomainSort[Key] extends AnySort<Name> ? SortToExprMap<DomainSort[Key], Name> : DomainSort[Key]; }, ]; export type CoercibleToArrayIndexType<Name extends string, DomainSort extends Sort<Name>[]> = [ ...{ [Key in keyof DomainSort]: DomainSort[Key] extends AnySort<Name> ? CoercibleToMap<SortToExprMap<DomainSort[Key], Name>, Name> : DomainSort[Key]; }, ]; /** * Represents Array expression * * @typeParam DomainSort The sort of the domain of the array (provided as an array of sorts) * @typeParam RangeSort The sort of the array range * @category Arrays */ export interface SMTArray< Name extends string = 'main', DomainSort extends NonEmptySortArray<Name> = [Sort<Name>, ...Sort<Name>[]], RangeSort extends Sort<Name> = Sort<Name>, > extends Expr<Name, SMTArraySort<Name, DomainSort, RangeSort>, Z3_ast> { /** @hidden */ readonly __typename: 'Array' | 'Lambda'; domain(): DomainSort[0]; domain_n<T extends number>(i: T): DomainSort[T]; range(): RangeSort; select(...indices: CoercibleToArrayIndexType<Name, DomainSort>): SortToExprMap<RangeSort, Name>; /** * value should be coercible to RangeSort * * @param indicesAndValue (idx0, idx1, ..., idxN, value) */ store( ...indicesAndValue: [ ...CoercibleToArrayIndexType<Name, DomainSort>, CoercibleToMap<SortToExprMap<RangeSort, Name>, Name>, ] ): SMTArray<Name, DomainSort, RangeSort>; } /** * Defines the expression type of the body of a quantifier expression * * @category Quantifiers */ export type BodyT< Name extends string = 'main', QVarSorts extends NonEmptySortArray<Name> = [Sort<Name>, ...Sort<Name>[]], QSort extends BoolSort<Name> | SMTArraySort<Name, QVarSorts> = BoolSort<Name> | SMTArraySort<Name, QVarSorts>, > = QSort extends BoolSort<Name> ? Bool<Name> : QSort extends SMTArray<Name, QVarSorts, infer RangeSort> ? SortToExprMap<RangeSort, Name> : never; /** @category Quantifiers */ export interface Quantifier< Name extends string = 'main', QVarSorts extends NonEmptySortArray<Name> = [Sort<Name>, ...Sort<Name>[]], QSort extends BoolSort<Name> | SMTArraySort<Name, QVarSorts> = BoolSort<Name> | SMTArraySort<Name, QVarSorts>, > extends Expr<Name, QSort> { readonly __typename: 'NonLambdaQuantifier' | 'Lambda'; is_forall(): boolean; is_exists(): boolean; is_lambda(): boolean; weight(): number; num_patterns(): number; pattern(i: number): Pattern<Name>; num_no_patterns(): number; no_pattern(i: number): Expr<Name>; body(): BodyT<Name, QVarSorts, QSort>; num_vars(): number; var_name(i: number): string | number; var_sort<T extends number>(i: T): QVarSorts[T]; children(): [BodyT<Name, QVarSorts, QSort>]; } export interface Probe<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'Probe'; readonly ctx: Context<Name>; readonly ptr: Z3_probe; } /** @hidden */ export interface TacticCtor<Name extends string> { new (name: string): Tactic<Name>; } export interface Tactic<Name extends string = 'main'> { /** @hidden */ readonly __typename: 'Tactic'; readonly ctx: Context<Name>; readonly ptr: Z3_tactic; } /** @hidden */ export interface AstVectorCtor<Name extends string> { new <Item extends Ast<Name> = AnyAst<Name>>(): AstVector<Name, Item>; } /** * Stores multiple {@link Ast} objects * * ```typescript * const vector = new AstVector<Bool>(); * vector.push(Bool.val(5)); * vector.push(Bool.const('x')) * * vector.length * // 2 * vector.get(1) * // x * [...vector.values()] * // [2, x] * ``` */ export interface AstVector<Name extends string = 'main', Item extends Ast<Name> = AnyAst<Name>> extends Iterable<Item> { /** @hidden */ readonly __typename: 'AstVector'; readonly ctx: Context<Name>; readonly ptr: Z3_ast_vector; length(): number; entries(): IterableIterator<[number, Item]>; keys(): IterableIterator<number>; values(): IterableIterator<Item>; get(i: number): Item; get(from: number, to: number): Item[]; set(i: number, v: Item): void; push(v: Item): void; resize(size: number): void; has(v: Item): boolean; sexpr(): string; } /** @hidden */ export interface AstMapCtor<Name extends string> { new <Key extends Ast<Name> = AnyAst<Name>, Value extends Ast<Name> = AnyAst<Name>>(): AstMap<Name, Key, Value>; } /** * Stores a mapping between different {@link Ast} objects * * ```typescript * const map = new Map<Arith, Bool>(); * const x = Int.const('x') * const y = Int.const('y') * map.set(x, Bool.val(true)) * map.Set(y, Bool.val(false)) * * map.size * // 2 * map.has(x) * // true * [...map.entries()] * // [[x, true], [y, false]] * map.clear() * map.size * // 0 * ``` */ export interface AstMap< Name extends string = 'main', Key extends Ast<Name> = AnyAst<Name>, Value extends Ast<Name> = AnyAst<Name>, > extends Iterable<[Key, Value]> { /** @hidden */ readonly __typename: 'AstMap'; readonly ctx: Context<Name>; readonly ptr: Z3_ast_map; get size(): number; entries(): IterableIterator<[Key, Value]>; keys(): AstVector<Name, Key>; values(): IterableIterator<Value>; get(key: Key): Value | undefined; set(key: Key, value: Value): void; delete(key: Key): void; clear(): void; has(key: Key): boolean; sexpr(): string; } /** * @category Global */ export interface Z3HighLevel { // Global functions enableTrace(tag: string): void; disableTrace(tag: string): void; getVersion(): { major: number; minor: number; build_number: number; revision_number: number; }; getVersionString(): string; getFullVersion(): string; openLog(filename: string): boolean; appendLog(s: string): void; /** * Set a Z3 parameter * * ```typescript * setParam('pp.decimal', true); * ``` */ setParam(key: string, value: any): void; /** * Set multiple Z3 parameters at once * * ```typescript * setParam({ * 'pp.decimal': true, * 'pp.decimal_precision': 20 * }); * ``` */ setParam(key: Record<string, any>): void; /** * Resets all Z3 parameters */ resetParams(): void; /** * Returns a global Z3 parameter */ getParam(name: string): string | null; /** * Use this to create new contexts * @see {@link Context} */ readonly Context: ContextCtor; }
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/src/high-level/types.ts
types.ts
import process from 'process'; import { init, Z3_error_code } from '../../build/node'; // demonstrates use of the raw API (async () => { let { em, Z3 } = await init(); Z3.global_param_set('verbose', '10'); console.log('verbosity:', Z3.global_param_get('verbose')); let config = Z3.mk_config(); let ctx = Z3.mk_context_rc(config); Z3.del_config(config); let unicodeStr = [...'hello™'].map(x => x.codePointAt(0)!); let strAst = Z3.mk_u32string(ctx, unicodeStr); Z3.inc_ref(ctx, strAst); console.log(Z3.is_string(ctx, strAst)); console.log(Z3.get_string(ctx, strAst)); console.log(Z3.get_string_contents(ctx, strAst, unicodeStr.length)); let bv = Z3.mk_bv_numeral(ctx, [true, true, false]); let bs = Z3.mk_ubv_to_str(ctx, bv); console.log(Z3.ast_to_string(ctx, bs)); let intSort = Z3.mk_int_sort(ctx); let big = Z3.mk_int64(ctx, 42n, intSort); console.log(Z3.get_numeral_string(ctx, big)); console.log(Z3.get_numeral_int64(ctx, big)); console.log(Z3.get_version()); let head_tail = [Z3.mk_string_symbol(ctx, 'car'), Z3.mk_string_symbol(ctx, 'cdr')]; let nil_con = Z3.mk_constructor(ctx, Z3.mk_string_symbol(ctx, 'nil'), Z3.mk_string_symbol(ctx, 'is_nil'), [], [], []); let cons_con = Z3.mk_constructor( ctx, Z3.mk_string_symbol(ctx, 'cons'), Z3.mk_string_symbol(ctx, 'is_cons'), head_tail, [null, null], [0, 0], ); let cell = Z3.mk_datatype(ctx, Z3.mk_string_symbol(ctx, 'cell'), [nil_con, cons_con]); console.log(Z3.query_constructor(ctx, nil_con, 0)); console.log(Z3.query_constructor(ctx, cons_con, 2)); if (Z3.get_error_code(ctx) !== Z3_error_code.Z3_OK) { throw new Error('something failed: ' + Z3.get_error_msg(ctx, Z3.get_error_code(ctx))); } await Z3.eval_smtlib2_string(ctx, '(simplify)'); if (Z3.get_error_code(ctx) === Z3_error_code.Z3_OK) { throw new Error('expected call to eval_smtlib2_string with invalid argument to fail'); } console.log('confirming error messages work:', Z3.get_error_msg(ctx, Z3.get_error_code(ctx))); Z3.dec_ref(ctx, strAst); Z3.del_context(ctx); em.PThread.terminateAllThreads(); })().catch(e => { console.error('error', e); process.exit(1); });
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/examples/low-level/example-raw.ts
example-raw.ts
import { init } from '../../build/node'; import type { Solver, Arith } from '../../build/node'; // solve the "miracle sudoku" // https://www.youtube.com/watch?v=yKf9aUIxdb4 // most of the interesting stuff is in `solve` // the process is: // - parse the board // - create a Solver // - create a Z3.Int variable for each square // - for known cells, add a constraint which says the variable for that cell equals that value // - add the usual uniqueness constraints // - add the special "miracle sudoku" constraints // - call `await solver.check()` // - if the result is "sat", the board is solvable // - call `solver.model()` to get a model, i.e. a concrete assignment of variables which satisfies the model // - for each variable, call `model.evaluate(v)` to recover its value function parseSudoku(str: string) { // derive a list of { row, col, val } records, one for each specified position // from a string like // ....1..3. // ..9..5..8 // 8.4..6.25 // ......6.. // ..8..4... // 12..87... // 3..9..2.. // .65..8... // 9........ let cells = []; let lines = str.trim().split('\n'); if (lines.length !== 9) { throw new Error(`expected 9 lines, got ${lines.length}`); } for (let row = 0; row < 9; ++row) { let line = lines[row].trim(); if (line.length !== 9) { throw new Error(`expected line of length 9, got length ${line.length}`); } for (let col = 0; col < 9; ++col) { let char = line[col]; if (char === '.') { continue; } if (char < '1' || char > '9') { throw new Error(`expected digit or '.', got ${char}`); } cells.push({ row, col, value: char.codePointAt(0)! - 48 /* '0' */ }); } } return cells; } (async () => { let { Context, em } = await init(); // if you use 'main' as your context name, you won't need to name it in types like Solver // if you're creating multiple contexts, give them different names // then the type system will prevent you from mixing them let Z3 = Context('main'); function addSudokuConstraints(solver: Solver, cells: Arith[][]) { // the usual constraints: // every square is between 1 and 9 for (let row of cells) { for (let cell of row) { solver.add(cell.ge(1)); solver.add(cell.le(9)); } } // values in each row are unique for (let row of cells) { solver.add(Z3.Distinct(...row)); } // values in each column are unique for (let col = 0; col < 9; ++col) { solver.add(Z3.Distinct(...cells.map(row => row[col]))); } // values in each 3x3 subdivision are unique for (let suprow = 0; suprow < 3; ++suprow) { for (let supcol = 0; supcol < 3; ++supcol) { let square = []; for (let row = 0; row < 3; ++row) { for (let col = 0; col < 3; ++col) { square.push(cells[suprow * 3 + row][supcol * 3 + col]); } } solver.add(Z3.Distinct(...square)); } } } function applyOffsets(x: number, y: number, offsets: [number, number][]) { let out = []; for (let offset of offsets) { let rx = x + offset[0]; let ry = y + offset[1]; if (rx >= 0 && rx < 9 && ry >= 0 && ry < 8) { out.push({ x: rx, y: ry }); } } return out; } function addMiracleConstraints(s: Solver, cells: Arith[][]) { // the special "miracle sudoku" constraints // any two cells separated by a knight's move or a kings move cannot contain the same digit let knightOffets: [number, number][] = [ [1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], ]; let kingOffsets: [number, number][] = [ [1, 1], [1, -1], [-1, 1], [-1, -1], ]; // skipping immediately adjacent because those are covered by normal sudoku rules let allOffets = [...knightOffets, ...kingOffsets]; for (let row = 0; row < 9; ++row) { for (let col = 0; col < 9; ++col) { for (let { x, y } of applyOffsets(row, col, allOffets)) { s.add(cells[row][col].neq(cells[x][y])); } } } // any two orthogonally adjacent cells cannot contain consecutive digits let orthoOffsets: [number, number][] = [ [0, 1], [0, -1], [1, 0], [-1, 0], ]; for (let row = 0; row < 9; ++row) { for (let col = 0; col < 9; ++col) { for (let { x, y } of applyOffsets(row, col, orthoOffsets)) { s.add(cells[row][col].sub(cells[x][y]).neq(1)); } } } } async function solve(str: string) { let solver = new Z3.Solver(); let cells = Array.from({ length: 9 }, (_, col) => Array.from({ length: 9 }, (_, row) => Z3.Int.const(`c_${row}_${col}`))); for (let { row, col, value } of parseSudoku(str)) { solver.add(cells[row][col].eq(value)); } addSudokuConstraints(solver, cells); addMiracleConstraints(solver, cells); // remove this line to solve normal sudokus let start = Date.now(); console.log('starting... this may take a minute or two'); let check = await solver.check(); console.log(`problem was determined to be ${check} in ${Date.now() - start} ms`); if (check === 'sat') { let model = solver.model(); let str = ''; for (let row = 0; row < 9; ++row) { for (let col = 0; col < 9; ++col) { str += model.eval(cells[row][col]).toString() + (col === 8 ? '' : ' '); if (col === 2 || col === 5) { str += ' '; } } str += '\n'; if (row === 2 || row === 5) { str += '\n'; } } console.log(str); } } await solve(` ......... ......... ......... ......... ..1...... ......2.. ......... ......... ......... `); em.PThread.terminateAllThreads(); })().catch(e => { console.error('error', e); process.exit(1); });
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/examples/high-level/miracle-sudoku.ts
miracle-sudoku.ts
import path from 'path'; import { asyncFuncs } from './async-fns'; import { functions } from './parse-api'; export function makeCCWrapper() { let wrappers = []; for (let fnName of asyncFuncs) { let fn = functions.find(f => f.name === fnName); if (fn == null) { throw new Error(`could not find definition for ${fnName}`); } let wrapper; if (fn.cRet === 'Z3_string') { wrapper = `wrapper_str`; } else if (['int', 'unsigned', 'void'].includes(fn.cRet) || fn.cRet.startsWith('Z3_')) { wrapper = `wrapper`; } else { throw new Error(`async function with unknown return type ${fn.cRet}`); } wrappers.push( ` extern "C" void async_${fn.name}(${fn.params .map(p => `${p.isConst ? 'const ' : ''}${p.cType}${p.isPtr ? '*' : ''} ${p.name}${p.isArray ? '[]' : ''}`) .join(', ')}) { ${wrapper}<decltype(&${fn.name}), &${fn.name}>(${fn.params.map(p => `${p.name}`).join(', ')}); } `.trim(), ); } return `// THIS FILE IS AUTOMATICALLY GENERATED BY ${path.basename(__filename)} // DO NOT EDIT IT BY HAND #include <thread> #include <emscripten.h> #include "../../z3.h" template<typename Fn, Fn fn, typename... Args> void wrapper(Args&&... args) { std::thread t([...args = std::forward<Args>(args)] { try { auto result = fn(args...); MAIN_THREAD_ASYNC_EM_ASM({ resolve_async($0); }, result); } catch (std::exception& e) { MAIN_THREAD_ASYNC_EM_ASM({ reject_async(new Error(UTF8ToString($0))); }, e.what()); } catch (...) { MAIN_THREAD_ASYNC_EM_ASM({ reject_async('failed with unknown exception'); }); } }); t.detach(); } template<typename Fn, Fn fn, typename... Args> void wrapper_str(Args&&... args) { std::thread t([...args = std::forward<Args>(args)] { try { auto result = fn(args...); MAIN_THREAD_ASYNC_EM_ASM({ resolve_async(UTF8ToString($0)); }, result); } catch (std::exception& e) { MAIN_THREAD_ASYNC_EM_ASM({ reject_async(new Error(UTF8ToString($0))); }, e.what()); } catch (...) { MAIN_THREAD_ASYNC_EM_ASM({ reject_async(new Error('failed with unknown exception')); }); } }); t.detach(); } class Z3Exception : public std::exception { public: const std::string m_msg; Z3Exception(const std::string& msg) : m_msg(msg) {} virtual const char* what() const throw () { return m_msg.c_str(); } }; void throwy_error_handler(Z3_context ctx, Z3_error_code c) { throw Z3Exception(Z3_get_error_msg(ctx, c)); } void noop_error_handler(Z3_context ctx, Z3_error_code c) { // pass } extern "C" void set_throwy_error_handler(Z3_context ctx) { Z3_set_error_handler(ctx, throwy_error_handler); } extern "C" void set_noop_error_handler(Z3_context ctx) { Z3_set_error_handler(ctx, noop_error_handler); } ${wrappers.join('\n\n')} `; } if (require.main === module) { console.log(makeCCWrapper()); }
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/scripts/make-cc-wrapper.ts
make-cc-wrapper.ts
import assert from 'assert'; import fs from 'fs'; import path from 'path'; import prettier from 'prettier'; import { asyncFuncs } from './async-fns'; import { enums, Func, FuncParam, functions, primitiveTypes, types } from './parse-api'; assert(process.argv.length === 4, `Usage: ${process.argv[0]} ${process.argv[1]} wrapperFilePath typesFilePath`); const wrapperFilePath = process.argv[2]; const typesFilePath = process.argv[3]; function makeTsWrapper() { const subtypes = { __proto__: null, Z3_sort: 'Z3_ast', Z3_func_decl: 'Z3_ast', } as unknown as Record<string, string>; const makePointerType = (t: string) => `export type ${t} = ` + (t in subtypes ? `Subpointer<'${t}', '${subtypes[t]}'>;` : `Pointer<'${t}'>;`); // this supports a up to 6 out integers/pointers // or up to 3 out int64s const BYTES_TO_ALLOCATE_FOR_OUT_PARAMS = 24; const CUSTOM_IMPLEMENTATIONS = ['Z3_mk_context', 'Z3_mk_context_rc']; function toEmType(type: string) { if (type in primitiveTypes) { type = primitiveTypes[type]; } if (['boolean', 'number', 'string', 'bigint', 'void'].includes(type)) { return type; } if (type.startsWith('Z3_')) { return 'number'; } throw new Error(`unknown parameter type ${type}`); } function isZ3PointerType(type: string) { return type.startsWith('Z3_'); } function toEm(p: string | FuncParam) { if (typeof p === 'string') { // we've already set this, e.g. by replacing it with an expression return p; } let { type } = p; if (p.kind === 'out') { throw new Error(`unknown out parameter type ${JSON.stringify(p)}`); } if (p.isArray) { if (isZ3PointerType(type) || type === 'unsigned' || type === 'int') { // this works for nullables also because null coerces to 0 return `intArrayToByteArr(${p.name} as unknown as number[])`; } else if (type === 'boolean') { return `boolArrayToByteArr(${p.name})`; } else { throw new Error(`only know how to deal with arrays of int/bool (got ${type})`); } } if (type in primitiveTypes) { type = primitiveTypes[type]; } if (['boolean', 'number', 'bigint', 'string'].includes(type)) { return p.name; } if (type.startsWith('Z3_')) { return p.name; } throw new Error(`unknown parameter type ${JSON.stringify(p)}`); } const isInParam = (p: FuncParam) => p.kind !== undefined && ['in', 'in_array'].includes(p.kind); function wrapFunction(fn: Func) { if (CUSTOM_IMPLEMENTATIONS.includes(fn.name)) { return null; } let inParams = fn.params.filter(isInParam); let outParams = fn.params.map((p, idx) => ({ ...p, idx })).filter(p => !isInParam(p)); // we'll figure out how to deal with these cases later let unknownInParam = inParams.find( p => p.isPtr || p.type === 'Z3_char_ptr' || (p.isArray && !(isZ3PointerType(p.type) || p.type === 'unsigned' || p.type === 'int' || p.type === 'boolean')), ); if (unknownInParam) { console.error(`skipping ${fn.name} - unknown in parameter ${JSON.stringify(unknownInParam)}`); return null; } if (fn.ret === 'Z3_char_ptr') { console.error(`skipping ${fn.name} - returns a string or char pointer`); return null; } // console.error(fn.name); let isAsync = asyncFuncs.includes(fn.name); let trivial = !['string', 'boolean', 'unsigned'].includes(fn.ret) && !fn.nullableRet && outParams.length === 0 && !inParams.some(p => p.type === 'string' || p.isArray || p.nullable); let name = fn.name.startsWith('Z3_') ? fn.name.substring(3) : fn.name; const params: (string | null)[] = inParams.map(p => { let type = p.type; if (p.isArray && p.nullable) { type = `(${type} | null)[]`; } else if (p.isArray) { type = `${type}[]`; } else if (p.nullable) { type = `${type} | null`; } return `${p.name}: ${type}`; }); if (trivial && isAsync) { // i.e. and async return `${name}: function (${params.join(', ')}): Promise<${fn.ret}> { return Mod.async_call(Mod._async_${fn.name}, ${fn.params.map(toEm).join(', ')}); }`; } if (trivial) { return `${name}: Mod._${fn.name} as ((${params.join(', ')}) => ${fn.ret})`; } // otherwise fall back to ccall const ctypes = fn.params.map(p => p.kind === 'in_array' ? 'array' : p.kind === 'out_array' ? 'number' : p.isPtr ? 'number' : toEmType(p.type), ); let prefix = ''; let infix = ''; let rv = 'ret'; let suffix = ''; const args: (string | FuncParam)[] = fn.params; let arrayLengthParams = new Map(); for (let p of inParams) { if (p.nullable && !p.isArray) { // this would be easy to implement - just map null to 0 - but nothing actually uses nullable non-array input parameters, so we can't ensure we've done it right console.error(`skipping ${fn.name} - nullable input parameter`); return null; } if (!p.isArray) { continue; } let { sizeIndex } = p; assert(sizeIndex !== undefined); if (arrayLengthParams.has(sizeIndex)) { let otherParam = arrayLengthParams.get(sizeIndex); prefix += ` if (${otherParam}.length !== ${p.name}.length) { throw new TypeError(\`${otherParam} and ${p.name} must be the same length (got \${${otherParam}.length} and \{${p.name}.length})\`); } `.trim(); continue; } arrayLengthParams.set(sizeIndex, p.name); const sizeParam = fn.params[sizeIndex]; if (!(sizeParam.kind === 'in' && sizeParam.type === 'unsigned' && !sizeParam.isPtr && !sizeParam.isArray)) { throw new Error( `size index is not unsigned int (for fn ${fn.name} parameter ${sizeIndex} got ${sizeParam.type})`, ); } args[sizeIndex] = `${p.name}.length`; params[sizeIndex] = null; } let returnType = fn.ret; let cReturnType = toEmType(fn.ret); if (outParams.length > 0) { let mapped = []; let memIdx = 0; // offset from `outAddress` where the data should get written, in units of 4 bytes for (let outParam of outParams) { if (outParam.isArray) { if (isZ3PointerType(outParam.type) || outParam.type === 'unsigned') { let { sizeIndex } = outParam; assert(sizeIndex !== undefined); let count; if (arrayLengthParams.has(sizeIndex)) { // i.e. this is also the length of an input array count = args[sizeIndex]; } else { let sizeParam = fn.params[sizeIndex]; if ( !(sizeParam.kind === 'in' && sizeParam.type === 'unsigned' && !sizeParam.isPtr && !sizeParam.isArray) ) { throw new Error( `size index is not unsigned int (for fn ${fn.name} parameter ${sizeIndex} got ${sizeParam.type})`, ); } count = sizeParam.name; } let outArrayAddress = `outArray_${outParam.name}`; prefix += ` let ${outArrayAddress} = Mod._malloc(4 * ${count}); try { `.trim(); suffix = ` } finally { Mod._free(${outArrayAddress}); } `.trim() + suffix; args[outParam.idx] = outArrayAddress; mapped.push({ name: outParam.name, read: `readUintArray(${outArrayAddress}, ${count})` + (outParam.type === 'unsigned' ? '' : `as unknown as ${outParam.type}[]`), type: `${outParam.type}[]`, }); } else { console.error(`skipping ${fn.name} - out array of ${outParam.type}`); return null; } } else if (outParam.isPtr) { function setArg() { args[outParam.idx] = memIdx === 0 ? 'outAddress' : `outAddress + ${memIdx * 4}`; } let read, type; if (outParam.type === 'string') { read = `Mod.UTF8ToString(getOutUint(${memIdx}))`; setArg(); ++memIdx; } else if (isZ3PointerType(outParam.type)) { read = `getOutUint(${memIdx}) as unknown as ${outParam.type}`; setArg(); ++memIdx; } else if (outParam.type === 'unsigned') { read = `getOutUint(${memIdx})`; setArg(); ++memIdx; } else if (outParam.type === 'int') { read = `getOutInt(${memIdx})`; setArg(); ++memIdx; } else if (outParam.type === 'uint64_t') { if (memIdx % 2 === 1) { ++memIdx; } read = `getOutUint64(${memIdx / 2})`; setArg(); memIdx += 2; } else if (outParam.type === 'int64_t') { if (memIdx % 2 === 1) { ++memIdx; } read = `getOutInt64(${memIdx / 2})`; setArg(); memIdx += 2; } else { console.error(`skipping ${fn.name} - unknown out parameter type ${outParam.type}`); return null; } if (memIdx > Math.floor(BYTES_TO_ALLOCATE_FOR_OUT_PARAMS / 4)) { // prettier-ignore console.error(`skipping ${fn.name} - out parameter sizes sum to ${memIdx * 4}, which is > ${BYTES_TO_ALLOCATE_FOR_OUT_PARAMS}`); return null; } mapped.push({ name: outParam.name, read, type: outParam.type, }); } else { console.error(`skipping ${fn.name} - out param is neither pointer nor array`); return null; } } let ignoreReturn = fn.ret === 'boolean' || fn.ret === 'void'; if (outParams.length === 1) { let outParam = mapped[0]; if (ignoreReturn) { returnType = outParam.type; rv = outParam.read; } else { returnType = `{ rv: ${fn.ret}, ${outParam.name} : ${outParam.type} }`; rv = `{ rv: ret, ${outParam.name} : ${outParam.read} }`; } } else { if (ignoreReturn) { returnType = `{ ${mapped.map(p => `${p.name} : ${p.type}`).join(', ')} }`; rv = `{ ${mapped.map(p => `${p.name}: ${p.read}`).join(', ')} }`; } else { returnType = `{ rv: ${fn.ret}, ${mapped.map(p => `${p.name} : ${p.type}`).join(', ')} }`; rv = `{ rv: ret, ${mapped.map(p => `${p.name}: ${p.read}`).join(', ')} }`; } } if (fn.ret === 'boolean') { // assume the boolean indicates success infix += ` if (!ret) { return null; } `.trim(); cReturnType = 'boolean'; returnType += ' | null'; } else if (fn.ret === 'void') { cReturnType = 'void'; } else if (isZ3PointerType(fn.ret) || fn.ret === 'unsigned') { cReturnType = 'number'; } else { console.error(`skipping ${fn.name} - out parameter for function which returns non-boolean`); return null; } } if (fn.nullableRet) { returnType += ' | null'; infix += ` if (ret === 0) { return null; } `.trim(); } else if (fn.ret === 'unsigned') { infix += ` ret = (new Uint32Array([ret]))[0]; `.trim(); } // prettier-ignore let invocation = `Mod.ccall('${isAsync ? "async_" : ""}${fn.name}', '${cReturnType}', ${JSON.stringify(ctypes)}, [${args.map(toEm).join(", ")}])`; if (isAsync) { invocation = `await Mod.async_call(() => ${invocation})`; returnType = `Promise<${returnType}>`; } let out = `${name}: ${isAsync ? 'async' : ''} function(${params.filter(p => p != null).join(', ')}): ${returnType} { ${prefix}`; if (infix === '' && suffix === '' && rv === 'ret') { out += `return ${invocation};`; } else { out += ` let ret = ${invocation}; ${infix}return ${rv};${suffix} `.trim(); } out += '}'; return out; } function wrapEnum(name: string, values: Record<string, number>) { let enumEntries = Object.entries(values); return `export enum ${name} { ${enumEntries.map(([k, v], i) => k + (v === (enumEntries[i - 1]?.[1] ?? -1) + 1 ? '' : ` = ${v}`) + ',').join('\n')} };`; } function getValidOutArrayIndexes(size: number) { return Array.from({ length: Math.floor(BYTES_TO_ALLOCATE_FOR_OUT_PARAMS / size) }, (_, i) => i).join(' | '); } const typesDocument = `// THIS FILE IS AUTOMATICALLY GENERATED BY ${path.basename(__filename)} // DO NOT EDIT IT BY HAND interface Pointer<T extends string> extends Number { readonly __typeName: T; } interface Subpointer<T extends string, S extends string> extends Pointer<S> { readonly __typeName2: T; } ${Object.keys(types) .filter(k => k.startsWith('Z3')) .map(makePointerType) .join('\n')} ${Object.entries(enums) .map(e => wrapEnum(e[0], e[1])) .join('\n\n')} `; const relativePath: string = path.relative(path.dirname(wrapperFilePath), path.dirname(typesFilePath)) || './'; const ext: string = path.extname(typesFilePath); const basename: string = path.basename(typesFilePath); const importPath = relativePath + basename.slice(0, -ext.length); const wrapperDocument = `// THIS FILE IS AUTOMATICALLY GENERATED BY ${path.basename(__filename)} // DO NOT EDIT IT BY HAND import { ${Object.keys(types) .filter(k => k.startsWith('Z3')) .join(',\n')}, ${Object.keys(enums).join(',\n')}, } from '${importPath}'; ${Object.entries(primitiveTypes) .filter(e => e[0] !== 'void') .map(e => `type ${e[0]} = ${e[1]};`) .join('\n')} export async function init(initModule: any) { let Mod = await initModule(); // this works for both signed and unsigned, because JS will wrap for you when constructing the Uint32Array function intArrayToByteArr(ints: number[]) { return new Uint8Array((new Uint32Array(ints)).buffer); } function boolArrayToByteArr(bools: boolean[]) { return bools.map(b => b ? 1 : 0); } function readUintArray(address: number, count: number) { return Array.from(new Uint32Array(Mod.HEAPU32.buffer, address, count)); } let outAddress = Mod._malloc(${BYTES_TO_ALLOCATE_FOR_OUT_PARAMS}); let outUintArray = (new Uint32Array(Mod.HEAPU32.buffer, outAddress, 4)); let getOutUint = (i: ${getValidOutArrayIndexes(4)}) => outUintArray[i]; let outIntArray = (new Int32Array(Mod.HEAPU32.buffer, outAddress, 4)); let getOutInt = (i: ${getValidOutArrayIndexes(4)}) => outIntArray[i]; let outUint64Array = (new BigUint64Array(Mod.HEAPU32.buffer, outAddress, 2)); let getOutUint64 = (i: ${getValidOutArrayIndexes(8)}) => outUint64Array[i]; let outInt64Array = (new BigInt64Array(Mod.HEAPU32.buffer, outAddress, 2)); let getOutInt64 = (i: ${getValidOutArrayIndexes(8)}) => outInt64Array[i]; return { em: Mod, Z3: { mk_context: function(c: Z3_config): Z3_context { let ctx = Mod._Z3_mk_context(c); Mod._set_noop_error_handler(ctx); return ctx; }, mk_context_rc: function(c: Z3_config): Z3_context { let ctx = Mod._Z3_mk_context_rc(c); Mod._set_noop_error_handler(ctx); return ctx; }, ${functions .map(wrapFunction) .filter(f => f != null) .join(',\n')} } }; } `; return { wrapperDocument: prettier.format(wrapperDocument, { singleQuote: true, parser: 'typescript' }), typesDocument: prettier.format(typesDocument, { singleQuote: true, parser: 'typescript' }), }; } const { wrapperDocument, typesDocument } = makeTsWrapper(); fs.mkdirSync(path.dirname(wrapperFilePath), { recursive: true }); fs.writeFileSync(wrapperFilePath, wrapperDocument); fs.mkdirSync(path.dirname(typesFilePath), { recursive: true }); fs.writeFileSync(typesFilePath, typesDocument);
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/scripts/make-ts-wrapper.ts
make-ts-wrapper.ts
import assert from 'assert'; import { SpawnOptions, spawnSync as originalSpawnSync } from 'child_process'; import fs, { existsSync } from 'fs'; import os from 'os'; import path from 'path'; import process from 'process'; import { asyncFuncs } from './async-fns'; import { makeCCWrapper } from './make-cc-wrapper'; import { functions } from './parse-api'; console.log('--- Building WASM'); const SWAP_OPTS: SpawnOptions = { shell: true, stdio: 'inherit', env: { ...process.env, CXXFLAGS: '-pthread -s USE_PTHREADS=1 -s DISABLE_EXCEPTION_CATCHING=0', LDFLAGS: '-s WASM_BIGINT -s -pthread -s USE_PTHREADS=1', FPMATH_ENABLED: 'False', // Until Safari supports WASM SSE, we have to disable fast FP support // TODO(ritave): Setting EM_CACHE breaks compiling on M1 MacBook //EM_CACHE: path.join(os.homedir(), '.emscripten/'), }, }; function spawnSync(command: string, opts: SpawnOptions = {}) { console.log(`- ${command}`); // TODO(ritave): Create a splitter that keeps track of quoted strings const [cmd, ...args] = command.split(' '); const { error, ...rest } = originalSpawnSync(cmd, args, { ...SWAP_OPTS, ...opts }); if (error !== undefined || rest.status !== 0) { if (error !== undefined) { console.error(error.message); } else { console.error(`Process exited with status ${rest.status}`); } process.exit(1); } return rest; } function exportedFuncs(): string[] { const extras = ['_malloc', '_set_throwy_error_handler', '_set_noop_error_handler', ...asyncFuncs.map(f => '_async_' + f)]; // TODO(ritave): This variable is unused in original script, find out if it's important const fns: any[] = (functions as any[]).filter(f => !asyncFuncs.includes(f.name)); return [...extras, ...(functions as any[]).map(f => '_' + f.name)]; } assert(fs.existsSync('./package.json'), 'Not in the root directory of js api'); const z3RootDir = path.join(process.cwd(), '../../../'); // TODO(ritave): Detect if it's in the configuration we need if (!existsSync(path.join(z3RootDir, 'build/Makefile'))) { spawnSync('emconfigure python scripts/mk_make.py --staticlib --single-threaded --arm64=false', { cwd: z3RootDir, }); } spawnSync(`emmake make -j${os.cpus().length} libz3.a`, { cwd: path.join(z3RootDir, 'build') }); const ccWrapperPath = 'build/async-fns.cc'; console.log(`- Building ${ccWrapperPath}`); fs.mkdirSync(path.dirname(ccWrapperPath), { recursive: true }); fs.writeFileSync(ccWrapperPath, makeCCWrapper()); const fns = JSON.stringify(exportedFuncs()); const methods = '["ccall","FS","allocate","UTF8ToString","intArrayFromString","ALLOC_NORMAL"]'; const libz3a = path.normalize('../../../build/libz3.a'); spawnSync( `emcc build/async-fns.cc ${libz3a} --std=c++20 --pre-js src/low-level/async-wrapper.js -g2 -pthread -fexceptions -s WASM_BIGINT -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=0 -s PTHREAD_POOL_SIZE_STRICT=0 -s MODULARIZE=1 -s 'EXPORT_NAME="initZ3"' -s EXPORTED_RUNTIME_METHODS=${methods} -s EXPORTED_FUNCTIONS=${fns} -s DISABLE_EXCEPTION_CATCHING=0 -s SAFE_HEAP=0 -s DEMANGLE_SUPPORT=1 -s TOTAL_MEMORY=1GB -I z3/src/api/ -o build/z3-built.js`, ); fs.rmSync(ccWrapperPath); console.log('--- WASM build finished');
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/scripts/build-wasm.ts
build-wasm.ts
import assert from 'assert'; import fs from 'fs'; import path from 'path'; const files = [ 'z3_api.h', 'z3_algebraic.h', 'z3_ast_containers.h', 'z3_fixedpoint.h', 'z3_fpa.h', 'z3_optimization.h', 'z3_polynomial.h', 'z3_rcf.h', 'z3_spacer.h', ]; const aliases = { __proto__: null, Z3_string: 'string', bool: 'boolean', signed: 'int', } as unknown as Record<string, string>; const primitiveTypes = { __proto__: null, Z3_char_ptr: 'string', unsigned: 'number', int: 'number', uint64_t: 'bigint', int64_t: 'bigint', double: 'number', float: 'number', } as unknown as Record<string, string>; const optTypes = { __proto__: null, Z3_sort_opt: 'Z3_sort', Z3_ast_opt: 'Z3_ast', Z3_func_interp_opt: 'Z3_func_interp', } as unknown as Record<string, string>; // parse type declarations const types = { __proto__: null, // these are function types I can't be bothered to parse // NSB: They can be extracted automatically from z3_api.h thanks to the use // of a macro. Z3_error_handler: 'Z3_error_handler', Z3_push_eh: 'Z3_push_eh', Z3_pop_eh: 'Z3_pop_eh', Z3_fresh_eh: 'Z3_fresh_eh', Z3_fixed_eh: 'Z3_fixed_eh', Z3_eq_eh: 'Z3_eq_eh', Z3_final_eh: 'Z3_final_eh', Z3_created_eh: 'Z3_created_eh', Z3_decide_eh: 'Z3_decide_eh', Z3_on_clause_eh: 'Z3_on_clause_eh', } as unknown as Record<string, string>; export type ApiParam = { kind: string; sizeIndex?: number; type: string }; export type Api = { params: ApiParam[]; ret: string; extra: boolean }; const defApis: Record<string, Api> = Object.create(null); export type FuncParam = { type: string; cType: string; name: string; isConst: boolean; isPtr: boolean; isArray: boolean; nullable: boolean; kind?: string; sizeIndex?: number; }; export type Func = { ret: string; cRet: string; name: string; params: FuncParam[]; nullableRet: boolean }; const functions: Func[] = []; let enums: Record<string, Record<string, number>> = Object.create(null); for (let file of files) { let contents = fs.readFileSync(path.join(__dirname, '..', '..', file), 'utf8'); // we _could_ use an actual C++ parser, which accounted for macros and everything // but that's super painful // and the files are regular enough that we can get away without it // we could also do this by modifying the `update_api.py` script // which we should probably do eventually // but this is easier while this remains not upstreamed // we need to parse the `def_API` stuff so we know which things are out parameters // unfortunately we also need to parse the actual declarations so we know the parameter names also let pytypes = Object.create(null); let typeMatches = contents.matchAll( /def_Type\(\s*'(?<name>[A-Za-z0-9_]+)',\s*'(?<cname>[A-Za-z0-9_]+)',\s*'(?<pname>[A-Za-z0-9_]+)'\)/g, ); for (let { groups } of typeMatches) { assert(groups !== undefined); pytypes[groups.name] = groups.cname; } // we don't have to pre-populate the types map with closure types // use the Z3_DECLARE_CLOSURE to identify closure types // for (let match of contents.matchAll(/Z3_DECLARE_CLOSURE\((?<type>[A-Za-z0-9_]+),/g)) { // types[match.groups.type] = match.groups.type // } // we filter first to ensure our regex isn't too strict let apiLines = contents.split('\n').filter(l => /def_API|extra_API/.test(l)); for (let line of apiLines) { let match = line.match( /^\s*(?<def>def_API|extra_API) *\(\s*'(?<name>[A-Za-z0-9_]+)'\s*,\s*(?<ret>[A-Za-z0-9_]+)\s*,\s*\((?<params>((_in|_out|_in_array|_out_array|_fnptr|_inout_array)\([^)]+\)\s*,?\s*)*)\)\s*\)\s*$/, ); if (match === null) { throw new Error(`failed to match def_API call ${JSON.stringify(line)}`); } assert(match.groups !== undefined); let { name, ret, def } = match.groups; let params = match.groups.params.trim(); let text = params; let parsedParams = []; while (true) { text = eatWs(text); ({ text, match } = eat(text, /^_(?<kind>in|out|in_array|out_array|inout_array|fnptr)\(/)); if (match == null) { break; } assert(match.groups !== undefined); let kind = match.groups.kind; if (kind === 'inout_array') kind = 'in_array'; // https://github.com/Z3Prover/z3/discussions/5761 if (kind === 'in' || kind === 'out' || kind == 'fnptr') { ({ text, match } = expect(text, /^[A-Za-z0-9_]+/)); parsedParams.push({ kind, type: match[0] }); } else { ({ text, match } = expect(text, /^(\d+),/)); let sizeIndex = Number(match[1]); text = eatWs(text); ({ text, match } = expect(text, /^[A-Za-z0-9_]+/)); parsedParams.push({ kind, sizeIndex, type: match[0] }); } ({ text, match } = expect(text, /^\)/)); text = eatWs(text); ({ text, match } = eat(text, /^,/)); } if (text !== '') { throw new Error(`extra text in parameter list ${JSON.stringify(text)}`); } if (name in defApis) { throw new Error(`multiple defApi calls for ${name}`); } defApis[name] = { params: parsedParams, ret, extra: def === 'extra_API' }; } for (let match of contents.matchAll(/DEFINE_TYPE\((?<type>[A-Za-z0-9_]+)\)/g)) { assert(match.groups !== undefined); types[match.groups.type] = match.groups.type; } // parse enum declarations for (let idx = 0; idx < contents.length; ) { let nextIdx = contents.indexOf('typedef enum', idx); if (nextIdx === -1) { break; } let lineStart = contents.lastIndexOf('\n', nextIdx); let lineEnd = contents.indexOf(';', nextIdx); if (lineStart === -1 || lineEnd === -1) { throw new Error(`could not parse enum at index ${nextIdx}`); } idx = lineEnd; let slice = contents.substring(lineStart, lineEnd); let { match, text } = eat(slice, /^\s*typedef enum\s*\{/); if (match === null) { throw new Error(`could not parse enum ${JSON.stringify(slice)}`); } let vals: Record<string, number> = Object.create(null); let next = 0; while (true) { let blank = true; while (blank) { ({ match, text } = eat(text, /^\s*(\/\/[^\n]*\n)?/)); assert(match !== null); blank = match[0].length > 0; } ({ match, text } = eat(text, /^[A-Za-z0-9_]+/)); if (match === null) { throw new Error(`could not parse enum value in ${slice}`); } let name = match[0]; text = eatWs(text); ({ match, text } = eat(text, /^= *(?<val>[^\n,\s]+)/)); if (match !== null) { assert(match.groups !== undefined); let parsedVal = Number(match.groups.val); if (Object.is(parsedVal, NaN)) { throw new Error('unknown value ' + match.groups.val); } vals[name] = parsedVal; next = parsedVal; } else { vals[name] = next; } text = eatWs(text); ({ match, text } = eat(text, /^,?\s*}/)); if (match !== null) { break; } ({ match, text } = expect(text, /^,/)); ++next; } text = eatWs(text); ({ match, text } = expect(text, /^[A-Za-z0-9_]+/)); if (match[0] in enums) { throw new Error(`duplicate enum definition ${match[0]}`); } enums[match[0]] = vals; text = eatWs(text); if (text !== '') { throw new Error('expected end of definition, got ' + text); } } // parse function declarations for (let idx = 0; idx < contents.length; ) { let nextIdx = contents.indexOf(' Z3_API ', idx); if (nextIdx === -1) { break; } let lineStart = contents.lastIndexOf('\n', nextIdx); let lineEnd = contents.indexOf(';', nextIdx); if (lineStart === -1 || lineEnd === -1) { throw new Error(`could not parse definition at index ${nextIdx}`); } idx = lineEnd; let slice = contents.substring(lineStart, lineEnd); let match = slice.match(/^\s*(?<ret>[A-Za-z0-9_]+) +Z3_API +(?<name>[A-Za-z0-9_]+)\s*\((?<params>[^)]*)\)/); if (match == null) { throw new Error(`failed to match c definition: ${JSON.stringify(slice)}`); } assert(match.groups !== undefined); let { ret, name, params } = match.groups; let parsedParams = []; if (params.trim() !== 'void') { for (let param of params.split(',')) { let paramType: string, paramName: string, isConst: boolean, isPtr: boolean, isArray: boolean; let { match, text } = eat(param, /^\s*/); ({ match, text } = eat(text, /^[A-Za-z0-9_]+/)); if (match === null) { throw new Error(`failed to parse param type in ${JSON.stringify(slice)} for param ${JSON.stringify(param)}`); } paramType = match[0]; text = eatWs(text); ({ match, text } = eat(text, /^const(?![A-Za-z0-9_])/)); isConst = match !== null; ({ match, text } = eat(text, /^\s*\*/)); isPtr = match !== null; text = eatWs(text); if (text === '') { paramName = 'UNNAMED'; isArray = false; } else { ({ match, text } = eat(text, /^[A-Za-z0-9_]+/)); if (match === null) { throw new Error( `failed to parse param name in ${JSON.stringify(slice)} for param ${JSON.stringify(param)}`, ); } paramName = match[0]; text = eatWs(text); ({ match, text } = eat(text, /^\[\]/)); isArray = match !== null; text = eatWs(text); if (text !== '') { throw new Error(`excess text in param in ${JSON.stringify(slice)} for param ${JSON.stringify(param)}`); } } if (paramType === 'Z3_string_ptr' && !isPtr) { paramType = 'Z3_string'; isPtr = true; } let nullable = false; if (paramType in optTypes) { nullable = true; paramType = optTypes[paramType]; } let cType = paramType; paramType = aliases[paramType] ?? paramType; parsedParams.push({ type: paramType, cType, name: paramName, isConst, isPtr, isArray, nullable }); } } let nullableRet = false; if (ret in optTypes) { nullableRet = true; ret = optTypes[ret]; } let cRet = ret; ret = aliases[ret] ?? ret; if (name in defApis) { functions.push({ ret, cRet, name, params: parsedParams, nullableRet }); } // only a few things are missing `def_API`; we'll skip those } } function isKnownType(t: string) { return t in enums || t in types || t in primitiveTypes || ['string', 'boolean', 'void'].includes(t); } for (let fn of functions) { if (!isKnownType(fn.ret)) { throw new Error(`unknown type ${fn.ret}`); } let defParams = defApis[fn.name].params; if (fn.params.length !== defParams.length) { throw new Error(`parameter length mismatch for ${fn.name}`); } let idx = 0; for (let param of fn.params) { if (!isKnownType(param.type)) { throw new Error(`unknown type ${param.type}`); } param.kind = defParams[idx].kind; if (param.kind === 'in_array' || param.kind === 'out_array') { if (defParams[idx].sizeIndex == null) { throw new Error(`function ${fn.name} parameter ${idx} is marked as ${param.kind} but has no index`); } param.sizeIndex = defParams[idx].sizeIndex; if (!param.isArray && param.isPtr) { // not clear why some things are written as `int * x` and others `int x[]` // but we can jsut cast param.isArray = true; param.isPtr = false; } if (!param.isArray) { throw new Error(`function ${fn.name} parameter ${idx} is marked as ${param.kind} but not typed as array`); } } ++idx; } } function eat(str: string, regex: string | RegExp) { const match: RegExpMatchArray | null = str.match(regex); if (match === null) { return { match, text: str }; } return { match, text: str.substring(match[0].length) }; } function eatWs(text: string) { return eat(text, /^\s*/).text; } function expect(str: string, regex: string | RegExp) { let { text, match } = eat(str, regex); if (match === null) { throw new Error(`expected ${regex}, got ${JSON.stringify(text)}`); } return { text, match }; } export { primitiveTypes, types, enums, functions };
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/src/api/js/scripts/parse-api.ts
parse-api.ts
import mk_genfile_common import argparse import logging import os import sys def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("api_files", nargs="+") parser.add_argument("--z3py-output-dir", dest="z3py_output_dir", default=None) parser.add_argument("--dotnet-output-dir", dest="dotnet_output_dir", default=None) parser.add_argument("--java-output-dir", dest="java_output_dir", default=None) parser.add_argument("--java-package-name", dest="java_package_name", default=None, help="Name to give the Java package (e.g. ``com.microsoft.z3``).") parser.add_argument("--ml-output-dir", dest="ml_output_dir", default=None) pargs = parser.parse_args(args) if not mk_genfile_common.check_files_exist(pargs.api_files): logging.error('One or more API files do not exist') return 1 count = 0 if pargs.z3py_output_dir: if not mk_genfile_common.check_dir_exists(pargs.z3py_output_dir): return 1 output = mk_genfile_common.mk_z3consts_py_internal(pargs.api_files, pargs.z3py_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if pargs.dotnet_output_dir: if not mk_genfile_common.check_dir_exists(pargs.dotnet_output_dir): return 1 output = mk_genfile_common.mk_z3consts_dotnet_internal( pargs.api_files, pargs.dotnet_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if pargs.java_output_dir: if pargs.java_package_name == None: logging.error('Java package name must be specified') return 1 if not mk_genfile_common.check_dir_exists(pargs.java_output_dir): return 1 outputs = mk_genfile_common.mk_z3consts_java_internal( pargs.api_files, pargs.java_package_name, pargs.java_output_dir) for generated_file in outputs: logging.info('Generated "{}"'.format(generated_file)) count += 1 if pargs.ml_output_dir: if not mk_genfile_common.check_dir_exists(pargs.ml_output_dir): return 1 output = mk_genfile_common.mk_z3consts_ml_internal( pargs.api_files, pargs.ml_output_dir) logging.info('Generated "{}"'.format(output)) count += 1 if count == 0: logging.info('No files generated. You need to specific an output directory' ' for the relevant language bindings') # TODO: Add support for other bindings return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_consts_files.py
mk_consts_files.py
import io import os import pprint import logging import re import sys # Logger for this module _logger = logging.getLogger(__name__) ############################################################################### # Utility functions ############################################################################### def check_dir_exists(output_dir): """ Returns ``True`` if ``output_dir`` exists, otherwise returns ``False``. """ if not os.path.isdir(output_dir): _logger.error('"{}" is not an existing directory'.format(output_dir)) return False return True def check_files_exist(files): assert isinstance(files, list) for f in files: if not os.path.exists(f): _logger.error('"{}" does not exist'.format(f)) return False return True def sorted_headers_by_component(l): """ Take a list of header files and sort them by the path after ``src/``. E.g. for ``src/ast/fpa/fpa2bv_converter.h`` the sorting key is ``ast/fpa/fpa2bv_converter.h``. The sort is done this way because for the CMake build there are two directories for every component (e.g. ``<src_dir>/src/ast/fpa`` and ``<build_dir>/src/ast/fpa``). We don't want to sort based on different ``<src_dir>`` and ``<build_dir>`` prefixes so that we can match the Python build system's behaviour. """ assert isinstance(l, list) def get_key(path): _logger.debug("get_key({})".format(path)) path_components = [] stripped_path = path assert 'src' in stripped_path.split(os.path.sep) or 'src' in stripped_path.split('/') # Keep stripping off directory components until we hit ``src`` while os.path.basename(stripped_path) != 'src': path_components.append(os.path.basename(stripped_path)) stripped_path = os.path.dirname(stripped_path) assert len(path_components) > 0 path_components.reverse() # For consistency across platforms use ``/`` rather than ``os.sep``. # This is a sorting key so it doesn't need to a platform suitable # path r = '/'.join(path_components) _logger.debug("return key:'{}'".format(r)) return r sorted_headers = sorted(l, key=get_key) _logger.debug('sorted headers:{}'.format(pprint.pformat(sorted_headers))) return sorted_headers ############################################################################### # Functions for generating constant declarations for language bindings ############################################################################### def mk_z3consts_py_internal(api_files, output_dir): """ Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") z3consts = open(os.path.join(output_dir, 'z3', 'z3consts.py'), 'w') z3consts_output_path = z3consts.name z3consts.write('# Automatically generated file\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] z3consts.write('# enum %s\n' % name) # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write('%s = %s\n' % (k, v)) z3consts.write('\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.close() return z3consts_output_path def mk_z3consts_dotnet_internal(api_files, output_dir): """ Generate ``Enumerations.cs`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] z3consts = open(os.path.join(output_dir, 'Enumerations.cs'), 'w') z3consts_output_path = z3consts.name z3consts.write('// Automatically generated file\n\n') z3consts.write('using System;\n\n' '#pragma warning disable 1591\n\n' 'namespace Microsoft.Z3\n' '{\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: z3consts.write(' /// <summary>%s</summary>\n' % name) z3consts.write(' public enum %s {\n' % name) z3consts.write # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write(' %s = %s,\n' % (k, v)) z3consts.write(' }\n\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.write('}\n'); z3consts.close() return z3consts_output_path def mk_z3consts_java_internal(api_files, package_name, output_dir): """ Generate "com.microsoft.z3.enumerations" package from the list of API header files in ``api_files`` and write the package directory into the ``output_dir`` directory Returns a list of the generated java source files. """ blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] gendir = os.path.join(output_dir, "enumerations") if not os.path.exists(gendir): os.mkdir(gendir) generated_enumeration_files = [] for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: efile = open('%s.java' % os.path.join(gendir, name), 'w') generated_enumeration_files.append(efile.name) efile.write('/**\n * Automatically generated file\n **/\n\n') efile.write('package %s.enumerations;\n\n' % package_name) efile.write('import java.util.HashMap;\n') efile.write('import java.util.Map;\n') efile.write('\n') efile.write('/**\n') efile.write(' * %s\n' % name) efile.write(' **/\n') efile.write('public enum %s {\n' % name) efile.write first = True # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): if first: first = False else: efile.write(',\n') efile.write(' %s (%s)' % (k, v)) efile.write(";\n") efile.write('\n private final int intValue;\n\n') efile.write(' %s(int v) {\n' % name) efile.write(' this.intValue = v;\n') efile.write(' }\n\n') efile.write(' // Cannot initialize map in constructor, so need to do it lazily.\n') efile.write(' // Easiest thread-safe way is the initialization-on-demand holder pattern.\n') efile.write(' private static class %s_MappingHolder {\n' % name) efile.write(' private static final Map<Integer, %s> intMapping = new HashMap<>();\n' % name) efile.write(' static {\n') efile.write(' for (%s k : %s.values())\n' % (name, name)) efile.write(' intMapping.put(k.toInt(), k);\n') efile.write(' }\n') efile.write(' }\n\n') efile.write(' public static final %s fromInt(int v) {\n' % name) efile.write(' %s k = %s_MappingHolder.intMapping.get(v);\n' % (name, name)) efile.write(' if (k != null) return k;\n') efile.write(' throw new IllegalArgumentException("Illegal value " + v + " for %s");\n' % name) efile.write(' }\n\n') efile.write(' public final int toInt() { return this.intValue; }\n') # efile.write(';\n %s(int v) {}\n' % name) efile.write('}\n\n') efile.close() mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() return generated_enumeration_files # Extract enumeration types from z3_api.h, and add ML definitions def mk_z3consts_ml_internal(api_files, output_dir): """ Generate ``z3enums.ml`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] if not os.path.exists(output_dir): os.mkdir(output_dir) efile = open('%s.ml' % os.path.join(output_dir, "z3enums"), 'w') z3consts_output_path = efile.name efile.write('(* Automatically generated file *)\n\n') efile.write('(** The enumeration types of Z3. *)\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: sorted_decls = sorted(decls.items(), key=lambda pair: pair[1]) efile.write('(** %s *)\n' % name[3:]) efile.write('type %s =\n' % name[3:]) # strip Z3_ for k, i in sorted_decls: efile.write(' | %s \n' % k[3:]) # strip Z3_ efile.write('\n') efile.write('(** Convert %s to int*)\n' % name[3:]) efile.write('let int_of_%s x : int =\n' % (name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %s -> %d\n' % (k[3:], i)) efile.write('\n') efile.write('(** Convert int to %s*)\n' % name[3:]) efile.write('let %s_of_int x : %s =\n' % (name[3:],name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %d -> %s\n' % (i, k[3:])) # use Z3.Exception? efile.write(' | _ -> raise (Failure "undefined enum value")\n\n') mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() efile.close() return z3consts_output_path # efile = open('%s.mli' % os.path.join(gendir, "z3enums"), 'w') # efile.write('(* Automatically generated file *)\n\n') # efile.write('(** The enumeration types of Z3. *)\n\n') # for api_file in api_files: # api_file_c = ml.find_file(api_file, ml.name) # api_file = os.path.join(api_file_c.src_dir, api_file) # api = open(api_file, 'r') # SEARCHING = 0 # FOUND_ENUM = 1 # IN_ENUM = 2 # mode = SEARCHING # decls = {} # idx = 0 # linenum = 1 # for line in api: # m1 = blank_pat.match(line) # m2 = comment_pat.match(line) # if m1 or m2: # # skip blank lines and comments # linenum = linenum + 1 # elif mode == SEARCHING: # m = typedef_pat.match(line) # if m: # mode = FOUND_ENUM # m = typedef2_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # elif mode == FOUND_ENUM: # m = openbrace_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # else: # assert False, "Invalid %s, line: %s" % (api_file, linenum) # else: # assert mode == IN_ENUM # words = re.split('[^\-a-zA-Z0-9_]+', line) # m = closebrace_pat.match(line) # if m: # name = words[1] # if name not in DeprecatedEnums: # efile.write('(** %s *)\n' % name[3:]) # efile.write('type %s =\n' % name[3:]) # strip Z3_ # for k, i in sorted(decls.items(), key=lambda pair: pair[1]): # efile.write(' | %s \n' % k[3:]) # strip Z3_ # efile.write('\n') # efile.write('(** Convert %s to int*)\n' % name[3:]) # efile.write('val int_of_%s : %s -> int\n' % (name[3:], name[3:])) # strip Z3_ # efile.write('(** Convert int to %s*)\n' % name[3:]) # efile.write('val %s_of_int : int -> %s\n' % (name[3:],name[3:])) # strip Z3_ # efile.write('\n') # mode = SEARCHING # else: # if words[2] != '': # if len(words[2]) > 1 and words[2][1] == 'x': # idx = int(words[2], 16) # else: # idx = int(words[2]) # decls[words[1]] = idx # idx = idx + 1 # linenum = linenum + 1 # api.close() # efile.close() # if VERBOSE: # print ('Generated "%s/z3enums.mli"' % ('%s' % gendir)) ############################################################################### # Functions for generating a "module definition file" for MSVC ############################################################################### def mk_def_file_internal(defname, dll_name, export_header_files): """ Writes to a module definition file to a file named ``defname``. ``dll_name`` is the name of the dll (without the ``.dll`` suffix). ``export_header_file`` is a list of header files to scan for symbols to include in the module definition file. """ assert isinstance(export_header_files, list) pat1 = re.compile(".*Z3_API.*") fout = open(defname, 'w') fout.write('LIBRARY "%s"\nEXPORTS\n' % dll_name) num = 1 for export_header_file in export_header_files: api = open(export_header_file, 'r') for line in api: m = pat1.match(line) if m: words = re.split('\W+', line) i = 0 for w in words: if w == 'Z3_API': f = words[i+1] fout.write('\t%s @%s\n' % (f, num)) i = i + 1 num = num + 1 api.close() fout.close() ############################################################################### # Functions for generating ``gparams_register_modules.cpp`` ############################################################################### def path_after_src(h_file): h_file = h_file.replace("\\","/") idx = h_file.rfind("src/") if idx == -1: return h_file return h_file[idx + 4:] def mk_gparams_register_modules_internal(h_files_full_path, path): """ Generate a ``gparams_register_modules.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedure ``` void gparams_register_modules() ``` This procedure is invoked by gparams::init() """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) cmds = [] mod_cmds = [] mod_descrs = [] fullname = os.path.join(path, 'gparams_register_modules.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "util/gparams.h"\n') reg_pat = re.compile('[ \t]*REG_PARAMS\(\'([^\']*)\'\)') reg_mod_pat = re.compile('[ \t]*REG_MODULE_PARAMS\(\'([^\']*)\', *\'([^\']*)\'\)') reg_mod_descr_pat = re.compile('[ \t]*REG_MODULE_DESCRIPTION\(\'([^\']*)\', *\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = reg_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) cmds.append((m.group(1))) m = reg_mod_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) mod_cmds.append((m.group(1), m.group(2))) m = reg_mod_descr_pat.match(line) if m: mod_descrs.append((m.group(1), m.group(2))) fout.write('void gparams_register_modules() {\n') for code in cmds: fout.write('{ param_descrs d; %s(d); gparams::register_global(d); }\n' % code) for (mod, code) in mod_cmds: fout.write('{ auto f = []() { auto* d = alloc(param_descrs); %s(*d); return d; }; gparams::register_module("%s", f); }\n' % (code, mod)) for (mod, descr) in mod_descrs: fout.write('gparams::register_module_descr("%s", "%s");\n' % (mod, descr)) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions/data structures for generating ``install_tactics.cpp`` ############################################################################### def mk_install_tactic_cpp_internal(h_files_full_path, path): """ Generate a ``install_tactics.cpp`` file in the directory ``path``. Returns the path the generated file. This file implements the procedure ``` void install_tactics(tactic_manager & ctx) ``` It installs all tactics declared in the given header files ``h_files_full_path`` The procedure looks for ``ADD_TACTIC`` and ``ADD_PROBE``commands in the ``.h`` and ``.hpp`` files of these components. """ ADD_TACTIC_DATA = [] ADD_SIMPLIFIER_DATA = [] ADD_PROBE_DATA = [] def ADD_TACTIC(name, descr, cmd): ADD_TACTIC_DATA.append((name, descr, cmd)) def ADD_PROBE(name, descr, cmd): ADD_PROBE_DATA.append((name, descr, cmd)) def ADD_SIMPLIFIER(name, descr, cmd): ADD_SIMPLIFIER_DATA.append((name, descr, cmd)) eval_globals = { 'ADD_TACTIC': ADD_TACTIC, 'ADD_PROBE': ADD_PROBE, 'ADD_SIMPLIFIER': ADD_SIMPLIFIER } assert isinstance(h_files_full_path, list) assert check_dir_exists(path) fullname = os.path.join(path, 'install_tactic.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "tactic/tactic.h"\n') fout.write('#include "cmd_context/tactic_cmds.h"\n') fout.write('#include "cmd_context/simplifier_cmds.h"\n') fout.write('#include "cmd_context/cmd_context.h"\n') tactic_pat = re.compile('[ \t]*ADD_TACTIC\(.*\)') probe_pat = re.compile('[ \t]*ADD_PROBE\(.*\)') simplifier_pat = re.compile('[ \t]*ADD_SIMPLIFIER\(.*\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False try: with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: if tactic_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_TACTIC command at '{}'\n{}".format( fullname, line)) raise e if probe_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_PROBE command at '{}'\n{}".format( fullname, line)) raise e if simplifier_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_SIMPLIFIER command at '{}'\n{}".format( fullname, line)) raise e except Exception as e: _logger.error("Failed to read file {}\n".format(h_file)) raise e # First pass will just generate the tactic factories fout.write('#define ADD_TACTIC_CMD(NAME, DESCR, CODE) ctx.insert(alloc(tactic_cmd, symbol(NAME), DESCR, [](ast_manager &m, const params_ref &p) { return CODE; }))\n') fout.write('#define ADD_PROBE(NAME, DESCR, PROBE) ctx.insert(alloc(probe_info, symbol(NAME), DESCR, PROBE))\n') fout.write('#define ADD_SIMPLIFIER_CMD(NAME, DESCR, CODE) ctx.insert(alloc(simplifier_cmd, symbol(NAME), DESCR, [](auto& m, auto& p, auto &s) -> dependent_expr_simplifier* { return CODE; }))\n') fout.write('void install_tactics(tactic_manager & ctx) {\n') for data in ADD_TACTIC_DATA: fout.write(' ADD_TACTIC_CMD("%s", "%s", %s);\n' % data) for data in ADD_PROBE_DATA: fout.write(' ADD_PROBE("%s", "%s", %s);\n' % data) for data in ADD_SIMPLIFIER_DATA: fout.write(' ADD_SIMPLIFIER_CMD("%s", "%s", %s);\n' % data) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``mem_initializer.cpp`` ############################################################################### def mk_mem_initializer_cpp_internal(h_files_full_path, path): """ Generate a ``mem_initializer.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedures ``` void mem_initialize() void mem_finalize() ``` These procedures are invoked by the Z3 memory_manager """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) initializer_cmds = [] finalizer_cmds = [] fullname = os.path.join(path, 'mem_initializer.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') initializer_pat = re.compile('[ \t]*ADD_INITIALIZER\(\'([^\']*)\'\)') # ADD_INITIALIZER with priority initializer_prio_pat = re.compile('[ \t]*ADD_INITIALIZER\(\'([^\']*)\',[ \t]*(-?[0-9]*)\)') finalizer_pat = re.compile('[ \t]*ADD_FINALIZER\(\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = initializer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), 0)) m = initializer_prio_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), int(m.group(2)))) m = finalizer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) finalizer_cmds.append(m.group(1)) initializer_cmds.sort(key=lambda tup: tup[1]) fout.write('void mem_initialize() {\n') for (cmd, prio) in initializer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.write('void mem_finalize() {\n') for cmd in finalizer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``database.h`` ############################################################################### def mk_pat_db_internal(inputFilePath, outputFilePath): """ Generate ``g_pattern_database[]`` declaration header file. """ with open(inputFilePath, 'r') as fin: with open(outputFilePath, 'w') as fout: fout.write('static char const g_pattern_database[] =\n') for line in fin: fout.write('"%s\\n"\n' % line.strip('\n')) fout.write(';\n') ############################################################################### # Functions and data structures for generating ``*_params.hpp`` files from # ``*.pyg`` files ############################################################################### UINT = 0 BOOL = 1 DOUBLE = 2 STRING = 3 SYMBOL = 4 UINT_MAX = 4294967295 TYPE2CPK = { UINT : 'CPK_UINT', BOOL : 'CPK_BOOL', DOUBLE : 'CPK_DOUBLE', STRING : 'CPK_STRING', SYMBOL : 'CPK_SYMBOL' } TYPE2CTYPE = { UINT : 'unsigned', BOOL : 'bool', DOUBLE : 'double', STRING : 'char const *', SYMBOL : 'symbol' } TYPE2GETTER = { UINT : 'get_uint', BOOL : 'get_bool', DOUBLE : 'get_double', STRING : 'get_str', SYMBOL : 'get_sym' } def pyg_default(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" return p[2] def pyg_default_as_c_literal(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" elif p[1] == STRING: return '"%s"' % p[2] elif p[1] == SYMBOL: return 'symbol("%s")' % p[2] elif p[1] == UINT: return '%su' % p[2] else: return p[2] def to_c_method(s): return s.replace('.', '_') def max_memory_param(): return ('max_memory', UINT, UINT_MAX, 'maximum amount of memory in megabytes') def max_steps_param(): return ('max_steps', UINT, UINT_MAX, 'maximum number of steps') def mk_hpp_from_pyg(pyg_file, output_dir): """ Generates the corresponding header file for the input pyg file at the path ``pyg_file``. The file is emitted into the directory ``output_dir``. Returns the path to the generated file """ CURRENT_PYG_HPP_DEST_DIR = output_dir # Note OUTPUT_HPP_FILE cannot be a string as we need a mutable variable # for the nested function to modify OUTPUT_HPP_FILE = [ ] # The function below has been nested so that it can use closure to capture # the above variables that aren't global but instead local to this # function. This avoids use of global state which makes this function safer. def def_module_params(module_name, export, params, class_name=None, description=None): dirname = CURRENT_PYG_HPP_DEST_DIR assert(os.path.exists(dirname)) if class_name is None: class_name = '%s_params' % module_name hpp = os.path.join(dirname, '%s.hpp' % class_name) out = open(hpp, 'w') out.write('// Automatically generated file\n') out.write('#pragma once\n') out.write('#include "util/params.h"\n') if export: out.write('#include "util/gparams.h"\n') out.write('struct %s {\n' % class_name) out.write(' params_ref const & p;\n') if export: out.write(' params_ref g;\n') out.write(' %s(params_ref const & _p = params_ref::get_empty()):\n' % class_name) out.write(' p(_p)') if export: out.write(', g(gparams::get_module("%s"))' % module_name) out.write(' {}\n') out.write(' static void collect_param_descrs(param_descrs & d) {\n') for param in params: out.write(' d.insert("%s", %s, "%s", "%s","%s");\n' % (param[0], TYPE2CPK[param[1]], param[3], pyg_default(param), module_name)) out.write(' }\n') if export: out.write(' /*\n') out.write(" REG_MODULE_PARAMS('%s', '%s::collect_param_descrs')\n" % (module_name, class_name)) if description is not None: out.write(" REG_MODULE_DESCRIPTION('%s', '%s')\n" % (module_name, description)) out.write(' */\n') # Generated accessors for param in params: if export: out.write(' %s %s() const { return p.%s("%s", g, %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) else: out.write(' %s %s() const { return p.%s("%s", %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) out.write('};\n') out.close() OUTPUT_HPP_FILE.append(hpp) # Globals to use when executing the ``.pyg`` file. pyg_globals = { 'UINT' : UINT, 'BOOL' : BOOL, 'DOUBLE' : DOUBLE, 'STRING' : STRING, 'SYMBOL' : SYMBOL, 'UINT_MAX' : UINT_MAX, 'max_memory_param' : max_memory_param, 'max_steps_param' : max_steps_param, # Note that once this function is enterred that function # executes with respect to the globals of this module and # not the globals defined here 'def_module_params' : def_module_params, } with open(pyg_file, 'r') as fh: eval(fh.read() + "\n", pyg_globals, None) assert len(OUTPUT_HPP_FILE) == 1 return OUTPUT_HPP_FILE[0]
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_genfile_common.py
mk_genfile_common.py
from mk_util import * def init_version(): set_version(4, 12, 2, 0) # express a default build version or pick up ci build version # Z3 Project definition def init_project_def(): init_version() add_lib('util', [], includes2install = ['z3_version.h']) add_lib('polynomial', ['util'], 'math/polynomial') add_lib('interval', ['util'], 'math/interval') add_lib('dd', ['util', 'interval'], 'math/dd') add_lib('simplex', ['util'], 'math/simplex') add_lib('hilbert', ['util'], 'math/hilbert') add_lib('automata', ['util'], 'math/automata') add_lib('params', ['util']) add_lib('realclosure', ['interval'], 'math/realclosure') add_lib('subpaving', ['interval'], 'math/subpaving') add_lib('ast', ['util', 'polynomial']) add_lib('smt_params', ['ast', 'params'], 'smt/params') add_lib('parser_util', ['ast'], 'parsers/util') add_lib('euf', ['ast'], 'ast/euf') add_lib('grobner', ['ast', 'dd', 'simplex'], 'math/grobner') add_lib('sat', ['params', 'util', 'dd', 'grobner']) add_lib('nlsat', ['polynomial', 'sat']) add_lib('lp', ['util', 'nlsat', 'grobner', 'interval', 'smt_params'], 'math/lp') add_lib('rewriter', ['ast', 'polynomial', 'interval', 'automata', 'params'], 'ast/rewriter') add_lib('bit_blaster', ['rewriter'], 'ast/rewriter/bit_blaster') add_lib('normal_forms', ['rewriter'], 'ast/normal_forms') add_lib('substitution', ['rewriter'], 'ast/substitution') add_lib('proofs', ['rewriter'], 'ast/proofs') add_lib('macros', ['rewriter'], 'ast/macros') add_lib('model', ['macros']) add_lib('converters', ['model'], 'ast/converters') add_lib('simplifiers', ['euf', 'normal_forms', 'bit_blaster', 'converters', 'substitution'], 'ast/simplifiers') add_lib('tactic', ['simplifiers']) add_lib('mbp', ['model', 'simplex'], 'qe/mbp') add_lib('qe_lite', ['tactic', 'mbp'], 'qe/lite') add_lib('solver', ['params', 'smt_params', 'model', 'tactic', 'qe_lite', 'proofs']) add_lib('cmd_context', ['solver', 'rewriter', 'params']) add_lib('smt2parser', ['cmd_context', 'parser_util'], 'parsers/smt2') add_lib('pattern', ['normal_forms', 'smt2parser', 'rewriter'], 'ast/pattern') add_lib('aig_tactic', ['tactic'], 'tactic/aig') add_lib('ackermannization', ['model', 'rewriter', 'ast', 'solver', 'tactic'], 'ackermannization') add_lib('fpa', ['ast', 'util', 'rewriter', 'model'], 'ast/fpa') add_lib('core_tactics', ['tactic', 'macros', 'normal_forms', 'rewriter', 'pattern'], 'tactic/core') add_lib('arith_tactics', ['core_tactics', 'sat'], 'tactic/arith') add_lib('solver_assertions', ['pattern','smt_params','cmd_context','qe_lite'], 'solver/assertions') add_lib('subpaving_tactic', ['core_tactics', 'subpaving'], 'math/subpaving/tactic') add_lib('proto_model', ['model', 'rewriter', 'smt_params'], 'smt/proto_model') add_lib('smt', ['bit_blaster', 'macros', 'normal_forms', 'cmd_context', 'proto_model', 'solver_assertions', 'substitution', 'grobner', 'simplex', 'proofs', 'pattern', 'parser_util', 'fpa', 'lp']) add_lib('sat_smt', ['sat', 'euf', 'smt', 'tactic', 'solver', 'smt_params', 'bit_blaster', 'fpa', 'mbp', 'normal_forms', 'lp', 'pattern', 'qe_lite'], 'sat/smt') add_lib('sat_tactic', ['tactic', 'sat', 'solver', 'sat_smt'], 'sat/tactic') add_lib('nlsat_tactic', ['nlsat', 'sat_tactic', 'arith_tactics'], 'nlsat/tactic') add_lib('bv_tactics', ['tactic', 'bit_blaster', 'core_tactics'], 'tactic/bv') add_lib('fuzzing', ['ast'], 'test/fuzzing') add_lib('smt_tactic', ['smt'], 'smt/tactic') add_lib('sls_tactic', ['tactic', 'normal_forms', 'core_tactics', 'bv_tactics'], 'tactic/sls') add_lib('qe', ['smt', 'mbp', 'qe_lite', 'nlsat', 'tactic', 'nlsat_tactic'], 'qe') add_lib('sat_solver', ['solver', 'core_tactics', 'aig_tactic', 'bv_tactics', 'arith_tactics', 'sat_tactic'], 'sat/sat_solver') add_lib('fd_solver', ['core_tactics', 'arith_tactics', 'sat_solver', 'smt'], 'tactic/fd_solver') add_lib('muz', ['smt', 'sat', 'smt2parser', 'aig_tactic', 'qe'], 'muz/base') add_lib('dataflow', ['muz'], 'muz/dataflow') add_lib('transforms', ['muz', 'hilbert', 'dataflow'], 'muz/transforms') add_lib('rel', ['muz', 'transforms'], 'muz/rel') add_lib('spacer', ['muz', 'transforms', 'arith_tactics', 'smt_tactic'], 'muz/spacer') add_lib('clp', ['muz', 'transforms'], 'muz/clp') add_lib('tab', ['muz', 'transforms'], 'muz/tab') add_lib('ddnf', ['muz', 'transforms', 'rel'], 'muz/ddnf') add_lib('bmc', ['muz', 'transforms', 'fd_solver'], 'muz/bmc') add_lib('fp', ['muz', 'clp', 'tab', 'rel', 'bmc', 'ddnf', 'spacer'], 'muz/fp') add_lib('smtlogic_tactics', ['ackermannization', 'sat_solver', 'arith_tactics', 'bv_tactics', 'nlsat_tactic', 'smt_tactic', 'aig_tactic', 'fp', 'muz', 'qe'], 'tactic/smtlogics') add_lib('ufbv_tactic', ['normal_forms', 'core_tactics', 'macros', 'smt_tactic', 'rewriter', 'smtlogic_tactics'], 'tactic/ufbv') add_lib('fpa_tactics', ['fpa', 'core_tactics', 'bv_tactics', 'sat_tactic', 'smt_tactic', 'arith_tactics', 'smtlogic_tactics'], 'tactic/fpa') add_lib('portfolio', ['smtlogic_tactics', 'sat_solver', 'ufbv_tactic', 'fpa_tactics', 'aig_tactic', 'fp', 'fd_solver', 'qe', 'sls_tactic', 'subpaving_tactic'], 'tactic/portfolio') add_lib('opt', ['smt', 'smtlogic_tactics', 'sls_tactic', 'sat_solver'], 'opt') API_files = ['z3_api.h', 'z3_ast_containers.h', 'z3_algebraic.h', 'z3_polynomial.h', 'z3_rcf.h', 'z3_fixedpoint.h', 'z3_optimization.h', 'z3_fpa.h', 'z3_spacer.h'] add_lib('extra_cmds', ['cmd_context', 'subpaving_tactic', 'qe', 'euf', 'arith_tactics'], 'cmd_context/extra_cmds') add_lib('api', ['portfolio', 'realclosure', 'opt', 'extra_cmds'], includes2install=['z3.h', 'z3_v1.h', 'z3_macros.h'] + API_files) add_exe('shell', ['api', 'sat', 'extra_cmds', 'opt'], exe_name='z3') add_exe('test', ['api', 'fuzzing', 'simplex', 'sat_smt'], exe_name='test-z3', install=False) _libz3Component = add_dll('api_dll', ['api', 'sat', 'extra_cmds'], 'api/dll', reexports=['api'], dll_name='libz3', static=build_static_lib(), export_files=API_files, staging_link='python') add_dot_net_core_dll('dotnet', ['api_dll'], 'api/dotnet', dll_name='Microsoft.Z3', default_key_file='src/api/dotnet/Microsoft.Z3.snk') add_java_dll('java', ['api_dll'], 'api/java', dll_name='libz3java', package_name="com.microsoft.z3", manifest_file='manifest') add_ml_lib('ml', ['api_dll'], 'api/ml', lib_name='libz3ml') add_hlib('cpp', 'api/c++', includes2install=['z3++.h']) set_z3py_dir('api/python') add_python(_libz3Component) add_python_install(_libz3Component) add_js() # Examples add_cpp_example('cpp_example', 'c++') add_cpp_example('z3_tptp', 'tptp') add_c_example('c_example', 'c') add_c_example('maxsat') add_dotnet_example('dotnet_example', 'dotnet') add_java_example('java_example', 'java') add_ml_example('ml_example', 'ml') add_z3py_example('py_example', 'python') return API_files
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_project.py
mk_project.py
import os import glob import re import getopt import sys import shutil import subprocess import zipfile from mk_exception import * from mk_project import * import mk_util BUILD_DIR='build-dist' BUILD_X64_DIR=os.path.join('build-dist', 'x64') BUILD_X86_DIR=os.path.join('build-dist', 'x86') VERBOSE=True DIST_DIR='dist' FORCE_MK=False ASSEMBLY_VERSION=None DOTNET_CORE_ENABLED=True DOTNET_KEY_FILE=None JAVA_ENABLED=True ZIP_BUILD_OUTPUTS=False GIT_HASH=False PYTHON_ENABLED=True X86ONLY=False X64ONLY=False MAKEJOBS=getenv("MAKEJOBS", "24") def set_verbose(flag): global VERBOSE VERBOSE = flag def is_verbose(): return VERBOSE def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(path): global BUILD_DIR, BUILD_X86_DIR, BUILD_X64_DIR BUILD_DIR = mk_util.norm_path(path) BUILD_X86_DIR = os.path.join(path, 'x86') BUILD_X64_DIR = os.path.join(path, 'x64') mk_dir(BUILD_X86_DIR) mk_dir(BUILD_X64_DIR) def display_help(): print("mk_win_dist.py: Z3 Windows distribution generator\n") print("This script generates the zip files containing executables, dlls, header files for Windows.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") print(" -b <sudir>, --build=<subdir> subdirectory where x86 and x64 Z3 versions will be built (default: build-dist).") print(" -f, --force force script to regenerate Makefiles.") print(" --assembly-version assembly version for dll") print(" --nodotnet do not include .NET bindings in the binary distribution files.") print(" --dotnet-key=<file> strongname sign the .NET assembly with the private key in <file>.") print(" --nojava do not include Java bindings in the binary distribution files.") print(" --nopython do not include Python bindings in the binary distribution files.") print(" --zip package build outputs in zip file.") print(" --githash include git hash in the Zip file.") print(" --x86-only x86 dist only.") print(" --x64-only x64 dist only.") exit(0) # Parse configuration option for mk_make script def parse_options(): global FORCE_MK, JAVA_ENABLED, ZIP_BUILD_OUTPUTS, GIT_HASH, DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, ASSEMBLY_VERSION, PYTHON_ENABLED, X86ONLY, X64ONLY path = BUILD_DIR options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:hsf', ['build=', 'help', 'silent', 'force', 'nojava', 'nodotnet', 'dotnet-key=', 'assembly-version=', 'zip', 'githash', 'nopython', 'x86-only', 'x64-only' ]) for opt, arg in options: if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') path = arg elif opt in ('-s', '--silent'): set_verbose(False) elif opt in ('-h', '--help'): display_help() elif opt in ('-f', '--force'): FORCE_MK = True elif opt == '--nodotnet': DOTNET_CORE_ENABLED = False elif opt == '--assembly-version': ASSEMBLY_VERSION = arg elif opt == '--nopython': PYTHON_ENABLED = False elif opt == '--dotnet-key': DOTNET_KEY_FILE = arg elif opt == '--nojava': JAVA_ENABLED = False elif opt == '--zip': ZIP_BUILD_OUTPUTS = True elif opt == '--githash': GIT_HASH = True elif opt == '--x86-only' and not X64ONLY: X86ONLY = True elif opt == '--x64-only' and not X86ONLY: X64ONLY = True else: raise MKException("Invalid command line option '%s'" % opt) set_build_dir(path) # Check whether build directory already exists or not def check_build_dir(path): return os.path.exists(path) and os.path.exists(os.path.join(path, 'Makefile')) # Create a build directory using mk_make.py def mk_build_dir(path, x64): if not check_build_dir(path) or FORCE_MK: parallel = '--parallel=' + MAKEJOBS opts = ["python", os.path.join('scripts', 'mk_make.py'), parallel, "-b", path] if DOTNET_CORE_ENABLED: opts.append('--dotnet') if DOTNET_KEY_FILE is not None: opts.append('--dotnet-key=' + DOTNET_KEY_FILE) if ASSEMBLY_VERSION is not None: opts.append('--assembly-version=' + ASSEMBLY_VERSION) if JAVA_ENABLED: opts.append('--java') if x64: opts.append('-x') if GIT_HASH: opts.append('--githash=%s' % mk_util.git_hash()) opts.append('--git-describe') if PYTHON_ENABLED: opts.append('--python') opts.append('--guardcf') if subprocess.call(opts) != 0: raise MKException("Failed to generate build directory at '%s'" % path) # Create build directories def mk_build_dirs(): mk_build_dir(BUILD_X86_DIR, False) mk_build_dir(BUILD_X64_DIR, True) # Check if on Visual Studio command prompt def check_vc_cmd_prompt(): try: DEVNULL = open(os.devnull, 'wb') subprocess.call(['cl'], stdout=DEVNULL, stderr=DEVNULL) except: raise MKException("You must execute the mk_win_dist.py script on a Visual Studio Command Prompt") def exec_cmds(cmds): cmd_file = 'z3_tmp.cmd' f = open(cmd_file, 'w') for cmd in cmds: f.write(cmd) f.write('\n') f.close() res = 0 try: res = subprocess.call(cmd_file, shell=True) except: res = 1 try: os.erase(cmd_file) except: pass return res # Compile Z3 (if x64 == True, then it builds it in x64 mode). def mk_z3(x64): cmds = [] if x64: cmds.append('call "%VCINSTALLDIR%Auxiliary\\build\\vcvarsall.bat" amd64') cmds.append('cd %s' % BUILD_X64_DIR) else: cmds.append('call "%VCINSTALLDIR%Auxiliary\\build\\vcvarsall.bat" x86') cmds.append('cd %s' % BUILD_X86_DIR) cmds.append('nmake') if exec_cmds(cmds) != 0: raise MKException("Failed to make z3, x64: %s" % x64) def mk_z3s(): mk_z3(False) mk_z3(True) def get_z3_name(x64): major, minor, build, revision = get_version() print("Assembly version:", major, minor, build, revision) if x64: platform = "x64" else: platform = "x86" if GIT_HASH: return 'z3-%s.%s.%s.%s-%s-win' % (major, minor, build, mk_util.git_hash(), platform) else: return 'z3-%s.%s.%s-%s-win' % (major, minor, build, platform) def mk_dist_dir(x64): if x64: platform = "x64" build_path = BUILD_X64_DIR else: platform = "x86" build_path = BUILD_X86_DIR dist_path = os.path.join(DIST_DIR, get_z3_name(x64)) mk_dir(dist_path) mk_win_dist(build_path, dist_path) if is_verbose(): print(f"Generated {platform} distribution folder at '{dist_path}'") def mk_dist_dirs(): mk_dist_dir(False) mk_dist_dir(True) def get_dist_path(x64): return get_z3_name(x64) def mk_zip(x64): dist_path = get_dist_path(x64) old = os.getcwd() try: os.chdir(DIST_DIR) zfname = '%s.zip' % dist_path zipout = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dist_path): for f in files: zipout.write(os.path.join(root, f)) if is_verbose(): print("Generated '%s'" % zfname) except: pass os.chdir(old) # Create a zip file for each platform def mk_zips(): mk_zip(False) mk_zip(True) VS_RUNTIME_PATS = [re.compile('vcomp.*\.dll'), re.compile('msvcp.*\.dll'), re.compile('msvcr.*\.dll'), re.compile('vcrun.*\.dll')] # Copy Visual Studio Runtime libraries def cp_vs_runtime(x64): if x64: platform = "x64" else: platform = "x86" vcdir = os.environ['VCINSTALLDIR'] path = '%sredist' % vcdir vs_runtime_files = [] print("Walking %s" % path) # Everything changes with every release of VS # Prior versions of VS had DLLs under "redist\x64" # There are now several variants of redistributables # The naming convention defies my understanding so # we use a "check_root" filter to find some hopefully suitable # redistributable. def check_root(root): return platform in root and ("CRT" in root or "MP" in root) and "onecore" not in root and "debug" not in root for root, dirs, files in os.walk(path): for filename in files: if fnmatch(filename, '*.dll') and check_root(root): print("Checking %s %s" % (root, filename)) for pat in VS_RUNTIME_PATS: if pat.match(filename): fname = os.path.join(root, filename) if not os.path.isdir(fname): vs_runtime_files.append(fname) if not vs_runtime_files: raise MKException("Did not find any runtime files to include") bin_dist_path = os.path.join(DIST_DIR, get_dist_path(x64), 'bin') for f in vs_runtime_files: shutil.copy(f, bin_dist_path) if is_verbose(): print("Copied '%s' to '%s'" % (f, bin_dist_path)) def cp_vs_runtimes(): cp_vs_runtime(True) cp_vs_runtime(False) def cp_license(x64): shutil.copy("LICENSE.txt", os.path.join(DIST_DIR, get_dist_path(x64))) def cp_licenses(): cp_license(True) cp_license(False) def init_flags(): global DOTNET_KEY_FILE, JAVA_ENABLED, PYTHON_ENABLED, ASSEMBLY_VERSION mk_util.DOTNET_CORE_ENABLED = True mk_util.DOTNET_KEY_FILE = DOTNET_KEY_FILE mk_util.ASSEMBLY_VERSION = ASSEMBLY_VERSION mk_util.JAVA_ENABLED = JAVA_ENABLED mk_util.PYTHON_ENABLED = PYTHON_ENABLED mk_util.ALWAYS_DYNAMIC_BASE = True # Entry point def main(): if os.name != 'nt': raise MKException("This script is for Windows only") parse_options() check_vc_cmd_prompt() init_flags() if X86ONLY: mk_build_dir(BUILD_X86_DIR, False) mk_z3(False) init_project_def() mk_dist_dir(False) cp_license(False) cp_vs_runtime(False) if ZIP_BUILD_OUTPUTS: mk_zip(False) elif X64ONLY: mk_build_dir(BUILD_X64_DIR, True) mk_z3(True) init_project_def() mk_dist_dir(True) cp_license(True) cp_vs_runtime(True) if ZIP_BUILD_OUTPUTS: mk_zip(True) else: mk_build_dirs() mk_z3s() init_project_def() mk_dist_dirs() cp_licenses() cp_vs_runtimes() if ZIP_BUILD_OUTPUTS: mk_zips() main()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_win_dist.py
mk_win_dist.py
import io import sys import os import re import getopt import shutil from mk_exception import * import mk_genfile_common from fnmatch import fnmatch import sysconfig import compileall import subprocess def getenv(name, default): try: return os.environ[name].strip(' "\'') except: return default CXX=getenv("CXX", None) CC=getenv("CC", None) CPPFLAGS=getenv("CPPFLAGS", "") CXXFLAGS=getenv("CXXFLAGS", "") AR=getenv("AR", "ar") EXAMP_DEBUG_FLAG='' LDFLAGS=getenv("LDFLAGS", "") JNI_HOME=getenv("JNI_HOME", None) OCAMLC=getenv("OCAMLC", "ocamlc") OCAMLOPT=getenv("OCAMLOPT", "ocamlopt") OCAML_LIB=getenv("OCAML_LIB", None) OCAMLFIND=getenv("OCAMLFIND", "ocamlfind") DOTNET="dotnet" # Standard install directories relative to PREFIX INSTALL_BIN_DIR=getenv("Z3_INSTALL_BIN_DIR", "bin") INSTALL_LIB_DIR=getenv("Z3_INSTALL_LIB_DIR", "lib") INSTALL_INCLUDE_DIR=getenv("Z3_INSTALL_INCLUDE_DIR", "include") INSTALL_PKGCONFIG_DIR=getenv("Z3_INSTALL_PKGCONFIG_DIR", os.path.join(INSTALL_LIB_DIR, 'pkgconfig')) CXX_COMPILERS=['g++', 'clang++'] C_COMPILERS=['gcc', 'clang'] JAVAC=None JAR=None PYTHON_PACKAGE_DIR=sysconfig.get_path('purelib') BUILD_DIR='build' REV_BUILD_DIR='..' SRC_DIR='src' EXAMPLE_DIR='examples' # Required Components Z3_DLL_COMPONENT='api_dll' PATTERN_COMPONENT='pattern' UTIL_COMPONENT='util' API_COMPONENT='api' DOTNET_COMPONENT='dotnet' DOTNET_CORE_COMPONENT='dotnet' JAVA_COMPONENT='java' ML_COMPONENT='ml' CPP_COMPONENT='cpp' PYTHON_COMPONENT='python' ##################### IS_WINDOWS=False IS_LINUX=False IS_HURD=False IS_OSX=False IS_ARCH_ARM64=False IS_FREEBSD=False IS_NETBSD=False IS_OPENBSD=False IS_SUNOS=False IS_CYGWIN=False IS_CYGWIN_MINGW=False IS_MSYS2=False VERBOSE=True DEBUG_MODE=False SHOW_CPPS = True VS_X64 = False VS_ARM = False LINUX_X64 = True ONLY_MAKEFILES = False Z3PY_SRC_DIR=None Z3JS_SRC_DIR=None VS_PROJ = False TRACE = False PYTHON_ENABLED=False DOTNET_CORE_ENABLED=False DOTNET_KEY_FILE=getenv("Z3_DOTNET_KEY_FILE", None) ASSEMBLY_VERSION=getenv("Z2_ASSEMBLY_VERSION", None) JAVA_ENABLED=False ML_ENABLED=False PYTHON_INSTALL_ENABLED=False STATIC_LIB=False STATIC_BIN=False VER_MAJOR=None VER_MINOR=None VER_BUILD=None VER_TWEAK=None PREFIX=sys.prefix GMP=False VS_PAR=False VS_PAR_NUM=8 GPROF=False GIT_HASH=False GIT_DESCRIBE=False SLOW_OPTIMIZE=False LOG_SYNC=False SINGLE_THREADED=False GUARD_CF=False ALWAYS_DYNAMIC_BASE=False FPMATH="Default" FPMATH_FLAGS="-mfpmath=sse -msse -msse2" FPMATH_ENABLED=getenv("FPMATH_ENABLED", "True") def check_output(cmd): out = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] if out != None: enc = sys.getdefaultencoding() if enc != None: return out.decode(enc).rstrip('\r\n') else: return out.rstrip('\r\n') else: return "" def git_hash(): try: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) r = check_output(['git', 'show-ref', '--abbrev=12', 'refs/heads/%s' % branch]) except: raise MKException("Failed to retrieve git hash") ls = r.split(' ') if len(ls) != 2: raise MKException("Unexpected git output " + r) return ls[0] def is_windows(): return IS_WINDOWS def is_linux(): return IS_LINUX def is_hurd(): return IS_HURD def is_freebsd(): return IS_FREEBSD def is_netbsd(): return IS_NETBSD def is_openbsd(): return IS_OPENBSD def is_sunos(): return IS_SUNOS def is_osx(): return IS_OSX def is_cygwin(): return IS_CYGWIN def is_cygwin_mingw(): return IS_CYGWIN_MINGW def is_msys2(): return IS_MSYS2 def norm_path(p): return os.path.expanduser(os.path.normpath(p)) def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in getenv("PATH", "").split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None class TempFile: def __init__(self, name): try: self.name = name self.fname = open(name, 'w') except: raise MKException("Failed to create temporary file '%s'" % self.name) def add(self, s): self.fname.write(s) def commit(self): self.fname.close() def __del__(self): self.fname.close() try: os.remove(self.name) except: pass def exec_cmd(cmd): if isinstance(cmd, str): cmd = cmd.split(' ') new_cmd = [] first = True for e in cmd: if first: first = False new_cmd.append(e) else: if e != "": se = e.split(' ') if len(se) > 1: for e2 in se: if e2 != "": new_cmd.append(e2) else: new_cmd.append(e) cmd = new_cmd null = open(os.devnull, 'wb') try: return subprocess.call(cmd, stdout=null, stderr=null) except: # Failed to create process return 1 finally: null.close() # rm -f fname def rmf(fname): if os.path.exists(fname): os.remove(fname) def exec_compiler_cmd(cmd): r = exec_cmd(cmd) # Windows rmf('a.exe') # Unix rmf('a.out') # Emscripten rmf('a.wasm') rmf('a.worker.js') return r def test_cxx_compiler(cc): if is_verbose(): print("Testing %s..." % cc) t = TempFile('tst.cpp') t.add('#include<iostream>\nint main() { return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, CXXFLAGS, 'tst.cpp', LDFLAGS]) == 0 def test_c_compiler(cc): if is_verbose(): print("Testing %s..." % cc) t = TempFile('tst.c') t.add('#include<stdio.h>\nint main() { return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, 'tst.c', LDFLAGS]) == 0 def test_gmp(cc): if is_verbose(): print("Testing GMP...") t = TempFile('tstgmp.cpp') t.add('#include<gmp.h>\nint main() { mpz_t t; mpz_init(t); mpz_clear(t); return 0; }\n') t.commit() return exec_compiler_cmd([cc, CPPFLAGS, 'tstgmp.cpp', LDFLAGS, '-lgmp']) == 0 def test_fpmath(cc): global FPMATH_FLAGS, IS_ARCH_ARM64, IS_OSX if FPMATH_ENABLED == "False": FPMATH_FLAGS="" return "Disabled" if IS_ARCH_ARM64 and IS_OSX: FPMATH_FLAGS = "" return "Disabled-ARM64" if is_verbose(): print("Testing floating point support...") t = TempFile('tstsse.cpp') t.add('int main() { return 42; }\n') t.commit() # -Werror is needed because some versions of clang warn about unrecognized # -m flags. # TODO(ritave): Safari doesn't allow SIMD WebAssembly extension, add a flag to build script if exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-msse -msse2 -msimd128']) == 0: FPMATH_FLAGS='-msse -msse2 -msimd128' return 'SSE2-EMSCRIPTEN' if exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpmath=sse -msse -msse2']) == 0: FPMATH_FLAGS="-mfpmath=sse -msse -msse2" return "SSE2-GCC" elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-msse -msse2']) == 0: FPMATH_FLAGS="-msse -msse2" return "SSE2-CLANG" elif exec_compiler_cmd([cc, CPPFLAGS, '-Werror', 'tstsse.cpp', LDFLAGS, '-mfpu=vfp -mfloat-abi=hard']) == 0: FPMATH_FLAGS="-mfpu=vfp -mfloat-abi=hard" return "ARM-VFP" else: FPMATH_FLAGS="" return "UNKNOWN" def find_jni_h(path): for root, dirs, files in os.walk(path): for f in files: if f == 'jni.h': return root return False def check_java(): global JNI_HOME global JAVAC global JAR JDK_HOME = getenv('JDK_HOME', None) # we only need to check this locally. if is_verbose(): print("Finding javac ...") if JDK_HOME is not None: if IS_WINDOWS: JAVAC = os.path.join(JDK_HOME, 'bin', 'javac.exe') else: JAVAC = os.path.join(JDK_HOME, 'bin', 'javac') if not os.path.exists(JAVAC): raise MKException("Failed to detect javac at '%s/bin'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME)) else: # Search for javac in the path. ind = 'javac' if IS_WINDOWS: ind = ind + '.exe' paths = os.getenv('PATH', None) if paths: spaths = paths.split(os.pathsep) for i in range(0, len(spaths)): cmb = os.path.join(spaths[i], ind) if os.path.exists(cmb): JAVAC = cmb break if JAVAC is None: raise MKException('No java compiler in the path, please adjust your PATH or set JDK_HOME to the location of the JDK.') if is_verbose(): print("Finding jar ...") if IS_WINDOWS: JAR = os.path.join(os.path.dirname(JAVAC), 'jar.exe') else: JAR = os.path.join(os.path.dirname(JAVAC), 'jar') if not os.path.exists(JAR): raise MKException("Failed to detect jar at '%s'; the environment variable JDK_HOME is probably set to the wrong path." % os.path.join(JDK_HOME)) if is_verbose(): print("Testing %s..." % JAVAC) t = TempFile('Hello.java') t.add('public class Hello { public static void main(String[] args) { System.out.println("Hello, World"); }}\n') t.commit() oo = TempFile('output') eo = TempFile('errout') try: subprocess.call([JAVAC, 'Hello.java', '-verbose', '-source', '1.8', '-target', '1.8' ], stdout=oo.fname, stderr=eo.fname) oo.commit() eo.commit() except: raise MKException('Found, but failed to run Java compiler at %s' % (JAVAC)) os.remove('Hello.class') if is_verbose(): print("Finding jni.h...") if JNI_HOME is not None: if not os.path.exists(os.path.join(JNI_HOME, 'jni.h')): raise MKException("Failed to detect jni.h '%s'; the environment variable JNI_HOME is probably set to the wrong path." % os.path.join(JNI_HOME)) else: # Search for jni.h in the library directories... t = open('errout', 'r') open_pat = re.compile("\[search path for class files: (.*)\]") cdirs = [] for line in t: m = open_pat.match(line) if m: libdirs = m.group(1).split(',') for libdir in libdirs: q = os.path.dirname(libdir) if cdirs.count(q) == 0 and len(q) > 0: cdirs.append(q) t.close() # ... plus some heuristic ones. extra_dirs = [] # For the libraries, even the JDK usually uses a JRE that comes with it. To find the # headers we have to go a little bit higher up. for dir in cdirs: extra_dirs.append(os.path.abspath(os.path.join(dir, '..'))) if IS_OSX: # Apparently Apple knows best where to put stuff... extra_dirs.append('/System/Library/Frameworks/JavaVM.framework/Headers/') cdirs[len(cdirs):] = extra_dirs for dir in cdirs: q = find_jni_h(dir) if q is not False: JNI_HOME = q if JNI_HOME is None: raise MKException("Failed to detect jni.h. Possible solution: set JNI_HOME with the path to JDK.") def test_csc_compiler(c): t = TempFile('hello.cs') t.add('public class hello { public static void Main() {} }') t.commit() if is_verbose(): print ('Testing %s...' % c) r = exec_cmd([c, 'hello.cs']) try: rmf('hello.cs') rmf('hello.exe') except: pass return r == 0 def check_dotnet_core(): if not IS_WINDOWS: return r = exec_cmd([DOTNET, '--help']) if r != 0: raise MKException('Failed testing dotnet. Make sure to install and configure dotnet core utilities') def check_ml(): t = TempFile('hello.ml') t.add('print_string "Hello world!\n";;') t.commit() if is_verbose(): print ('Testing %s...' % OCAMLC) r = exec_cmd([OCAMLC, '-o', 'a.out', 'hello.ml']) if r != 0: raise MKException('Failed testing ocamlc compiler. Set environment variable OCAMLC with the path to the Ocaml compiler') if is_verbose(): print ('Testing %s...' % OCAMLOPT) r = exec_cmd([OCAMLOPT, '-o', 'a.out', 'hello.ml']) if r != 0: raise MKException('Failed testing ocamlopt compiler. Set environment variable OCAMLOPT with the path to the Ocaml native compiler. Note that ocamlopt may require flexlink to be in your path.') try: rmf('hello.cmi') rmf('hello.cmo') rmf('hello.cmx') rmf('a.out') rmf('hello.o') except: pass find_ml_lib() find_ocaml_find() def find_ocaml_find(): global OCAMLFIND if is_verbose(): print ("Testing %s..." % OCAMLFIND) r = exec_cmd([OCAMLFIND, 'printconf']) if r != 0: OCAMLFIND = '' def find_ml_lib(): global OCAML_LIB if is_verbose(): print ('Finding OCAML_LIB...') t = TempFile('output') null = open(os.devnull, 'wb') try: subprocess.call([OCAMLC, '-where'], stdout=t.fname, stderr=null) t.commit() except: raise MKException('Failed to find Ocaml library; please set OCAML_LIB') finally: null.close() t = open('output', 'r') for line in t: OCAML_LIB = line[:-1] if is_verbose(): print ('OCAML_LIB=%s' % OCAML_LIB) t.close() rmf('output') return def is64(): global LINUX_X64 if is_sunos() and sys.version_info.major < 3: return LINUX_X64 else: return LINUX_X64 and sys.maxsize >= 2**32 def check_ar(): if is_verbose(): print("Testing ar...") if which(AR) is None: raise MKException('%s (archive tool) was not found' % AR) def find_cxx_compiler(): global CXX, CXX_COMPILERS if CXX is not None: if test_cxx_compiler(CXX): return CXX for cxx in CXX_COMPILERS: if test_cxx_compiler(cxx): CXX = cxx return CXX raise MKException('C++ compiler was not found. Try to set the environment variable CXX with the C++ compiler available in your system.') def find_c_compiler(): global CC, C_COMPILERS if CC is not None: if test_c_compiler(CC): return CC for c in C_COMPILERS: if test_c_compiler(c): CC = c return CC raise MKException('C compiler was not found. Try to set the environment variable CC with the C compiler available in your system.') def set_version(major, minor, build, revision): global ASSEMBLY_VERSION, VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK, GIT_DESCRIBE # We need to give the assembly a build specific version # global version overrides local default expression if ASSEMBLY_VERSION is not None: versionSplits = ASSEMBLY_VERSION.split('.') if len(versionSplits) > 3: VER_MAJOR = versionSplits[0] VER_MINOR = versionSplits[1] VER_BUILD = versionSplits[2] VER_TWEAK = versionSplits[3] print("Set Assembly Version (BUILD):", VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) return # use parameters to set up version if not provided by script args VER_MAJOR = major VER_MINOR = minor VER_BUILD = build VER_TWEAK = revision # update VER_TWEAK base on github if GIT_DESCRIBE: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) VER_TWEAK = int(check_output(['git', 'rev-list', '--count', 'HEAD'])) print("Set Assembly Version (DEFAULT):", VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) def get_version(): return (VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) def get_version_string(n): if n == 3: return "{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD) return "{}.{}.{}.{}".format(VER_MAJOR,VER_MINOR,VER_BUILD,VER_TWEAK) def build_static_lib(): return STATIC_LIB def build_static_bin(): return STATIC_BIN def is_cr_lf(fname): # Check whether text files use cr/lf f = open(fname, 'r') line = f.readline() f.close() sz = len(line) return sz >= 2 and line[sz-2] == '\r' and line[sz-1] == '\n' # dos2unix in python # cr/lf --> lf def dos2unix(fname): if is_cr_lf(fname): fin = open(fname, 'r') fname_new = '%s.new' % fname fout = open(fname_new, 'w') for line in fin: line = line.rstrip('\r\n') fout.write(line) fout.write('\n') fin.close() fout.close() shutil.move(fname_new, fname) if is_verbose(): print("dos2unix '%s'" % fname) def dos2unix_tree(): for root, dirs, files in os.walk('src'): for f in files: dos2unix(os.path.join(root, f)) def check_eol(): if not IS_WINDOWS: # Linux/OSX/BSD check if the end-of-line is cr/lf if is_cr_lf('LICENSE.txt'): if is_verbose(): print("Fixing end of line...") dos2unix_tree() if os.name == 'nt': IS_WINDOWS=True # Visual Studio already displays the files being compiled SHOW_CPPS=False elif os.name == 'posix': if os.uname()[0] == 'Darwin': IS_OSX=True elif os.uname()[0] == 'Linux': IS_LINUX=True elif os.uname()[0] == 'GNU': IS_HURD=True elif os.uname()[0] == 'FreeBSD': IS_FREEBSD=True elif os.uname()[0] == 'NetBSD': IS_NETBSD=True elif os.uname()[0] == 'OpenBSD': IS_OPENBSD=True elif os.uname()[0] == 'SunOS': IS_SUNOS=True elif os.uname()[0][:6] == 'CYGWIN': IS_CYGWIN=True if (CC != None and "mingw" in CC): IS_CYGWIN_MINGW=True elif os.uname()[0].startswith('MSYS_NT') or os.uname()[0].startswith('MINGW'): IS_MSYS2=True if os.uname()[4] == 'x86_64': LINUX_X64=True else: LINUX_X64=False if os.name == 'posix' and os.uname()[4] == 'arm64': IS_ARCH_ARM64 = True def display_help(exit_code): print("mk_make.py: Z3 Makefile generator\n") print("This script generates the Makefile for the Z3 theorem prover.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") if not IS_WINDOWS: print(" -p <dir>, --prefix=<dir> installation prefix (default: %s)." % PREFIX) else: print(" --parallel=num use cl option /MP with 'num' parallel processes") print(" --pypkgdir=<dir> Force a particular Python package directory (default %s)" % PYTHON_PACKAGE_DIR) print(" -b <subdir>, --build=<subdir> subdirectory where Z3 will be built (default: %s)." % BUILD_DIR) print(" --githash=hash include the given hash in the binaries.") print(" --git-describe include the output of 'git describe' in the version information.") print(" -d, --debug compile Z3 in debug mode.") print(" -t, --trace enable tracing in release mode.") if IS_WINDOWS: print(" --guardcf enable Control Flow Guard runtime checks.") print(" -x, --x64 create 64 binary when using Visual Studio.") else: print(" --x86 force 32-bit x86 build on x64 systems.") print(" --arm64=<bool> forcearm64 bit build on/off (supported for Darwin).") print(" -m, --makefiles generate only makefiles.") if IS_WINDOWS: print(" -v, --vsproj generate Visual Studio Project Files.") print(" --optimize generate optimized code during linking.") print(" --dotnet generate .NET platform bindings.") print(" --dotnet-key=<file> sign the .NET assembly using the private key in <file>.") print(" --assembly-version=<x.x.x.x> provide version number for build") print(" --java generate Java bindings.") print(" --ml generate OCaml bindings.") print(" --js generate JScript bindings.") print(" --python generate Python bindings.") print(" --staticlib build Z3 static library.") print(" --staticbin build a statically linked Z3 binary.") if not IS_WINDOWS: print(" -g, --gmp use GMP.") print(" --gprof enable gprof") print(" --log-sync synchronize access to API log files to enable multi-thread API logging.") print(" --single-threaded non-thread-safe build") print("") print("Some influential environment variables:") if not IS_WINDOWS: print(" CXX C++ compiler") print(" CC C compiler") print(" LDFLAGS Linker flags, e.g., -L<lib dir> if you have libraries in a non-standard directory") print(" CPPFLAGS Preprocessor flags, e.g., -I<include dir> if you have header files in a non-standard directory") print(" CXXFLAGS C++ compiler flags") print(" JDK_HOME JDK installation directory (only relevant if -j or --java option is provided)") print(" JNI_HOME JNI bindings directory (only relevant if -j or --java option is provided)") print(" OCAMLC Ocaml byte-code compiler (only relevant with --ml)") print(" OCAMLFIND Ocaml find tool (only relevant with --ml)") print(" OCAMLOPT Ocaml native compiler (only relevant with --ml)") print(" OCAML_LIB Ocaml library directory (only relevant with --ml)") print(" Z3_INSTALL_BIN_DIR Install directory for binaries relative to install prefix") print(" Z3_INSTALL_LIB_DIR Install directory for libraries relative to install prefix") print(" Z3_INSTALL_INCLUDE_DIR Install directory for header files relative to install prefix") print(" Z3_INSTALL_PKGCONFIG_DIR Install directory for pkgconfig files relative to install prefix") exit(exit_code) # Parse configuration option for mk_make script def parse_options(): global VERBOSE, DEBUG_MODE, IS_WINDOWS, VS_X64, ONLY_MAKEFILES, SHOW_CPPS, VS_PROJ, TRACE, VS_PAR, VS_PAR_NUM global DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, ASSEMBLY_VERSION, JAVA_ENABLED, ML_ENABLED, STATIC_LIB, STATIC_BIN, PREFIX, GMP, PYTHON_PACKAGE_DIR, GPROF, GIT_HASH, GIT_DESCRIBE, PYTHON_INSTALL_ENABLED, PYTHON_ENABLED global LINUX_X64, SLOW_OPTIMIZE, LOG_SYNC, SINGLE_THREADED global GUARD_CF, ALWAYS_DYNAMIC_BASE, IS_ARCH_ARM64 try: options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:df:sxa:hmcvtnp:gj', ['build=', 'debug', 'silent', 'x64', 'arm64=', 'help', 'makefiles', 'showcpp', 'vsproj', 'guardcf', 'trace', 'dotnet', 'dotnet-key=', 'assembly-version=', 'staticlib', 'prefix=', 'gmp', 'java', 'parallel=', 'gprof', 'js', 'githash=', 'git-describe', 'x86', 'ml', 'optimize', 'pypkgdir=', 'python', 'staticbin', 'log-sync', 'single-threaded']) except: print("ERROR: Invalid command line option") display_help(1) for opt, arg in options: print('opt = %s, arg = %s' % (opt, arg)) if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') set_build_dir(arg) elif opt in ('-s', '--silent'): VERBOSE = False elif opt in ('-d', '--debug'): DEBUG_MODE = True elif opt in ('-x', '--x64'): if not IS_WINDOWS: raise MKException('x64 compilation mode can only be specified when using Visual Studio') VS_X64 = True elif opt in ('--x86'): LINUX_X64=False elif opt in ('--arm64'): IS_ARCH_ARM64 = arg in ('true','on','True','TRUE') elif opt in ('-h', '--help'): display_help(0) elif opt in ('-m', '--makefiles'): ONLY_MAKEFILES = True elif opt in ('-c', '--showcpp'): SHOW_CPPS = True elif opt in ('-v', '--vsproj'): VS_PROJ = True elif opt in ('-t', '--trace'): TRACE = True elif opt in ('--dotnet',): DOTNET_CORE_ENABLED = True elif opt in ('--dotnet-key'): DOTNET_KEY_FILE = arg elif opt in ('--assembly-version'): ASSEMBLY_VERSION = arg elif opt in ('--staticlib'): STATIC_LIB = True elif opt in ('--staticbin'): STATIC_BIN = True elif opt in ('--optimize'): SLOW_OPTIMIZE = True elif not IS_WINDOWS and opt in ('-p', '--prefix'): PREFIX = arg elif opt in ('--pypkgdir'): PYTHON_PACKAGE_DIR = arg elif IS_WINDOWS and opt == '--parallel': VS_PAR = True VS_PAR_NUM = int(arg) elif opt in ('-g', '--gmp'): GMP = True elif opt in ('-j', '--java'): JAVA_ENABLED = True elif opt == '--gprof': GPROF = True elif opt == '--githash': GIT_HASH=arg elif opt == '--git-describe': GIT_DESCRIBE = True elif opt in ('', '--ml'): ML_ENABLED = True elif opt in ('', '--log-sync'): LOG_SYNC = True elif opt == '--single-threaded': SINGLE_THREADED = True elif opt in ('--python'): PYTHON_ENABLED = True PYTHON_INSTALL_ENABLED = True elif opt == '--guardcf': GUARD_CF = True ALWAYS_DYNAMIC_BASE = True # /GUARD:CF requires /DYNAMICBASE else: print("ERROR: Invalid command line option '%s'" % opt) display_help(1) # Return a list containing a file names included using '#include' in # the given C/C++ file named fname. def extract_c_includes(fname): result = {} # We look for well behaved #include directives std_inc_pat = re.compile("[ \t]*#include[ \t]*\"(.*)\"[ \t]*") system_inc_pat = re.compile("[ \t]*#include[ \t]*\<.*\>[ \t]*") # We should generate and error for any occurrence of #include that does not match the previous pattern. non_std_inc_pat = re.compile(".*#include.*") f = io.open(fname, encoding='utf-8', mode='r') linenum = 1 for line in f: m1 = std_inc_pat.match(line) if m1: root_file_name = m1.group(1) slash_pos = root_file_name.rfind('/') if slash_pos >= 0 and root_file_name.find("..") < 0 : #it is a hack for lp include files that behave as continued from "src" # print(root_file_name) root_file_name = root_file_name[slash_pos+1:] result[root_file_name] = m1.group(1) elif not system_inc_pat.match(line) and non_std_inc_pat.match(line): raise MKException("Invalid #include directive at '%s':%s" % (fname, line)) linenum = linenum + 1 f.close() return result # Given a path dir1/subdir2/subdir3 returns ../../.. def reverse_path(p): # Filter out empty components (e.g. will have one if path ends in a slash) l = list(filter(lambda x: len(x) > 0, p.split(os.sep))) n = len(l) r = '..' for i in range(1, n): r = os.path.join(r, '..') return r def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(d): global BUILD_DIR, REV_BUILD_DIR BUILD_DIR = norm_path(d) REV_BUILD_DIR = reverse_path(d) def set_z3py_dir(p): global SRC_DIR, Z3PY_SRC_DIR p = norm_path(p) full = os.path.join(SRC_DIR, p) if not os.path.exists(full): raise MKException("Python bindings directory '%s' does not exist" % full) Z3PY_SRC_DIR = full if VERBOSE: print("Python bindings directory was detected.") _UNIQ_ID = 0 def mk_fresh_name(prefix): global _UNIQ_ID r = '%s_%s' % (prefix, _UNIQ_ID) _UNIQ_ID = _UNIQ_ID + 1 return r _Id = 0 _Components = [] _ComponentNames = set() _Name2Component = {} _Processed_Headers = set() # Return the Component object named name def get_component(name): return _Name2Component[name] def get_components(): return _Components # Return the directory where the python bindings are located. def get_z3py_dir(): return Z3PY_SRC_DIR # Return true if in verbose mode def is_verbose(): return VERBOSE def is_java_enabled(): return JAVA_ENABLED def is_ml_enabled(): return ML_ENABLED def is_dotnet_core_enabled(): return DOTNET_CORE_ENABLED def is_python_enabled(): return PYTHON_ENABLED def is_python_install_enabled(): return PYTHON_INSTALL_ENABLED def is_compiler(given, expected): """ Return True if the 'given' compiler is the expected one. >>> is_compiler('g++', 'g++') True >>> is_compiler('/home/g++', 'g++') True >>> is_compiler(os.path.join('home', 'g++'), 'g++') True >>> is_compiler('clang++', 'g++') False >>> is_compiler(os.path.join('home', 'clang++'), 'clang++') True """ if given == expected: return True if len(expected) < len(given): return given[len(given) - len(expected) - 1] == os.sep and given[len(given) - len(expected):] == expected return False def is_CXX_gpp(): return is_compiler(CXX, 'g++') def is_clang_in_gpp_form(cc): str = check_output([cc, '--version']) try: version_string = str.encode('utf-8') except: version_string = str clang = 'clang'.encode('utf-8') return version_string.find(clang) != -1 def is_CXX_clangpp(): if is_compiler(CXX, 'g++'): return is_clang_in_gpp_form(CXX) return is_compiler(CXX, 'clang++') def get_files_with_ext(path, ext): return filter(lambda f: f.endswith(ext), os.listdir(path)) def get_cpp_files(path): return get_files_with_ext(path,'.cpp') def get_c_files(path): return get_files_with_ext(path,'.c') def get_cs_files(path): return get_files_with_ext(path,'.cs') def get_java_files(path): return get_files_with_ext(path,'.java') def get_ml_files(path): return get_files_with_ext(path,'.ml') def find_all_deps(name, deps): new_deps = [] for dep in deps: if dep in _ComponentNames: if not (dep in new_deps): new_deps.append(dep) for dep_dep in get_component(dep).deps: if not (dep_dep in new_deps): new_deps.append(dep_dep) else: raise MKException("Unknown component '%s' at '%s'." % (dep, name)) return new_deps class Component: def __init__(self, name, path, deps): global BUILD_DIR, SRC_DIR, REV_BUILD_DIR if name in _ComponentNames: raise MKException("Component '%s' was already defined." % name) if path is None: path = name self.name = name path = norm_path(path) self.path = path self.deps = find_all_deps(name, deps) self.build_dir = path self.src_dir = os.path.join(SRC_DIR, path) self.to_src_dir = os.path.join(REV_BUILD_DIR, self.src_dir) def get_link_name(self): return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)' # Find fname in the include paths for the given component. # ownerfile is only used for creating error messages. # That is, we were looking for fname when processing ownerfile def find_file(self, fname, ownerfile, orig_include=None): full_fname = os.path.join(self.src_dir, fname) # Store all our possible locations possibilities = set() # If the our file exists in the current directory, then we store it if os.path.exists(full_fname): # We cannot return here, as we might have files with the same # basename, but different include paths possibilities.add(self) for dep in self.deps: c_dep = get_component(dep) full_fname = os.path.join(c_dep.src_dir, fname) if os.path.exists(full_fname): possibilities.add(c_dep) if possibilities: # We have ambiguity if len(possibilities) > 1: # We expect orig_path to be non-None here, so we can disambiguate assert orig_include is not None # Get the original directory name orig_dir = os.path.dirname(orig_include) # Iterate through all of the possibilities for possibility in possibilities: path = possibility.path.replace("\\","/") # If we match the suffix of the path ... if path.endswith(orig_dir): # ... use our new match return possibility # This means we didn't make an exact match ... # # We return any one possibility, just to ensure we don't break Z3's # builds return possibilities.pop() raise MKException("Failed to find include file '%s' for '%s' when processing '%s'." % (fname, ownerfile, self.name)) # Display all dependencies of file basename located in the given component directory. # The result is displayed at out def add_cpp_h_deps(self, out, basename): includes = extract_c_includes(os.path.join(self.src_dir, basename)) out.write(os.path.join(self.to_src_dir, basename)) for include, orig_include in includes.items(): owner = self.find_file(include, basename, orig_include) out.write(' %s.node' % os.path.join(owner.build_dir, include)) # Add a rule for each #include directive in the file basename located at the current component. def add_rule_for_each_include(self, out, basename): fullname = os.path.join(self.src_dir, basename) includes = extract_c_includes(fullname) for include, orig_include in includes.items(): owner = self.find_file(include, fullname, orig_include) owner.add_h_rule(out, include) # Display a Makefile rule for an include file located in the given component directory. # 'include' is something of the form: ast.h, polynomial.h # The rule displayed at out is of the form # ast/ast_pp.h.node : ../src/util/ast_pp.h util/util.h.node ast/ast.h.node # @echo "done" > ast/ast_pp.h.node def add_h_rule(self, out, include): include_src_path = os.path.join(self.to_src_dir, include) if include_src_path in _Processed_Headers: return _Processed_Headers.add(include_src_path) self.add_rule_for_each_include(out, include) include_node = '%s.node' % os.path.join(self.build_dir, include) out.write('%s: ' % include_node) self.add_cpp_h_deps(out, include) out.write('\n') out.write('\t@echo done > %s\n' % include_node) def add_cpp_rules(self, out, include_defs, cppfile): self.add_rule_for_each_include(out, cppfile) objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) srcfile = os.path.join(self.to_src_dir, cppfile) out.write('%s: ' % objfile) self.add_cpp_h_deps(out, cppfile) out.write('\n') if SHOW_CPPS: out.write('\t@echo %s\n' % os.path.join(self.src_dir, cppfile)) out.write('\t@$(CXX) $(CXXFLAGS) $(%s) $(CXX_OUT_FLAG)%s %s\n' % (include_defs, objfile, srcfile)) def mk_makefile(self, out): include_defs = mk_fresh_name('includes') out.write('%s =' % include_defs) for dep in self.deps: out.write(' -I%s' % get_component(dep).to_src_dir) out.write(' -I%s' % os.path.join(REV_BUILD_DIR,"src")) out.write('\n') mk_dir(os.path.join(BUILD_DIR, self.build_dir)) if VS_PAR and IS_WINDOWS: cppfiles = list(get_cpp_files(self.src_dir)) dependencies = set() for cppfile in cppfiles: dependencies.add(os.path.join(self.to_src_dir, cppfile)) self.add_rule_for_each_include(out, cppfile) includes = extract_c_includes(os.path.join(self.src_dir, cppfile)) for include, orig_include in includes.items(): owner = self.find_file(include, cppfile, orig_include) dependencies.add('%s.node' % os.path.join(owner.build_dir, include)) for cppfile in cppfiles: out.write('%s$(OBJ_EXT) ' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0])) out.write(': ') for dep in dependencies: out.write(dep) out.write(' ') out.write('\n') out.write('\t@$(CXX) $(CXXFLAGS) /MP%s $(%s)' % (VS_PAR_NUM, include_defs)) for cppfile in cppfiles: out.write(' ') out.write(os.path.join(self.to_src_dir, cppfile)) out.write('\n') out.write('\tmove *.obj %s\n' % self.build_dir) else: for cppfile in get_cpp_files(self.src_dir): self.add_cpp_rules(out, include_defs, cppfile) # Return true if the component should be included in the all: rule def main_component(self): return False # Return true if the component contains an AssemblyInfo.cs file that needs to be updated. def has_assembly_info(self): return False # Return true if the component needs builder to generate an install_tactics.cpp file def require_install_tactics(self): return False # Return true if the component needs a def file def require_def_file(self): return False # Return true if the component needs builder to generate a mem_initializer.cpp file with mem_initialize() and mem_finalize() functions. def require_mem_initializer(self): return False def mk_install_deps(self, out): return def mk_install(self, out): return def mk_uninstall(self, out): return def is_example(self): return False # Invoked when creating a (windows) distribution package using components at build_path, and # storing them at dist_path def mk_win_dist(self, build_path, dist_path): return def mk_unix_dist(self, build_path, dist_path): return # Used to print warnings or errors after mk_make.py is done, so that they # are not quite as easy to miss. def final_info(self): pass class LibComponent(Component): def __init__(self, name, path, deps, includes2install): Component.__init__(self, name, path, deps) self.includes2install = includes2install def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for lib objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) libfile = '%s$(LIB_EXT)' % os.path.join(self.build_dir, self.name) out.write('%s:' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('%s: %s\n\n' % (self.name, libfile)) def mk_install_deps(self, out): return def mk_install(self, out): for include in self.includes2install: MakeRuleCmd.install_files( out, os.path.join(self.to_src_dir, include), os.path.join(INSTALL_INCLUDE_DIR, include) ) def mk_uninstall(self, out): for include in self.includes2install: MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_INCLUDE_DIR, include)) def mk_win_dist(self, build_path, dist_path): mk_dir(os.path.join(dist_path, INSTALL_INCLUDE_DIR)) for include in self.includes2install: shutil.copy(os.path.join(self.src_dir, include), os.path.join(dist_path, INSTALL_INCLUDE_DIR, include)) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) # "Library" containing only .h files. This is just a placeholder for includes files to be installed. class HLibComponent(LibComponent): def __init__(self, name, path, includes2install): LibComponent.__init__(self, name, path, [], includes2install) def mk_makefile(self, out): return # Auxiliary function for sort_components def comp_components(c1, c2): id1 = get_component(c1).id id2 = get_component(c2).id return id2 - id1 # Sort components based on (reverse) definition time def sort_components(cnames): return sorted(cnames, key=lambda c: get_component(c).id, reverse=True) class ExeComponent(Component): def __init__(self, name, exe_name, path, deps, install): Component.__init__(self, name, path, deps) if exe_name is None: exe_name = name self.exe_name = exe_name self.install = install def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for exe exefile = '%s$(EXE_EXT)' % self.exe_name out.write('%s:' % exefile) deps = sort_components(self.deps) objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) for obj in objs: out.write(' ') out.write(obj) for dep in deps: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write('\n') extra_opt = '-static' if not IS_WINDOWS and STATIC_BIN else '' out.write('\t$(LINK) %s $(LINK_OUT_FLAG)%s $(LINK_FLAGS)' % (extra_opt, exefile)) for obj in objs: out.write(' ') out.write(obj) for dep in deps: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('%s: %s\n\n' % (self.name, exefile)) def require_install_tactics(self): return ('tactic' in self.deps) and ('cmd_context' in self.deps) def require_mem_initializer(self): return True # All executables (to be installed) are included in the all: rule def main_component(self): return self.install def mk_install_deps(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name out.write('%s' % exefile) def mk_install(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name MakeRuleCmd.install_files(out, exefile, os.path.join(INSTALL_BIN_DIR, exefile)) def mk_uninstall(self, out): if self.install: exefile = '%s$(EXE_EXT)' % self.exe_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_BIN_DIR, exefile)) def mk_win_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.exe' % os.path.join(build_path, self.exe_name), '%s.exe' % os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name)) def mk_unix_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy(os.path.join(build_path, self.exe_name), os.path.join(dist_path, INSTALL_BIN_DIR, self.exe_name)) class ExtraExeComponent(ExeComponent): def __init__(self, name, exe_name, path, deps, install): ExeComponent.__init__(self, name, exe_name, path, deps, install) def main_component(self): return False def require_mem_initializer(self): return False def get_so_ext(): sysname = os.uname()[0] if sysname == 'Darwin': return 'dylib' elif sysname == 'Linux' or sysname == 'GNU' or sysname == 'FreeBSD' or sysname == 'NetBSD' or sysname == 'OpenBSD': return 'so' elif sysname == 'CYGWIN' or sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'): return 'dll' else: assert(False) return 'dll' class DLLComponent(Component): def __init__(self, name, dll_name, path, deps, export_files, reexports, install, static, staging_link=None): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name self.dll_name = dll_name self.export_files = export_files self.reexports = reexports self.install = install self.static = static self.staging_link = staging_link # link a copy of the shared object into this directory on build def get_link_name(self): if self.static: return os.path.join(self.build_dir, self.name) + '$(LIB_EXT)' else: return self.name + '$(SO_EXT)' def dll_file(self): """ Return file name of component suitable for use in a Makefile """ return '%s$(SO_EXT)' % self.dll_name def install_path(self): """ Return install location of component (relative to prefix) suitable for use in a Makefile """ return os.path.join(INSTALL_LIB_DIR, self.dll_file()) def mk_makefile(self, out): Component.mk_makefile(self, out) # generate rule for (SO_EXT) out.write('%s:' % self.dll_file()) deps = sort_components(self.deps) objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) # Explicitly include obj files of reexport. This fixes problems with exported symbols on Linux and OSX. for reexport in self.reexports: reexport = get_component(reexport) for cppfile in get_cpp_files(reexport.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(reexport.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) for obj in objs: out.write(' ') out.write(obj) for dep in deps: if dep not in self.reexports: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write('\n') out.write('\t$(LINK) $(SLINK_OUT_FLAG)%s $(SLINK_FLAGS)' % self.dll_file()) for obj in objs: out.write(' ') out.write(obj) for dep in deps: if dep not in self.reexports: c_dep = get_component(dep) out.write(' ' + c_dep.get_link_name()) out.write(' $(SLINK_EXTRA_FLAGS)') if IS_WINDOWS: out.write(' /DEF:%s.def' % os.path.join(self.to_src_dir, self.name)) if self.staging_link: if IS_WINDOWS: out.write('\n\tcopy %s %s' % (self.dll_file(), self.staging_link)) elif IS_OSX: out.write('\n\tcp %s %s' % (self.dll_file(), self.staging_link)) else: out.write('\n\tln -f -s %s %s' % (os.path.join(reverse_path(self.staging_link), self.dll_file()), self.staging_link)) out.write('\n') if self.static: if IS_WINDOWS: libfile = '%s-static$(LIB_EXT)' % self.dll_name else: libfile = '%s$(LIB_EXT)' % self.dll_name self.mk_static(out, libfile) out.write('%s: %s %s\n\n' % (self.name, self.dll_file(), libfile)) else: out.write('%s: %s\n\n' % (self.name, self.dll_file())) def mk_static(self, out, libfile): # generate rule for lib objs = [] for cppfile in get_cpp_files(self.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(self.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) # we have to "reexport" all object files for dep in self.deps: dep = get_component(dep) for cppfile in get_cpp_files(dep.src_dir): objfile = '%s$(OBJ_EXT)' % os.path.join(dep.build_dir, os.path.splitext(cppfile)[0]) objs.append(objfile) out.write('%s:' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') out.write('\t@$(AR) $(AR_FLAGS) $(AR_OUTFLAG)%s' % libfile) for obj in objs: out.write(' ') out.write(obj) out.write('\n') def main_component(self): return self.install def require_install_tactics(self): return ('tactic' in self.deps) and ('cmd_context' in self.deps) def require_mem_initializer(self): return True def require_def_file(self): return IS_WINDOWS and self.export_files def mk_install_deps(self, out): out.write('%s$(SO_EXT)' % self.dll_name) if self.static: out.write(' %s$(LIB_EXT)' % self.dll_name) def mk_install(self, out): if self.install: MakeRuleCmd.install_files(out, self.dll_file(), self.install_path()) if self.static: libfile = '%s$(LIB_EXT)' % self.dll_name MakeRuleCmd.install_files(out, libfile, os.path.join(INSTALL_LIB_DIR, libfile)) def mk_uninstall(self, out): MakeRuleCmd.remove_installed_files(out, self.install_path()) libfile = '%s$(LIB_EXT)' % self.dll_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, libfile)) def mk_win_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.lib' % os.path.join(build_path, self.dll_name), '%s.lib' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_unix_dist(self, build_path, dist_path): if self.install: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) so = get_so_ext() shutil.copy('%s.%s' % (os.path.join(build_path, self.dll_name), so), '%s.%s' % (os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name), so)) shutil.copy('%s.a' % os.path.join(build_path, self.dll_name), '%s.a' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) class JsComponent(Component): def __init__(self): Component.__init__(self, "js", None, []) def main_component(self): return False def mk_win_dist(self, build_path, dist_path): return def mk_unix_dist(self, build_path, dist_path): return def mk_makefile(self, out): return class PythonComponent(Component): def __init__(self, name, libz3Component): assert isinstance(libz3Component, DLLComponent) global PYTHON_ENABLED Component.__init__(self, name, None, []) self.libz3Component = libz3Component def main_component(self): return False def mk_win_dist(self, build_path, dist_path): if not is_python_enabled(): return src = os.path.join(build_path, 'python', 'z3') dst = os.path.join(dist_path, INSTALL_BIN_DIR, 'python', 'z3') if os.path.exists(dst): shutil.rmtree(dst) shutil.copytree(src, dst) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) def mk_makefile(self, out): return class PythonInstallComponent(Component): def __init__(self, name, libz3Component): assert isinstance(libz3Component, DLLComponent) global PYTHON_INSTALL_ENABLED Component.__init__(self, name, None, []) self.pythonPkgDir = None self.in_prefix_install = True self.libz3Component = libz3Component if not PYTHON_INSTALL_ENABLED: return if IS_WINDOWS: # Installing under Windows doesn't make sense as the install prefix is used # but that doesn't make sense under Windows # CMW: It makes perfectly good sense; the prefix is Python's sys.prefix, # i.e., something along the lines of C:\Python\... At the moment we are not # sure whether we would want to install libz3.dll into that directory though. PYTHON_INSTALL_ENABLED = False return else: PYTHON_INSTALL_ENABLED = True if IS_WINDOWS or IS_OSX: # Use full path that is possibly outside of install prefix self.in_prefix_install = PYTHON_PACKAGE_DIR.startswith(PREFIX) self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX) else: # Use path inside the prefix (should be the normal case on Linux) # CMW: Also normal on *BSD? if not PYTHON_PACKAGE_DIR.startswith(PREFIX): raise MKException(('The python package directory ({}) must live ' + 'under the install prefix ({}) to install the python bindings.' + 'Use --pypkgdir and --prefix to set the python package directory ' + 'and install prefix respectively. Note that the python package ' + 'directory does not need to exist and will be created if ' + 'necessary during install.').format( PYTHON_PACKAGE_DIR, PREFIX)) self.pythonPkgDir = strip_path_prefix(PYTHON_PACKAGE_DIR, PREFIX) self.in_prefix_install = True if self.in_prefix_install: assert not os.path.isabs(self.pythonPkgDir) def final_info(self): if not PYTHON_PACKAGE_DIR.startswith(PREFIX) and PYTHON_INSTALL_ENABLED: print("Warning: The detected Python package directory (%s) is not " "in the installation prefix (%s). This can lead to a broken " "Python API installation. Use --pypkgdir= to change the " "Python package directory." % (PYTHON_PACKAGE_DIR, PREFIX)) def main_component(self): return False def mk_install(self, out): if not is_python_install_enabled(): return MakeRuleCmd.make_install_directory(out, os.path.join(self.pythonPkgDir, 'z3'), in_prefix=self.in_prefix_install) MakeRuleCmd.make_install_directory(out, os.path.join(self.pythonPkgDir, 'z3', 'lib'), in_prefix=self.in_prefix_install) # Sym-link or copy libz3 into python package directory if IS_WINDOWS or IS_OSX: MakeRuleCmd.install_files(out, self.libz3Component.dll_file(), os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file()), in_prefix=self.in_prefix_install ) else: # Create symbolic link to save space. # It's important that this symbolic link be relative (rather # than absolute) so that the install is relocatable (needed for # staged installs that use DESTDIR). MakeRuleCmd.create_relative_symbolic_link(out, self.libz3Component.install_path(), os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file() ), ) MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '*.py'), os.path.join(self.pythonPkgDir, 'z3'), in_prefix=self.in_prefix_install) if sys.version >= "3": pythonPycacheDir = os.path.join(self.pythonPkgDir, 'z3', '__pycache__') MakeRuleCmd.make_install_directory(out, pythonPycacheDir, in_prefix=self.in_prefix_install) MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '__pycache__', '*.pyc'), pythonPycacheDir, in_prefix=self.in_prefix_install) else: MakeRuleCmd.install_files(out, os.path.join('python', 'z3', '*.pyc'), os.path.join(self.pythonPkgDir,'z3'), in_prefix=self.in_prefix_install) if PYTHON_PACKAGE_DIR != sysconfig.get_path('purelib'): out.write('\t@echo Z3Py was installed at \'%s\', make sure this directory is in your PYTHONPATH environment variable.' % PYTHON_PACKAGE_DIR) def mk_uninstall(self, out): if not is_python_install_enabled(): return MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, self.libz3Component.dll_file()), in_prefix=self.in_prefix_install ) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '*.py'), in_prefix=self.in_prefix_install) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '*.pyc'), in_prefix=self.in_prefix_install) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', '__pycache__', '*.pyc'), in_prefix=self.in_prefix_install ) MakeRuleCmd.remove_installed_files(out, os.path.join(self.pythonPkgDir, 'z3', 'lib', self.libz3Component.dll_file())) def mk_makefile(self, out): return def set_key_file(self): global DOTNET_KEY_FILE # We need to give the assembly a strong name so that it # can be installed into the GAC with ``make install`` if not DOTNET_KEY_FILE is None: self.key_file = DOTNET_KEY_FILE if not self.key_file is None: if os.path.isfile(self.key_file): self.key_file = os.path.abspath(self.key_file) elif os.path.isfile(os.path.join(self.src_dir, self.key_file)): self.key_file = os.path.abspath(os.path.join(self.src_dir, self.key_file)) else: print("Keyfile '%s' could not be found; %s.dll will be unsigned." % (self.key_file, self.dll_name)) self.key_file = None # build for dotnet core class DotNetDLLComponent(Component): def __init__(self, name, dll_name, path, deps, assembly_info_dir, default_key_file): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name if assembly_info_dir is None: assembly_info_dir = "." self.dll_name = dll_name self.assembly_info_dir = assembly_info_dir self.key_file = default_key_file def mk_makefile(self, out): if not is_dotnet_core_enabled(): return cs_fp_files = [] for cs_file in get_cs_files(self.src_dir): cs_fp_files.append(os.path.join(self.to_src_dir, cs_file)) if self.assembly_info_dir != '.': for cs_file in get_cs_files(os.path.join(self.src_dir, self.assembly_info_dir)): cs_fp_files.append(os.path.join(self.to_src_dir, self.assembly_info_dir, cs_file)) dllfile = '%s.dll' % self.dll_name out.write('%s: %s$(SO_EXT)' % (dllfile, get_component(Z3_DLL_COMPONENT).dll_name)) for cs_file in cs_fp_files: out.write(' ') out.write(cs_file) out.write('\n') set_key_file(self) key = "" if not self.key_file is None: key = "<AssemblyOriginatorKeyFile>%s</AssemblyOriginatorKeyFile>" % self.key_file key += "\n<SignAssembly>true</SignAssembly>" version = get_version_string(4) print("Version output to csproj:", version) core_csproj_str = """<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.4</TargetFramework> <LangVersion>8.0</LangVersion> <DefineConstants>$(DefineConstants);DOTNET_CORE</DefineConstants> <DebugType>full</DebugType> <AssemblyName>Microsoft.Z3</AssemblyName> <OutputType>Library</OutputType> <PackageId>Microsoft.Z3</PackageId> <GenerateDocumentationFile>true</GenerateDocumentationFile> <RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion> <Version>%s</Version> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <Authors>Microsoft</Authors> <Company>Microsoft</Company> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <Description>Z3 is a satisfiability modulo theories solver from Microsoft Research.</Description> <Copyright>Copyright Microsoft Corporation. All rights reserved.</Copyright> <PackageTags>smt constraint solver theorem prover</PackageTags> %s </PropertyGroup> <ItemGroup> <Compile Include="..\%s\*.cs;*.cs" Exclude="bin\**;obj\**;**\*.xproj;packages\**" /> </ItemGroup> </Project>""" % (version, key, self.to_src_dir) mk_dir(os.path.join(BUILD_DIR, 'dotnet')) csproj = os.path.join('dotnet', 'z3.csproj') with open(os.path.join(BUILD_DIR, csproj), 'w') as ous: ous.write(core_csproj_str) dotnetCmdLine = [DOTNET, "build", csproj] dotnetCmdLine.extend(['-c']) if DEBUG_MODE: dotnetCmdLine.extend(['Debug']) else: dotnetCmdLine.extend(['Release']) path = os.path.join(os.path.abspath(BUILD_DIR), ".") dotnetCmdLine.extend(['-o', "\"%s\"" % path]) MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine)) out.write('\n') out.write('%s: %s\n\n' % (self.name, dllfile)) def main_component(self): return is_dotnet_core_enabled() def has_assembly_info(self): # TBD: is this required for dotnet core given that version numbers are in z3.csproj file? return False def mk_win_dist(self, build_path, dist_path): if is_dotnet_core_enabled(): mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.xml' % os.path.join(build_path, self.dll_name), '%s.xml' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name), '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) if DEBUG_MODE: shutil.copy('%s.pdb' % os.path.join(build_path, self.dll_name), '%s.pdb' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_unix_dist(self, build_path, dist_path): if is_dotnet_core_enabled(): mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.dll' % os.path.join(build_path, self.dll_name), '%s.dll' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.xml' % os.path.join(build_path, self.dll_name), '%s.xml' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) shutil.copy('%s.deps.json' % os.path.join(build_path, self.dll_name), '%s.deps.json' % os.path.join(dist_path, INSTALL_BIN_DIR, self.dll_name)) def mk_install_deps(self, out): pass def mk_install(self, out): pass def mk_uninstall(self, out): pass class JavaDLLComponent(Component): def __init__(self, name, dll_name, package_name, manifest_file, path, deps): Component.__init__(self, name, path, deps) if dll_name is None: dll_name = name self.dll_name = dll_name self.package_name = package_name self.manifest_file = manifest_file self.install = not is_windows() def mk_makefile(self, out): global JAVAC global JAR if is_java_enabled(): mk_dir(os.path.join(BUILD_DIR, 'api', 'java', 'classes')) dllfile = '%s$(SO_EXT)' % self.dll_name out.write('libz3java$(SO_EXT): libz3$(SO_EXT) %s\n' % os.path.join(self.to_src_dir, 'Native.cpp')) t = '\t$(CXX) $(CXXFLAGS) $(CXX_OUT_FLAG)api/java/Native$(OBJ_EXT) -I"%s" -I"%s/PLATFORM" -I%s %s/Native.cpp\n' % (JNI_HOME, JNI_HOME, get_component('api').to_src_dir, self.to_src_dir) if IS_OSX: t = t.replace('PLATFORM', 'darwin') elif is_linux(): t = t.replace('PLATFORM', 'linux') elif is_hurd(): t = t.replace('PLATFORM', 'hurd') elif IS_FREEBSD: t = t.replace('PLATFORM', 'freebsd') elif IS_NETBSD: t = t.replace('PLATFORM', 'netbsd') elif IS_OPENBSD: t = t.replace('PLATFORM', 'openbsd') elif IS_SUNOS: t = t.replace('PLATFORM', 'SunOS') elif IS_CYGWIN: t = t.replace('PLATFORM', 'cygwin') elif IS_MSYS2: t = t.replace('PLATFORM', 'win32') else: t = t.replace('PLATFORM', 'win32') out.write(t) if IS_WINDOWS: # On Windows, CL creates a .lib file to link against. out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(LIB_EXT)\n' % os.path.join('api', 'java', 'Native')) elif IS_OSX and IS_ARCH_ARM64: out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) -arch arm64 %s$(OBJ_EXT) libz3$(SO_EXT)\n' % os.path.join('api', 'java', 'Native')) else: out.write('\t$(SLINK) $(SLINK_OUT_FLAG)libz3java$(SO_EXT) $(SLINK_FLAGS) %s$(OBJ_EXT) libz3$(SO_EXT)\n' % os.path.join('api', 'java', 'Native')) out.write('%s.jar: libz3java$(SO_EXT) ' % self.package_name) deps = '' for jfile in get_java_files(self.src_dir): deps += ('%s ' % os.path.join(self.to_src_dir, jfile)) for jfile in get_java_files(os.path.join(self.src_dir, "enumerations")): deps += '%s ' % os.path.join(self.to_src_dir, 'enumerations', jfile) out.write(deps) out.write('\n') #if IS_WINDOWS: JAVAC = '"%s"' % JAVAC JAR = '"%s"' % JAR t = ('\t%s -source 1.8 -target 1.8 %s.java -d %s\n' % (JAVAC, os.path.join(self.to_src_dir, 'enumerations', '*'), os.path.join('api', 'java', 'classes'))) out.write(t) t = ('\t%s -source 1.8 -target 1.8 -cp %s %s.java -d %s\n' % (JAVAC, os.path.join('api', 'java', 'classes'), os.path.join(self.to_src_dir, '*'), os.path.join('api', 'java', 'classes'))) out.write(t) out.write('\t%s cfm %s.jar %s -C %s .\n' % (JAR, self.package_name, os.path.join(self.to_src_dir, 'manifest'), os.path.join('api', 'java', 'classes'))) out.write('java: %s.jar\n\n' % self.package_name) def main_component(self): return is_java_enabled() def mk_win_dist(self, build_path, dist_path): if JAVA_ENABLED: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.jar' % os.path.join(build_path, self.package_name), '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name)) shutil.copy(os.path.join(build_path, 'libz3java.dll'), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.dll')) shutil.copy(os.path.join(build_path, 'libz3java.lib'), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.lib')) def mk_unix_dist(self, build_path, dist_path): if JAVA_ENABLED: mk_dir(os.path.join(dist_path, INSTALL_BIN_DIR)) shutil.copy('%s.jar' % os.path.join(build_path, self.package_name), '%s.jar' % os.path.join(dist_path, INSTALL_BIN_DIR, self.package_name)) so = get_so_ext() shutil.copy(os.path.join(build_path, 'libz3java.%s' % so), os.path.join(dist_path, INSTALL_BIN_DIR, 'libz3java.%s' % so)) def mk_install(self, out): if is_java_enabled() and self.install: dllfile = '%s$(SO_EXT)' % self.dll_name MakeRuleCmd.install_files(out, dllfile, os.path.join(INSTALL_LIB_DIR, dllfile)) jarfile = '{}.jar'.format(self.package_name) MakeRuleCmd.install_files(out, jarfile, os.path.join(INSTALL_LIB_DIR, jarfile)) def mk_uninstall(self, out): if is_java_enabled() and self.install: dllfile = '%s$(SO_EXT)' % self.dll_name MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, dllfile)) jarfile = '{}.jar'.format(self.package_name) MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, jarfile)) class MLComponent(Component): def __init__(self, name, lib_name, path, deps): Component.__init__(self, name, path, deps) if lib_name is None: lib_name = name self.lib_name = lib_name self.modules = ["z3enums", "z3native", "z3"] # dependencies in this order! self.stubs = "z3native_stubs" self.sub_dir = os.path.join('api', 'ml') self.destdir = "" self.ldconf = "" # Calling _init_ocamlfind_paths() is postponed to later because # OCAMLFIND hasn't been checked yet. def _install_bindings(self): # FIXME: Depending on global state is gross. We can't pre-compute this # in the constructor because we haven't tested for ocamlfind yet return OCAMLFIND != '' def _init_ocamlfind_paths(self): """ Initialises self.destdir and self.ldconf Do not call this from the MLComponent constructor because OCAMLFIND has not been checked at that point """ if self.destdir != "" and self.ldconf != "": # Initialisation already done return # Use Ocamlfind to get the default destdir and ldconf path self.destdir = check_output([OCAMLFIND, 'printconf', 'destdir']) if self.destdir == "": raise MKException('Failed to get OCaml destdir') if not os.path.isdir(self.destdir): raise MKException('The destdir reported by {ocamlfind} ({destdir}) does not exist'.format(ocamlfind=OCAMLFIND, destdir=self.destdir)) self.ldconf = check_output([OCAMLFIND, 'printconf', 'ldconf']) if self.ldconf == "": raise MKException('Failed to get OCaml ldconf path') def final_info(self): if not self._install_bindings(): print("WARNING: Could not find ocamlfind utility. OCaml bindings will not be installed") def mk_makefile(self, out): if is_ml_enabled(): CP_CMD = 'cp' if IS_WINDOWS: CP_CMD='copy' OCAML_FLAGS = '' if DEBUG_MODE: OCAML_FLAGS += '-g' if OCAMLFIND: OCAMLCF = OCAMLFIND + ' ' + 'ocamlc -package zarith' + ' ' + OCAML_FLAGS OCAMLOPTF = OCAMLFIND + ' ' + 'ocamlopt -package zarith' + ' ' + OCAML_FLAGS else: OCAMLCF = OCAMLC + ' ' + OCAML_FLAGS OCAMLOPTF = OCAMLOPT + ' ' + OCAML_FLAGS src_dir = self.to_src_dir mk_dir(os.path.join(BUILD_DIR, self.sub_dir)) api_src = get_component(API_COMPONENT).to_src_dir # remove /GL and -std=c++17; the ocaml tools don't like them. if IS_WINDOWS: out.write('CXXFLAGS_OCAML=$(CXXFLAGS:/GL=)\n') else: out.write('CXXFLAGS_OCAML=$(subst -std=c++17,,$(CXXFLAGS))\n') substitutions = { 'VERSION': "{}.{}.{}.{}".format(VER_MAJOR, VER_MINOR, VER_BUILD, VER_TWEAK) } configure_file(os.path.join(self.src_dir, 'META.in'), os.path.join(BUILD_DIR, self.sub_dir, 'META'), substitutions) stubsc = os.path.join(src_dir, self.stubs + '.c') stubso = os.path.join(self.sub_dir, self.stubs) + '$(OBJ_EXT)' base_dll_name = get_component(Z3_DLL_COMPONENT).dll_name if STATIC_LIB: z3link = 'z3-static' z3linkdep = base_dll_name + '-static$(LIB_EXT)' out.write('%s: %s\n' % (z3linkdep, base_dll_name + '$(LIB_EXT)')) out.write('\tcp $< $@\n') else: z3link = 'z3' z3linkdep = base_dll_name + '$(SO_EXT)' out.write('%s: %s %s\n' % (stubso, stubsc, z3linkdep)) out.write('\t%s -ccopt "$(CXXFLAGS_OCAML) -I %s -I %s -I %s $(CXX_OUT_FLAG)%s" -c %s\n' % (OCAMLCF, OCAML_LIB, api_src, src_dir, stubso, stubsc)) cmos = '' for m in self.modules: ml = os.path.join(src_dir, m + '.ml') cmo = os.path.join(self.sub_dir, m + '.cmo') existing_mli = os.path.join(src_dir, m + '.mli') mli = os.path.join(self.sub_dir, m + '.mli') cmi = os.path.join(self.sub_dir, m + '.cmi') out.write('%s: %s %s\n' % (cmo, ml, cmos)) if (os.path.exists(existing_mli[3:])): out.write('\t%s %s %s\n' % (CP_CMD, existing_mli, mli)) else: out.write('\t%s -i -I %s -c %s > %s\n' % (OCAMLCF, self.sub_dir, ml, mli)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmi, mli)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLCF, self.sub_dir, cmo, ml)) cmos = cmos + cmo + ' ' cmxs = '' for m in self.modules: ff = os.path.join(src_dir, m + '.ml') ft = os.path.join(self.sub_dir, m + '.cmx') out.write('%s: %s %s %s\n' % (ft, ff, cmos, cmxs)) out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLOPTF, self.sub_dir, ft, ff)) cmxs = cmxs + ' ' + ft OCAMLMKLIB = 'ocamlmklib' LIBZ3 = '-l' + z3link + ' -lstdc++' if is_cygwin() and not(is_cygwin_mingw()): LIBZ3 = z3linkdep LIBZ3 = LIBZ3 + ' ' + ' '.join(map(lambda x: '-cclib ' + x, LDFLAGS.split())) stubs_install_path = '$$(%s printconf destdir)/stublibs' % OCAMLFIND if not STATIC_LIB: loadpath = '-ccopt -L' + stubs_install_path dllpath = '-dllpath ' + stubs_install_path LIBZ3 = LIBZ3 + ' ' + loadpath + ' ' + dllpath if DEBUG_MODE and not(is_cygwin()): # Some ocamlmklib's don't like -g; observed on cygwin, but may be others as well. OCAMLMKLIB += ' -g' z3mls = os.path.join(self.sub_dir, 'z3ml') LIBZ3ML = '' if STATIC_LIB: LIBZ3ML = '-oc ' + os.path.join(self.sub_dir, 'z3ml-static') out.write('%s.cma: %s %s %s\n' % (z3mls, cmos, stubso, z3linkdep)) out.write('\t%s -o %s %s -I %s -L. %s %s %s\n' % (OCAMLMKLIB, z3mls, LIBZ3ML, self.sub_dir, stubso, cmos, LIBZ3)) out.write('%s.cmxa: %s %s %s %s.cma\n' % (z3mls, cmxs, stubso, z3linkdep, z3mls)) out.write('\t%s -o %s %s -I %s -L. %s %s %s\n' % (OCAMLMKLIB, z3mls, LIBZ3ML, self.sub_dir, stubso, cmxs, LIBZ3)) out.write('%s.cmxs: %s.cmxa\n' % (z3mls, z3mls)) out.write('\t%s -linkall -shared -o %s.cmxs -I . -I %s %s.cmxa\n' % (OCAMLOPTF, z3mls, self.sub_dir, z3mls)) out.write('\n') out.write('ml: %s.cma %s.cmxa %s.cmxs\n' % (z3mls, z3mls, z3mls)) if IS_OSX: out.write('\tinstall_name_tool -id %s/libz3.dylib libz3.dylib\n' % (stubs_install_path)) out.write('\tinstall_name_tool -change libz3.dylib %s/libz3.dylib api/ml/dllz3ml.so\n' % (stubs_install_path)) out.write('\n') if IS_WINDOWS: out.write('ocamlfind_install: ') self.mk_install_deps(out) out.write('\n') self.mk_install(out) out.write('\n') out.write('ocamlfind_uninstall:\n') self.mk_uninstall(out) out.write('\n') # The following three functions may be out of date. def mk_install_deps(self, out): if is_ml_enabled() and self._install_bindings(): out.write(get_component(Z3_DLL_COMPONENT).dll_name + '$(SO_EXT) ') out.write(os.path.join(self.sub_dir, 'META ')) out.write(os.path.join(self.sub_dir, 'z3ml.cma ')) out.write(os.path.join(self.sub_dir, 'z3ml.cmxa ')) out.write(os.path.join(self.sub_dir, 'z3ml.cmxs ')) def mk_install(self, out): if is_ml_enabled() and self._install_bindings(): self._init_ocamlfind_paths() in_prefix = self.destdir.startswith(PREFIX) maybe_stripped_destdir = strip_path_prefix(self.destdir, PREFIX) # Note that when doing a staged install with DESTDIR that modifying # OCaml's ``ld.conf`` may fail. Therefore packagers will need to # make their packages modify it manually at package install time # as opposed to ``make install`` time. MakeRuleCmd.make_install_directory(out, maybe_stripped_destdir, in_prefix=in_prefix) out.write('\t@{ocamlfind} install -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3 {metafile}'.format( ldconf=self.ldconf, ocamlfind=OCAMLFIND, ocaml_destdir=self.destdir, metafile=os.path.join(self.sub_dir, 'META'))) for m in self.modules: mli = os.path.join(self.src_dir, m) + '.mli' if os.path.exists(mli): out.write(' ' + os.path.join(self.to_src_dir, m) + '.mli') else: out.write(' ' + os.path.join(self.sub_dir, m) + '.mli') out.write(' ' + os.path.join(self.sub_dir, m) + '.cmi') out.write(' ' + os.path.join(self.sub_dir, m) + '.cmx') out.write(' %s' % ((os.path.join(self.sub_dir, 'libz3ml$(LIB_EXT)')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml$(LIB_EXT)')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cma')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxa')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'z3ml.cmxs')))) out.write(' %s' % ((os.path.join(self.sub_dir, 'dllz3ml')))) if is_windows() or is_cygwin_mingw() or is_msys2(): out.write('.dll') else: out.write('.so') # .so also on OSX! out.write('\n') def mk_uninstall(self, out): if is_ml_enabled() and self._install_bindings(): self._init_ocamlfind_paths() out.write('\t@{ocamlfind} remove -ldconf $(DESTDIR){ldconf} -destdir $(DESTDIR){ocaml_destdir} Z3\n'.format( ldconf=self.ldconf, ocamlfind=OCAMLFIND, ocaml_destdir=self.destdir)) def main_component(self): return is_ml_enabled() class ExampleComponent(Component): def __init__(self, name, path): Component.__init__(self, name, path, []) self.ex_dir = os.path.join(EXAMPLE_DIR, self.path) self.to_ex_dir = os.path.join(REV_BUILD_DIR, self.ex_dir) def is_example(self): return True class CppExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def compiler(self): return "$(CXX)" def src_files(self): return get_cpp_files(self.ex_dir) def mk_makefile(self, out): dll_name = get_component(Z3_DLL_COMPONENT).dll_name dll = '%s$(SO_EXT)' % dll_name objfiles = '' for cppfile in self.src_files(): objfile = '%s$(OBJ_EXT)' % (cppfile[:cppfile.rfind('.')]) objfiles = objfiles + ('%s ' % objfile) out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cppfile))); out.write('\t%s $(CXXFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(CXX_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile)) # Add include dir components out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir) out.write(' -I%s' % get_component(CPP_COMPONENT).to_src_dir) out.write(' %s' % os.path.join(self.to_ex_dir, cppfile)) out.write('\n') exefile = '%s$(EXE_EXT)' % self.name out.write('%s: %s %s\n' % (exefile, dll, objfiles)) out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles)) if IS_WINDOWS: out.write('%s.lib' % dll_name) else: out.write(dll) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('_ex_%s: %s\n\n' % (self.name, exefile)) class CExampleComponent(CppExampleComponent): def __init__(self, name, path): CppExampleComponent.__init__(self, name, path) def compiler(self): return "$(CC)" def src_files(self): return get_c_files(self.ex_dir) def mk_makefile(self, out): dll_name = get_component(Z3_DLL_COMPONENT).dll_name dll = '%s$(SO_EXT)' % dll_name objfiles = '' for cfile in self.src_files(): objfile = '%s$(OBJ_EXT)' % (cfile[:cfile.rfind('.')]) objfiles = objfiles + ('%s ' % objfile) out.write('%s: %s\n' % (objfile, os.path.join(self.to_ex_dir, cfile))); out.write('\t%s $(CFLAGS) $(OS_DEFINES) $(EXAMP_DEBUG_FLAG) $(C_OUT_FLAG)%s $(LINK_FLAGS)' % (self.compiler(), objfile)) out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir) out.write(' %s' % os.path.join(self.to_ex_dir, cfile)) out.write('\n') exefile = '%s$(EXE_EXT)' % self.name out.write('%s: %s %s\n' % (exefile, dll, objfiles)) out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles)) if IS_WINDOWS: out.write('%s.lib' % dll_name) else: out.write(dll) out.write(' $(LINK_EXTRA_FLAGS)\n') out.write('_ex_%s: %s\n\n' % (self.name, exefile)) class DotNetExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return is_dotnet_core_enabled() def mk_makefile(self, out): if is_dotnet_core_enabled(): proj_name = 'dotnet_example.csproj' out.write('_ex_%s:' % self.name) for csfile in get_cs_files(self.ex_dir): out.write(' ') out.write(os.path.join(self.to_ex_dir, csfile)) mk_dir(os.path.join(BUILD_DIR, 'dotnet_example')) csproj = os.path.join('dotnet_example', proj_name) if VS_X64: platform = 'x64' elif VS_ARM: platform = 'ARM' else: platform = 'x86' dotnet_proj_str = """<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.0</TargetFramework> <PlatformTarget>%s</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="..\%s/*.cs" /> <Reference Include="Microsoft.Z3"> <HintPath>..\Microsoft.Z3.dll</HintPath> </Reference> </ItemGroup> </Project>""" % (platform, self.to_ex_dir) with open(os.path.join(BUILD_DIR, csproj), 'w') as ous: ous.write(dotnet_proj_str) out.write('\n') dotnetCmdLine = [DOTNET, "build", csproj] dotnetCmdLine.extend(['-c']) if DEBUG_MODE: dotnetCmdLine.extend(['Debug']) else: dotnetCmdLine.extend(['Release']) MakeRuleCmd.write_cmd(out, ' '.join(dotnetCmdLine)) out.write('\n') class JavaExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return JAVA_ENABLED def mk_makefile(self, out): if JAVA_ENABLED: pkg = get_component(JAVA_COMPONENT).package_name + '.jar' out.write('JavaExample.class: %s' % (pkg)) deps = '' for jfile in get_java_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, jfile)) if IS_WINDOWS: deps = deps.replace('/', '\\') out.write('%s\n' % deps) out.write('\t%s -cp %s ' % (JAVAC, pkg)) win_ex_dir = self.to_ex_dir for javafile in get_java_files(self.ex_dir): out.write(' ') out.write(os.path.join(win_ex_dir, javafile)) out.write(' -d .\n') out.write('_ex_%s: JavaExample.class\n\n' % (self.name)) class MLExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) def is_example(self): return ML_ENABLED def mk_makefile(self, out): if ML_ENABLED: out.write('ml_example.byte: api/ml/z3ml.cma') for mlfile in get_ml_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, mlfile)) out.write('\n') out.write('\tocamlfind %s ' % OCAMLC) if DEBUG_MODE: out.write('-g ') out.write('-custom -o ml_example.byte -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cma') for mlfile in get_ml_files(self.ex_dir): out.write(' %s/%s' % (self.to_ex_dir, mlfile)) out.write('\n') out.write('ml_example$(EXE_EXT): api/ml/z3ml.cmxa') for mlfile in get_ml_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, mlfile)) out.write('\n') out.write('\tocamlfind %s ' % OCAMLOPT) if DEBUG_MODE: out.write('-g ') out.write('-o ml_example$(EXE_EXT) -package zarith -I api/ml -cclib "-L. -lpthread -lstdc++ -lz3" -linkpkg z3ml.cmxa') for mlfile in get_ml_files(self.ex_dir): out.write(' %s/%s' % (self.to_ex_dir, mlfile)) out.write('\n') out.write('_ex_%s: ml_example.byte ml_example$(EXE_EXT)\n\n' % self.name) debug_opt = '-g ' if DEBUG_MODE else '' if STATIC_LIB: opam_z3_opts = '-thread -package z3-static -linkpkg' ml_post_install_tests = [ (OCAMLC, 'ml_example_static.byte'), (OCAMLC + ' -custom', 'ml_example_static_custom.byte'), (OCAMLOPT, 'ml_example_static$(EXE_EXT)') ] else: opam_z3_opts = '-thread -package z3 -linkpkg' ml_post_install_tests = [ (OCAMLC, 'ml_example_shared.byte'), (OCAMLC + ' -custom', 'ml_example_shared_custom.byte'), (OCAMLOPT, 'ml_example_shared$(EXE_EXT)') ] for ocaml_compiler, testname in ml_post_install_tests: out.write(testname + ':') for mlfile in get_ml_files(self.ex_dir): out.write(' %s' % os.path.join(self.to_ex_dir, mlfile)) out.write('\n') out.write('\tocamlfind %s -o %s %s %s ' % (ocaml_compiler, debug_opt, testname, opam_z3_opts)) for mlfile in get_ml_files(self.ex_dir): out.write(' %s/%s' % (self.to_ex_dir, mlfile)) out.write('\n') if STATIC_LIB: out.write('_ex_ml_example_post_install: ml_example_static.byte ml_example_static_custom.byte ml_example_static$(EXE_EXT)\n') else: out.write('_ex_ml_example_post_install: ml_example_shared.byte ml_example_shared_custom.byte ml_example_shared$(EXE_EXT)\n') out.write('\n') class PythonExampleComponent(ExampleComponent): def __init__(self, name, path): ExampleComponent.__init__(self, name, path) # Python examples are just placeholders, we just copy the *.py files when mk_makefile is invoked. # We don't need to include them in the :examples rule def mk_makefile(self, out): full = os.path.join(EXAMPLE_DIR, self.path) for py in filter(lambda f: f.endswith('.py'), os.listdir(full)): shutil.copyfile(os.path.join(full, py), os.path.join(BUILD_DIR, 'python', py)) if is_verbose(): print("Copied Z3Py example '%s' to '%s'" % (py, os.path.join(BUILD_DIR, 'python'))) out.write('_ex_%s: \n\n' % self.name) def mk_win_dist(self, build_path, dist_path): full = os.path.join(EXAMPLE_DIR, self.path) py = 'example.py' shutil.copyfile(os.path.join(full, py), os.path.join(dist_path, INSTALL_BIN_DIR, 'python', py)) def mk_unix_dist(self, build_path, dist_path): self.mk_win_dist(build_path, dist_path) def reg_component(name, c): global _Id, _Components, _ComponentNames, _Name2Component c.id = _Id _Id = _Id + 1 _Components.append(c) _ComponentNames.add(name) _Name2Component[name] = c if VERBOSE: print("New component: '%s'" % name) def add_lib(name, deps=[], path=None, includes2install=[]): c = LibComponent(name, path, deps, includes2install) reg_component(name, c) def add_clib(name, deps=[], path=None, includes2install=[]): c = CLibComponent(name, path, deps, includes2install) reg_component(name, c) def add_hlib(name, path=None, includes2install=[]): c = HLibComponent(name, path, includes2install) reg_component(name, c) def add_exe(name, deps=[], path=None, exe_name=None, install=True): c = ExeComponent(name, exe_name, path, deps, install) reg_component(name, c) def add_extra_exe(name, deps=[], path=None, exe_name=None, install=True): c = ExtraExeComponent(name, exe_name, path, deps, install) reg_component(name, c) def add_dll(name, deps=[], path=None, dll_name=None, export_files=[], reexports=[], install=True, static=False, staging_link=None): c = DLLComponent(name, dll_name, path, deps, export_files, reexports, install, static, staging_link) reg_component(name, c) return c def add_dot_net_core_dll(name, deps=[], path=None, dll_name=None, assembly_info_dir=None, default_key_file=None): c = DotNetDLLComponent(name, dll_name, path, deps, assembly_info_dir, default_key_file) reg_component(name, c) def add_java_dll(name, deps=[], path=None, dll_name=None, package_name=None, manifest_file=None): c = JavaDLLComponent(name, dll_name, package_name, manifest_file, path, deps) reg_component(name, c) def add_python(libz3Component): name = 'python' reg_component(name, PythonComponent(name, libz3Component)) def add_js(): reg_component('js', JsComponent()) def add_python_install(libz3Component): name = 'python_install' reg_component(name, PythonInstallComponent(name, libz3Component)) def add_ml_lib(name, deps=[], path=None, lib_name=None): c = MLComponent(name, lib_name, path, deps) reg_component(name, c) def add_cpp_example(name, path=None): c = CppExampleComponent(name, path) reg_component(name, c) def add_c_example(name, path=None): c = CExampleComponent(name, path) reg_component(name, c) def add_dotnet_example(name, path=None): c = DotNetExampleComponent(name, path) reg_component(name, c) def add_java_example(name, path=None): c = JavaExampleComponent(name, path) reg_component(name, c) def add_ml_example(name, path=None): c = MLExampleComponent(name, path) reg_component(name, c) def add_z3py_example(name, path=None): c = PythonExampleComponent(name, path) reg_component(name, c) def mk_config(): if ONLY_MAKEFILES: return config = open(os.path.join(BUILD_DIR, 'config.mk'), 'w') global CXX, CC, GMP, GUARD_CF, STATIC_BIN, GIT_HASH, CPPFLAGS, CXXFLAGS, LDFLAGS, EXAMP_DEBUG_FLAG, FPMATH_FLAGS, LOG_SYNC, SINGLE_THREADED, IS_ARCH_ARM64 if IS_WINDOWS: CXXFLAGS = '/nologo /Zi /D WIN32 /D _WINDOWS /EHsc /GS /Gd /std:c++17' config.write( 'CC=cl\n' 'CXX=cl\n' 'CXX_OUT_FLAG=/Fo\n' 'C_OUT_FLAG=/Fo\n' 'OBJ_EXT=.obj\n' 'LIB_EXT=.lib\n' 'AR=lib\n' 'AR_OUTFLAG=/OUT:\n' 'EXE_EXT=.exe\n' 'LINK=cl\n' 'LINK_OUT_FLAG=/Fe\n' 'SO_EXT=.dll\n' 'SLINK=cl\n' 'SLINK_OUT_FLAG=/Fe\n' 'OS_DEFINES=/D _WINDOWS\n') extra_opt = '' link_extra_opt = '' if LOG_SYNC: extra_opt = '%s /DZ3_LOG_SYNC' % extra_opt if SINGLE_THREADED: extra_opt = '%s /DSINGLE_THREAD' % extra_opt if GIT_HASH: extra_opt = ' %s /D Z3GITHASH=%s' % (extra_opt, GIT_HASH) if GUARD_CF: extra_opt = ' %s /guard:cf' % extra_opt link_extra_opt = ' %s /GUARD:CF' % link_extra_opt if STATIC_BIN: static_opt = '/MT' else: static_opt = '/MD' maybe_disable_dynamic_base = '/DYNAMICBASE' if ALWAYS_DYNAMIC_BASE else '/DYNAMICBASE:NO' if DEBUG_MODE: static_opt = static_opt + 'd' config.write( 'AR_FLAGS=/nologo\n' 'LINK_FLAGS=/nologo %s\n' 'SLINK_FLAGS=/nologo /LDd\n' % static_opt) if VS_X64: config.write( 'CXXFLAGS=/c %s /W3 /WX- /Od /Oy- /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /Gm- /RTC1 %s %s\n' % (CXXFLAGS, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X64 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X64 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt)) elif VS_ARM: print("ARM on VS is unsupported") exit(1) else: config.write( 'CXXFLAGS=/c %s /W3 /WX- /Od /Oy- /D _DEBUG /D Z3DEBUG /D _CONSOLE /D _TRACE /Gm- /RTC1 /arch:SSE2 %s %s\n' % (CXXFLAGS, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link /DEBUG /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (link_extra_opt, maybe_disable_dynamic_base, link_extra_opt)) else: # Windows Release mode LTCG=' /LTCG' if SLOW_OPTIMIZE else '' GL = ' /GL' if SLOW_OPTIMIZE else '' config.write( 'AR_FLAGS=/nologo %s\n' 'LINK_FLAGS=/nologo %s\n' 'SLINK_FLAGS=/nologo /LD\n' % (LTCG, static_opt)) if TRACE: extra_opt = '%s /D _TRACE ' % extra_opt if VS_X64: config.write( 'CXXFLAGS=/c%s %s /W3 /WX- /O2 /D _EXTERNAL_RELEASE /D NDEBUG /D _LIB /D UNICODE /Gm- /GF /Gy /TP %s %s\n' % (GL, CXXFLAGS, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link%s /profile /MACHINE:X64 /SUBSYSTEM:CONSOLE /STACK:8388608 %s\n' 'SLINK_EXTRA_FLAGS=/link%s /profile /MACHINE:X64 /SUBSYSTEM:WINDOWS /STACK:8388608 %s\n' % (LTCG, link_extra_opt, LTCG, link_extra_opt)) elif VS_ARM: print("ARM on VS is unsupported") exit(1) else: config.write( 'CXXFLAGS=/c%s %s /WX- /O2 /Oy- /D _EXTERNAL_RELEASE /D NDEBUG /D _CONSOLE /D ASYNC_COMMANDS /Gm- /arch:SSE2 %s %s\n' % (GL, CXXFLAGS, extra_opt, static_opt)) config.write( 'LINK_EXTRA_FLAGS=/link%s /DEBUG /MACHINE:X86 /SUBSYSTEM:CONSOLE /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 /DYNAMICBASE /NXCOMPAT %s\n' 'SLINK_EXTRA_FLAGS=/link%s /DEBUG /MACHINE:X86 /SUBSYSTEM:WINDOWS /INCREMENTAL:NO /STACK:8388608 /OPT:REF /OPT:ICF /TLBID:1 %s %s\n' % (LTCG, link_extra_opt, LTCG, maybe_disable_dynamic_base, link_extra_opt)) config.write('CFLAGS=$(CXXFLAGS)\n') # End of Windows VS config.mk if is_verbose(): print('64-bit: %s' % is64()) if is_java_enabled(): print('JNI Bindings: %s' % JNI_HOME) print('Java Compiler: %s' % JAVAC) if is_ml_enabled(): print('OCaml Compiler: %s' % OCAMLC) print('OCaml Find tool: %s' % OCAMLFIND) print('OCaml Native: %s' % OCAMLOPT) print('OCaml Library: %s' % OCAML_LIB) else: OS_DEFINES = "" ARITH = "internal" check_ar() CXX = find_cxx_compiler() CC = find_c_compiler() SLIBEXTRAFLAGS = '' # SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so.0' % LDFLAGS EXE_EXT = '' LIB_EXT = '.a' if GPROF: CXXFLAGS = '%s -pg' % CXXFLAGS LDFLAGS = '%s -pg' % LDFLAGS if GMP: test_gmp(CXX) ARITH = "gmp" CPPFLAGS = '%s -D_MP_GMP' % CPPFLAGS LDFLAGS = '%s -lgmp' % LDFLAGS SLIBEXTRAFLAGS = '%s -lgmp' % SLIBEXTRAFLAGS else: CPPFLAGS = '%s -D_MP_INTERNAL' % CPPFLAGS if GIT_HASH: CPPFLAGS = '%s -DZ3GITHASH=%s' % (CPPFLAGS, GIT_HASH) CXXFLAGS = '%s -std=c++17' % CXXFLAGS CXXFLAGS = '%s -fvisibility=hidden -fvisibility-inlines-hidden -c' % CXXFLAGS FPMATH = test_fpmath(CXX) CXXFLAGS = '%s %s' % (CXXFLAGS, FPMATH_FLAGS) if LOG_SYNC: CXXFLAGS = '%s -DZ3_LOG_SYNC' % CXXFLAGS if SINGLE_THREADED: CXXFLAGS = '%s -DSINGLE_THREAD' % CXXFLAGS if DEBUG_MODE: CXXFLAGS = '%s -g -Wall' % CXXFLAGS EXAMP_DEBUG_FLAG = '-g' CPPFLAGS = '%s -DZ3DEBUG -D_DEBUG' % CPPFLAGS else: CXXFLAGS = '%s -O3' % CXXFLAGS if GPROF: CXXFLAGS += '-fomit-frame-pointer' CPPFLAGS = '%s -DNDEBUG -D_EXTERNAL_RELEASE' % CPPFLAGS if is_CXX_clangpp(): CXXFLAGS = '%s -Wno-unknown-pragmas -Wno-overloaded-virtual -Wno-unused-value' % CXXFLAGS sysname, _, _, _, machine = os.uname() if sysname == 'Darwin': SO_EXT = '.dylib' SLIBFLAGS = '-dynamiclib' elif sysname == 'Linux': SO_EXT = '.so' SLIBFLAGS = '-shared' SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so' % SLIBEXTRAFLAGS elif sysname == 'GNU': SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'FreeBSD': SO_EXT = '.so' SLIBFLAGS = '-shared' SLIBEXTRAFLAGS = '%s -Wl,-soname,libz3.so' % SLIBEXTRAFLAGS elif sysname == 'NetBSD': SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'OpenBSD': SO_EXT = '.so' SLIBFLAGS = '-shared' elif sysname == 'SunOS': SO_EXT = '.so' SLIBFLAGS = '-shared' SLIBEXTRAFLAGS = '%s -mimpure-text' % SLIBEXTRAFLAGS elif sysname.startswith('CYGWIN'): SO_EXT = '.dll' SLIBFLAGS = '-shared' elif sysname.startswith('MSYS_NT') or sysname.startswith('MINGW'): SO_EXT = '.dll' SLIBFLAGS = '-shared' EXE_EXT = '.exe' LIB_EXT = '.lib' else: raise MKException('Unsupported platform: %s' % sysname) if is64(): if not sysname.startswith('CYGWIN') and not sysname.startswith('MSYS') and not sysname.startswith('MINGW'): CXXFLAGS = '%s -fPIC' % CXXFLAGS elif not LINUX_X64: CXXFLAGS = '%s -m32' % CXXFLAGS LDFLAGS = '%s -m32' % LDFLAGS SLIBFLAGS = '%s -m32' % SLIBFLAGS if TRACE or DEBUG_MODE: CPPFLAGS = '%s -D_TRACE' % CPPFLAGS if is_cygwin_mingw() or is_msys2(): # when cross-compiling with MinGW, we need to statically link its standard libraries # and to make it create an import library. SLIBEXTRAFLAGS = '%s -static-libgcc -static-libstdc++ -Wl,--out-implib,libz3.dll.a' % SLIBEXTRAFLAGS LDFLAGS = '%s -static-libgcc -static-libstdc++' % LDFLAGS if sysname == 'Linux' and machine.startswith('armv7') or machine.startswith('armv8'): CXXFLAGS = '%s -fpic' % CXXFLAGS if IS_OSX and IS_ARCH_ARM64: print("Setting arm64") CXXFLAGS = '%s -arch arm64' % CXXFLAGS LDFLAGS = '%s -arch arm64' % LDFLAGS SLIBEXTRAFLAGS = '%s -arch arm64' % SLIBEXTRAFLAGS config.write('PREFIX=%s\n' % PREFIX) config.write('CC=%s\n' % CC) config.write('CXX=%s\n' % CXX) config.write('CXXFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS)) config.write('CFLAGS=%s %s\n' % (CPPFLAGS, CXXFLAGS.replace('-std=c++17', ''))) config.write('EXAMP_DEBUG_FLAG=%s\n' % EXAMP_DEBUG_FLAG) config.write('CXX_OUT_FLAG=-o \n') config.write('C_OUT_FLAG=-o \n') config.write('OBJ_EXT=.o\n') config.write('LIB_EXT=%s\n' % LIB_EXT) config.write('AR=%s\n' % AR) config.write('AR_FLAGS=rcs\n') config.write('AR_OUTFLAG=\n') config.write('EXE_EXT=%s\n' % EXE_EXT) config.write('LINK=%s\n' % CXX) config.write('LINK_FLAGS=\n') config.write('LINK_OUT_FLAG=-o \n') if is_linux() and (build_static_lib() or build_static_bin()): config.write('LINK_EXTRA_FLAGS=-Wl,--whole-archive -lrt -lpthread -Wl,--no-whole-archive %s\n' % LDFLAGS) else: config.write('LINK_EXTRA_FLAGS=-lpthread %s\n' % LDFLAGS) config.write('SO_EXT=%s\n' % SO_EXT) config.write('SLINK=%s\n' % CXX) config.write('SLINK_FLAGS=%s\n' % SLIBFLAGS) config.write('SLINK_EXTRA_FLAGS=-lpthread %s\n' % SLIBEXTRAFLAGS) config.write('SLINK_OUT_FLAG=-o \n') config.write('OS_DEFINES=%s\n' % OS_DEFINES) if is_verbose(): print('Host platform: %s' % sysname) print('C++ Compiler: %s' % CXX) print('C Compiler : %s' % CC) if is_cygwin_mingw(): print('MinGW32 cross: %s' % (is_cygwin_mingw())) print('Archive Tool: %s' % AR) print('Arithmetic: %s' % ARITH) print('Prefix: %s' % PREFIX) print('64-bit: %s' % is64()) print('FP math: %s' % FPMATH) print("Python pkg dir: %s" % PYTHON_PACKAGE_DIR) if GPROF: print('gprof: enabled') print('Python version: %s' % sysconfig.get_python_version()) if is_java_enabled(): print('JNI Bindings: %s' % JNI_HOME) print('Java Compiler: %s' % JAVAC) if is_ml_enabled(): print('OCaml Compiler: %s' % OCAMLC) print('OCaml Find tool: %s' % OCAMLFIND) print('OCaml Native: %s' % OCAMLOPT) print('OCaml Library: %s' % OCAML_LIB) if is_dotnet_core_enabled(): print('C# Compiler: %s' % DOTNET) config.close() def mk_install(out): out.write('install: ') for c in get_components(): c.mk_install_deps(out) out.write(' ') out.write('\n') MakeRuleCmd.make_install_directory(out, INSTALL_BIN_DIR) MakeRuleCmd.make_install_directory(out, INSTALL_INCLUDE_DIR) MakeRuleCmd.make_install_directory(out, INSTALL_LIB_DIR) for c in get_components(): c.mk_install(out) out.write('\t@echo Z3 was successfully installed.\n') out.write('\n') def mk_uninstall(out): out.write('uninstall:\n') for c in get_components(): c.mk_uninstall(out) out.write('\t@echo Z3 was successfully uninstalled.\n') out.write('\n') # Generate the Z3 makefile def mk_makefile(): mk_dir(BUILD_DIR) mk_config() if VERBOSE: print("Writing %s" % os.path.join(BUILD_DIR, 'Makefile')) out = open(os.path.join(BUILD_DIR, 'Makefile'), 'w') out.write('# Automatically generated file.\n') out.write('include config.mk\n') # Generate :all rule out.write('all:') for c in get_components(): if c.main_component(): out.write(' %s' % c.name) out.write('\n\t@echo Z3 was successfully built.\n') out.write("\t@echo \"Z3Py scripts can already be executed in the \'%s\' directory.\"\n" % os.path.join(BUILD_DIR, 'python')) pathvar = "DYLD_LIBRARY_PATH" if IS_OSX else "PATH" if IS_WINDOWS else "LD_LIBRARY_PATH" out.write("\t@echo \"Z3Py scripts stored in arbitrary directories can be executed if the \'%s\' directory is added to the PYTHONPATH environment variable and the \'%s\' directory is added to the %s environment variable.\"\n" % (os.path.join(BUILD_DIR, 'python'), BUILD_DIR, pathvar)) if not IS_WINDOWS: out.write("\t@echo Use the following command to install Z3 at prefix $(PREFIX).\n") out.write('\t@echo " sudo make install"\n\n') # out.write("\t@echo If you are doing a staged install you can use DESTDIR.\n") # out.write('\t@echo " make DESTDIR=/some/temp/directory install"\n') # Generate :examples rule out.write('examples:') for c in get_components(): if c.is_example(): out.write(' _ex_%s' % c.name) out.write('\n\t@echo Z3 examples were successfully built.\n') # Generate components for c in get_components(): c.mk_makefile(out) # Generate install/uninstall rules if not WINDOWS if not IS_WINDOWS: mk_install(out) mk_uninstall(out) for c in get_components(): c.final_info() out.close() # Finalize if VERBOSE: print("Makefile was successfully generated.") if DEBUG_MODE: print(" compilation mode: Debug") else: print(" compilation mode: Release") if IS_WINDOWS: if VS_X64: print(" platform: x64\n") print("To build Z3, open a [Visual Studio x64 Command Prompt], then") elif VS_ARM: print(" platform: ARM\n") print("To build Z3, open a [Visual Studio ARM Command Prompt], then") else: print(" platform: x86") print("To build Z3, open a [Visual Studio Command Prompt], then") print("type 'cd %s && nmake'\n" % os.path.join(os.getcwd(), BUILD_DIR)) print('Remark: to open a Visual Studio Command Prompt, go to: "Start > All Programs > Visual Studio > Visual Studio Tools"') else: print("Type 'cd %s; make' to build Z3" % BUILD_DIR) # Generate automatically generated source code def mk_auto_src(): if not ONLY_MAKEFILES: exec_pyg_scripts() mk_pat_db() mk_all_install_tactic_cpps() mk_all_mem_initializer_cpps() mk_all_gparams_register_modules() def _execfile(file, globals=globals(), locals=locals()): if sys.version < "2.7": execfile(file, globals, locals) else: with open(file, "r") as fh: exec(fh.read()+"\n", globals, locals) # Execute python auxiliary scripts that generate extra code for Z3. def exec_pyg_scripts(): for root, dirs, files in os.walk('src'): for f in files: if f.endswith('.pyg'): script = os.path.join(root, f) generated_file = mk_genfile_common.mk_hpp_from_pyg(script, root) if is_verbose(): print("Generated '{}'".format(generated_file)) # TODO: delete after src/ast/pattern/expr_pattern_match # database.smt ==> database.h def mk_pat_db(): c = get_component(PATTERN_COMPONENT) fin = os.path.join(c.src_dir, 'database.smt2') fout = os.path.join(c.src_dir, 'database.h') mk_genfile_common.mk_pat_db_internal(fin, fout) if VERBOSE: print("Generated '{}'".format(fout)) # Update version numbers def update_version(): major = VER_MAJOR minor = VER_MINOR build = VER_BUILD revision = VER_TWEAK print("UpdateVersion:", get_full_version_string(major, minor, build, revision)) if major is None or minor is None or build is None or revision is None: raise MKException("set_version(major, minor, build, revision) must be used before invoking update_version()") if not ONLY_MAKEFILES: mk_version_dot_h(major, minor, build, revision) mk_all_assembly_infos(major, minor, build, revision) mk_def_files() def get_full_version_string(major, minor, build, revision): global GIT_HASH, GIT_DESCRIBE res = "Z3 %s.%s.%s.%s" % (major, minor, build, revision) if GIT_HASH: res += " " + GIT_HASH if GIT_DESCRIBE: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) res += " " + branch + " " + check_output(['git', 'describe']) return '"' + res + '"' # Update files with the version number def mk_version_dot_h(major, minor, build, revision): c = get_component(UTIL_COMPONENT) version_template = os.path.join(c.src_dir, 'z3_version.h.in') version_header_output = os.path.join(c.src_dir, 'z3_version.h') # Note the substitution names are what is used by the CMake # builds system. If you change these you should change them # in the CMake build too configure_file(version_template, version_header_output, { 'Z3_VERSION_MAJOR': str(major), 'Z3_VERSION_MINOR': str(minor), 'Z3_VERSION_PATCH': str(build), 'Z3_VERSION_TWEAK': str(revision), 'Z3_FULL_VERSION': get_full_version_string(major, minor, build, revision) } ) if VERBOSE: print("Generated '%s'" % version_header_output) # Generate AssemblyInfo.cs files with the right version numbers by using ``AssemblyInfo.cs.in`` files as a template def mk_all_assembly_infos(major, minor, build, revision): for c in get_components(): if c.has_assembly_info(): c.make_assembly_info(major, minor, build, revision) def get_header_files_for_components(component_src_dirs): assert isinstance(component_src_dirs, list) h_files_full_path = [] for component_src_dir in sorted(component_src_dirs): h_files = filter(lambda f: f.endswith('.h') or f.endswith('.hpp'), os.listdir(component_src_dir)) h_files = list(map(lambda p: os.path.join(component_src_dir, p), h_files)) h_files_full_path.extend(h_files) return h_files_full_path def mk_install_tactic_cpp(cnames, path): component_src_dirs = [] for cname in cnames: print("Component %s" % cname) c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_install_tactic_cpp_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_install_tactic_cpps(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_install_tactics(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_install_tactic_cpp(cnames, c.src_dir) def mk_mem_initializer_cpp(cnames, path): component_src_dirs = [] for cname in cnames: c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_mem_initializer_cpp_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_mem_initializer_cpps(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_mem_initializer(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_mem_initializer_cpp(cnames, c.src_dir) def mk_gparams_register_modules(cnames, path): component_src_dirs = [] for cname in cnames: c = get_component(cname) component_src_dirs.append(c.src_dir) h_files_full_path = get_header_files_for_components(component_src_dirs) generated_file = mk_genfile_common.mk_gparams_register_modules_internal(h_files_full_path, path) if VERBOSE: print("Generated '{}'".format(generated_file)) def mk_all_gparams_register_modules(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_mem_initializer(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_gparams_register_modules(cnames, c.src_dir) # Generate a .def based on the files at c.export_files slot. def mk_def_file(c): defname = '%s.def' % os.path.join(c.src_dir, c.name) dll_name = c.dll_name export_header_files = [] for dot_h in c.export_files: dot_h_c = c.find_file(dot_h, c.name) api = os.path.join(dot_h_c.src_dir, dot_h) export_header_files.append(api) mk_genfile_common.mk_def_file_internal(defname, dll_name, export_header_files) if VERBOSE: print("Generated '%s'" % defname) def mk_def_files(): if not ONLY_MAKEFILES: for c in get_components(): if c.require_def_file(): mk_def_file(c) def cp_z3py_to_build(): mk_dir(BUILD_DIR) mk_dir(os.path.join(BUILD_DIR, 'python')) z3py_dest = os.path.join(BUILD_DIR, 'python', 'z3') z3py_src = os.path.join(Z3PY_SRC_DIR, 'z3') # Erase existing .pyc files for root, dirs, files in os.walk(Z3PY_SRC_DIR): for f in files: if f.endswith('.pyc'): rmf(os.path.join(root, f)) # Compile Z3Py files if compileall.compile_dir(z3py_src, force=1) != 1: raise MKException("failed to compile Z3Py sources") if is_verbose: print("Generated python bytecode") # Copy sources to build mk_dir(z3py_dest) for py in filter(lambda f: f.endswith('.py'), os.listdir(z3py_src)): shutil.copyfile(os.path.join(z3py_src, py), os.path.join(z3py_dest, py)) if is_verbose(): print("Copied '%s'" % py) # Python 2.x support for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(z3py_src)): shutil.copyfile(os.path.join(z3py_src, pyc), os.path.join(z3py_dest, pyc)) if is_verbose(): print("Copied '%s'" % pyc) # Python 3.x support src_pycache = os.path.join(z3py_src, '__pycache__') target_pycache = os.path.join(z3py_dest, '__pycache__') if os.path.exists(src_pycache): for pyc in filter(lambda f: f.endswith('.pyc'), os.listdir(src_pycache)): mk_dir(target_pycache) shutil.copyfile(os.path.join(src_pycache, pyc), os.path.join(target_pycache, pyc)) if is_verbose(): print("Copied '%s'" % pyc) # Copy z3test.py shutil.copyfile(os.path.join(Z3PY_SRC_DIR, 'z3test.py'), os.path.join(BUILD_DIR, 'python', 'z3test.py')) def mk_bindings(api_files): if not ONLY_MAKEFILES: mk_z3consts_py(api_files) new_api_files = [] api = get_component(API_COMPONENT) for api_file in api_files: api_file_path = api.find_file(api_file, api.name) new_api_files.append(os.path.join(api_file_path.src_dir, api_file)) g = globals() g["API_FILES"] = new_api_files if is_java_enabled(): check_java() mk_z3consts_java(api_files) # Generate some of the bindings and "api" module files import update_api dotnet_output_dir = None if is_dotnet_core_enabled(): dotnet_output_dir = os.path.join(BUILD_DIR, 'dotnet') mk_dir(dotnet_output_dir) java_input_dir = None java_output_dir = None java_package_name = None if is_java_enabled(): java_output_dir = get_component('java').src_dir java_input_dir = get_component('java').src_dir java_package_name = get_component('java').package_name ml_output_dir = None if is_ml_enabled(): ml_output_dir = get_component('ml').src_dir # Get the update_api module to do the work for us update_api.VERBOSE = is_verbose() update_api.generate_files(api_files=new_api_files, api_output_dir=get_component('api').src_dir, z3py_output_dir=get_z3py_dir(), dotnet_output_dir=dotnet_output_dir, java_input_dir=java_input_dir, java_output_dir=java_output_dir, java_package_name=java_package_name, ml_output_dir=ml_output_dir, ml_src_dir=ml_output_dir ) cp_z3py_to_build() if is_ml_enabled(): check_ml() mk_z3consts_ml(api_files) if is_dotnet_core_enabled(): check_dotnet_core() mk_z3consts_dotnet(api_files, dotnet_output_dir) # Extract enumeration types from API files, and add python definitions. def mk_z3consts_py(api_files): if Z3PY_SRC_DIR is None: raise MKException("You must invoke set_z3py_dir(path):") full_path_api_files = [] api_dll = get_component(Z3_DLL_COMPONENT) for api_file in api_files: api_file_c = api_dll.find_file(api_file, api_dll.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_py_internal(full_path_api_files, Z3PY_SRC_DIR) if VERBOSE: print("Generated '{}".format(generated_file)) # Extract enumeration types from z3_api.h, and add .Net definitions def mk_z3consts_dotnet(api_files, output_dir): dotnet = get_component(DOTNET_COMPONENT) if not dotnet: dotnet = get_component(DOTNET_CORE_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = dotnet.find_file(api_file, dotnet.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_dotnet_internal(full_path_api_files, output_dir) if VERBOSE: print("Generated '{}".format(generated_file)) # Extract enumeration types from z3_api.h, and add Java definitions def mk_z3consts_java(api_files): java = get_component(JAVA_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = java.find_file(api_file, java.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_files = mk_genfile_common.mk_z3consts_java_internal( full_path_api_files, java.package_name, java.src_dir) if VERBOSE: for generated_file in generated_files: print("Generated '{}'".format(generated_file)) # Extract enumeration types from z3_api.h, and add ML definitions def mk_z3consts_ml(api_files): ml = get_component(ML_COMPONENT) full_path_api_files = [] for api_file in api_files: api_file_c = ml.find_file(api_file, ml.name) api_file = os.path.join(api_file_c.src_dir, api_file) full_path_api_files.append(api_file) generated_file = mk_genfile_common.mk_z3consts_ml_internal( full_path_api_files, ml.src_dir) if VERBOSE: print ('Generated "%s"' % generated_file) def mk_gui_str(id): return '4D2F40D8-E5F9-473B-B548-%012d' % id def get_platform_toolset_str(): default = 'v110'; vstr = check_output(['msbuild', '/ver']) lines = vstr.split('\n') lline = lines[-1] tokens = lline.split('.') if len(tokens) < 2: return default else: if tokens[0] == "15": # Visual Studio 2017 reports 15.* but the PlatformToolsetVersion is 141 return "v141" else: return 'v' + tokens[0] + tokens[1] def mk_vs_proj_property_groups(f, name, target_ext, type): f.write(' <ItemGroup Label="ProjectConfigurations">\n') f.write(' <ProjectConfiguration Include="Debug|Win32">\n') f.write(' <Configuration>Debug</Configuration>\n') f.write(' <Platform>Win32</Platform>\n') f.write(' </ProjectConfiguration>\n') f.write(' <ProjectConfiguration Include="Release|Win32">\n') f.write(' <Configuration>Release</Configuration>\n') f.write(' <Platform>Win32</Platform>\n') f.write(' </ProjectConfiguration>\n') f.write(' </ItemGroup>\n') f.write(' <PropertyGroup Label="Globals">\n') f.write(' <ProjectGuid>{%s}</ProjectGuid>\n' % mk_gui_str(0)) f.write(' <ProjectName>%s</ProjectName>\n' % name) f.write(' <Keyword>Win32Proj</Keyword>\n') f.write(' <PlatformToolset>%s</PlatformToolset>\n' % get_platform_toolset_str()) f.write(' </PropertyGroup>\n') f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'" Label="Configuration">\n') f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type) f.write(' <CharacterSet>Unicode</CharacterSet>\n') f.write(' <UseOfMfc>false</UseOfMfc>\n') f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'" Label="Configuration">\n') f.write(' <ConfigurationType>%s</ConfigurationType>\n' % type) f.write(' <CharacterSet>Unicode</CharacterSet>\n') f.write(' <UseOfMfc>false</UseOfMfc>\n') f.write(' </PropertyGroup>\n') f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\n') f.write(' <ImportGroup Label="ExtensionSettings" />\n') f.write(' <ImportGroup Label="PropertySheets">\n') f.write(' <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists(\'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props\')" Label="LocalAppDataPlatform" /> </ImportGroup>\n') f.write(' <PropertyGroup Label="UserMacros" />\n') f.write(' <PropertyGroup>\n') f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">$(SolutionDir)\$(ProjectName)\$(Configuration)\</OutDir>\n') f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">%s</TargetName>\n' % name) f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">.%s</TargetExt>\n' % target_ext) f.write(' <OutDir Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">$(SolutionDir)\$(ProjectName)\$(Configuration)\</OutDir>\n') f.write(' <TargetName Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">%s</TargetName>\n' % name) f.write(' <TargetExt Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">.%s</TargetExt>\n' % target_ext) f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') f.write(' <IntDir>$(ProjectName)\$(Configuration)\</IntDir>\n') f.write(' </PropertyGroup>\n') f.write(' <PropertyGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') f.write(' <IntDir>$(ProjectName)\$(Configuration)\</IntDir>\n') f.write(' </PropertyGroup>\n') def mk_vs_proj_cl_compile(f, name, components, debug): f.write(' <ClCompile>\n') f.write(' <Optimization>Disabled</Optimization>\n') if debug: f.write(' <PreprocessorDefinitions>WIN32;_DEBUG;Z3DEBUG;_TRACE;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n') else: f.write(' <PreprocessorDefinitions>WIN32;NDEBUG;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n') if VS_PAR: f.write(' <MinimalRebuild>false</MinimalRebuild>\n') f.write(' <MultiProcessorCompilation>true</MultiProcessorCompilation>\n') else: f.write(' <MinimalRebuild>true</MinimalRebuild>\n') f.write(' <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\n') f.write(' <WarningLevel>Level3</WarningLevel>\n') if debug: f.write(' <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>\n') else: f.write(' <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>\n') f.write(' <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\n') f.write(' <AdditionalIncludeDirectories>') deps = find_all_deps(name, components) first = True for dep in deps: if first: first = False else: f.write(';') f.write(get_component(dep).to_src_dir) f.write(';%s\n' % os.path.join(REV_BUILD_DIR, SRC_DIR)) f.write('</AdditionalIncludeDirectories>\n') f.write(' </ClCompile>\n') def mk_vs_proj_dep_groups(f, name, components): f.write(' <ItemGroup>\n') deps = find_all_deps(name, components) for dep in deps: dep = get_component(dep) for cpp in filter(lambda f: f.endswith('.cpp'), os.listdir(dep.src_dir)): f.write(' <ClCompile Include="%s" />\n' % os.path.join(dep.to_src_dir, cpp)) f.write(' </ItemGroup>\n') def mk_vs_proj_link_exe(f, name, debug): f.write(' <Link>\n') f.write(' <OutputFile>$(OutDir)%s.exe</OutputFile>\n' % name) f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n') f.write(' <SubSystem>Console</SubSystem>\n') f.write(' <StackReserveSize>8388608</StackReserveSize>\n') f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n') f.write(' <DataExecutionPrevention/>\n') f.write(' <TargetMachine>MachineX86</TargetMachine>\n') f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n') f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n') f.write(' </Link>\n') def mk_vs_proj(name, components): if not VS_PROJ: return proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name) modes=['Debug', 'Release'] PLATFORMS=['Win32'] f = open(proj_name, 'w') f.write('<?xml version="1.0" encoding="utf-8"?>\n') f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n') mk_vs_proj_property_groups(f, name, 'exe', 'Application') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=True) mk_vs_proj_link_exe(f, name, debug=True) f.write(' </ItemDefinitionGroup>\n') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=False) mk_vs_proj_link_exe(f, name, debug=False) f.write(' </ItemDefinitionGroup>\n') mk_vs_proj_dep_groups(f, name, components) f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n') f.write(' <ImportGroup Label="ExtensionTargets">\n') f.write(' </ImportGroup>\n') f.write('</Project>\n') f.close() if is_verbose(): print("Generated '%s'" % proj_name) def mk_vs_proj_link_dll(f, name, debug): f.write(' <Link>\n') f.write(' <OutputFile>$(OutDir)%s.dll</OutputFile>\n' % name) f.write(' <GenerateDebugInformation>true</GenerateDebugInformation>\n') f.write(' <SubSystem>Console</SubSystem>\n') f.write(' <StackReserveSize>8388608</StackReserveSize>\n') f.write(' <RandomizedBaseAddress>false</RandomizedBaseAddress>\n') f.write(' <DataExecutionPrevention/>\n') f.write(' <TargetMachine>MachineX86</TargetMachine>\n') f.write(' <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n') f.write(' <AdditionalDependencies>psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n') f.write(' <ModuleDefinitionFile>%s</ModuleDefinitionFile>' % os.path.join(get_component('api_dll').to_src_dir, 'api_dll.def')) f.write(' </Link>\n') def mk_vs_proj_dll(name, components): if not VS_PROJ: return proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name) modes=['Debug', 'Release'] PLATFORMS=['Win32'] f = open(proj_name, 'w') f.write('<?xml version="1.0" encoding="utf-8"?>\n') f.write('<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n') mk_vs_proj_property_groups(f, name, 'dll', 'DynamicLibrary') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Debug|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=True) mk_vs_proj_link_dll(f, name, debug=True) f.write(' </ItemDefinitionGroup>\n') f.write(' <ItemDefinitionGroup Condition="\'$(Configuration)|$(Platform)\'==\'Release|Win32\'">\n') mk_vs_proj_cl_compile(f, name, components, debug=False) mk_vs_proj_link_dll(f, name, debug=False) f.write(' </ItemDefinitionGroup>\n') mk_vs_proj_dep_groups(f, name, components) f.write(' <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n') f.write(' <ImportGroup Label="ExtensionTargets">\n') f.write(' </ImportGroup>\n') f.write('</Project>\n') f.close() if is_verbose(): print("Generated '%s'" % proj_name) def mk_win_dist(build_path, dist_path): for c in get_components(): c.mk_win_dist(build_path, dist_path) def mk_unix_dist(build_path, dist_path): for c in get_components(): c.mk_unix_dist(build_path, dist_path) # Add Z3Py to bin directory for pyc in filter(lambda f: f.endswith('.pyc') or f.endswith('.py'), os.listdir(build_path)): shutil.copy(os.path.join(build_path, pyc), os.path.join(dist_path, INSTALL_BIN_DIR, pyc)) class MakeRuleCmd(object): """ These class methods provide a convenient way to emit frequently needed commands used in Makefile rules Note that several of the method are meant for use during ``make install`` and ``make uninstall``. These methods correctly use ``$(PREFIX)`` and ``$(DESTDIR)`` and therefore are preferable to writing commands manually which can be error prone. """ @classmethod def install_root(cls): """ Returns a string that will expand to the install location when used in a makefile rule. """ # Note: DESTDIR is to support staged installs return "$(DESTDIR)$(PREFIX)/" @classmethod def _is_str(cls, obj): if sys.version_info.major > 2: # Python 3 or newer. Strings are always unicode and of type str return isinstance(obj, str) else: # Python 2. Has byte-string and unicode representation, allow both return isinstance(obj, str) or isinstance(obj, unicode) @classmethod def _install_root(cls, path, in_prefix, out, is_install=True): if not in_prefix: # The Python bindings on OSX are sometimes not installed inside the prefix. install_root = "$(DESTDIR)" action_string = 'install' if is_install else 'uninstall' cls.write_cmd(out, 'echo "WARNING: {}ing files/directories ({}) that are not in the install prefix ($(PREFIX))."'.format( action_string, path)) #print("WARNING: Generating makefile rule that {}s {} '{}' which is outside the installation prefix '{}'.".format( # action_string, 'to' if is_install else 'from', path, PREFIX)) else: # assert not os.path.isabs(path) install_root = cls.install_root() return install_root @classmethod def install_files(cls, out, src_pattern, dest, in_prefix=True): assert len(dest) > 0 assert cls._is_str(src_pattern) assert not ' ' in src_pattern assert cls._is_str(dest) assert not ' ' in dest assert not os.path.isabs(src_pattern) install_root = cls._install_root(dest, in_prefix, out) cls.write_cmd(out, "cp {src_pattern} {install_root}{dest}".format( src_pattern=src_pattern, install_root=install_root, dest=dest)) @classmethod def remove_installed_files(cls, out, pattern, in_prefix=True): assert len(pattern) > 0 assert cls._is_str(pattern) assert not ' ' in pattern install_root = cls._install_root(pattern, in_prefix, out, is_install=False) cls.write_cmd(out, "rm -f {install_root}{pattern}".format( install_root=install_root, pattern=pattern)) @classmethod def make_install_directory(cls, out, dir, in_prefix=True): assert len(dir) > 0 assert cls._is_str(dir) assert not ' ' in dir install_root = cls._install_root(dir, in_prefix, out) if is_windows(): cls.write_cmd(out, "IF NOT EXIST {dir} (mkdir {dir})".format( install_root=install_root, dir=dir)) else: cls.write_cmd(out, "mkdir -p {install_root}{dir}".format( install_root=install_root, dir=dir)) @classmethod def _is_path_prefix_of(cls, temp_path, target_as_abs): """ Returns True iff ``temp_path`` is a path prefix of ``target_as_abs`` """ assert cls._is_str(temp_path) assert cls._is_str(target_as_abs) assert len(temp_path) > 0 assert len(target_as_abs) > 0 assert os.path.isabs(temp_path) assert os.path.isabs(target_as_abs) # Need to stick extra slash in front otherwise we might think that # ``/lib`` is a prefix of ``/lib64``. Of course if ``temp_path == # '/'`` then we shouldn't else we would check if ``//`` (rather than # ``/``) is a prefix of ``/lib64``, which would fail. if len(temp_path) > 1: temp_path += os.sep return target_as_abs.startswith(temp_path) @classmethod def create_relative_symbolic_link(cls, out, target, link_name): assert cls._is_str(target) assert cls._is_str(link_name) assert len(target) > 0 assert len(link_name) > 0 assert not os.path.isabs(target) assert not os.path.isabs(link_name) # We can't test to see if link_name is a file or directory # because it may not exist yet. Instead follow the convention # that if there is a leading slash target is a directory otherwise # it's a file if link_name[-1] != '/': # link_name is a file temp_path = os.path.dirname(link_name) else: # link_name is a directory temp_path = link_name[:-1] temp_path = '/' + temp_path relative_path = "" targetAsAbs = '/' + target assert os.path.isabs(targetAsAbs) assert os.path.isabs(temp_path) # Keep walking up the directory tree until temp_path # is a prefix of targetAsAbs while not cls._is_path_prefix_of(temp_path, targetAsAbs): assert temp_path != '/' temp_path = os.path.dirname(temp_path) relative_path += '../' # Now get the path from the common prefix directory to the target target_from_prefix = targetAsAbs[len(temp_path):] relative_path += target_from_prefix # Remove any double slashes relative_path = relative_path.replace('//','/') cls.create_symbolic_link(out, relative_path, link_name) @classmethod def create_symbolic_link(cls, out, target, link_name): assert cls._is_str(target) assert cls._is_str(link_name) assert not os.path.isabs(target) cls.write_cmd(out, 'ln -s {target} {install_root}{link_name}'.format( target=target, install_root=cls.install_root(), link_name=link_name)) # TODO: Refactor all of the build system to emit commands using this # helper to simplify code. This will also let us replace ``@`` with # ``$(Verb)`` and have it set to ``@`` or empty at build time depending on # a variable (e.g. ``VERBOSE``) passed to the ``make`` invocation. This # would be very helpful for debugging. @classmethod def write_cmd(cls, out, line): out.write("\t@{}\n".format(line)) def strip_path_prefix(path, prefix): if path.startswith(prefix): stripped_path = path[len(prefix):] stripped_path.replace('//','/') if stripped_path[0] == '/': stripped_path = stripped_path[1:] assert not os.path.isabs(stripped_path) return stripped_path else: return path def configure_file(template_file_path, output_file_path, substitutions): """ Read a template file ``template_file_path``, perform substitutions found in the ``substitutions`` dictionary and write the result to the output file ``output_file_path``. The template file should contain zero or more template strings of the form ``@NAME@``. The substitutions dictionary maps old strings (without the ``@`` symbols) to their replacements. """ assert isinstance(template_file_path, str) assert isinstance(output_file_path, str) assert isinstance(substitutions, dict) assert len(template_file_path) > 0 assert len(output_file_path) > 0 print("Generating {} from {}".format(output_file_path, template_file_path)) if not os.path.exists(template_file_path): raise MKException('Could not find template file "{}"'.format(template_file_path)) # Read whole template file into string template_string = None with open(template_file_path, 'r') as f: template_string = f.read() # Do replacements for (old_string, replacement) in substitutions.items(): template_string = template_string.replace('@{}@'.format(old_string), replacement) # Write the string to the file with open(output_file_path, 'w') as f: f.write(template_string) if __name__ == '__main__': import doctest doctest.testmod()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_util.py
mk_util.py
import argparse import logging import re import os import sys VERBOSE = True def is_verbose(): return VERBOSE ########################################################## # TODO: rewrite this file without using global variables. # This file is a big HACK. # It started as small simple script. # Now, it is too big, and is invoked from mk_make.py # ########################################################## IN = 0 OUT = 1 INOUT = 2 IN_ARRAY = 3 OUT_ARRAY = 4 INOUT_ARRAY = 5 OUT_MANAGED_ARRAY = 6 FN_PTR = 7 # Primitive Types VOID = 0 VOID_PTR = 1 INT = 2 UINT = 3 INT64 = 4 UINT64 = 5 STRING = 6 STRING_PTR = 7 BOOL = 8 SYMBOL = 9 PRINT_MODE = 10 ERROR_CODE = 11 DOUBLE = 12 FLOAT = 13 CHAR = 14 CHAR_PTR = 15 LBOOL = 16 FIRST_FN_ID = 50 FIRST_OBJ_ID = 100 def is_obj(ty): return ty >= FIRST_OBJ_ID def is_fn(ty): return FIRST_FN_ID <= ty and ty < FIRST_OBJ_ID Type2Str = { VOID : 'void', VOID_PTR : 'void*', INT : 'int', UINT : 'unsigned', INT64 : 'int64_t', UINT64 : 'uint64_t', DOUBLE : 'double', FLOAT : 'float', STRING : 'Z3_string', STRING_PTR : 'Z3_string_ptr', BOOL : 'bool', SYMBOL : 'Z3_symbol', PRINT_MODE : 'Z3_ast_print_mode', ERROR_CODE : 'Z3_error_code', CHAR: 'char', CHAR_PTR: 'Z3_char_ptr', LBOOL : 'Z3_lbool' } Type2PyStr = { VOID_PTR : 'ctypes.c_void_p', INT : 'ctypes.c_int', UINT : 'ctypes.c_uint', INT64 : 'ctypes.c_longlong', UINT64 : 'ctypes.c_ulonglong', DOUBLE : 'ctypes.c_double', FLOAT : 'ctypes.c_float', STRING : 'ctypes.c_char_p', STRING_PTR : 'ctypes.POINTER(ctypes.c_char_p)', BOOL : 'ctypes.c_bool', SYMBOL : 'Symbol', PRINT_MODE : 'ctypes.c_uint', ERROR_CODE : 'ctypes.c_uint', CHAR : 'ctypes.c_char', CHAR_PTR: 'ctypes.POINTER(ctypes.c_char)', LBOOL : 'ctypes.c_int' } # Mapping to .NET types Type2Dotnet = { VOID : 'void', VOID_PTR : 'IntPtr', INT : 'int', UINT : 'uint', INT64 : 'Int64', UINT64 : 'UInt64', DOUBLE : 'double', FLOAT : 'float', STRING : 'string', STRING_PTR : 'byte**', BOOL : 'byte', SYMBOL : 'IntPtr', PRINT_MODE : 'uint', ERROR_CODE : 'uint', CHAR : 'char', CHAR_PTR : 'IntPtr', LBOOL : 'int' } # Mapping to ML types Type2ML = { VOID : 'unit', VOID_PTR : 'ptr', INT : 'int', UINT : 'int', INT64 : 'int64', UINT64 : 'int64', DOUBLE : 'float', FLOAT : 'float', STRING : 'string', STRING_PTR : 'char**', BOOL : 'bool', SYMBOL : 'z3_symbol', PRINT_MODE : 'int', ERROR_CODE : 'int', CHAR : 'char', CHAR_PTR : 'string', LBOOL : 'int' } Closures = [] class APITypes: def __init__(self): self.next_type_id = FIRST_OBJ_ID self.next_fntype_id = FIRST_FN_ID def def_Type(self, var, c_type, py_type): """Process type definitions of the form def_Type(var, c_type, py_type) The variable 'var' is set to a unique number and recorded globally using exec It is used by 'def_APIs' to that uses the unique numbers to access the corresponding C and Python types. """ id = self.next_type_id exec('%s = %s' % (var, id), globals()) Type2Str[id] = c_type Type2PyStr[id] = py_type self.next_type_id += 1 def def_Types(self, api_files): global Closures pat1 = re.compile(" *def_Type\(\'(.*)\',[^\']*\'(.*)\',[^\']*\'(.*)\'\)[ \t]*") pat2 = re.compile("Z3_DECLARE_CLOSURE\((.*),(.*), \((.*)\)\)") for api_file in api_files: with open(api_file, 'r') as api: for line in api: m = pat1.match(line) if m: self.def_Type(m.group(1), m.group(2), m.group(3)) continue m = pat2.match(line) if m: self.fun_Type(m.group(1)) Closures += [(m.group(1), m.group(2), m.group(3))] continue # # Populate object type entries in dotnet and ML bindings. # for k in Type2Str: v = Type2Str[k] if is_obj(k) or is_fn(k): Type2Dotnet[k] = v Type2ML[k] = v.lower() def fun_Type(self, var): """Process function type definitions""" id = self.next_fntype_id exec('%s = %s' % (var, id), globals()) Type2Str[id] = var Type2PyStr[id] = var self.next_fntype_id += 1 def type2str(ty): global Type2Str return Type2Str[ty] def type2pystr(ty): global Type2PyStr return Type2PyStr[ty] def type2dotnet(ty): global Type2Dotnet return Type2Dotnet[ty] def type2ml(ty): global Type2ML q = Type2ML[ty] if q[0:3] == 'z3_': return q[3:] else: return q; def _in(ty): return (IN, ty) def _in_array(sz, ty): return (IN_ARRAY, ty, sz) def _fnptr(ty): return (FN_PTR, ty) def _out(ty): return (OUT, ty) def _out_array(sz, ty): return (OUT_ARRAY, ty, sz, sz) # cap contains the position of the argument that stores the capacity of the array # sz contains the position of the output argument that stores the (real) size of the array def _out_array2(cap, sz, ty): return (OUT_ARRAY, ty, cap, sz) def _inout_array(sz, ty): return (INOUT_ARRAY, ty, sz, sz) def _out_managed_array(sz,ty): return (OUT_MANAGED_ARRAY, ty, 0, sz) def param_kind(p): return p[0] def param_type(p): return p[1] def param_array_capacity_pos(p): return p[2] def param_array_size_pos(p): return p[3] def param2str(p): if param_kind(p) == IN_ARRAY: return "%s const *" % (type2str(param_type(p))) elif param_kind(p) == OUT_ARRAY or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY: return "%s*" % (type2str(param_type(p))) elif param_kind(p) == OUT: return "%s*" % (type2str(param_type(p))) elif param_kind(p) == FN_PTR: return "%s*" % (type2str(param_type(p))) else: return type2str(param_type(p)) def param2dotnet(p): k = param_kind(p) if k == OUT: if param_type(p) == STRING: return "out IntPtr" else: return "[In, Out] ref %s" % type2dotnet(param_type(p)) elif k == IN_ARRAY: return "[In] %s[]" % type2dotnet(param_type(p)) elif k == INOUT_ARRAY: return "[In, Out] %s[]" % type2dotnet(param_type(p)) elif k == OUT_ARRAY: return "[Out] %s[]" % type2dotnet(param_type(p)) elif k == OUT_MANAGED_ARRAY: return "[Out] out %s[]" % type2dotnet(param_type(p)) else: return type2dotnet(param_type(p)) # -------------- def param2pystr(p): if param_kind(p) == IN_ARRAY or param_kind(p) == OUT_ARRAY or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT: return "ctypes.POINTER(%s)" % type2pystr(param_type(p)) else: return type2pystr(param_type(p)) # -------------- # ML def param2ml(p): k = param_kind(p) if k == OUT: if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL: return "int" elif param_type(p) == INT64 or param_type(p) == UINT64: return "int64" elif param_type(p) == STRING: return "string" else: return "ptr" elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: return "%s list" % type2ml(param_type(p)) elif k == OUT_MANAGED_ARRAY: return "%s list" % type2ml(param_type(p)) else: return type2ml(param_type(p)) # Save name, result, params to generate wrapper _API2PY = [] def mk_py_binding(name, result, params): global core_py global _API2PY _API2PY.append((name, result, params)) if result != VOID: core_py.write("_lib.%s.restype = %s\n" % (name, type2pystr(result))) core_py.write("_lib.%s.argtypes = [" % name) first = True for p in params: if first: first = False else: core_py.write(", ") core_py.write(param2pystr(p)) core_py.write("]\n") def extra_API(name, result, params): mk_py_binding(name, result, params) reg_dotnet(name, result, params) def display_args(num): for i in range(num): if i > 0: core_py.write(", ") core_py.write("a%s" % i) def display_args_to_z3(params): i = 0 for p in params: if i > 0: core_py.write(", ") if param_type(p) == STRING: core_py.write("_str_to_bytes(a%s)" % i) else: core_py.write("a%s" % i) i = i + 1 NULLWrapped = [ 'Z3_mk_context', 'Z3_mk_context_rc' ] Unwrapped = [ 'Z3_del_context', 'Z3_get_error_code' ] Unchecked = frozenset([ 'Z3_dec_ref', 'Z3_params_dec_ref', 'Z3_model_dec_ref', 'Z3_func_interp_dec_ref', 'Z3_func_entry_dec_ref', 'Z3_goal_dec_ref', 'Z3_tactic_dec_ref', 'Z3_simplifier_dec_ref', 'Z3_probe_dec_ref', 'Z3_fixedpoint_dec_ref', 'Z3_param_descrs_dec_ref', 'Z3_ast_vector_dec_ref', 'Z3_ast_map_dec_ref', 'Z3_apply_result_dec_ref', 'Z3_solver_dec_ref', 'Z3_stats_dec_ref', 'Z3_optimize_dec_ref']) def mk_py_wrappers(): core_py.write(""" class Elementaries: def __init__(self, f): self.f = f self.get_error_code = _lib.Z3_get_error_code self.get_error_message = _lib.Z3_get_error_msg self.OK = Z3_OK self.Exception = Z3Exception def Check(self, ctx): err = self.get_error_code(ctx) if err != self.OK: raise self.Exception(self.get_error_message(ctx, err)) def Z3_set_error_handler(ctx, hndlr, _elems=Elementaries(_lib.Z3_set_error_handler)): ceh = _error_handler_type(hndlr) _elems.f(ctx, ceh) _elems.Check(ctx) return ceh def Z3_solver_register_on_clause(ctx, s, user_ctx, on_clause_eh, _elems = Elementaries(_lib.Z3_solver_register_on_clause)): _elems.f(ctx, s, user_ctx, on_clause_eh) _elems.Check(ctx) def Z3_solver_propagate_init(ctx, s, user_ctx, push_eh, pop_eh, fresh_eh, _elems = Elementaries(_lib.Z3_solver_propagate_init)): _elems.f(ctx, s, user_ctx, push_eh, pop_eh, fresh_eh) _elems.Check(ctx) def Z3_solver_propagate_final(ctx, s, final_eh, _elems = Elementaries(_lib.Z3_solver_propagate_final)): _elems.f(ctx, s, final_eh) _elems.Check(ctx) def Z3_solver_propagate_fixed(ctx, s, fixed_eh, _elems = Elementaries(_lib.Z3_solver_propagate_fixed)): _elems.f(ctx, s, fixed_eh) _elems.Check(ctx) def Z3_solver_propagate_eq(ctx, s, eq_eh, _elems = Elementaries(_lib.Z3_solver_propagate_eq)): _elems.f(ctx, s, eq_eh) _elems.Check(ctx) def Z3_solver_propagate_diseq(ctx, s, diseq_eh, _elems = Elementaries(_lib.Z3_solver_propagate_diseq)): _elems.f(ctx, s, diseq_eh) _elems.Check(ctx) def Z3_optimize_register_model_eh(ctx, o, m, user_ctx, on_model_eh, _elems = Elementaries(_lib.Z3_optimize_register_model_eh)): _elems.f(ctx, o, m, user_ctx, on_model_eh) _elems.Check(ctx) """) for sig in _API2PY: mk_py_wrapper_single(sig) if sig[1] == STRING: mk_py_wrapper_single(sig, decode_string=False) def mk_py_wrapper_single(sig, decode_string=True): name = sig[0] result = sig[1] params = sig[2] num = len(params) def_name = name if not decode_string: def_name += '_bytes' core_py.write("def %s(" % def_name) display_args(num) comma = ", " if num != 0 else "" core_py.write("%s_elems=Elementaries(_lib.%s)):\n" % (comma, name)) lval = "r = " if result != VOID else "" core_py.write(" %s_elems.f(" % lval) display_args_to_z3(params) core_py.write(")\n") if len(params) > 0 and param_type(params[0]) == CONTEXT and not name in Unwrapped and not name in Unchecked: core_py.write(" _elems.Check(a0)\n") if result == STRING and decode_string: core_py.write(" return _to_pystr(r)\n") elif result != VOID: core_py.write(" return r\n") core_py.write("\n") ## .NET API native interface _dotnet_decls = [] def reg_dotnet(name, result, params): global _dotnet_decls _dotnet_decls.append((name, result, params)) def mk_dotnet(dotnet): global Type2Str dotnet.write('// Automatically generated file\n') dotnet.write('using System;\n') dotnet.write('using System.Collections.Generic;\n') dotnet.write('using System.Text;\n') dotnet.write('using System.Runtime.InteropServices;\n\n') dotnet.write('#pragma warning disable 1591\n\n') dotnet.write('namespace Microsoft.Z3\n') dotnet.write('{\n') for k in Type2Str: v = Type2Str[k] if is_obj(k): dotnet.write(' using %s = System.IntPtr;\n' % v) dotnet.write(' using voidp = System.IntPtr;\n') dotnet.write('\n') dotnet.write(' public class Native\n') dotnet.write(' {\n\n') for name, ret, sig in Closures: sig = sig.replace("void*","voidp").replace("unsigned","uint") sig = sig.replace("Z3_ast*","ref IntPtr").replace("uint*","ref uint").replace("Z3_lbool*","ref int") ret = ret.replace("void*","voidp").replace("unsigned","uint") if "*" in sig or "*" in ret: continue dotnet.write(' [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n') dotnet.write(' public delegate %s %s(%s);\n' % (ret,name,sig)) dotnet.write(' public class LIB\n') dotnet.write(' {\n') dotnet.write(' const string Z3_DLL_NAME = \"libz3\";\n' ' \n') dotnet.write(' [DllImport(Z3_DLL_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n') dotnet.write(' public extern static void Z3_set_error_handler(Z3_context a0, Z3_error_handler a1);\n\n') for name, result, params in _dotnet_decls: dotnet.write(' [DllImport(Z3_DLL_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n') dotnet.write(' ') if result == STRING: dotnet.write('public extern static IntPtr %s(' % (name)) else: dotnet.write('public extern static %s %s(' % (type2dotnet(result), name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') dotnet.write('%s a%d' % (param2dotnet(param), i)) i = i + 1 dotnet.write(');\n\n') dotnet.write(' }\n') def mk_dotnet_wrappers(dotnet): global Type2Str dotnet.write("\n") dotnet.write(" public static void Z3_set_error_handler(Z3_context a0, Z3_error_handler a1) {\n") dotnet.write(" LIB.Z3_set_error_handler(a0, a1);\n") dotnet.write(" Z3_error_code err = (Z3_error_code)LIB.Z3_get_error_code(a0);\n") dotnet.write(" if (err != Z3_error_code.Z3_OK)\n") dotnet.write(" throw new Z3Exception(Marshal.PtrToStringAnsi(LIB.Z3_get_error_msg(a0, (uint)err)));\n") dotnet.write(" }\n\n") for name, result, params in _dotnet_decls: if result == STRING: dotnet.write(' public static string %s(' % (name)) else: dotnet.write(' public static %s %s(' % (type2dotnet(result), name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') dotnet.write('%s a%d' % (param2dotnet(param), i)) i = i + 1 dotnet.write(') {\n') dotnet.write(' ') if result == STRING: dotnet.write('IntPtr r = ') elif result != VOID: dotnet.write('%s r = ' % type2dotnet(result)) dotnet.write('LIB.%s(' % (name)) first = True i = 0 for param in params: if first: first = False else: dotnet.write(', ') if param_kind(param) == OUT: if param_type(param) == STRING: dotnet.write('out ') else: dotnet.write('ref ') elif param_kind(param) == OUT_MANAGED_ARRAY: dotnet.write('out ') dotnet.write('a%d' % i) i = i + 1 dotnet.write(');\n') if name not in Unwrapped: if name in NULLWrapped: dotnet.write(" if (r == IntPtr.Zero)\n") dotnet.write(" throw new Z3Exception(\"Object allocation failed.\");\n") else: if len(params) > 0 and param_type(params[0]) == CONTEXT and name not in Unchecked: dotnet.write(" Z3_error_code err = (Z3_error_code)LIB.Z3_get_error_code(a0);\n") dotnet.write(" if (err != Z3_error_code.Z3_OK)\n") dotnet.write(" throw new Z3Exception(Marshal.PtrToStringAnsi(LIB.Z3_get_error_msg(a0, (uint)err)));\n") if result == STRING: dotnet.write(" return Marshal.PtrToStringAnsi(r);\n") elif result != VOID: dotnet.write(" return r;\n") dotnet.write(" }\n\n") dotnet.write(" }\n\n") dotnet.write("}\n\n") # ---------------------- # Java Type2Java = { VOID : 'void', VOID_PTR : 'long', INT : 'int', UINT : 'int', INT64 : 'long', UINT64 : 'long', DOUBLE : 'double', FLOAT : 'float', STRING : 'String', STRING_PTR : 'StringPtr', BOOL : 'boolean', SYMBOL : 'long', PRINT_MODE : 'int', ERROR_CODE : 'int', CHAR : 'char', CHAR_PTR : 'long', LBOOL : 'int' } Type2JavaW = { VOID : 'void', VOID_PTR : 'jlong', INT : 'jint', UINT : 'jint', INT64 : 'jlong', UINT64 : 'jlong', DOUBLE : 'jdouble', FLOAT : 'jfloat', STRING : 'jstring', STRING_PTR : 'jobject', BOOL : 'jboolean', SYMBOL : 'jlong', PRINT_MODE : 'jint', ERROR_CODE : 'jint', CHAR : 'jchar', CHAR_PTR : 'jlong', LBOOL : 'jint'} def type2java(ty): global Type2Java if (ty >= FIRST_FN_ID): return 'long' else: return Type2Java[ty] def type2javaw(ty): global Type2JavaW if (ty >= FIRST_FN_ID): return 'jlong' else: return Type2JavaW[ty] def param2java(p): k = param_kind(p) if k == OUT: if param_type(p) == INT or param_type(p) == UINT: return "IntPtr" elif param_type(p) == INT64 or param_type(p) == UINT64 or param_type(p) == VOID_PTR or param_type(p) >= FIRST_OBJ_ID: return "LongPtr" elif param_type(p) == STRING: return "StringPtr" else: print("ERROR: unreachable code") assert(False) exit(1) elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: return "%s[]" % type2java(param_type(p)) elif k == OUT_MANAGED_ARRAY: if param_type(p) == UINT: return "UIntArrayPtr" else: return "ObjArrayPtr" elif k == FN_PTR: return "LongPtr" else: return type2java(param_type(p)) def param2javaw(p): k = param_kind(p) if k == OUT: return "jobject" elif k == IN_ARRAY or k == INOUT_ARRAY or k == OUT_ARRAY: if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL: return "jintArray" else: return "jlongArray" elif k == OUT_MANAGED_ARRAY: return "jlong" else: return type2javaw(param_type(p)) def java_method_name(name): result = '' name = name[3:] # Remove Z3_ n = len(name) i = 0 while i < n: if name[i] == '_': i = i + 1 if i < n: result += name[i].upper() else: result += name[i] i = i + 1 return result # Return the type of the java array elements def java_array_element_type(p): if param_type(p) == INT or param_type(p) == UINT or param_type(p) == BOOL: return 'jint' else: return 'jlong' def mk_java(java_src, java_dir, package_name): java_nativef = os.path.join(java_dir, 'Native.java') java_wrapperf = os.path.join(java_dir, 'Native.cpp') java_native = open(java_nativef, 'w') java_native.write('// Automatically generated file\n') java_native.write('package %s;\n' % package_name) java_native.write('import %s.enumerations.*;\n' % package_name) java_native.write('public final class Native {\n') java_native.write(' public static class IntPtr { public int value; }\n') java_native.write(' public static class LongPtr { public long value; }\n') java_native.write(' public static class StringPtr { public String value; }\n') java_native.write(' public static class ObjArrayPtr { public long[] value; }\n') java_native.write(' public static class UIntArrayPtr { public int[] value; }\n') java_native.write(' public static native void setInternalErrorHandler(long ctx);\n\n') java_native.write(' static {\n') java_native.write(' if (!Boolean.parseBoolean(System.getProperty("z3.skipLibraryLoad"))) {\n') java_native.write(' try {\n') java_native.write(' System.loadLibrary("z3java");\n') java_native.write(' } catch (UnsatisfiedLinkError ex) {\n') java_native.write(' System.loadLibrary("libz3java");\n') java_native.write(' }\n') java_native.write(' }\n') java_native.write(' }\n') java_native.write('\n') for name, result, params in _dotnet_decls: java_native.write(' protected static native %s INTERNAL%s(' % (type2java(result), java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('%s a%d' % (param2java(param), i)) i = i + 1 java_native.write(');\n') java_native.write('\n\n') # Exception wrappers for name, result, params in _dotnet_decls: java_native.write(' public static %s %s(' % (type2java(result), java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('%s a%d' % (param2java(param), i)) i = i + 1 java_native.write(')') if (len(params) > 0 and param_type(params[0]) == CONTEXT) or name in NULLWrapped: java_native.write(' throws Z3Exception') java_native.write('\n') java_native.write(' {\n') java_native.write(' ') if result != VOID: java_native.write('%s res = ' % type2java(result)) java_native.write('INTERNAL%s(' % (java_method_name(name))) first = True i = 0 for param in params: if first: first = False else: java_native.write(', ') java_native.write('a%d' % i) i = i + 1 java_native.write(');\n') if name not in Unwrapped: if name in NULLWrapped: java_native.write(" if (res == 0)\n") java_native.write(" throw new Z3Exception(\"Object allocation failed.\");\n") else: if len(params) > 0 and param_type(params[0]) == CONTEXT and name not in Unchecked: java_native.write(' Z3_error_code err = Z3_error_code.fromInt(INTERNALgetErrorCode(a0));\n') java_native.write(' if (err != Z3_error_code.Z3_OK)\n') java_native.write(' throw new Z3Exception(INTERNALgetErrorMsg(a0, err.toInt()));\n') if result != VOID: java_native.write(' return res;\n') java_native.write(' }\n\n') java_native.write('}\n') java_wrapper = open(java_wrapperf, 'w') pkg_str = package_name.replace('.', '_') java_wrapper.write("// Automatically generated file\n") with open(java_src + "/NativeStatic.txt") as ins: for line in ins: java_wrapper.write(line) for name, result, params in _dotnet_decls: java_wrapper.write('DLL_VIS JNIEXPORT %s JNICALL Java_%s_Native_INTERNAL%s(JNIEnv * jenv, jclass cls' % (type2javaw(result), pkg_str, java_method_name(name))) i = 0 for param in params: java_wrapper.write(', ') java_wrapper.write('%s a%d' % (param2javaw(param), i)) i = i + 1 java_wrapper.write(') {\n') # preprocess arrays, strings, in/out arguments i = 0 for param in params: k = param_kind(param) if k == OUT or k == INOUT: java_wrapper.write(' %s _a%s;\n' % (type2str(param_type(param)), i)) elif k == IN_ARRAY or k == INOUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' %s * _a%s = (%s*) jenv->GetIntArrayElements(a%s, NULL);\n' % (type2str(param_type(param)), i, type2str(param_type(param)), i)) else: java_wrapper.write(' GETLONGAELEMS(%s, a%s, _a%s);\n' % (type2str(param_type(param)), i, i)) elif k == OUT_ARRAY: java_wrapper.write(' %s * _a%s = (%s *) malloc(((unsigned)a%s) * sizeof(%s));\n' % (type2str(param_type(param)), i, type2str(param_type(param)), param_array_capacity_pos(param), type2str(param_type(param)))) if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->GetIntArrayRegion(a%s, 0, (jsize)a%s, (jint*)_a%s);\n' % (i, param_array_capacity_pos(param), i)) else: java_wrapper.write(' GETLONGAREGION(%s, a%s, 0, a%s, _a%s);\n' % (type2str(param_type(param)), i, param_array_capacity_pos(param), i)) elif k == IN and param_type(param) == STRING: java_wrapper.write(' Z3_string _a%s = (Z3_string) jenv->GetStringUTFChars(a%s, NULL);\n' % (i, i)) elif k == OUT_MANAGED_ARRAY: java_wrapper.write(' %s * _a%s = 0;\n' % (type2str(param_type(param)), i)) i = i + 1 # invoke procedure java_wrapper.write(' ') if result != VOID: java_wrapper.write('%s result = ' % type2str(result)) java_wrapper.write('%s(' % name) i = 0 first = True for param in params: if first: first = False else: java_wrapper.write(', ') k = param_kind(param) if k == OUT or k == INOUT: java_wrapper.write('&_a%s' % i) elif k == OUT_ARRAY or k == IN_ARRAY or k == INOUT_ARRAY: java_wrapper.write('_a%s' % i) elif k == OUT_MANAGED_ARRAY: java_wrapper.write('&_a%s' % i) elif k == IN and param_type(param) == STRING: java_wrapper.write('_a%s' % i) else: java_wrapper.write('(%s)a%i' % (param2str(param), i)) i = i + 1 java_wrapper.write(');\n') # cleanup i = 0 for param in params: k = param_kind(param) if k == OUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->SetIntArrayRegion(a%s, 0, (jsize)a%s, (jint*)_a%s);\n' % (i, param_array_capacity_pos(param), i)) else: java_wrapper.write(' SETLONGAREGION(a%s, 0, a%s, _a%s);\n' % (i, param_array_capacity_pos(param), i)) java_wrapper.write(' free(_a%s);\n' % i) elif k == IN_ARRAY or k == OUT_ARRAY: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' jenv->ReleaseIntArrayElements(a%s, (jint*)_a%s, JNI_ABORT);\n' % (i, i)) else: java_wrapper.write(' RELEASELONGAELEMS(a%s, _a%s);\n' % (i, i)) elif k == OUT or k == INOUT: if param_type(param) == INT or param_type(param) == UINT or param_type(param) == BOOL: java_wrapper.write(' {\n') java_wrapper.write(' jclass mc = jenv->GetObjectClass(a%s);\n' % i) java_wrapper.write(' jfieldID fid = jenv->GetFieldID(mc, "value", "I");\n') java_wrapper.write(' jenv->SetIntField(a%s, fid, (jint) _a%s);\n' % (i, i)) java_wrapper.write(' }\n') elif param_type(param) == STRING: java_wrapper.write(' {\n') java_wrapper.write(' jclass mc = jenv->GetObjectClass(a%s);\n' % i) java_wrapper.write(' jfieldID fid = jenv->GetFieldID(mc, "value", "Ljava/lang/String;");') java_wrapper.write(' jstring fval = jenv->NewStringUTF(_a%s);\n' % i) java_wrapper.write(' jenv->SetObjectField(a%s, fid, fval);\n' % i) java_wrapper.write(' }\n') else: java_wrapper.write(' {\n') java_wrapper.write(' jclass mc = jenv->GetObjectClass(a%s);\n' % i) java_wrapper.write(' jfieldID fid = jenv->GetFieldID(mc, "value", "J");\n') java_wrapper.write(' jenv->SetLongField(a%s, fid, (jlong) _a%s);\n' % (i, i)) java_wrapper.write(' }\n') elif k == OUT_MANAGED_ARRAY: java_wrapper.write(' *(jlong**)a%s = (jlong*)_a%s;\n' % (i, i)) elif k == IN and param_type(param) == STRING: java_wrapper.write(' jenv->ReleaseStringUTFChars(a%s, _a%s);\n' % (i, i)); i = i + 1 # return if result == STRING: java_wrapper.write(' return jenv->NewStringUTF(result);\n') elif result != VOID: java_wrapper.write(' return (%s) result;\n' % type2javaw(result)) java_wrapper.write('}\n') java_wrapper.write('#ifdef __cplusplus\n') java_wrapper.write('}\n') java_wrapper.write('#endif\n') if is_verbose(): print("Generated '%s'" % java_nativef) def mk_log_header(file, name, params): file.write("void log_%s(" % name) i = 0 for p in params: if i > 0: file.write(", ") file.write("%s a%s" % (param2str(p), i)) i = i + 1 file.write(")") # --------------------------------- # Logging def log_param(p): kind = param_kind(p) ty = param_type(p) return is_obj(ty) and (kind == OUT or kind == INOUT or kind == OUT_ARRAY or kind == INOUT_ARRAY) def log_result(result, params): for p in params: if log_param(p): return True return False def mk_log_macro(file, name, params): file.write("#define LOG_%s(" % name) i = 0 for p in params: if i > 0: file.write(", ") file.write("_ARG%s" % i) i = i + 1 file.write(") z3_log_ctx _LOG_CTX; ") auxs = set() i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) if cap not in auxs: auxs.add(cap) file.write("unsigned _Z3_UNUSED Z3ARG%s = 0; " % cap) sz = param_array_size_pos(p) if sz not in auxs: auxs.add(sz) file.write("unsigned * _Z3_UNUSED Z3ARG%s = 0; " % sz) file.write("%s _Z3_UNUSED Z3ARG%s = 0; " % (param2str(p), i)) i = i + 1 file.write("if (_LOG_CTX.enabled()) { log_%s(" % name) i = 0 for p in params: if (i > 0): file.write(', ') file.write("_ARG%s" %i) i = i + 1 file.write("); ") auxs = set() i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) if cap not in auxs: auxs.add(cap) file.write("Z3ARG%s = _ARG%s; " % (cap, cap)) sz = param_array_size_pos(p) if sz not in auxs: auxs.add(sz) file.write("Z3ARG%s = _ARG%s; " % (sz, sz)) file.write("Z3ARG%s = _ARG%s; " % (i, i)) i = i + 1 file.write("}\n") def mk_log_result_macro(file, name, result, params): file.write("#define RETURN_%s" % name) if is_obj(result): file.write("(Z3RES)") file.write(" ") file.write("if (_LOG_CTX.enabled()) { ") if is_obj(result): file.write("SetR(Z3RES); ") i = 0 for p in params: if log_param(p): kind = param_kind(p) if kind == OUT_ARRAY or kind == INOUT_ARRAY: cap = param_array_capacity_pos(p) sz = param_array_size_pos(p) if cap == sz: file.write("for (unsigned i = 0; i < Z3ARG%s; i++) { SetAO(Z3ARG%s[i], %s, i); } " % (sz, i, i)) else: file.write("for (unsigned i = 0; Z3ARG%s && i < *Z3ARG%s; i++) { SetAO(Z3ARG%s[i], %s, i); } " % (sz, sz, i, i)) if kind == OUT or kind == INOUT: file.write("SetO((Z3ARG%s == 0 ? 0 : *Z3ARG%s), %s); " % (i, i, i)) i = i + 1 file.write("} ") if is_obj(result): file.write("return Z3RES\n") else: file.write("return\n") def mk_exec_header(file, name): file.write("void exec_%s(z3_replayer & in)" % name) def error(msg): sys.stderr.write(msg) exit(-1) next_id = 0 API2Id = {} def def_API(name, result, params): global API2Id, next_id global log_h, log_c mk_py_binding(name, result, params) reg_dotnet(name, result, params) API2Id[next_id] = name mk_log_header(log_h, name, params) log_h.write(';\n') mk_log_header(log_c, name, params) log_c.write(' {\n R();\n') mk_exec_header(exe_c, name) exe_c.write(' {\n') # Create Log function & Function call i = 0 exe_c.write(" ") if is_obj(result): exe_c.write("%s result = " % type2str(result)) exe_c.write("%s(\n " % name) for p in params: kind = param_kind(p) ty = param_type(p) if (i > 0): exe_c.write(",\n ") if kind == IN: if is_obj(ty): log_c.write(" P(a%s);\n" % i) exe_c.write("reinterpret_cast<%s>(in.get_obj(%s))" % (param2str(p), i)) elif ty == STRING: log_c.write(" S(a%s);\n" % i) exe_c.write("in.get_str(%s)" % i) elif ty == SYMBOL: log_c.write(" Sy(a%s);\n" % i) exe_c.write("in.get_symbol(%s)" % i) elif ty == UINT: log_c.write(" U(a%s);\n" % i) exe_c.write("in.get_uint(%s)" % i) elif ty == UINT64: log_c.write(" U(a%s);\n" % i) exe_c.write("in.get_uint64(%s)" % i) elif ty == INT: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_int(%s)" % i) elif ty == INT64: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_int64(%s)" % i) elif ty == DOUBLE: log_c.write(" D(a%s);\n" % i) exe_c.write("in.get_double(%s)" % i) elif ty == FLOAT: log_c.write(" D(a%s);\n" % i) exe_c.write("in.get_float(%s)" % i) elif ty == BOOL: log_c.write(" I(a%s);\n" % i) exe_c.write("in.get_bool(%s)" % i) elif ty == VOID_PTR: log_c.write(" P(0);\n") exe_c.write("in.get_obj_addr(%s)" % i) elif ty == LBOOL: log_c.write(" I(static_cast<signed>(a%s));\n" % i) exe_c.write("static_cast<%s>(in.get_int(%s))" % (type2str(ty), i)) elif ty == PRINT_MODE or ty == ERROR_CODE: log_c.write(" U(static_cast<unsigned>(a%s));\n" % i) exe_c.write("static_cast<%s>(in.get_uint(%s))" % (type2str(ty), i)) else: error("unsupported parameter for %s, %s" % (name, p)) elif kind == INOUT: error("unsupported parameter for %s, %s" % (name, p)) elif kind == OUT: if is_obj(ty): log_c.write(" P(0);\n") exe_c.write("reinterpret_cast<%s>(in.get_obj_addr(%s))" % (param2str(p), i)) elif ty == STRING: log_c.write(" S(\"\");\n") exe_c.write("in.get_str_addr(%s)" % i) elif ty == UINT: log_c.write(" U(0);\n") exe_c.write("in.get_uint_addr(%s)" % i) elif ty == UINT64: log_c.write(" U(0);\n") exe_c.write("in.get_uint64_addr(%s)" % i) elif ty == INT: log_c.write(" I(0);\n") exe_c.write("in.get_int_addr(%s)" % i) elif ty == INT64: log_c.write(" I(0);\n") exe_c.write("in.get_int64_addr(%s)" % i) elif ty == VOID_PTR: log_c.write(" P(0);\n") exe_c.write("in.get_obj_addr(%s)" % i) else: error("unsupported parameter for %s, %s" % (name, p)) elif kind == IN_ARRAY or kind == INOUT_ARRAY: sz = param_array_capacity_pos(p) log_c.write(" for (unsigned i = 0; i < a%s; i++) { " % sz) if is_obj(ty): log_c.write("P(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Ap(a%s);\n" % sz) exe_c.write("reinterpret_cast<%s*>(in.get_obj_array(%s))" % (type2str(ty), i)) elif ty == SYMBOL: log_c.write("Sy(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Asy(a%s);\n" % sz) exe_c.write("in.get_symbol_array(%s)" % i) elif ty == UINT: log_c.write("U(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Au(a%s);\n" % sz) exe_c.write("in.get_uint_array(%s)" % i) elif ty == INT: log_c.write("I(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Ai(a%s);\n" % sz) exe_c.write("in.get_int_array(%s)" % i) elif ty == BOOL: log_c.write("U(a%s[i]);" % i) log_c.write(" }\n") log_c.write(" Au(a%s);\n" % sz) exe_c.write("in.get_bool_array(%s)" % i) else: error ("unsupported parameter for %s, %s, %s" % (ty, name, p)) elif kind == OUT_ARRAY: sz = param_array_capacity_pos(p) sz_p = params[sz] sz_p_k = param_kind(sz_p) tstr = type2str(ty) if sz_p_k == OUT or sz_p_k == INOUT: sz_e = ("(*a%s)" % sz) else: sz_e = ("a%s" % sz) log_c.write(" for (unsigned i = 0; i < %s; i++) { " % sz_e) if is_obj(ty): log_c.write("P(0);") log_c.write(" }\n") log_c.write(" Ap(%s);\n" % sz_e) exe_c.write("reinterpret_cast<%s*>(in.get_obj_array(%s))" % (tstr, i)) elif ty == UINT: log_c.write("U(0);") log_c.write(" }\n") log_c.write(" Au(%s);\n" % sz_e) exe_c.write("in.get_uint_array(%s)" % i) else: error ("unsupported parameter for %s, %s" % (name, p)) elif kind == OUT_MANAGED_ARRAY: sz = param_array_size_pos(p) sz_p = params[sz] sz_p_k = param_kind(sz_p) tstr = type2str(ty) if sz_p_k == OUT or sz_p_k == INOUT: sz_e = ("(*a%s)" % sz) else: sz_e = ("a%s" % sz) log_c.write(" for (unsigned i = 0; i < %s; i++) { " % sz_e) log_c.write("P(0);") log_c.write(" }\n") log_c.write(" Ap(%s);\n" % sz_e) exe_c.write("reinterpret_cast<%s**>(in.get_obj_array(%s))" % (tstr, i)) elif kind == FN_PTR: log_c.write("// P(a%s);\n" % i) exe_c.write("reinterpret_cast<%s>(in.get_obj(%s))" % (param2str(p), i)) else: error ("unsupported parameter for %s, %s" % (name, p)) i = i + 1 log_c.write(" C(%s);\n" % next_id) exe_c.write(");\n") if is_obj(result): exe_c.write(" in.store_result(result);\n") if name == 'Z3_mk_context' or name == 'Z3_mk_context_rc': exe_c.write(" Z3_set_error_handler(result, Z3_replayer_error_handler);") log_c.write('}\n') exe_c.write('}\n') mk_log_macro(log_h, name, params) if log_result(result, params): mk_log_result_macro(log_h, name, result, params) next_id = next_id + 1 def mk_bindings(exe_c): exe_c.write("void register_z3_replayer_cmds(z3_replayer & in) {\n") for key, val in API2Id.items(): exe_c.write(" in.register_cmd(%s, exec_%s, \"%s\");\n" % (key, val, val)) exe_c.write("}\n") def ml_method_name(name): return name[3:] # Remove Z3_ def is_out_param(p): if param_kind(p) == OUT or param_kind(p) == INOUT or param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT_MANAGED_ARRAY: return True else: return False def outparams(params): op = [] for param in params: if is_out_param(param): op.append(param) return op def is_in_param(p): if param_kind(p) == IN or param_kind(p) == INOUT or param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY: return True else: return False def inparams(params): ip = [] for param in params: if is_in_param(param): ip.append(param) return ip def is_array_param(p): if param_kind(p) == IN_ARRAY or param_kind(p) == INOUT_ARRAY or param_kind(p) == OUT_ARRAY: return True else: return False def arrayparams(params): op = [] for param in params: if is_array_param(param): op.append(param) return op def ml_plus_type(ts): if ts == 'Z3_context': return 'Z3_context_plus' elif ts == 'Z3_ast' or ts == 'Z3_sort' or ts == 'Z3_func_decl' or ts == 'Z3_app' or ts == 'Z3_pattern': return 'Z3_ast_plus' elif ts == 'Z3_symbol': return 'Z3_symbol_plus' elif ts == 'Z3_constructor': return 'Z3_constructor_plus' elif ts == 'Z3_constructor_list': return 'Z3_constructor_list_plus' elif ts == 'Z3_rcf_num': return 'Z3_rcf_num_plus' elif ts == 'Z3_params': return 'Z3_params_plus' elif ts == 'Z3_param_descrs': return 'Z3_param_descrs_plus' elif ts == 'Z3_model': return 'Z3_model_plus' elif ts == 'Z3_func_interp': return 'Z3_func_interp_plus' elif ts == 'Z3_func_entry': return 'Z3_func_entry_plus' elif ts == 'Z3_goal': return 'Z3_goal_plus' elif ts == 'Z3_tactic': return 'Z3_tactic_plus' elif ts == 'Z3_simplifier': return 'Z3_simplifier_plus' elif ts == 'Z3_probe': return 'Z3_probe_plus' elif ts == 'Z3_apply_result': return 'Z3_apply_result_plus' elif ts == 'Z3_solver': return 'Z3_solver_plus' elif ts == 'Z3_stats': return 'Z3_stats_plus' elif ts == 'Z3_ast_vector': return 'Z3_ast_vector_plus' elif ts == 'Z3_ast_map': return 'Z3_ast_map_plus' elif ts == 'Z3_fixedpoint': return 'Z3_fixedpoint_plus' elif ts == 'Z3_optimize': return 'Z3_optimize_plus' else: return ts def ml_minus_type(ts): if ts == 'Z3_ast' or ts == 'Z3_sort' or ts == 'Z3_func_decl' or ts == 'Z3_app' or ts == 'Z3_pattern': return 'Z3_ast' if ts == 'Z3_ast_plus' or ts == 'Z3_sort_plus' or ts == 'Z3_func_decl_plus' or ts == 'Z3_app_plus' or ts == 'Z3_pattern_plus': return 'Z3_ast' elif ts == 'Z3_constructor_plus': return 'Z3_constructor' elif ts == 'Z3_constructor_list_plus': return 'Z3_constructor_list' elif ts == 'Z3_rcf_num_plus': return 'Z3_rcf_num' elif ts == 'Z3_params_plus': return 'Z3_params' elif ts == 'Z3_param_descrs_plus': return 'Z3_param_descrs' elif ts == 'Z3_model_plus': return 'Z3_model' elif ts == 'Z3_func_interp_plus': return 'Z3_func_interp' elif ts == 'Z3_func_entry_plus': return 'Z3_func_entry' elif ts == 'Z3_goal_plus': return 'Z3_goal' elif ts == 'Z3_tactic_plus': return 'Z3_tactic' elif ts == 'Z3_simplifier_plus': return 'Z3_simplifier' elif ts == 'Z3_probe_plus': return 'Z3_probe' elif ts == 'Z3_apply_result_plus': return 'Z3_apply_result' elif ts == 'Z3_solver_plus': return 'Z3_solver' elif ts == 'Z3_stats_plus': return 'Z3_stats' elif ts == 'Z3_ast_vector_plus': return 'Z3_ast_vector' elif ts == 'Z3_ast_map_plus': return 'Z3_ast_map' elif ts == 'Z3_fixedpoint_plus': return 'Z3_fixedpoint' elif ts == 'Z3_optimize_plus': return 'Z3_optimize' else: return ts def ml_plus_type_raw(ts): if ml_has_plus_type(ts): return ml_plus_type(ts) + '_raw'; else: return ts def ml_plus_ops_type(ts): if ml_has_plus_type(ts): return ml_plus_type(ts) + '_custom_ops' else: return 'default_custom_ops' def ml_has_plus_type(ts): return ts != ml_plus_type(ts) def ml_unwrap(t, ts, s): if t == STRING: return '(' + ts + ') String_val(' + s + ')' elif t == BOOL or (type2str(t) == 'bool'): return '(' + ts + ') Bool_val(' + s + ')' elif t == INT or t == PRINT_MODE or t == ERROR_CODE or t == LBOOL: return '(' + ts + ') Int_val(' + s + ')' elif t == UINT: return '(' + ts + ') Unsigned_int_val(' + s + ')' elif t == INT64: return '(' + ts + ') Int64_val(' + s + ')' elif t == UINT64: return '(' + ts + ') Int64_val(' + s + ')' elif t == DOUBLE: return '(' + ts + ') Double_val(' + s + ')' elif ml_has_plus_type(ts): pts = ml_plus_type(ts) return '(' + ts + ') ' + ml_plus_type_raw(ts) + '((' + pts + '*) Data_custom_val(' + s + '))' else: return '* ((' + ts + '*) Data_custom_val(' + s + '))' def ml_set_wrap(t, d, n): if t == VOID: return d + ' = Val_unit;' elif t == BOOL or (type2str(t) == 'bool'): return d + ' = Val_bool(' + n + ');' elif t == INT or t == UINT or t == PRINT_MODE or t == ERROR_CODE or t == LBOOL: return d + ' = Val_int(' + n + ');' elif t == INT64 or t == UINT64: return d + ' = caml_copy_int64(' + n + ');' elif t == DOUBLE: return d + '= caml_copy_double(' + n + ');' elif t == STRING: return d + ' = caml_copy_string((const char*) ' + n + ');' else: pts = ml_plus_type(type2str(t)) return '*(' + pts + '*)Data_custom_val(' + d + ') = ' + n + ';' def ml_alloc_and_store(t, lhs, rhs): if t == VOID or t == BOOL or t == INT or t == UINT or t == PRINT_MODE or t == ERROR_CODE or t == INT64 or t == UINT64 or t == DOUBLE or t == STRING or t == LBOOL or (type2str(t) == 'bool'): return ml_set_wrap(t, lhs, rhs) else: pts = ml_plus_type(type2str(t)) pops = ml_plus_ops_type(type2str(t)) alloc_str = '%s = caml_alloc_custom(&%s, sizeof(%s), 0, 1); ' % (lhs, pops, pts) return alloc_str + ml_set_wrap(t, lhs, rhs) z3_long_funs = frozenset([ 'Z3_solver_check', 'Z3_solver_check_assumptions', 'Z3_simplify', 'Z3_simplify_ex', ]) z3_ml_overrides = frozenset([ 'Z3_mk_config']) z3_ml_callbacks = frozenset([ 'Z3_solver_propagate_init', 'Z3_solver_propagate_fixed', 'Z3_solver_propagate_final', 'Z3_solver_propagate_eq', 'Z3_solver_propagate_diseq', 'Z3_solver_propagate_created', 'Z3_solver_propagate_decide', 'Z3_solver_register_on_clause' ]) def mk_ml(ml_src_dir, ml_output_dir): global Type2Str ml_nativef = os.path.join(ml_output_dir, 'z3native.ml') ml_native = open(ml_nativef, 'w') ml_native.write('(* Automatically generated file *)\n\n') ml_pref = open(os.path.join(ml_src_dir, 'z3native.ml.pre'), 'r') for s in ml_pref: ml_native.write(s); ml_pref.close() ml_native.write('\n') for name, result, params in _dotnet_decls: if name in z3_ml_callbacks: continue ml_native.write('external %s : ' % ml_method_name(name)) ip = inparams(params) op = outparams(params) if len(ip) == 0: ml_native.write(' unit -> ') for p in ip: ml_native.write('%s -> ' % param2ml(p)) if len(op) > 0: ml_native.write('(') first = True if result != VOID or len(op) == 0: ml_native.write('%s' % type2ml(result)) first = False for p in op: if first: first = False else: ml_native.write(' * ') ml_native.write('%s' % param2ml(p)) if len(op) > 0: ml_native.write(')') if len(ip) > 5: ml_native.write(' = "n_%s_bytecode" "n_%s"\n' % (ml_method_name(name), ml_method_name(name))) else: ml_native.write(' = "n_%s"\n' % ml_method_name(name)) ml_native.write('\n') # null pointer helpers for type_id in Type2Str: type_name = Type2Str[type_id] if ml_has_plus_type(type_name) and not type_name in ['Z3_context', 'Z3_sort', 'Z3_func_decl', 'Z3_app', 'Z3_pattern']: ml_name = type2ml(type_id) ml_native.write('external context_of_%s : %s -> context = "n_context_of_%s"\n' % (ml_name, ml_name, ml_name)) ml_native.write('external is_null_%s : %s -> bool = "n_is_null_%s"\n' % (ml_name, ml_name, ml_name)) ml_native.write('external mk_null_%s : context -> %s = "n_mk_null_%s"\n\n' % (ml_name, ml_name, ml_name)) ml_native.write('(**/**)\n') ml_native.close() if is_verbose(): print ('Generated "%s"' % ml_nativef) mk_z3native_stubs_c(ml_src_dir, ml_output_dir) def mk_z3native_stubs_c(ml_src_dir, ml_output_dir): # C interface ml_wrapperf = os.path.join(ml_output_dir, 'z3native_stubs.c') ml_wrapper = open(ml_wrapperf, 'w') ml_wrapper.write('// Automatically generated file\n\n') ml_pref = open(os.path.join(ml_src_dir, 'z3native_stubs.c.pre'), 'r') for s in ml_pref: ml_wrapper.write(s); ml_pref.close() for name, result, params in _dotnet_decls: if name in z3_ml_overrides: continue if name in z3_ml_callbacks: continue ip = inparams(params) op = outparams(params) ap = arrayparams(params) ret_size = len(op) if result != VOID: ret_size = ret_size + 1 # Setup frame ml_wrapper.write('CAMLprim DLL_PUBLIC value n_%s(' % ml_method_name(name)) first = True i = 0 for p in params: if is_in_param(p): if first: first = False else: ml_wrapper.write(', ') ml_wrapper.write('value a%d' % i) i = i + 1 ml_wrapper.write(') {\n') ml_wrapper.write(' CAMLparam%d(' % len(ip)) i = 0 first = True for p in params: if is_in_param(p): if first: first = False else: ml_wrapper.write(', ') ml_wrapper.write('a%d' % i) i = i + 1 ml_wrapper.write(');\n') i = 0 if len(op) + len(ap) == 0: ml_wrapper.write(' CAMLlocal1(result);\n') else: c = 0 needs_tmp_value = False for p in params: if is_out_param(p) or is_array_param(p): c = c + 1 needs_tmp_value = needs_tmp_value or param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY if needs_tmp_value: c = c + 1 if len(ap) > 0: c = c + 1 ml_wrapper.write(' CAMLlocal%s(result, z3rv_val' % (c+2)) for p in params: if is_out_param(p) or is_array_param(p): ml_wrapper.write(', _a%s_val' % i) i = i + 1 if needs_tmp_value: ml_wrapper.write(', tmp_val') if len(ap) != 0: ml_wrapper.write(', _iter'); ml_wrapper.write(');\n') if len(ap) > 0: ml_wrapper.write(' unsigned _i;\n') # determine if the function has a context as parameter. have_context = (len(params) > 0) and (param_type(params[0]) == CONTEXT) if have_context and name not in Unwrapped and name not in Unchecked: ml_wrapper.write(' Z3_error_code ec;\n') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' %s z3rv_m;\n' % ts) ml_wrapper.write(' %s z3rv;\n' % pts) else: ml_wrapper.write(' %s z3rv;\n' % ts) # declare all required local variables # To comply with C89, we need to first declare the variables and initialize them # only afterwards. i = 0 for param in params: if param_type(param) == CONTEXT and i == 0: ml_wrapper.write(' Z3_context_plus ctx_p;\n') ml_wrapper.write(' Z3_context _a0;\n') else: k = param_kind(param) if k == OUT_ARRAY: ml_wrapper.write(' %s * _a%s;\n' % (type2str(param_type(param)), i)) elif k == OUT_MANAGED_ARRAY: ml_wrapper.write(' %s * _a%s;\n' % (type2str(param_type(param)), i)) elif k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' %s * _a%s;\n' % (ts, i)) elif k == IN: t = param_type(param) ml_wrapper.write(' %s _a%s;\n' % (type2str(t), i)) elif k == OUT or k == INOUT: t = param_type(param) ml_wrapper.write(' %s _a%s;\n' % (type2str(t), i)) ts = type2str(t) if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' %s _a%dp;\n' % (pts, i)) i = i + 1 # End of variable declarations in outermost block: # To comply with C89, no variable declarations may occur in the outermost block # from that point onwards (breaks builds with at least VC 2012 and prior) ml_wrapper.write('\n') # Declare locals, preprocess arrays, strings, in/out arguments i = 0 for param in params: if param_type(param) == CONTEXT and i == 0: ml_wrapper.write(' ctx_p = *(Z3_context_plus*) Data_custom_val(a' + str(i) + ');\n') ml_wrapper.write(' _a0 = ctx_p->ctx;\n') else: k = param_kind(param) if k == OUT_ARRAY: ml_wrapper.write(' _a%s = (%s*) malloc(sizeof(%s) * (_a%s));\n' % ( i, type2str(param_type(param)), type2str(param_type(param)), param_array_capacity_pos(param))) elif k == OUT_MANAGED_ARRAY: ml_wrapper.write(' _a%s = 0;\n' % i) elif k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' _a%s = (%s*) malloc(sizeof(%s) * _a%s);\n' % (i, ts, ts, param_array_capacity_pos(param))) elif k == IN: t = param_type(param) ml_wrapper.write(' _a%s = %s;\n' % (i, ml_unwrap(t, type2str(t), 'a' + str(i)))) i = i + 1 i = 0 for param in params: k = param_kind(param) if k == IN_ARRAY or k == INOUT_ARRAY: t = param_type(param) ts = type2str(t) ml_wrapper.write(' _iter = a' + str(i) + ';\n') ml_wrapper.write(' for (_i = 0; _i < _a%s; _i++) {\n' % param_array_capacity_pos(param)) ml_wrapper.write(' assert(_iter != Val_emptylist);\n') ml_wrapper.write(' _a%s[_i] = %s;\n' % (i, ml_unwrap(t, ts, 'Field(_iter, 0)'))) ml_wrapper.write(' _iter = Field(_iter, 1);\n') ml_wrapper.write(' }\n') ml_wrapper.write(' assert(_iter == Val_emptylist);\n\n') i = i + 1 release_caml_gc= name in z3_long_funs if release_caml_gc: ml_wrapper.write('\n caml_release_runtime_system();\n') ml_wrapper.write('\n /* invoke Z3 function */\n ') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): ml_wrapper.write('z3rv_m = ') else: ml_wrapper.write('z3rv = ') # invoke procedure ml_wrapper.write('%s(' % name) i = 0 first = True for param in params: if first: first = False else: ml_wrapper.write(', ') k = param_kind(param) if k == OUT or k == INOUT or k == OUT_MANAGED_ARRAY: ml_wrapper.write('&_a%s' % i) else: ml_wrapper.write('_a%i' % i) i = i + 1 ml_wrapper.write(');\n') if name in NULLWrapped: ml_wrapper.write(' if (z3rv_m == NULL) {\n') ml_wrapper.write(' caml_raise_with_string(*caml_named_value("Z3EXCEPTION"), "Object allocation failed");\n') ml_wrapper.write(' }\n') if release_caml_gc: ml_wrapper.write('\n caml_acquire_runtime_system();\n') if have_context and name not in Unwrapped and name not in Unchecked: ml_wrapper.write(' ec = Z3_get_error_code(ctx_p->ctx);\n') ml_wrapper.write(' if (ec != Z3_OK) {\n') ml_wrapper.write(' const char * msg = Z3_get_error_msg(ctx_p->ctx, ec);\n') ml_wrapper.write(' caml_raise_with_string(*caml_named_value("Z3EXCEPTION"), msg);\n') ml_wrapper.write(' }\n') if result != VOID: ts = type2str(result) if ml_has_plus_type(ts): pts = ml_plus_type(ts) if name in NULLWrapped: ml_wrapper.write(' z3rv = %s_mk(z3rv_m);\n' % pts) else: ml_wrapper.write(' z3rv = %s_mk(ctx_p, (%s) z3rv_m);\n' % (pts, ml_minus_type(ts))) # convert output params if len(op) > 0: # we have output parameters (i.e. call-by-reference arguments to the Z3 native # code function). Hence, the value returned by the OCaml native wrapper is a tuple # which contains the Z3 native function's return value (if it is non-void) in its # first and the output parameters in the following components. ml_wrapper.write('\n /* construct return tuple */\n') ml_wrapper.write(' result = caml_alloc(%s, 0);\n' % ret_size) i = 0 for p in params: pt = param_type(p) ts = type2str(pt) if param_kind(p) == OUT_ARRAY or param_kind(p) == INOUT_ARRAY: # convert a C-array into an OCaml list and return it ml_wrapper.write('\n _a%s_val = Val_emptylist;\n' % i) ml_wrapper.write(' for (_i = _a%s; _i > 0; _i--) {\n' % param_array_capacity_pos(p)) pts = ml_plus_type(ts) pops = ml_plus_ops_type(ts) if ml_has_plus_type(ts): ml_wrapper.write(' %s _a%dp = %s_mk(ctx_p, (%s) _a%d[_i - 1]);\n' % (pts, i, pts, ml_minus_type(ts), i)) ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, 'tmp_val', '_a%dp' % i)) else: ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, 'tmp_val', '_a%d[_i - 1]' % i)) ml_wrapper.write(' _iter = caml_alloc(2,0);\n') ml_wrapper.write(' Store_field(_iter, 0, tmp_val);\n') ml_wrapper.write(' Store_field(_iter, 1, _a%s_val);\n' % i) ml_wrapper.write(' _a%s_val = _iter;\n' % i) ml_wrapper.write(' }\n\n') elif param_kind(p) == OUT_MANAGED_ARRAY: wrp = ml_set_wrap(pt, '_a%d_val' % i, '_a%d' % i) wrp = wrp.replace('*)', '**)') wrp = wrp.replace('_plus', '') ml_wrapper.write(' %s\n' % wrp) elif is_out_param(p): if ml_has_plus_type(ts): pts = ml_plus_type(ts) ml_wrapper.write(' _a%dp = %s_mk(ctx_p, (%s) _a%d);\n' % (i, pts, ml_minus_type(ts), i)) ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, '_a%d_val' % i, '_a%dp' % i)) else: ml_wrapper.write(' %s\n' % ml_alloc_and_store(pt, '_a%d_val' % i, '_a%d' % i)) i = i + 1 # return tuples i = j = 0 if result != VOID: ml_wrapper.write(' %s' % ml_alloc_and_store(result, 'z3rv_val', 'z3rv')) ml_wrapper.write(' Store_field(result, 0, z3rv_val);\n') j = j + 1 for p in params: if is_out_param(p): ml_wrapper.write(' Store_field(result, %s, _a%s_val);\n' % (j, i)) j = j + 1 i = i + 1 else: # As we have no output parameters, we simply return the result ml_wrapper.write('\n /* construct simple return value */\n') ml_wrapper.write(' %s' % ml_alloc_and_store(result, "result", "z3rv")) # local array cleanup ml_wrapper.write('\n /* cleanup and return */\n') i = 0 for p in params: k = param_kind(p) if k == OUT_ARRAY or k == IN_ARRAY or k == INOUT_ARRAY: ml_wrapper.write(' free(_a%s);\n' % i) i = i + 1 # return ml_wrapper.write(' CAMLreturn(result);\n') ml_wrapper.write('}\n\n') if len(ip) > 5: ml_wrapper.write('CAMLprim DLL_PUBLIC value n_%s_bytecode(value * argv, int argn) {\n' % ml_method_name(name)) ml_wrapper.write(' return n_%s(' % ml_method_name(name)) i = 0 while i < len(ip): if i == 0: ml_wrapper.write('argv[0]') else: ml_wrapper.write(', argv[%s]' % i) i = i + 1 ml_wrapper.write(');\n}\n') ml_wrapper.write('\n\n') ml_wrapper.write('#ifdef __cplusplus\n') ml_wrapper.write('}\n') ml_wrapper.write('#endif\n') if is_verbose(): print ('Generated "%s"' % ml_wrapperf) # Collect API(...) commands from def def_APIs(api_files): pat1 = re.compile(" *def_API.*") pat2 = re.compile(" *extra_API.*") for api_file in api_files: api = open(api_file, 'r') for line in api: line = line.strip('\r\n\t ') try: m = pat1.match(line) if m: eval(line) m = pat2.match(line) if m: eval(line) except Exception as e: error('ERROR: While processing: %s: %s\n' % (e, line)) def write_log_h_preamble(log_h): log_h.write('// Automatically generated file\n') log_h.write('#include\"api/z3.h\"\n') log_h.write('#ifdef __GNUC__\n') log_h.write('#define _Z3_UNUSED __attribute__((unused))\n') log_h.write('#else\n') log_h.write('#define _Z3_UNUSED\n') log_h.write('#endif\n') # log_h.write('#include "util/mutex.h"\n') log_h.write('extern atomic<bool> g_z3_log_enabled;\n') log_h.write('void ctx_enable_logging();\n') log_h.write('class z3_log_ctx { bool m_prev; public: z3_log_ctx() { ATOMIC_EXCHANGE(m_prev, g_z3_log_enabled, false); } ~z3_log_ctx() { if (m_prev) g_z3_log_enabled = true; } bool enabled() const { return m_prev; } };\n') log_h.write('void SetR(void * obj);\nvoid SetO(void * obj, unsigned pos);\nvoid SetAO(void * obj, unsigned pos, unsigned idx);\n') log_h.write('#define RETURN_Z3(Z3RES) do { auto tmp_ret = Z3RES; if (_LOG_CTX.enabled()) { SetR(tmp_ret); } return tmp_ret; } while (0)\n') def write_log_c_preamble(log_c): log_c.write('// Automatically generated file\n') log_c.write('#include\"api/z3.h\"\n') log_c.write('#include\"api/api_log_macros.h\"\n') log_c.write('#include\"api/z3_logger.h\"\n') def write_exe_c_preamble(exe_c): exe_c.write('// Automatically generated file\n') exe_c.write('#include\"api/z3.h\"\n') exe_c.write('#include\"api/z3_replayer.h\"\n') # exe_c.write('void Z3_replayer_error_handler(Z3_context ctx, Z3_error_code c) { printf("[REPLAYER ERROR HANDLER]: %s\\n", Z3_get_error_msg(ctx, c)); }\n') def write_core_py_post(core_py): core_py.write(""" # Clean up del _lib del _default_dirs del _all_dirs del _ext """) def write_core_py_preamble(core_py): core_py.write( """ # Automatically generated file import sys, os import ctypes import pkg_resources from .z3types import * from .z3consts import * _ext = 'dll' if sys.platform in ('win32', 'cygwin') else 'dylib' if sys.platform == 'darwin' else 'so' _lib = None _default_dirs = ['.', os.path.dirname(os.path.abspath(__file__)), pkg_resources.resource_filename('z3', 'lib'), os.path.join(sys.prefix, 'lib'), None] _all_dirs = [] # search the default dirs first _all_dirs.extend(_default_dirs) if sys.version < '3': import __builtin__ if hasattr(__builtin__, "Z3_LIB_DIRS"): _all_dirs = __builtin__.Z3_LIB_DIRS else: import builtins if hasattr(builtins, "Z3_LIB_DIRS"): _all_dirs = builtins.Z3_LIB_DIRS for v in ('Z3_LIBRARY_PATH', 'PATH', 'PYTHONPATH'): if v in os.environ: lp = os.environ[v]; lds = lp.split(';') if sys.platform in ('win32') else lp.split(':') _all_dirs.extend(lds) _failures = [] for d in _all_dirs: try: d = os.path.realpath(d) if os.path.isdir(d): d = os.path.join(d, 'libz3.%s' % _ext) if os.path.isfile(d): _lib = ctypes.CDLL(d) break except Exception as e: _failures += [e] pass if _lib is None: # If all else failed, ask the system to find it. try: _lib = ctypes.CDLL('libz3.%s' % _ext) except Exception as e: _failures += [e] pass if _lib is None: print("Could not find libz3.%s; consider adding the directory containing it to" % _ext) print(" - your system's PATH environment variable,") print(" - the Z3_LIBRARY_PATH environment variable, or ") print(" - to the custom Z3_LIB_DIRS Python-builtin before importing the z3 module, e.g. via") if sys.version < '3': print(" import __builtin__") print(" __builtin__.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) else: print(" import builtins") print(" builtins.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) print(_failures) raise Z3Exception("libz3.%s not found." % _ext) if sys.version < '3': def _str_to_bytes(s): return s def _to_pystr(s): return s else: def _str_to_bytes(s): if isinstance(s, str): enc = sys.getdefaultencoding() return s.encode(enc if enc != None else 'latin-1') else: return s def _to_pystr(s): if s != None: enc = sys.getdefaultencoding() return s.decode(enc if enc != None else 'latin-1') else: return "" _error_handler_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint) _lib.Z3_set_error_handler.restype = None _lib.Z3_set_error_handler.argtypes = [ContextObj, _error_handler_type] Z3_on_clause_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Z3_push_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p) Z3_pop_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint) Z3_fresh_eh = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Z3_fixed_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Z3_final_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p) Z3_eq_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Z3_created_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) Z3_decide_eh = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) _lib.Z3_solver_register_on_clause.restype = None _lib.Z3_solver_propagate_init.restype = None _lib.Z3_solver_propagate_final.restype = None _lib.Z3_solver_propagate_fixed.restype = None _lib.Z3_solver_propagate_eq.restype = None _lib.Z3_solver_propagate_diseq.restype = None _lib.Z3_solver_propagate_decide.restype = None on_model_eh_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p) _lib.Z3_optimize_register_model_eh.restype = None _lib.Z3_optimize_register_model_eh.argtypes = [ContextObj, OptimizeObj, ModelObj, ctypes.c_void_p, on_model_eh_type] """ ) log_h = None log_c = None exe_c = None core_py = None # FIXME: This can only be called once from this module # due to its use of global state! def generate_files(api_files, api_output_dir=None, z3py_output_dir=None, dotnet_output_dir=None, java_input_dir=None, java_output_dir=None, java_package_name=None, ml_output_dir=None, ml_src_dir=None): """ Scan the api files in ``api_files`` and emit the relevant API files into the output directories specified. If an output directory is set to ``None`` then the files for that language binding or module are not emitted. The reason for this function interface is: * The CMake build system needs to control where files are emitted. * The CMake build system needs to be able to choose which API files are emitted. * This function should be as decoupled from the Python build system as much as possible but it must be possible for the Python build system code to use this function. Therefore we: * Do not use the ``mk_util.is_*_enabled()`` functions to determine if certain files should be or should not be emitted. * Do not use the components declared in the Python build system to determine the output directory paths. """ # FIXME: These should not be global global log_h, log_c, exe_c, core_py assert isinstance(api_files, list) # Hack: Avoid emitting files when we don't want them # by writing to temporary files that get deleted when # closed. This allows us to work around the fact that # existing code is designed to always emit these files. def mk_file_or_temp(output_dir, file_name, mode='w'): if output_dir != None: assert os.path.exists(output_dir) and os.path.isdir(output_dir) return open(os.path.join(output_dir, file_name), mode) else: # Return a file that we can write to without caring print("Faking emission of '{}'".format(file_name)) import tempfile return tempfile.TemporaryFile(mode=mode) apiTypes = APITypes() with mk_file_or_temp(api_output_dir, 'api_log_macros.h') as log_h: with mk_file_or_temp(api_output_dir, 'api_log_macros.cpp') as log_c: with mk_file_or_temp(api_output_dir, 'api_commands.cpp') as exe_c: with mk_file_or_temp(z3py_output_dir, os.path.join('z3', 'z3core.py')) as core_py: # Write preambles write_log_h_preamble(log_h) write_log_c_preamble(log_c) write_exe_c_preamble(exe_c) write_core_py_preamble(core_py) # FIXME: these functions are awful apiTypes.def_Types(api_files) def_APIs(api_files) mk_bindings(exe_c) mk_py_wrappers() write_core_py_post(core_py) if is_verbose(): print("Generated '{}'".format(log_h.name)) print("Generated '{}'".format(log_c.name)) print("Generated '{}'".format(exe_c.name)) print("Generated '{}'".format(core_py.name)) if dotnet_output_dir: with open(os.path.join(dotnet_output_dir, 'Native.cs'), 'w') as dotnet_file: mk_dotnet(dotnet_file) mk_dotnet_wrappers(dotnet_file) if is_verbose(): print("Generated '{}'".format(dotnet_file.name)) if java_output_dir: mk_java(java_input_dir, java_output_dir, java_package_name) if ml_output_dir: assert not ml_src_dir is None mk_ml(ml_src_dir, ml_output_dir) def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("api_files", nargs="+", help="API header files to generate files from") parser.add_argument("--api_output_dir", default=None, help="Directory to emit files for api module. If not specified no files are emitted.") parser.add_argument("--z3py-output-dir", dest="z3py_output_dir", default=None, help="Directory to emit z3py files. If not specified no files are emitted.") parser.add_argument("--dotnet-output-dir", dest="dotnet_output_dir", default=None, help="Directory to emit dotnet files. If not specified no files are emitted.") parser.add_argument("--java-input-dir", dest="java_input_dir", default=None, help="Directory where Java sources reside.") parser.add_argument("--java-output-dir", dest="java_output_dir", default=None, help="Directory to emit Java files. If not specified no files are emitted.") parser.add_argument("--java-package-name", dest="java_package_name", default=None, help="Name to give the Java package (e.g. ``com.microsoft.z3``).") parser.add_argument("--ml-src-dir", dest="ml_src_dir", default=None, help="Directory containing OCaml source files. If not specified no files are emitted") parser.add_argument("--ml-output-dir", dest="ml_output_dir", default=None, help="Directory to emit OCaml files. If not specified no files are emitted.") pargs = parser.parse_args(args) if pargs.java_output_dir: if pargs.java_package_name == None: logging.error('--java-package-name must be specified') return 1 if pargs.java_input_dir is None: logging.error('--java-input-dir must be specified') return 1 if pargs.ml_output_dir: if pargs.ml_src_dir is None: logging.error('--ml-src-dir must be specified') return 1 for api_file in pargs.api_files: if not os.path.exists(api_file): logging.error('"{}" does not exist'.format(api_file)) return 1 generate_files(api_files=pargs.api_files, api_output_dir=pargs.api_output_dir, z3py_output_dir=pargs.z3py_output_dir, dotnet_output_dir=pargs.dotnet_output_dir, java_input_dir=pargs.java_input_dir, java_output_dir=pargs.java_output_dir, java_package_name=pargs.java_package_name, ml_output_dir=pargs.ml_output_dir, ml_src_dir=pargs.ml_src_dir) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/update_api.py
update_api.py
import os import glob import re import getopt import sys import shutil import subprocess import zipfile from mk_exception import * from mk_project import * import mk_util BUILD_DIR='build-dist' VERBOSE=True DIST_DIR='dist' FORCE_MK=False DOTNET_CORE_ENABLED=True DOTNET_KEY_FILE=None JAVA_ENABLED=True GIT_HASH=False PYTHON_ENABLED=True MAKEJOBS=getenv("MAKEJOBS", '8') OS_NAME=None def set_verbose(flag): global VERBOSE VERBOSE = flag def is_verbose(): return VERBOSE def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(path): global BUILD_DIR BUILD_DIR = mk_util.norm_path(path) mk_dir(BUILD_DIR) def display_help(): print("mk_unix_dist.py: Z3 Linux/OSX/BSD distribution generator\n") print("This script generates the zip files containing executables, shared objects, header files for Linux/OSX/BSD.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") print(" -b <sudir>, --build=<subdir> subdirectory where x86 and x64 Z3 versions will be built (default: build-dist).") print(" -f, --force force script to regenerate Makefiles.") print(" --nodotnet do not include .NET bindings in the binary distribution files.") print(" --dotnet-key=<file> sign the .NET assembly with the private key in <file>.") print(" --arch=<arch> set architecture (to arm64) to force arm64 build") print(" --nojava do not include Java bindings in the binary distribution files.") print(" --os=<os> set OS version.") print(" --nopython do not include Python bindings in the binary distribution files.") print(" --githash include git hash in the Zip file.") exit(0) # Parse configuration option for mk_make script def parse_options(): global FORCE_MK, JAVA_ENABLED, GIT_HASH, DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, PYTHON_ENABLED, OS_NAME path = BUILD_DIR options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:hsf', ['build=', 'help', 'silent', 'force', 'nojava', 'nodotnet', 'dotnet-key=', 'arch=', 'os=', 'githash', 'nopython' ]) for opt, arg in options: if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') path = arg elif opt in ('-s', '--silent'): set_verbose(False) elif opt in ('-h', '--help'): display_help() elif opt in ('-f', '--force'): FORCE_MK = True elif opt == '--nodotnet': DOTNET_CORE_ENABLED = False elif opt == '--nopython': PYTHON_ENABLED = False elif opt == '--dotnet-key': DOTNET_KEY_FILE = arg elif opt == '--nojava': JAVA_ENABLED = False elif opt == '--githash': GIT_HASH = True elif opt == '--arch': if arg == "arm64": mk_util.IS_ARCH_ARM64 = True else: raise MKException("Invalid architecture directive '%s'. Legal directives: arm64" % arg) elif opt == '--os': OS_NAME = arg else: raise MKException("Invalid command line option '%s'" % opt) set_build_dir(path) # Check whether build directory already exists or not def check_build_dir(path): return os.path.exists(path) and os.path.exists(os.path.join(path, 'Makefile')) # Create a build directory using mk_make.py def mk_build_dir(path): if not check_build_dir(path) or FORCE_MK: opts = [sys.executable, os.path.join('scripts', 'mk_make.py'), "-b", path, "--staticlib"] if DOTNET_CORE_ENABLED: opts.append('--dotnet') if not DOTNET_KEY_FILE is None: opts.append('--dotnet-key=' + DOTNET_KEY_FILE) if JAVA_ENABLED: opts.append('--java') if GIT_HASH: opts.append('--githash=%s' % mk_util.git_hash()) opts.append('--git-describe') if PYTHON_ENABLED: opts.append('--python') if mk_util.IS_ARCH_ARM64: opts.append('--arm64=true') if subprocess.call(opts) != 0: raise MKException("Failed to generate build directory at '%s'" % path) # Create build directories def mk_build_dirs(): mk_build_dir(BUILD_DIR) class cd: def __init__(self, newPath): self.newPath = newPath def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) def mk_z3(): with cd(BUILD_DIR): try: return subprocess.call(['make', '-j', MAKEJOBS]) except: return 1 def get_os_name(): if OS_NAME is not None: return OS_NAME import platform basic = os.uname()[0].lower() if basic == 'linux': dist = platform.libc_ver() if len(dist) == 2 and len(dist[0]) > 0 and len(dist[1]) > 0: return '%s-%s' % (dist[0].lower(), dist[1].lower()) else: return basic elif basic == 'darwin': ver = platform.mac_ver() if len(ver) == 3 and len(ver[0]) > 0: return 'osx-%s' % ver[0] else: return 'osx' elif basic == 'freebsd': ver = platform.version() idx1 = ver.find(' ') idx2 = ver.find('-') if idx1 < 0 or idx2 < 0 or idx1 >= idx2: return basic else: return 'freebsd-%s' % ver[(idx1+1):idx2] else: return basic def get_z3_name(): major, minor, build, revision = get_version() if mk_util.IS_ARCH_ARM64: platform = "arm64" elif sys.maxsize >= 2**32: platform = "x64" else: platform = "x86" osname = get_os_name() if GIT_HASH: return 'z3-%s.%s.%s.%s-%s-%s' % (major, minor, build, mk_util.git_hash(), platform, osname) else: return 'z3-%s.%s.%s-%s-%s' % (major, minor, build, platform, osname) def mk_dist_dir(): build_path = BUILD_DIR dist_path = os.path.join(DIST_DIR, get_z3_name()) mk_dir(dist_path) mk_util.DOTNET_CORE_ENABLED = DOTNET_CORE_ENABLED mk_util.DOTNET_ENABLED = False mk_util.DOTNET_KEY_FILE = DOTNET_KEY_FILE mk_util.JAVA_ENABLED = JAVA_ENABLED mk_util.PYTHON_ENABLED = PYTHON_ENABLED mk_unix_dist(build_path, dist_path) if is_verbose(): print("Generated distribution folder at '%s'" % dist_path) def get_dist_path(): return get_z3_name() def mk_zip(): dist_path = get_dist_path() old = os.getcwd() try: os.chdir(DIST_DIR) zfname = '%s.zip' % dist_path zipout = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dist_path): for f in files: zipout.write(os.path.join(root, f)) if is_verbose(): print("Generated '%s'" % zfname) except: pass os.chdir(old) def cp_license(): shutil.copy("LICENSE.txt", os.path.join(DIST_DIR, get_dist_path())) # Entry point def main(): parse_options() mk_build_dirs() mk_z3() init_project_def() mk_dist_dir() cp_license() mk_zip() main()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_unix_dist.py
mk_unix_dist.py
# 1. copy over dlls # 2. copy over libz3.dll for the different architectures # 3. copy over Microsoft.Z3.dll from suitable distribution # 4. copy nuspec file from packages # 5. call nuget pack # 6. sign package import json import os import zipfile import sys import os.path import shutil import subprocess def mk_dir(d): if not os.path.exists(d): os.makedirs(d) os_info = { 'ubuntu-latest' : ('so', 'linux-x64'), 'ubuntu-18' : ('so', 'linux-x64'), 'ubuntu-20' : ('so', 'linux-x64'), 'glibc' : ('so', 'linux-x64'), #'glibc-2.35' : ('so', 'linux-x64'), 'x64-win' : ('dll', 'win-x64'), 'x86-win' : ('dll', 'win-x86'), 'x64-osx' : ('dylib', 'osx-x64'), 'arm64-osx' : ('dylib', 'osx-arm64'), 'debian' : ('so', 'linux-x64') } def classify_package(f, arch): for os_name in os_info: if os_name in f: ext, dst = os_info[os_name] return os_name, f[:-4], ext, dst print("Could not classify", f) return None def replace(src, dst): try: os.remove(dst) except: shutil.move(src, dst) def unpack(packages, symbols, arch): # unzip files in packages # out # +- runtimes # +- win-x64 # +- win-x86 # +- linux-x64 # +- osx-x64 # + tmp = "tmp" if not symbols else "tmpsym" for f in os.listdir(packages): print(f) if f.endswith(".zip") and classify_package(f, arch): os_name, package_dir, ext, dst = classify_package(f, arch) path = os.path.abspath(os.path.join(packages, f)) zip_ref = zipfile.ZipFile(path, 'r') zip_ref.extract(f"{package_dir}/bin/libz3.{ext}", f"{tmp}") mk_dir(f"out/runtimes/{dst}/native") replace(f"{tmp}/{package_dir}/bin/libz3.{ext}", f"out/runtimes/{dst}/native/libz3.{ext}") if "x64-win" in f or "x86-win" in f: mk_dir("out/lib/netstandard2.0/") if symbols: zip_ref.extract(f"{package_dir}/bin/libz3.pdb", f"{tmp}") replace(f"{tmp}/{package_dir}/bin/libz3.pdb", f"out/runtimes/{dst}/native/libz3.pdb") files = ["Microsoft.Z3.dll"] if symbols: files += ["Microsoft.Z3.pdb", "Microsoft.Z3.xml"] for b in files: zip_ref.extract(f"{package_dir}/bin/{b}", f"{tmp}") replace(f"{tmp}/{package_dir}/bin/{b}", f"out/lib/netstandard2.0/{b}") def mk_targets(source_root): mk_dir("out/build") shutil.copy(f"{source_root}/src/api/dotnet/Microsoft.Z3.targets.in", "out/build/Microsoft.Z3.targets") def mk_icon(source_root): mk_dir("out/content") shutil.copy(f"{source_root}/resources/icon.jpg", "out/content/icon.jpg") def create_nuget_spec(version, repo, branch, commit, symbols, arch): arch = f".{arch}" if arch == "x86" else "" contents = """<?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata> <id>Microsoft.Z3{4}</id> <version>{0}</version> <authors>Microsoft</authors> <description> Z3 is a satisfiability modulo theories solver from Microsoft Research. Linux Dependencies: libgomp.so.1 installed </description> <copyright>&#169; Microsoft Corporation. All rights reserved.</copyright> <tags>smt constraint solver theorem prover</tags> <icon>content/icon.jpg</icon> <projectUrl>https://github.com/Z3Prover/z3</projectUrl> <license type="expression">MIT</license> <repository type="git" url="{1}" branch="{2}" commit="{3}" /> <requireLicenseAcceptance>true</requireLicenseAcceptance> <language>en</language> <dependencies> <group targetFramework=".netstandard2.0" /> </dependencies> </metadata> </package>""".format(version, repo, branch, commit, arch) print(contents) sym = "sym." if symbols else "" file = f"out/Microsoft.Z3{arch}.{sym}nuspec" print(file) with open(file, 'w') as f: f.write(contents) class Env: def __init__(self, argv): self.packages = argv[1] self.version = argv[2] self.repo = argv[3] self.branch = argv[4] self.commit = argv[5] self.source_root = argv[6] self.symbols = False self.arch = "x64" if len(argv) > 7 and "symbols" == argv[7]: self.symbols = True if len(argv) > 8: self.arch = argv[8] def create(self): mk_dir(self.packages) unpack(self.packages, self.symbols, self.arch) mk_targets(self.source_root) mk_icon(self.source_root) create_nuget_spec(self.version, self.repo, self.branch, self.commit, self.symbols, self.arch) def main(): env = Env(sys.argv) print(env.packages) env.create() main()
z3-solver
/z3-solver-4.12.2.0.tar.gz/z3-solver-4.12.2.0/core/scripts/mk_nuget_task.py
mk_nuget_task.py
<h1 align="center">Tap-Mongodb</h1> <p align="center"> <a href="https://github.com/z3z1ma/tap-mongodb/actions/"><img alt="Actions Status" src="https://github.com/z3z1ma/tap-mongodb/actions/workflows/ci_workflow.yml/badge.svg"></a> <a href="https://github.com/z3z1ma/tap-mongodb/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a> <a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a> </p> `tap-mongodb` is a Singer tap for MongoDB. This tap differentiates itself from existing taps in a few ways. First, rather than expose a very specific set of configuration options for the underlying pymongo driver, we expose all possible arguments by accepting an object underneath the `mongo` key which pass all kwargs straight through to the driver. There are over 40 configurable kwargs available as seen [here](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#module-pymongo.mongo_client). This gives it more flexibility in contrast to a constrained interface. Secondly, this tap has three output modes configurable via `strategy: raw | envelope | infer`. - **Strategy 1** (`strategy: raw`) merely outputs data as-is with an `additonalProperties: true` schema. This is ideal for loading to unstructured sources such as blob storage where it may be preferable to keep documents exactly as they are. - **Strategy 2** (`strategy: envelope`) will wrap the document in a `document` key and output a fixed schema. The schema will use `type: object` and the target should be able to handle unstructured data, ie. via a VARIANT/JSON column. - **Strategy 3** (`strategy: infer`) infers the schema of each collection from a configurable sample size of records. This allows the tap to work with strongly typed destinations. This is an attractive option. Particularly when we don't expect the documents to vary dramatically. The last differentiator is the minimal code footprint in comparison to existing Mongo taps. I hope that this tap exemplifies how we can use as little code as possible with the existing plumbing in the SDK. The SDK means the tap supports the `BATCH` specification out of the box and is able to receive ongoing updates and improvements as the SDK continues to mature. ## Installation The package on pypi is named `z3-tap-mongodb` but the executable it ships with is simply `tap-mongodb`. This allows me to release work without concerns of naming conflicts on the package index. ```bash # Use pipx or pip pipx install z3-tap-mongodb # Verify it is installed tap-mongodb --version ``` ## Incremental Syncs We support incremental syncs on a collection by collection basis. All this requires is the developer adding a `replication_key` to the catalog for a stream. After dumping the `tap-mongodb --config ... --discover > catalog.json`, you can modify the catalog and version control it for ongoing use. If using meltano, you can use the `metadata` key to update the catalog dynamically achieving the same affect. One caveat of our incrementality is that this relies on an alphanumerically sortable replication key. This accounts for a majority of use cases but there are some edge cases. Integer based replication keys (such as epochs) work fine obviously, ISO formatted dates work fine, but any other format may not work as expected. ## Settings | Setting | Required | Default | Description | |:------------------------|:--------:|:-------:|:------------| | mongo | True | None | These props are passed directly to pymongo MongoClient allowing the tap user full flexibility not provided in any other Mongo tap since every kwarg can be tuned. | | stream_prefix | False | | Optionally add a prefix for all streams, useful if ingesting from multiple shards/clusters via independent tap-mongodb configs. This is applied during catalog generation. Regenerate the catalog to apply a new stream prefix. | | optional_replication_key| False | 0 | This setting allows the tap to continue processing if a document is missing the replication key. Useful if a very small percentage of documents are missing the property. | | database_includes | False | None | A list of databases to include. If this list is empty, all databases will be included. | | database_excludes | False | None | A list of databases to exclude. If this list is empty, no databases will be excluded. | | strategy | False | "raw" | The strategy to use for schema resolution. Defaults to 'raw'. The 'raw' strategy uses a relaxed schema using additionalProperties: true to accept the document as-is leaving the target to respect it. Useful for blob or jsonl. The 'envelope' strategy will envelope the document under a key named `document`. The target should use a variant type for this key. The 'infer' strategy will infer the schema from the data based on a configurable number of documents. | | infer_schema_max_docs | False | 2000 | The maximum number of documents to sample when inferring the schema. This is only used when `strategy` is set to `infer`. | | batch_config | False | None | Batch configuration as defined [here](https://sdk.meltano.com/en/latest/batch.html#batch-configuration) | | stream_maps | False | None | | | stream_map_config | False | None | User-defined config values to be used within map expressions. | | flattening_enabled | False | None | 'True' to enable schema flattening and automatically expand nested properties. | | flattening_max_depth | False | None | The max depth to flatten schemas. | A full list of supported settings and capabilities is available by running: `tap-mongodb --about` ### Configure using environment variables This Singer tap will automatically import any environment variables within the working directory's `.env` if the `--config=ENV` is provided, such that config values will be considered if a matching environment variable is set either in the terminal context or in the `.env` file. ### Capabilities * `batch` * `catalog` * `state` * `discover` * `about` * `stream-maps` * `schema-flattening` ## Usage You can easily run `tap-mongodb` by itself or in a pipeline using [Meltano](https://meltano.com/). ### Executing the Tap Directly ```bash tap-mongodb --version tap-mongodb --help tap-mongodb --config CONFIG --discover > ./catalog.json ``` ## Developer Resources ### Initialize your Development Environment ```bash pipx install poetry poetry install ``` ### Create and Run Tests Create tests within the `tap_mongodb/tests` subfolder and then run: ```bash poetry run pytest ``` You can also test the `tap-mongodb` CLI interface directly using `poetry run`: ```bash poetry run tap-mongodb --help ``` ### Testing with [Meltano](https://www.meltano.com) _**Note:** This tap will work in any Singer environment and does not require Meltano. Examples here are for convenience and to streamline end-to-end orchestration scenarios._ Your project comes with a custom `meltano.yml` project file already created. Open the `meltano.yml` and follow any _"TODO"_ items listed in the file. Next, install Meltano (if you haven't already) and any needed plugins: ```bash # Install meltano pipx install meltano # Initialize meltano within this directory cd tap-mongodb meltano install ``` Now you can test and orchestrate using Meltano: ```bash # Test invocation: meltano invoke tap-mongodb --version # OR run a test `elt` pipeline: meltano elt tap-mongodb target-jsonl ``` ### SDK Dev Guide See the [dev guide](https://sdk.meltano.com/en/latest/dev_guide.html) for more instructions on how to use the SDK to develop your own taps and targets. Built with the [Meltano Tap SDK](https://sdk.meltano.com) for Singer Taps.
z3-tap-mongodb
/z3_tap_mongodb-0.4.5.tar.gz/z3_tap_mongodb-0.4.5/README.md
README.md
from __future__ import annotations import collections import os from typing import Any, Generator, Iterable, MutableMapping import orjson import singer_sdk._singerlib as singer import singer_sdk.helpers._flattening from bson.objectid import ObjectId from bson.timestamp import Timestamp from pymongo.collection import Collection from singer_sdk import Stream from singer_sdk.helpers._state import increment_state from singer_sdk.helpers._util import utc_now from singer_sdk.plugin_base import PluginBase as TapBaseClass from singer_sdk.streams.core import ( REPLICATION_INCREMENTAL, REPLICATION_LOG_BASED, TypeConformanceLevel, ) def _flatten_record( record_node: MutableMapping[Any, Any], flattened_schema: dict | None = None, parent_key: list[str] | None = None, separator: str = "__", level: int = 0, max_level: int = 0, ) -> dict: if parent_key is None: parent_key = [] items: list[tuple[str, Any]] = [] for k, v in record_node.items(): new_key = singer_sdk.helpers._flattening.flatten_key(k, parent_key, separator) if isinstance(v, collections.abc.MutableMapping) and level < max_level: items.extend( _flatten_record( v, flattened_schema, parent_key + [k], separator=separator, level=level + 1, max_level=max_level, ).items() ) else: items.append( ( new_key, # Override the default json encoder to use orjson # and a string encoder for ObjectIds, etc. orjson.dumps( v, default=lambda o: str(o), option=orjson.OPT_OMIT_MICROSECONDS ).decode("utf-8") if singer_sdk.helpers._flattening._should_jsondump_value(k, v, flattened_schema) else v, ) ) return dict(items) # Monkey patch the singer lib to use orjson + bson json_util default singer_sdk.helpers._flattening._flatten_record = _flatten_record class CollectionStream(Stream): """Collection stream class. This stream is used to represent a collection in a database. It is a generic stream that can be used to represent any collection in a database.""" # The output stream will always have _id as the primary key primary_keys = ["_id"] # Disable timestamp replication keys. One caveat is this relies on an # alphanumerically sortable replication key. Python __gt__ and __lt__ are # used to compare the replication key values. This works for most cases. is_timestamp_replication_key = False # No conformance level is set by default since this is a generic stream TYPE_CONFORMANCE_LEVEL = TypeConformanceLevel.NONE def __init__( self, tap: TapBaseClass, schema: str | os.PathLike | dict[str, Any] | singer.Schema | None = None, name: str | None = None, *, collection: Collection, ) -> None: """Initialize the stream.""" super().__init__(tap=tap, schema=schema, name=name) self._collection = collection self._strategy = self.config.get("strategy", "raw") def _make_resume_token(oplog_doc: dict): """Make a resume token the hard way for Mongo <=3.6 The idea here is to use change streams but there are nuances that don't fit a batch use case such as the fact it is a capped collection.""" rt = b"\x82" rt += oplog_doc["ts"].time.to_bytes(4, byteorder="big") + oplog_doc["ts"].inc.to_bytes( 4, byteorder="big" ) rt += b"\x46\x64\x5f\x69\x64\x00\x64" rt += bytes.fromhex(str(oplog_doc["o"]["_id"])) rt += b"\x00\x5a\x10\x04" rt += oplog_doc["ui"].bytes rt += b"\x04" return {"_data": rt} def _make_start_op_time(self): """Make a Timestamp used to resume a change stream for Mongo >3.6 The idea here is to use change streams but there are nuances that don't fit a batch use case such as the fact it is a capped collection.""" first_record: ObjectId = list(self._collection.find(projection=[]).sort("_id", 1).limit(1))[ 0 ]["_id"] return Timestamp(first_record.generation_time, first_record._inc) def get_records(self, context: dict | None) -> Iterable[dict]: bookmark = self.get_starting_replication_key_value(context) for record in self._collection.find( {self.replication_key: {"$gt": bookmark}} if bookmark else {} ): if self._strategy == "envelope": # Return the record wrapped in a document key yield {"_id": record["_id"], "document": record} else: # Return the record as is yield record def _generate_record_messages( self, record: dict, ) -> Generator[singer.RecordMessage, None, None]: for stream_map in self.stream_maps: mapped_record = stream_map.transform(record) if mapped_record is not None: record_message = singer.RecordMessage( stream=stream_map.stream_alias, record=mapped_record, version=None, time_extracted=utc_now(), ) yield record_message def _increment_stream_state( self, latest_record: dict[str, Any], *, context: dict | None = None ) -> None: """This override adds error handling for replication key incrementing. This is useful since a single bad document could otherwise break the stream.""" state_dict = self.get_context_state(context) if latest_record: if self.replication_method in [REPLICATION_INCREMENTAL, REPLICATION_LOG_BASED]: if not self.replication_key: raise ValueError( f"Could not detect replication key for '{self.name}' stream" f"(replication method={self.replication_method})" ) treat_as_sorted = self.is_sorted if not treat_as_sorted and self.state_partitioning_keys is not None: # Streams with custom state partitioning are not resumable. treat_as_sorted = False try: increment_state( state_dict, replication_key=self.replication_key, latest_record=latest_record, is_sorted=treat_as_sorted, check_sorted=self.check_sorted, ) except Exception as e: # Handle the case where the replication key is not in the latest record # since this is a valid case for Mongo if self.config.get("optional_replication_key", False): self.logger.warn("Failed to increment state. Ignoring...") return raise RuntimeError( "Failed to increment state. Got record %s", latest_record ) from e class MockCollection: """Mock collection class. This class is used to mock a collection in the unit tests.""" def __init__(self, name: str, schema: dict[str, Any]) -> None: self.name = name self.schema = schema def find(self, query: dict[str, Any]) -> list[dict[str, Any]]: """Mock find method.""" return [{"_id": "1", "name": "test"}] def aggregate(self, pipeline: list[dict[str, Any]]) -> list[dict[str, Any]]: """Mock aggregate method.""" return [{"_id": "1", "name": "test"}] def distinct(self, key: str) -> list[str]: """Mock distinct method.""" return ["test"] def count_documents(self, query: dict[str, Any]) -> int: """Mock count_documents method.""" return 1 def drop(self) -> None: """Mock drop method.""" pass
z3-tap-mongodb
/z3_tap_mongodb-0.4.5.tar.gz/z3_tap_mongodb-0.4.5/tap_mongodb/collection.py
collection.py
from __future__ import annotations import os import orjson import genson import singer_sdk._singerlib.messages import singer_sdk.helpers._typing from pymongo.mongo_client import MongoClient from singer_sdk import Stream, Tap from singer_sdk import typing as th from singer_sdk._singerlib.catalog import Catalog, CatalogEntry from tap_mongodb.collection import CollectionStream, MockCollection _BLANK = "" """A sentinel value to represent a blank value in the config.""" # Monkey patch the singer lib to use orjson singer_sdk._singerlib.messages.format_message = lambda message: orjson.dumps( message.to_dict(), default=lambda o: str(o), option=orjson.OPT_OMIT_MICROSECONDS ).decode("utf-8") def noop(*args, **kwargs) -> None: """No-op function to silence the warning about unmapped properties.""" pass # Monkey patch the singer lib to silence the warning about unmapped properties singer_sdk.helpers._typing._warn_unmapped_properties = noop def recursively_drop_required(schema: dict) -> None: """Recursively drop the required property from a schema. This is used to clean up genson generated schemas which are strict by default.""" schema.pop("required", None) if "properties" in schema: for prop in schema["properties"]: if schema["properties"][prop].get("type") == "object": recursively_drop_required(schema["properties"][prop]) class TapMongoDB(Tap): """MongoDB tap class.""" name = "tap-mongodb" config_jsonschema = th.PropertiesList( th.Property( "mongo", th.ObjectType(), description=( "These props are passed directly to pymongo MongoClient allowing the " "tap user full flexibility not provided in other Mongo taps since every kwarg " "can be tuned." ), required=True, ), th.Property( "stream_prefix", th.StringType, description=( "Optionally add a prefix for all streams, useful if ingesting from multiple" " shards/clusters via independent tap-mongodb configs. This is applied during" " catalog generation. Regenerate the catalog to apply a new stream prefix." ), default=_BLANK, ), th.Property( "optional_replication_key", th.BooleanType, description=( "This setting allows the tap to continue processing if a document is" " missing the replication key. Useful if a very small percentage of documents" " are missing the property." ), default=False, ), th.Property( "database_includes", th.ArrayType(th.StringType), description=( "A list of databases to include. If this list is empty, all databases" " will be included." ), ), th.Property( "database_excludes", th.ArrayType(th.StringType), description=( "A list of databases to exclude. If this list is empty, no databases" " will be excluded." ), ), th.Property( "strategy", th.StringType, description=( "The strategy to use for schema resolution. Defaults to 'raw'. The 'raw' strategy" " uses a relaxed schema using additionalProperties: true to accept the document" " as-is leaving the target to respect it. Useful for blob or jsonl. The 'envelope'" " strategy will envelope the document under a key named `document`. The target" " should use a variant type for this key. The 'infer' strategy will infer the" " schema from the data based on a configurable number of documents." ), default="raw", allowed_values=["raw", "envelope", "infer"], ), th.Property( "infer_schema_max_docs", th.IntegerType, description=( "The maximum number of documents to sample when inferring the schema." " This is only used when infer_schema is true." ), default=2_000, ), th.Property("stream_maps", th.ObjectType()), th.Property("stream_map_config", th.ObjectType()), th.Property("batch_config", th.ObjectType()), ).to_dict() @property def catalog_dict(self) -> dict: """Get catalog dictionary. Returns: The tap's catalog as a dict """ # Use cached catalog if available if hasattr(self, "_catalog_dict") and self._catalog_dict: return self._catalog_dict # Defer to passed in catalog if available if self.input_catalog: return self.input_catalog.to_dict() # Handle discovery in test mode if "TAP_MONGO_TEST_NO_DB" in os.environ: return {"streams": [{"tap_stream_id": "test", "stream": "test"}]} # If no catalog is provided, discover streams catalog = Catalog() client = MongoClient(**self.config["mongo"]) try: client.server_info() except Exception as exc: raise RuntimeError("Could not connect to MongoDB to generate catalog") from exc db_includes = self.config.get("database_includes", []) db_excludes = self.config.get("database_excludes", []) for db_name in client.list_database_names(): if db_includes and db_name not in db_includes: continue if db_excludes and db_name in db_excludes: continue try: collections = client[db_name].list_collection_names() except Exception: # Skip databases that are not accessible by the authenticated user # This is a common case when using a shared cluster # https://docs.mongodb.com/manual/core/security-users/#database-user-privileges # TODO: vet the list of exceptions that can be raised here to be more explicit self.logger.debug( "Skipping database %s, authenticated user does not have permission to access", db_name, ) continue for collection in collections: try: client[db_name][collection].find_one() except Exception: # Skip collections that are not accessible by the authenticated user # This is a common case when using a shared cluster # https://docs.mongodb.com/manual/core/security-users/#database-user-privileges # TODO: vet the list of exceptions that can be raised here to be more explicit self.logger.debug( ( "Skipping collections %s, authenticated user does not have permission" " to access" ), db_name, ) continue self.logger.info("Discovered collection %s.%s", db_name, collection) stream_prefix = self.config.get("stream_prefix", _BLANK) stream_prefix += db_name.replace("-", "_").replace(".", "_") stream_name = f"{stream_prefix}_{collection}" entry = CatalogEntry.from_dict({"tap_stream_id": stream_name}) entry.stream = stream_name strategy: str | None = self.config.get("strategy") if strategy == "infer": builder = genson.SchemaBuilder(schema_uri=None) for record in client[db_name][collection].aggregate( [{"$sample": {"size": self.config.get("infer_schema_max_docs", 2_000)}}] ): builder.add_object( orjson.loads( orjson.dumps( record, default=lambda o: str(o), option=orjson.OPT_OMIT_MICROSECONDS, ).decode("utf-8") ) ) schema = builder.to_schema() recursively_drop_required(schema) if not schema: # If the schema is empty, skip the stream # this errs on the side of strictness continue self.logger.info("Inferred schema: %s", schema) elif strategy == "envelope": schema = { "type": "object", "properties": { "_id": { "type": ["string", "null"], "description": "The document's _id", }, "document": { "type": "object", "additionalProperties": True, "description": "The document from the collection", }, }, } elif strategy == "raw": schema = { "type": "object", "additionalProperties": True, "description": "The document from the collection", "properties": { "_id": { "type": ["string", "null"], "description": "The document's _id", }, }, } else: raise RuntimeError(f"Unknown strategy {strategy}") entry.schema = entry.schema.from_dict(schema) entry.key_properties = ["_id"] entry.metadata = entry.metadata.get_standard_metadata( schema=schema, key_properties=["_id"] ) entry.database = db_name entry.table = collection catalog.add_stream(entry) self._catalog_dict = catalog.to_dict() return self._catalog_dict def discover_streams(self) -> list[Stream]: """Return a list of discovered streams.""" if "TAP_MONGO_TEST_NO_DB" in os.environ: # This is a hack to allow the tap to be tested without a MongoDB instance return [ CollectionStream( tap=self, name="test", schema={ "type": "object", "properties": { "_id": { "type": ["string", "null"], "description": "The document's _id", }, }, "additionalProperties": True, }, collection=MockCollection( name="test", schema={}, ), ) ] client = MongoClient(**self.config["mongo"]) try: client.server_info() except Exception as e: raise RuntimeError("Could not connect to MongoDB") from e db_includes = self.config.get("database_includes", []) db_excludes = self.config.get("database_excludes", []) for entry in self.catalog.streams: if entry.database in db_excludes: continue if db_includes and entry.database not in db_includes: continue stream = CollectionStream( tap=self, name=entry.tap_stream_id, schema=entry.schema, collection=client[entry.database][entry.table], ) stream.apply_catalog(self.catalog) yield stream
z3-tap-mongodb
/z3_tap_mongodb-0.4.5.tar.gz/z3_tap_mongodb-0.4.5/tap_mongodb/tap.py
tap.py
<h1 align="center">Target-BigQuery</h1> <p align="center"> <a href="https://github.com/z3z1ma/target-bigquery/actions/"><img alt="Actions Status" src="https://github.com/z3z1ma/target-bigquery/actions/workflows/ci.yml/badge.svg"></a> <a href="https://github.com/z3z1ma/target-bigquery/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a> <a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a> </p> **A rare 💎 you have stumbled upon** `target-bigquery` is a Singer target for BigQuery. It is the most versatile target for BigQuery. Extremely performant, resource efficient, and fast in all configurations enabling 20 different ingestion patterns. Denormalized variants indicate data is unpacked during load with a resultant schema in BigQuery based on the tap schema. Non-denormalized means we have a fixed schema which loads all data into an unstructured `JSON` column. They are both useful patterns. The latter allowing BigQuery to work with schemaless or rapidly changing sources such as MongoDB instantly, while the former is more performant and convenient to start modeling quickly. **Patterns** 🛠 (more details below) - Batch Job, Denormalized, Overwrite - Batch Job, Denormalized, Upsert - Batch Job, Denormalized, Append - Batch Job, Fixed Schema, Overwrite - Batch Job, Fixed Schema, Append - GCS Staging Data Lake, Denormalized, Overwrite - GCS Staging Data Lake, Denormalized, Upsert - GCS Staging Data Lake, Denormalized, Append - GCS Staging Data Lake, Fixed Schema, Overwrite - GCS Staging Data Lake, Fixed Schema, Append - Storage Write API, Denormalized, Overwrite - Storage Write API, Denormalized, Upsert - Storage Write API, Denormalized, Append - Storage Write API, Fixed Schema, Overwrite - Storage Write API, Fixed Schema, Append - Legacy Streaming API, Denormalized, Overwrite - Legacy Streaming API, Denormalized, Upsert - Legacy Streaming API, Denormalized, Append - Legacy Streaming API, Fixed Schema, Overwrite - Legacy Streaming API, Fixed Schema, Append ## Installation 📈 The package on pypi is named `z3-target-bigquery` but the executable it ships with is simply `target-bigquery`. This allows me to release work without concerns of naming conflicts on the package index. ```bash # Use pipx or pip pipx install z3-target-bigquery # Verify it is installed target-bigquery --version ``` ## Usage Notes ### Denormalization So denormalized is a loaded term, so lets clarify here what we mean by it: > In the context of JSON objects, denormalization refers to the process of flattening a hierarchical or nested JSON object into a simpler, more "denormalized" structure that can be easier to work with for certain use cases. Denormalized=False (default) means we load all data into a single `JSON` column. This means all access requires an accessor such as `SELECT data.my_column FROM table` instead of `SELECT my_column FROM table`. Hence the term denormalized is relative to the `data` column which is the default for this target. This is a tradeoff between convenience/resilience and performance. This is the default because most _resilient_. IE a load will **never** fail due to a schema change or an invalid schema. You can always denormalize later via `dbt`. However, it is not the most performant and slower to transform. If your tap has a high quality and consistent schema, denormalization is the way to go to get the best performance and start modeling quickly. Denormalized=True means we unpack the data into a schema which is derived from the tap schema. It does _not_ mean we will flatten the data. There is a separate option for flattening. We will convert arrays to repeated fields and records to structs. All top level keys will end up as columns which is was you might expect from more typical targets. #### Resolver Versions There are 2 resolver versions. The config option `schema_resolver_version` lets you select which version you want to use. This versioning exists because we want to support evolving how we resolve schemas whilst not creating breaking changes for long-time users dependent on how a schema is resolved. The default is `1` which behaves very similarly to existing flavors of `target-bigquery`. It works well enough but has plenty of edge cases where it simply cannot resolve valid jsonschemas to a bq schema. The new version `2` is much more robust and will resolve most, if not all schemas due to it falling back to `JSON` when in doubt. You must opt-in to this version by setting `schema_resolver_version: 2` in your config. ### Overwrite vs Append Sometimes you want to overwrite a table on every load. This can be achieved by either setting `overwrite: true` which will full refresh ALL tables **or** setting `overwrite: [table1, table2, table_*_other, !table_v1_other]` which will only overwrite the specified tables and supports pattern matching. This is useful if you have a table which is a lookup table and you want to overwrite it on every load. You can also set `overwrite: false` which will append to the table. This is the default behavior. ### Upsert (aka Merge) If you want to merge data into a table, you can set `merge: true` which will use the `MERGE` statement to upsert data. This supports pattern matching like the above setting. It requires `denormalized: true` takes precedence over `overwrite`. It will only work on tables which have a primary key as defined by the `key_properties` sent by the tap. There is a supporting config option called `dedupe_before_upsert` which will dedupe the data before upserting. This is useful if you are replicating data which has a primary key but is not unique. This occurs when you are replicating data from a source which has a primary key but does not enforce it. This is the case for MongoDB. It can also happen when moving data from a data lake in S3/GCS to a database. This is not the default behavior because it is slower and requires more resources. ## Features ✨ - Autoscaling self-healing worker pool using either threads (default) or multiprocessing, configurable by the user for the _fastest_ possible data ingestion. Particularly when leveraging colocated compute in GCP. - Denormalized load pattern where data is unpacked in flight into a statically typed BigQuery schema derived from the input stream json schemas. - Fix schema load pattern where all data is loaded into a `JSON` column which has been GA in BigQuery since mid 2022. - Autogenerated `VIEW` support for fixed schema load patterns which essentially overlays a statically typed schema allowing you to get the best of both worlds when using fixed schema ingestion. - JIT compilation of protobuf schemas allowing the Storage Write API to use a denormalized load pattern. - BATCH message support 😎 ## Load Patterns 🏎 - `Batch Load Job` ingestion pattern using in memory compression (fixed schema + denormalized) - `Storage Write API` ingestion pattern using gRPC and protocol buffers supporting both streaming and batch patterns. Capable of JIT compilation of BQ schemas to protobuf to enable denormalized loads of input structures only known at runtime. (fixed schema + denormalized 🎉) - `GCS Staging` ingestion pattern using in memory compression and a GCS staging layer which generates a well organized data lake which backs the data warehouse providing additional failsafes and data sources (fixed schema + denormalized) - `Legacy Streaming` ingestion pattern which emphasizes simplicity and fast start up / tear down. I would highly recommend the storage write API instead unless data volume is small (fixed schema + denormalized) **Choosing between denormalized and fixed schema (JSON support)?** 🙇🏾‍♂️ The gap between the methods is closed due in part to the target's ability to automatically generating a `VIEW` which will unpack (or rather provide typing as a more accurate take) a JSON based ingestion source for you. Unless operating at tens of millions of rows with JSON objects containing multiple hundreds of keys, its quite performant. Particularly if accessing a small subset of keys. It does however fall off (quite hard) given enough scale as I mentioned (I've pushed it to the limits). Denormalized is recommended for high volume where the schema is fairly consistent. Fixed is recommended for lower volume, inconsistent schemas or for taps which are inherently schemaless in which case its the ideal (only...) logical pattern. Fixed schema can also be used for taps which routinely break down on BQ due to json schemas being inexpressible in a static way (ie patternProperties, additionalProperties...) **Old Header (still true, here for posterity)** 🧪 This is the first truly unstructured sink for BigQuery leveraging the recent GA feature in BigQuery for JSON support. This allows this target to load from essentially any tap regardless of the quality or explicitness of its jsonschema. Observations in existing taps note things such as `patternProperties` used in jsonschema objects which break down on all existing BigQuery taps due to the previous need for strong typing. Also taps such as MongoDB which inherently deal with unstructured data are seamlessly enabled by this target without klutzy collection scraping of a sample of records which we _hope_ are repesentative of all documents. Built with the [Meltano Target SDK](https://sdk.meltano.com). ## Configuration 🔨 ### Settings First a valid example to give context to the below including a nested key example (denoted via a `.` in the setting path) as seen with `column_name_transforms.snake_case` ```json { "project": "my-bq-project", "method": "storage_write_api", "denormalized": true, "credentials_path": "...", "dataset": "my_dataset", "location": "us-central1", "batch_size": 500, "column_name_transforms": { "snake_case": true } } ``` | Setting | Required | Default | Description | |:---------------------------------------------------|:--------:|:-----------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | credentials_path | False | None | The path to a gcp credentials json file. | | credentials_json | False | None | A JSON string of your service account JSON file. | | project | True | None | The target GCP project to materialize data into. | | dataset | True | None | The target dataset to materialize data into. | | location | False | US | The target dataset location to materialize data into. Applies also to the GCS bucket if using `gcs_stage` load method. | | batch_size | False | 500 | The maximum number of rows to send in a single batch to the worker. This should be configured based on load method. For `storage_write_api` and `streaming_insert` it should be `<=500`, for the LoadJob sinks, it can be much higher, ie `>100,000` | | timeout | False | 600 | Default timeout for batch_job and gcs_stage derived LoadJobs. | | fail_fast | False | True | Fail the entire load job if any row fails to insert. | | denormalized | False | False | Determines whether to denormalize the data before writing to BigQuery. A false value will write data using a fixed JSON column based schema, while a true value will write data using a dynamic schema derived from the tap. | | method | True | storage_write_api | The method to use for writing to BigQuery. Must be one of `batch_job`, `storage_write_api`, `gcs_stage`, `streaming_insert` | | generate_view | False | False | Determines whether to generate a view based on the SCHEMA message parsed from the tap. Only valid if denormalized=false meaning you are using the fixed JSON column based schema. | | upsert | False | False | Determines if we should upsert. Defaults to false. A value of true will write to a temporary table and then merge into the target table (upsert). This requires the target table to be unique on the key properties. A value of false will write to the target table directly (append). A value of an array of strings will evaluate the strings in order using fnmatch. At the end of the array, the value of the last match will be used. If not matched, the default value is false (append). | | overwrite | False | False | Determines if the target table should be overwritten on load. Defaults to false. A value of true will write to a temporary table and then overwrite the target table inside a transaction (so it is safe). A value of false will write to the target table directly (append). A value of an array of strings will evaluate the strings in order using fnmatch. At the end of the array, the value of the last match will be used. If not matched, the default value is false. This is mutually exclusive with the `upsert` option. If both are set, `upsert` will take precedence. | | dedupe_before_upsert | False | False | This option is only used if `upsert` is enabled for a stream. The selection criteria for the stream's candidacy is the same as upsert. If the stream is marked for deduping before upsert, we will create a _session scoped temporary table during the merge transaction to dedupe the ingested records. This is useful for streams that are not unique on the key properties during an ingest but are unique in the source system. Data lake ingestion is often a good example of this where the same unique record may exist in the lake at different points in time from different extracts. | | bucket | False | None | The GCS bucket to use for staging data. Only used if method is gcs_stage. | | cluster_on_key_properties | False | 0 | Determines whether to cluster on the key properties from the tap. Defaults to false. When false, clustering will be based on _sdc_batched_at instead. | | partition_granularity | False | "month" | Indicates the granularity of the created table partitioning scheme which is based on `_sdc_batched_at`. By default the granularity is monthly. Must be one of: "hour", "day", "month", "year". | | column_name_transforms.lower | False | None | Lowercase column names. | | column_name_transforms.quote | False | None | Quote column names in any generated DDL. | | column_name_transforms.add_underscore_when_invalid | False | None | Add an underscore to the column name if it starts with a digit to make it valid. | | column_name_transforms.snake_case | False | None | Snake case all incoming column names. Does not apply to fixed schema loads but _does_ apply to the view auto-generated over them. | | options.storage_write_batch_mode | False | None | By default, we use the default stream (Committed mode) in the [storage_write_api](https://cloud.google.com/bigquery/docs/write-api) load method which results in streaming records which are immediately available and is generally fastest. If this is set to true, we will use the application created streams (pending mode) to transactionally batch data on STATE messages and at end of pipe. | | options.process_pool | False | None | By default we use an autoscaling threadpool to write to BigQuery. If set to true, we will use a process pool. | | options.max_workers | False | None | By default, each sink type has a preconfigured max worker pool limit. This sets an override for maximum number of workers in the pool. | | schema_resolver_version | False | 1 | The version of the schema resolver to use. Defaults to 1. Version 2 uses JSON as a fallback during denormalization. This only has an effect if denormalized=true | | stream_maps | False | None | Config object for stream maps capability. For more information check out [Stream Maps](https://sdk.meltano.com/en/latest/stream_maps.html). | | stream_map_config | False | None | User-defined config values to be used within map expressions. | | flattening_enabled | False | None | 'True' to enable schema flattening and automatically expand nested properties. | | flattening_max_depth | False | None | The max depth to flatten schemas. | A full list of supported settings and capabilities is available by running: `target-bigquery --about` ### Configure using environment variables ✏️ This Singer target will automatically import any environment variables within the working directory's `.env` if the `--config=ENV` is provided, such that config values will be considered if a matching environment variable is set either in the terminal context or in the `.env` file. ### Source Authentication and Authorization 👮🏽‍♂️ Authenticate via service account key file or Application Default Credentials (ADC) https://cloud.google.com/bigquery/docs/authentication ## Capabilities ✨ * `about` * `stream-maps` * `schema-flattening` * `batch` ## Usage 👷‍♀️ You can easily run `target-bigquery` by itself or in a pipeline using [Meltano](https://meltano.com/). ### Executing the Target Directly 🚧 ```bash target-bigquery --version target-bigquery --help # Test using the "Carbon Intensity" sample: tap-carbon-intensity | target-bigquery --config /path/to/target-bigquery-config.json ``` ## Developer Resources 👩🏼‍💻 ### Initialize your Development Environment ```bash pipx install poetry poetry install ``` ### Create and Run Tests Create tests within the `target_bigquery/tests` subfolder and then run: ```bash poetry run pytest ``` You can also test the `target-bigquery` CLI interface directly using `poetry run`: ```bash poetry run target-bigquery --help ``` ### Testing with [Meltano](https://meltano.com/) _**Note:** This target will work in any Singer environment and does not require Meltano. Examples here are for convenience and to streamline end-to-end orchestration scenarios._ Next, install Meltano (if you haven't already) and any needed plugins: ```bash # Install meltano pipx install meltano # Initialize meltano within this directory cd target-bigquery meltano install ``` Now you can test and orchestrate using Meltano: ```bash # Test invocation: meltano invoke target-bigquery --version # OR run a test `elt` pipeline with the Carbon Intensity sample tap: meltano elt tap-carbon-intensity target-bigquery ``` ### SDK Dev Guide See the [dev guide](https://sdk.meltano.com/en/latest/dev_guide.html) for more instructions on how to use the Meltano SDK to develop your own Singer taps and targets.
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/README.md
README.md
"""BigQuery target class.""" import os import copy import time import uuid from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Type, Union from singer_sdk import Sink from singer_sdk import typing as th from singer_sdk.target_base import Target from target_bigquery.batch_job import BigQueryBatchJobDenormalizedSink, BigQueryBatchJobSink from target_bigquery.core import BaseBigQuerySink, BaseWorker, BigQueryCredentials, ParType from target_bigquery.gcs_stage import BigQueryGcsStagingDenormalizedSink, BigQueryGcsStagingSink from target_bigquery.storage_write import ( BigQueryStorageWriteDenormalizedSink, BigQueryStorageWriteSink, ) from target_bigquery.streaming_insert import ( BigQueryStreamingInsertDenormalizedSink, BigQueryStreamingInsertSink, ) if TYPE_CHECKING: from multiprocessing import Process, Queue from multiprocessing.connection import Connection # Defaults for target worker pool parameters MAX_WORKERS = 15 """Maximum number of workers to spawn.""" MAX_JOBS_QUEUED = 30 """Maximum number of jobs placed in the global queue to avoid memory overload.""" WORKER_CAPACITY_FACTOR = 5 """Jobs enqueued must exceed the number of active workers times this number.""" WORKER_CREATION_MIN_INTERVAL = 5 """Minimum time between worker creation attempts.""" class TargetBigQuery(Target): """Target for BigQuery.""" _MAX_RECORD_AGE_IN_MINUTES = 5.0 name = "target-bigquery" config_jsonschema = th.PropertiesList( th.Property( "credentials_path", th.StringType, description="The path to a gcp credentials json file.", ), th.Property( "credentials_json", th.StringType, description="A JSON string of your service account JSON file.", ), th.Property( "project", th.StringType, description="The target GCP project to materialize data into.", required=True, ), th.Property( "dataset", th.StringType, description="The target dataset to materialize data into.", required=True, ), th.Property( "location", th.StringType, description="The target dataset/bucket location to materialize data into.", default="US", ), th.Property( "batch_size", th.IntegerType, description="The maximum number of rows to send in a single batch or commit.", default=500, ), th.Property( "fail_fast", th.BooleanType, description="Fail the entire load job if any row fails to insert.", default=True, ), th.Property( "timeout", th.IntegerType, description="Default timeout for batch_job and gcs_stage derived LoadJobs.", default=600, ), th.Property( "denormalized", th.BooleanType, description=( "Determines whether to denormalize the data before writing to BigQuery. A false" " value will write data using a fixed JSON column based schema, while a true value" " will write data using a dynamic schema derived from the tap." ), default=False, ), th.Property( "method", th.CustomType( { "type": "string", "enum": [ "storage_write_api", "batch_job", "gcs_stage", "streaming_insert", ], } ), description="The method to use for writing to BigQuery.", default="storage_write_api", required=True, ), th.Property( "generate_view", th.BooleanType, description=( "Determines whether to generate a view based on the SCHEMA message parsed from the" " tap. Only valid if denormalized=false meaning you are using the fixed JSON column" " based schema." ), default=False, ), th.Property( "bucket", th.StringType, description="The GCS bucket to use for staging data. Only used if method is gcs_stage.", ), th.Property( "partition_granularity", th.CustomType( { "type": "string", "enum": [ "year", "month", "day", "hour", ], } ), default="month", description="The granularity of the partitioning strategy. Defaults to month.", ), th.Property( "cluster_on_key_properties", th.BooleanType, default=False, description=( "Determines whether to cluster on the key properties from the tap. Defaults to" " false. When false, clustering will be based on _sdc_batched_at instead." ), ), th.Property( "column_name_transforms", th.ObjectType( th.Property( "lower", th.BooleanType, default=False, description="Lowercase column names", ), th.Property( "quote", th.BooleanType, default=False, description="Quote columns during DDL generation", ), th.Property( "add_underscore_when_invalid", th.BooleanType, default=False, description="Add an underscore when a column starts with a digit", ), th.Property( "snake_case", th.BooleanType, default=False, description="Convert columns to snake case", ), ), description=( "Accepts a JSON object of options with boolean values to enable them. The available" " options are `quote` (quote columns in DDL), `lower` (lowercase column names)," " `add_underscore_when_invalid` (add underscore if column starts with digit), and" " `snake_case` (convert to snake case naming). For fixed schema, this transform" " only applies to the generated view if enabled." ), required=False, ), th.Property( "options", th.ObjectType( th.Property( "storage_write_batch_mode", th.BooleanType, default=False, description=( "By default, we use the default stream (Committed mode) in the" " storage_write_api load method which results in streaming records which" " are immediately available and is generally fastest. If this is set to" " true, we will use the application created streams (Committed mode) to" " transactionally batch data on STATE messages and at end of pipe." ), ), th.Property( "process_pool", th.BooleanType, default=False, description=( "By default we use an autoscaling threadpool to write to BigQuery. If set" " to true, we will use a process pool." ), ), th.Property( "max_workers", th.IntegerType, required=False, description=( "By default, each sink type has a preconfigured max worker pool limit." " This sets an override for maximum number of workers in the pool." ), ), ), description=( "Accepts a JSON object of options with boolean values to enable them. These are" " more advanced options that shouldn't need tweaking but are here for flexibility." ), ), th.Property( "upsert", th.CustomType( { "anyOf": [ {"type": "boolean"}, {"type": "array", "items": {"type": "string"}}, ] } ), default=False, description=( "Determines if we should upsert. Defaults to false. A value of true will write to a" " temporary table and then merge into the target table (upsert). This requires the" " target table to be unique on the key properties. A value of false will write to" " the target table directly (append). A value of an array of strings will evaluate" " the strings in order using fnmatch. At the end of the array, the value of the" " last match will be used. If not matched, the default value is false (append)." ), ), th.Property( "overwrite", th.CustomType( { "anyOf": [ {"type": "boolean"}, {"type": "array", "items": {"type": "string"}}, ] } ), default=False, description=( "Determines if the target table should be overwritten on load. Defaults to false. A" " value of true will write to a temporary table and then overwrite the target table" " inside a transaction (so it is safe). A value of false will write to the target" " table directly (append). A value of an array of strings will evaluate the strings" " in order using fnmatch. At the end of the array, the value of the last match will" " be used. If not matched, the default value is false. This is mutually exclusive" " with the `upsert` option. If both are set, `upsert` will take precedence." ), ), th.Property( "dedupe_before_upsert", th.CustomType( { "anyOf": [ {"type": "boolean"}, {"type": "array", "items": {"type": "string"}}, ] } ), default=False, description=( "This option is only used if `upsert` is enabled for a stream. The selection" " criteria for the stream's candidacy is the same as upsert. If the stream is" " marked for deduping before upsert, we will create a _session scoped temporary" " table during the merge transaction to dedupe the ingested records. This is useful" " for streams that are not unique on the key properties during an ingest but are" " unique in the source system. Data lake ingestion is often a good example of this" " where the same unique record may exist in the lake at different points in time" " from different extracts." ), ), th.Property( "schema_resolver_version", th.IntegerType, default=1, description=( "The version of the schema resolver to use. Defaults to 1. Version 2 uses JSON as a" " fallback during denormalization. This only has an effect if denormalized=true" ), allowed_values=[1, 2], ), ).to_dict() def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.max_parallelism = 1 ( self.proc_cls, self.pipe_cls, self.queue_cls, self.par_typ, ) = self.get_parallelization_components() self.queue = self.queue_cls() self.job_notification, self.job_notifier = self.pipe_cls(False) self.log_notification, self.log_notifier = self.pipe_cls(False) self.error_notification, self.error_notifier = self.pipe_cls(False) self._credentials = BigQueryCredentials( self.config.get("credentials_path"), self.config.get("credentials_json"), self.config["project"], ) def worker_factory(): return self.get_sink_class().worker_cls_factory( self.proc_cls, self.config, )( ext_id=uuid.uuid4().hex, queue=self.queue, credentials=self._credentials, job_notifier=self.job_notifier, log_notifier=self.log_notifier, error_notifier=self.error_notifier, ) self.worker_factory = worker_factory self.workers: List[Union[BaseWorker, "Process"]] = [] self.worker_pings: Dict[str, float] = {} self._jobs_enqueued = 0 self._last_worker_creation = 0.0 def increment_jobs_enqueued(self) -> None: """Increment the number of jobs enqueued.""" self._jobs_enqueued += 1 # We can expand this to support other parallelization methods in the future. # We woulod approach this by adding a new ParType enum and interpreting the # the Process, Pipe, and Queue classes as protocols which can be duck-typed. def get_parallelization_components( self, default=ParType.THREAD ) -> Tuple[ Type["Process"], Callable[[bool], Tuple["Connection", "Connection"]], Callable[[], "Queue"], ParType, ]: """Get the appropriate Process, Pipe, and Queue classes and the assoc ParTyp enum.""" use_procs: Optional[bool] = self.config.get("options", {}).get("process_pool") if use_procs is None: use_procs = default == ParType.PROCESS if not use_procs: from multiprocessing.dummy import Pipe, Process, Queue self.logger.info("Using thread-based parallelism") return Process, Pipe, Queue, ParType.THREAD else: from multiprocessing import Pipe, Process, Queue self.logger.info("Using process-based parallelism") return Process, Pipe, Queue, ParType.PROCESS # Worker management methods, which are used to manage the number of # workers in the pool. The ensure_workers method should be called # periodically to ensure that the pool is at the correct size, ideally # once per batch. @property def add_worker_predicate(self) -> bool: """Predicate determining when it is valid to add a worker to the pool.""" return ( self._jobs_enqueued > getattr(self.get_sink_class(), "WORKER_CAPACITY_FACTOR", WORKER_CAPACITY_FACTOR) * (len(self.workers) + 1) and len(self.workers) < self.config.get("options", {}).get( "max_workers", getattr(self.get_sink_class(), "MAX_WORKERS", MAX_WORKERS), ) and time.time() - self._last_worker_creation > getattr( self.get_sink_class(), "WORKER_CREATION_MIN_INTERVAL", WORKER_CREATION_MIN_INTERVAL, ) ) def resize_worker_pool(self) -> None: """Right-sizes the worker pool. Workers self terminate when they have been idle for a while. This method will remove terminated workers and add new workers if the add_worker_predicate evaluates to True. It will always ensure that there is at least one worker in the pool.""" workers_to_cull = [] worker_spawned = False for i, worker in enumerate(self.workers): if not worker.is_alive(): workers_to_cull.append(i) for i in reversed(workers_to_cull): worker = self.workers.pop(i) worker.join() # Wait for the worker to terminate. This should be a no-op. self.logger.info("Culling terminated worker %s", worker.ext_id) while self.add_worker_predicate or not self.workers: worker = self.worker_factory() worker.start() self.workers.append(worker) worker_spawned = True self.logger.info("Adding worker %s", worker.ext_id) self._last_worker_creation = time.time() if worker_spawned: ... # SDK overrides to inject our worker management logic and sink selection. def get_sink_class(self, stream_name: Optional[str] = None) -> Type[BaseBigQuerySink]: """Returns the sink class to use for a given stream based on user config.""" _ = stream_name method, denormalized = self.config.get("method", "storage_write_api"), self.config.get( "denormalized", False ) if method == "batch_job": if denormalized: return BigQueryBatchJobDenormalizedSink return BigQueryBatchJobSink elif method == "streaming_insert": if denormalized: return BigQueryStreamingInsertDenormalizedSink return BigQueryStreamingInsertSink elif method == "gcs_stage": if denormalized: return BigQueryGcsStagingDenormalizedSink return BigQueryGcsStagingSink elif method == "storage_write_api": if denormalized: return BigQueryStorageWriteDenormalizedSink return BigQueryStorageWriteSink raise ValueError(f"Unknown method: {method}") def get_sink( self, stream_name: str, *, record: Optional[dict] = None, schema: Optional[dict] = None, key_properties: Optional[List[str]] = None, ) -> Sink: """Get a sink for a stream. If the sink does not exist, create it. This override skips sink recreation on schema change. Meaningful mid stream schema changes are not supported and extremely rare to begin with. Most taps provide a static schema at stream init. We handle +90% of cases with this override without the undue complexity or overhead of mid-stream schema evolution. If you need to support mid-stream schema evolution on a regular basis, you should be using the fixed schema load pattern.""" _ = record if schema is None: self._assert_sink_exists(stream_name) return self._sinks_active[stream_name] existing_sink = self._sinks_active.get(stream_name, None) if not existing_sink: return self.add_sink(stream_name, schema, key_properties) return existing_sink def drain_one(self, sink: Sink) -> None: # type: ignore """Drain a sink. Includes a hook to manage the worker pool and notifications.""" #self.logger.info(f"Jobs queued : {self.queue.qsize()} | Max nb jobs queued : {os.cpu_count() * 4} | Nb workers : {len(self.workers)} | Max nb workers : {os.cpu_count() * 2}") self.resize_worker_pool() while self.job_notification.poll(): ext_id = self.job_notification.recv() self.worker_pings[ext_id] = time.time() self._jobs_enqueued -= 1 while self.log_notification.poll(): msg = self.log_notification.recv() self.logger.info(msg) if self.error_notification.poll(): e, msg = self.error_notification.recv() if self.config.get("fail_fast", True): self.logger.error(msg) try: # Try to drain if we can. This is a best effort. # TODO: we should consider if draining here is the right thing # to do. It's _possible_ we increment the state message when # data is not actually written. Its _unlikely_ so the upside is # greater than the downside for now but will revisit this. self.logger.error("Draining all sinks and terminating.") self.drain_all(is_endofpipe=True) except Exception: self.logger.error("Drain failed.") raise RuntimeError(msg) from e super().drain_one(sink) def drain_all(self, is_endofpipe: bool = False) -> None: # type: ignore """Drain all sinks and write state message. If is_endofpipe, execute clean_up() on all sinks. Includes an additional hook to allow sinks to do any pre-state message processing.""" state = copy.deepcopy(self._latest_state) sink: BaseBigQuerySink self._drain_all(list(self._sinks_active.values()), self.max_parallelism) if is_endofpipe: for worker in self.workers: if worker.is_alive(): self.queue.put(None) while len(self.workers): worker.join() worker = self.workers.pop() for sink in self._sinks_active.values(): sink.clean_up() else: for worker in self.workers: worker.join() for sink in self._sinks_active.values(): sink.pre_state_hook() self._write_state_message(state) self._reset_max_record_age()
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/target.py
target.py
import datetime import gzip import json import mmap import re import shutil import sys import time import traceback from abc import ABC, abstractmethod try: from functools import cache except ImportError: from functools import lru_cache as cache from contextlib import contextmanager from copy import copy from dataclasses import dataclass, field from enum import Enum from fnmatch import fnmatch from io import BytesIO from multiprocessing import Process, Queue from multiprocessing.connection import Connection from pathlib import Path from subprocess import PIPE, Popen from tempfile import TemporaryFile from textwrap import dedent, indent from typing import IO, TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type, Union from google.api_core.exceptions import Conflict from google.cloud import bigquery, bigquery_storage_v1, storage from google.cloud.bigquery import SchemaField from google.cloud.bigquery.table import TimePartitioning, TimePartitioningType from singer_sdk.sinks import BatchSink from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from target_bigquery.constants import DEFAULT_SCHEMA if TYPE_CHECKING: from target_bigquery.target import TargetBigQuery class IngestionStrategy(Enum): FIXED = "fixed-schema" DENORMALIZED = "denormalized-schema" class ParType(str, Enum): THREAD = "Thread" PROCESS = "Process" PARTITION_STRATEGY = { "YEAR": TimePartitioningType.YEAR, "MONTH": TimePartitioningType.MONTH, "DAY": TimePartitioningType.DAY, "HOUR": TimePartitioningType.HOUR, } class SchemaResolverVersion(Enum): """The schema resolver version to use.""" V1 = 1 V2 = 2 def __str__(self) -> str: return str(self.value) @dataclass class BigQueryTable: name: str """The name of the table.""" dataset: str """The dataset that this table belongs to.""" project: str """The project that this table belongs to.""" jsonschema: Dict[str, Any] """The jsonschema for this table.""" ingestion_strategy: IngestionStrategy """The ingestion strategy for this table.""" transforms: Dict[str, bool] = field(default_factory=dict) """A dict of transformation rules to apply to the table schema.""" schema_resolver_version: SchemaResolverVersion = SchemaResolverVersion.V1 @property def schema_translator(self) -> "SchemaTranslator": """Returns a SchemaTranslator instance for this table.""" if not hasattr(self, "_schema_translator"): self._schema_translator = SchemaTranslator( schema=self.jsonschema, transforms=self.transforms, resolver_version=self.schema_resolver_version, ) return self._schema_translator def get_schema(self, apply_transforms: bool = False) -> List[bigquery.SchemaField]: """Returns the jsonschema to bigquery schema translation for this table.""" if apply_transforms: return self.schema_translator.translated_schema_transformed return self.schema_translator.translated_schema def get_escaped_name(self, suffix: str = '') -> str: """Returns the table name as as escaped SQL string.""" return f"`{self.project}`.`{self.dataset}`.`{self.name}{suffix}`" def get_resolved_schema(self, apply_transforms: bool = False) -> List[bigquery.SchemaField]: """Returns the schema for this table after factoring in the ingestion strategy.""" if self.ingestion_strategy is IngestionStrategy.FIXED: return DEFAULT_SCHEMA elif self.ingestion_strategy is IngestionStrategy.DENORMALIZED: return self.get_schema(apply_transforms) def __str__(self) -> str: return f"{self.project}.{self.dataset}.{self.name}" def as_ref(self) -> bigquery.TableReference: """Returns a TableReference for this table.""" return bigquery.TableReference.from_string(str(self)) def as_dataset_ref(self) -> bigquery.DatasetReference: """Returns a DatasetReference for this table.""" return bigquery.DatasetReference(self.project, self.dataset) @cache def as_table(self, apply_transforms: bool = False, **kwargs) -> bigquery.Table: """Returns a Table instance for this table.""" table = bigquery.Table( self.as_ref(), schema=self.get_resolved_schema(apply_transforms), ) config = {**self.default_table_options(), **kwargs} for option, value in config.items(): setattr(table, option, value) return table def as_dataset(self, **kwargs) -> bigquery.Dataset: """Returns a Dataset instance for this dataset.""" dataset = bigquery.Dataset(self.as_dataset_ref()) config = {**self.default_dataset_options(), **kwargs} for option, value in config.items(): setattr(dataset, option, value) return dataset def create_table( self, client: bigquery.Client, apply_transforms: bool = False, **kwargs, ) -> Tuple[bigquery.Dataset, bigquery.Table]: """Creates a dataset and table for this table. This is a convenience method that wraps the creation of a dataset and table in a single method call. It is idempotent and will not create a new table if one already exists.""" if not hasattr(self, "_dataset"): try: self._dataset = client.create_dataset( self.as_dataset(**kwargs["dataset"]), exists_ok=False ) except Conflict: dataset = client.get_dataset(self.as_dataset(**kwargs["dataset"])) if dataset.location != kwargs["dataset"]["location"]: raise Exception( f"Location of existing dataset {dataset.dataset_id} ({dataset.location}) " f"does not match specified location: {kwargs['dataset']['location']}" ) else: self._dataset = dataset if not hasattr(self, "_table"): try: self._table = client.create_table( self.as_table( apply_transforms and self.ingestion_strategy != IngestionStrategy.FIXED, **kwargs["table"], ) ) except Conflict: self._table = client.get_table(self.as_ref()) else: # Wait for eventual consistency time.sleep(5) return self._dataset, self._table def default_table_options(self) -> Dict[str, Any]: """Returns the default table options for this table.""" schema_dump = json.dumps(self.jsonschema) return { "clustering_fields": ["_sdc_batched_at"], "description": ( "Generated by target-bigquery.\nStream Schema\n{schema}\nBigQuery Ingestion" " Strategy: {strategy}".format( schema=( (schema_dump[:16000] + "...") if len(schema_dump) > 16000 else schema_dump ), strategy=self.ingestion_strategy, ) ), "time_partitioning": TimePartitioning( type_=TimePartitioningType.MONTH, field="_sdc_batched_at" ), } @staticmethod def default_dataset_options() -> Dict[str, Any]: """Returns the default dataset options for this dataset.""" return {"location": "US"} def __hash__(self) -> int: return hash((self.name, self.dataset, self.project, json.dumps(self.jsonschema))) @dataclass class BigQueryCredentials: """BigQuery credentials.""" path: Optional[Union[str, Path]] = None json: Optional[str] = None project: Optional[str] = None def __hash__(self) -> int: return hash((self.path, self.json, self.project)) class BaseWorker(ABC): """Base class for workers.""" def __init__( self, ext_id: str, queue: "Queue", credentials: BigQueryCredentials, # 3 connections for job, error, and non-error log notifications job_notifier: "Connection", error_notifier: "Connection", log_notifier: "Connection", ): """Initialize a worker.""" super().__init__() self.ext_id: str = ext_id self.queue: "Queue" = queue self.credentials: BigQueryCredentials = credentials self.job_notifier: "Connection" = job_notifier self.error_notifier: "Connection" = error_notifier self.log_notifier: "Connection" = log_notifier @abstractmethod def run(self) -> None: """Run the worker.""" raise NotImplementedError def serialize_exception(self, exc: Exception) -> str: """Serialize an exception to a string.""" msg = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__, chain=False)) msg += f"\nWorker ID: {self.ext_id}\n" return msg # Base class for sinks which use a fixed schema, optionally # including a view which is created on top of the table to unpack the data class BaseBigQuerySink(BatchSink): """BigQuery target sink class, which handles writing streams.""" include_sdc_metadata_properties: bool = True ingestion_strategy = IngestionStrategy.FIXED def __init__( self, target: "TargetBigQuery", stream_name: str, schema: Dict[str, Any], key_properties: Optional[List[str]], ) -> None: """Initialize the sink.""" super().__init__(target, stream_name, schema, key_properties) self._credentials = BigQueryCredentials( self.config.get("credentials_path"), self.config.get("credentials_json"), self.config["project"], ) self.client = bigquery_client_factory(self._credentials) opts = { "project": self.config["project"], "dataset": self.config["dataset"], "jsonschema": self.schema, "transforms": self.config.get("column_name_transforms", {}), "ingestion_strategy": self.ingestion_strategy, "schema_resolver_version": SchemaResolverVersion(self.config.get("schema_resolver_version", 1)), } self.table = BigQueryTable(name=self.table_name, **opts) self.create_target(key_properties=key_properties) self.update_schema() self.merge_target: Optional[BigQueryTable] = None self.overwrite_target: Optional[BigQueryTable] = None # In absence of dedupe or overwrite candidacy, we append to the target table directly # If the stream is marked for one of these strategies, we create a temporary table instead # and merge or overwrite the target table with the temporary table after the ingest. if ( key_properties and self.ingestion_strategy is IngestionStrategy.DENORMALIZED and self._is_upsert_candidate() ): self.merge_target = copy(self.table) self.table = BigQueryTable(name=f"{self.table_name}__{int(time.time())}", **opts) self.table.create_table( self.client, self.apply_transforms, **{ "table": { "expires": datetime.datetime.now() + datetime.timedelta(days=1), }, "dataset": { "location": self.config.get( "location", BigQueryTable.default_dataset_options()["location"] ) }, }, ) time.sleep(2.5) # Wait for eventual consistency elif self._is_overwrite_candidate(): self.overwrite_target = copy(self.table) self.table = BigQueryTable(name=f"{self.table_name}__{int(time.time())}", **opts) self.table.create_table( self.client, self.apply_transforms, **{ "table": { "expires": datetime.datetime.now() + datetime.timedelta(days=1), }, "dataset": { "location": self.config.get( "location", BigQueryTable.default_dataset_options()["location"] ) }, }, ) time.sleep(2.5) # Wait for eventual consistency self.global_par_typ = target.par_typ self.global_queue = target.queue self.increment_jobs_enqueued = target.increment_jobs_enqueued def _is_upsert_candidate(self) -> bool: """Determine if this stream is an upsert candidate based on user configuration.""" upsert_selection = self.config.get("upsert", False) upsert_candidate = False if isinstance(upsert_selection, list): selection: str for selection in upsert_selection: invert = selection.startswith("!") if invert: selection = selection[1:] if fnmatch(self.stream_name, selection): upsert_candidate = True ^ invert elif upsert_selection: upsert_candidate = True return upsert_candidate def _is_overwrite_candidate(self) -> bool: """Determine if this stream is an overwrite candidate based on user configuration.""" overwrite_selection = self.config.get("overwrite", False) overwrite_candidate = False if isinstance(overwrite_selection, list): selection: str for selection in overwrite_selection: invert = selection.startswith("!") if invert: selection = selection[1:] if fnmatch(self.stream_name, selection): overwrite_candidate = True ^ invert elif overwrite_selection: overwrite_candidate = True return overwrite_candidate def _is_dedupe_before_upsert_candidate(self) -> bool: """Determine if this stream is a dedupe before upsert candidate based on user configuration.""" # TODO: we can enable this for `overwrite` too if we want but the purpose would # be less for functional reasons (merge constraints) and more for convenience dedupe_before_upsert_selection = self.config.get("dedupe_before_upsert", False) dedupe_before_upsert_candidate = False if isinstance(dedupe_before_upsert_selection, list): selection: str for selection in dedupe_before_upsert_selection: invert = selection.startswith("!") if invert: selection = selection[1:] if fnmatch(self.stream_name, selection): dedupe_before_upsert_candidate = True ^ invert elif dedupe_before_upsert_selection: dedupe_before_upsert_candidate = True return dedupe_before_upsert_candidate @property def table_name(self) -> str: """Returns the table name.""" return self.stream_name.lower().replace("-", "_").replace(".", "_") @property def max_size(self) -> int: """Maximum size of a batch.""" return self.config.get("batch_size", 10_000) @property def apply_transforms(self) -> bool: """Whether to apply column name transforms.""" return self.ingestion_strategy is not IngestionStrategy.FIXED @property def generate_view(self) -> bool: """Whether to generate a view on top of the table.""" return self.ingestion_strategy is IngestionStrategy.FIXED and self.config.get( "generate_view", False ) def _validate_and_parse(self, record: dict) -> dict: return record def preprocess_record(self, record: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]: """Preprocess a record before writing it to the sink.""" metadata = { k: record.pop(k, None) for k in ( "_sdc_extracted_at", "_sdc_received_at", "_sdc_batched_at", "_sdc_deleted_at", "_sdc_sequence", "_sdc_table_version", ) } return {"data": record, **metadata} @retry( retry=retry_if_exception_type(ConnectionError), stop=stop_after_attempt(3), wait=wait_fixed(1), reraise=True, ) def create_target(self, key_properties: Optional[List[str]] = None) -> None: """Create the table in BigQuery.""" kwargs = {"table": {}, "dataset": {}} # Table opts if key_properties and self.config.get("cluster_on_key_properties", False): kwargs["table"]["clustering_fields"] = key_properties[:4] partition_grain: str = self.config.get("partition_granularity") if partition_grain: kwargs["table"]["time_partitioning"] = TimePartitioning( type_=PARTITION_STRATEGY[partition_grain.upper()], field="_sdc_batched_at", ) # Dataset opts location: str = self.config.get( "location", BigQueryTable.default_dataset_options()["location"] ) kwargs["dataset"]["location"] = location # Create the table self.table.create_table(self.client, self.apply_transforms, **kwargs) if self.generate_view: self.client.query( self.table.schema_translator.generate_view_statement( self.table, ) ).result() def update_schema(self) -> None: """Update the target schema in BigQuery.""" pass def pre_state_hook(self) -> None: """Called before state is emitted to stdout.""" pass @staticmethod @abstractmethod def worker_cls_factory( worker_executor_cls: Type["Process"], config: Dict[str, Any] ) -> Union[Type[BaseWorker], Type["Process"]]: """Return a worker class for the given parallelization type.""" raise NotImplementedError def clean_up(self) -> None: """Clean up the target table.""" if self.merge_target is not None: # We must merge the temp table into the target table. target = self.merge_target.as_table() date_columns = ["_sdc_extracted_at", "_sdc_received_at"] tmp, ctas_tmp = None, "SELECT 1 AS _no_op" if self._is_dedupe_before_upsert_candidate(): # We can't use MERGE with a non-unique key, so we need to dedupe the temp table into # a _SESSION scoped intermediate table. tmp = f"{self.merge_target.name}__tmp" dedupe_query = ( f"SELECT * FROM {self.table.get_escaped_name()} " f"QUALIFY ROW_NUMBER() OVER (PARTITION BY {', '.join(self.key_properties)} " f"ORDER BY COALESCE({', '.join(date_columns)}) DESC) = 1" ) ctas_tmp = f"CREATE OR REPLACE TEMP TABLE `{tmp}` AS {dedupe_query}" merge_clause = ( f"MERGE `{self.merge_target}` AS target USING `{tmp or self.table}` AS source ON " + " AND ".join(f"target.`{f}` = source.`{f}`" for f in self.key_properties) ) update_clause = "UPDATE SET " + ", ".join( f"target.`{f.name}` = source.`{f.name}`" for f in target.schema ) insert_clause = ( f"INSERT ({', '.join(f'`{f.name}`' for f in target.schema)}) " f"VALUES ({', '.join(f'source.`{f.name}`' for f in target.schema)})" ) self.client.query( f"{ctas_tmp}; {merge_clause} " f"WHEN MATCHED THEN {update_clause} " f"WHEN NOT MATCHED THEN {insert_clause}; " f"DROP TABLE IF EXISTS {self.table.get_escaped_name()};" ).result() self.table = self.merge_target self.merge_target = None elif self.overwrite_target is not None: # We must overwrite the target table with the temp table. # Do it in a transaction to avoid partial writes. target = self.overwrite_target.as_table() self.client.query( f"DROP TABLE IF EXISTS {self.overwrite_target.get_escaped_name()}; CREATE TABLE" f" {self.overwrite_target.get_escaped_name()} AS SELECT * FROM" f" {self.table.get_escaped_name()}; DROP TABLE IF EXISTS" f" {self.table.get_escaped_name()};" ).result() self.table = self.merge_target self.merge_target = None class Denormalized: """This class provides common overrides for denormalized sinks and should be subclassed with an existing sink with higher MRO: DenormalizedSink(Denormalized, ExistingSink).""" ingestion_strategy = IngestionStrategy.DENORMALIZED @retry( retry=retry_if_exception_type(ConnectionError), stop=stop_after_attempt(3), wait=wait_fixed(1), reraise=True, ) def update_schema(self: BaseBigQuerySink) -> None: """Update the target schema.""" table = self.table.as_table() current_schema = table.schema[:] mut_schema = table.schema[:] for expected_field in self.table.get_resolved_schema(self.apply_transforms): if not any(field.name == expected_field.name for field in current_schema): mut_schema.append(expected_field) if len(mut_schema) > len(current_schema): table.schema = mut_schema self.client.update_table( table, ["schema"], retry=bigquery.DEFAULT_RETRY.with_timeout(15), ) def preprocess_record( self: BaseBigQuerySink, record: Dict[str, Any], context: Dict[str, Any] ) -> Dict[str, Any]: """Preprocess a record before writing it to the sink.""" return self.table.schema_translator.translate_record(record) @contextmanager def augmented_syspath(new_paths: Optional[Iterable[str]] = None): """Context manager to temporarily add paths to sys.path.""" original_sys_path = sys.path if new_paths is not None: sys.path = list(new_paths) + sys.path try: yield finally: sys.path = original_sys_path @cache def bigquery_client_factory(creds: BigQueryCredentials) -> bigquery.Client: """Get a BigQuery client.""" if creds.path: return bigquery.Client.from_service_account_json(creds.path, project=creds.project ) elif creds.json: return bigquery.Client.from_service_account_info( json.loads(creds.json), project=creds.project ) return bigquery.Client(project=creds.project) @cache def gcs_client_factory(creds: BigQueryCredentials) -> storage.Client: """Get a GCS client.""" if creds.path: return storage.Client.from_service_account_json(creds.path, project=creds.project) elif creds.json: return storage.Client.from_service_account_info( json.loads(creds.json), project=creds.project ) return storage.Client(project=creds.project) @cache def storage_client_factory( creds: BigQueryCredentials, ) -> bigquery_storage_v1.BigQueryWriteClient: """Get a BigQuery Storage Write client.""" if creds.path: return bigquery_storage_v1.BigQueryWriteClient.from_service_account_file(creds.path) elif creds.json: return bigquery_storage_v1.BigQueryWriteClient.from_service_account_info( json.loads(creds.json) ) return bigquery_storage_v1.BigQueryWriteClient() @dataclass class _FieldProjection: projection: str alias: str def as_sql(self) -> str: """Return the SQL representation of this projection""" return f'{self.projection} as {self.alias.lstrip()},\n' # This class translates a JSON schema into a BigQuery schema. # It also uses the translated schema to generate a CREATE VIEW statement. class SchemaTranslator: """Translate a JSON schema into a BigQuery schema.""" def __init__( self, schema: Dict[str, Any], transforms: Dict[str, bool], resolver_version: SchemaResolverVersion = SchemaResolverVersion.V1, ) -> None: self.schema = schema self.transforms = transforms self.resolver_version = resolver_version # Used by fixed schema strategy where we defer transformation # to the view statement self._translated_schema = None # Used by the denormalized strategy where we eagerly transform # the target schema self._translated_schema_transformed = None @property def translated_schema(self) -> List[SchemaField]: """Translate the schema into a BigQuery schema.""" if not self._translated_schema: self._translated_schema = [ self._jsonschema_property_to_bigquery_column(name, contents) for name, contents in self.schema.get("properties", {}).items() ] return self._translated_schema @property def translated_schema_transformed(self) -> List[SchemaField]: """Translate the schema into a BigQuery schema using the SchemaTranslator `transforms`.""" if not self._translated_schema_transformed: self._translated_schema_transformed = [ self._jsonschema_property_to_bigquery_column( transform_column_name(name, **self.transforms), contents ) for name, contents in self.schema.get("properties", {}).items() ] return self._translated_schema_transformed def translate_record(self, record: dict) -> dict: """Translate a record using the SchemaTranslator `transforms`.""" if not self.transforms: return record output = dict( [ (transform_column_name(k, **{**self.transforms, "quote": False}), v) for k, v in record.items() ] ) for k, v in output.items(): if isinstance(v, list): for i, inner in enumerate(v): if isinstance(inner, dict): output[k][i] = self.translate_record(inner) if isinstance(v, dict): output[k] = self.translate_record(v) return output def generate_view_statement(self, table_name: BigQueryTable) -> str: """Generate a CREATE VIEW statement for the SchemaTranslator `schema`.""" projection = "" for field_ in self.translated_schema[:]: if field_.mode == "REPEATED": projection += indent(self._wrap_json_array(field_, path="$", depth=1), " " * 4) else: projection += indent(self._bigquery_field_to_projection(field_).as_sql(), " " * 4) return ( f"CREATE OR REPLACE VIEW {table_name.get_escaped_name('_view')} AS \nSELECT \n{projection} FROM {table_name.get_escaped_name()}" ) def _jsonschema_property_to_bigquery_column( self, name: str, schema_property: dict ) -> SchemaField: """Translate a JSON schema property into a BigQuery column. The v1 resolver is very similar to how existing target-bigquery implementations worked. The v2 resolver uses JSON in all cases the schema property is unresolvable making it _much_ more flexible though the denormalization can only be said to be partial if a type is not resolved. Most of the time this is fine but for the sake of consistency, we default to v1. """ if self.resolver_version == SchemaResolverVersion.V1: # This is the original resolver, which is used by the denormalized strategy if "anyOf" in schema_property and len(schema_property["anyOf"]) > 0: # I have only seen this used in the wild with tap-salesforce, which # is incidentally an important one so lets handle the anyOf case # by giving the 0th index priority. property_type = schema_property["anyOf"][0].get("type", "string") property_format = schema_property["anyOf"][0].get("format", None) else: property_type = schema_property.get("type", "string") property_format = schema_property.get("format", None) if "array" in property_type: if "items" not in schema_property: return SchemaField(name, "JSON", "REPEATED") items_schema: dict = schema_property["items"] items_type = bigquery_type(items_schema["type"], items_schema.get("format", None)) if items_type == "record": return self._translate_record_to_bigquery_schema(name, items_schema, "REPEATED") return SchemaField(name, items_type, "REPEATED") elif "object" in property_type: return self._translate_record_to_bigquery_schema(name, schema_property) else: result_type = bigquery_type(property_type, property_format) return SchemaField(name, result_type, "NULLABLE") elif self.resolver_version == SchemaResolverVersion.V2: # This is the new resolver, which is far more lenient and falls back to JSON # if it doesn't know how to translate a property. try: if "anyOf" in schema_property and len(schema_property["anyOf"]) > 0: # I have only seen this used in the wild with tap-salesforce, which # is incidentally an important one so lets handle the anyOf case # by giving the 0th index priority. property_type = schema_property["anyOf"][0].get("type", "string") property_format = schema_property["anyOf"][0].get("format", None) else: property_type = schema_property["type"] property_format = schema_property.get("format", None) if "array" in property_type: if "items" not in schema_property or "type" not in schema_property["items"]: return SchemaField(name, "JSON", "REPEATED") items_schema: dict = schema_property["items"] if "patternProperties" in items_schema: return SchemaField(name, "JSON", "REPEATED") items_type = bigquery_type(items_schema["type"], items_schema.get("format", None)) if items_type == "record": return self._translate_record_to_bigquery_schema(name, items_schema, "REPEATED") return SchemaField(name, items_type, "REPEATED") elif "object" in property_type: if "properties" not in schema_property or len(schema_property["properties"]) == 0 or "patternProperties" in schema_property: return SchemaField(name, "JSON", "NULLABLE") return self._translate_record_to_bigquery_schema(name, schema_property) else: if "patternProperties" in schema_property: return SchemaField(name, "JSON", "NULLABLE") result_type = bigquery_type(property_type, property_format) return SchemaField(name, result_type, "NULLABLE") except Exception: return SchemaField(name, "JSON", "NULLABLE") def _translate_record_to_bigquery_schema( self, name: str, schema_property: dict, mode: str = "NULLABLE" ) -> SchemaField: """Translate a JSON schema record into a BigQuery schema.""" fields = [ self._jsonschema_property_to_bigquery_column(col, t) for col, t in schema_property.get("properties", {}).items() ] return SchemaField(name, "RECORD", mode, fields=fields) def _bigquery_field_to_projection( self, field: SchemaField, path: str = "$", depth: int = 0, base: str = "data" ) -> _FieldProjection: """Translate a BigQuery schema field into a SQL projection.""" # Pass-through _sdc columns into the projection as-is if field.name.startswith("_sdc_"): return _FieldProjection(field.name, field.name) scalar = f"{base}.{field.name}" from_base = f"{path}.{field.name}" if base == "data" else "$" # Records are handled recursively if field.field_type.upper() == "RECORD": return _FieldProjection( (" " * depth * 2) + "STRUCT(\n{}\n".format( "".join( [ ( self._bigquery_field_to_projection( f, path=from_base, depth=depth + 1, base=base ).as_sql() if not f.mode == "REPEATED" else self._wrap_json_array( f, path=from_base, depth=depth, base=base ) ) for f in field.fields ] ).rstrip(",\n"), ) + (" " * depth * 2) + ")", f"{transform_column_name(field.name, **self.transforms)}" ) # Nullable fields require a JSON_VALUE call which creates a 2-stage cast elif field.is_nullable: _field = self._wrap_nullable_json_value(field, path=path, base=base) return _FieldProjection((" " * depth * 2) + _field.projection, _field.alias) # These are not nullable so if the type is known, we can do a 1-stage extract & cast elif field.field_type.upper() == "STRING": return _FieldProjection(( " " * depth * 2 ) + f"STRING({scalar})", f"{transform_column_name(field.name, **self.transforms)}") elif field.field_type.upper() == "INTEGER": return _FieldProjection(( " " * depth * 2 ) + f"INT64({scalar})", f"{transform_column_name(field.name, **self.transforms)}") elif field.field_type.upper() == "FLOAT": return _FieldProjection( (" " * depth * 2) + f"FLOAT64({scalar})", f"{transform_column_name(field.name, **self.transforms)}" ) elif field.field_type.upper() == "BOOLEAN": return _FieldProjection(( " " * depth * 2 ) + f"BOOL({scalar})", f"{transform_column_name(field.name, **self.transforms)}") # Fallback to a 2-stage extract & cast else: _field = self._wrap_nullable_json_value(field, path, base) return _FieldProjection((" " * depth * 2) + _field.projection, _field.alias) def _wrap_json_array( self, field: SchemaField, path: str, depth: int = 0, base: str = "data" ) -> str: """Translate a BigQuery schema field into a SQL projection for a repeated field.""" _v = self._bigquery_field_to_projection( field, path="$", depth=depth, base=f"{field.name}__rows" ) v = _v.as_sql().rstrip(", \n") return (" " * depth * 2) + indent( dedent( f""" ARRAY( SELECT {v} FROM UNNEST( JSON_QUERY_ARRAY({base}, '{path}.{field.name}') ) AS {field.name}__rows WHERE {_v.projection} IS NOT NULL """ + (" " * depth * 2) + f") AS {field.name},\n" ).lstrip(), " " * depth * 2, ) def _wrap_nullable_json_value( self, field: SchemaField, path: str = "$", base: str = "data" ) -> _FieldProjection: """Translate a BigQuery schema field into a SQL projection for a nullable field.""" typ = field.field_type.upper() if typ == "STRING": return _FieldProjection( f"JSON_VALUE({base}, '{path}.{field.name}')", f" {transform_column_name(field.name, **self.transforms)}" ) if typ == "FLOAT": typ = "FLOAT64" if typ in ("INT", "INTEGER"): typ = "INT64" return _FieldProjection( f"CAST(JSON_VALUE({base}, '{path}.{field.name}') as {typ})", f" {transform_column_name(field.name, **self.transforms)}" ) class Compressor: """Compresses streams of bytes using gzip.""" def __init__(self) -> None: """Initialize the compressor.""" self._compressor = None self._closed = False if shutil.which("gzip") is not None: self._buffer = TemporaryFile() self._compressor = Popen(["gzip", "-"], stdin=PIPE, stdout=self._buffer) if self._compressor.stdin is None: raise RuntimeError("gzip stdin is None") self._gzip = self._compressor.stdin else: self._buffer = BytesIO() self._gzip = gzip.GzipFile(fileobj=self._buffer, mode="wb") def write(self, data: bytes) -> None: """Write data to the compressor.""" if self._closed: raise ValueError("I/O operation on closed compressor.") self._gzip.write(data) def flush(self) -> None: """Flush the compressor buffer.""" self._gzip.flush() self._buffer.flush() def close(self) -> None: """Close the compressor and wait for the gzip process to finish.""" if self._closed: return self._gzip.close() if self._compressor is not None: self._compressor.wait() self._buffer.flush() self._buffer.seek(0) self._closed = True def getvalue(self) -> bytes: """Return the compressed buffer as a bytes object.""" if not self._closed: self.close() if self._compressor is not None: return self._buffer.read() return self._buffer.getvalue() def getbuffer(self) -> Union[memoryview, mmap.mmap]: """Return the compressed buffer as a memoryview or mmap.""" if not self._closed: self.close() if self._compressor is not None: return mmap.mmap(self._buffer.fileno(), 0, access=mmap.ACCESS_READ) return self._buffer.getbuffer() @property def buffer(self) -> IO[bytes]: """Return the compressed buffer as a file-like object.""" return self._buffer def __del__(self) -> None: """Close the compressor and wait for the gzip process to finish. Dereference the buffer.""" if not self._closed: self.close() # close the buffer, ignore error if we have an incremented rc due to memoryview # the gc will take care of the rest when the worker dereferences the buffer try: self._buffer.close() except BufferError: pass if self._compressor is not None and self._compressor.poll() is None: self._compressor.kill() self._compressor.wait() # dereference self._buffer = None # pylint: disable=no-else-return,too-many-branches,too-many-return-statements def bigquery_type(property_type: List[str], property_format: Optional[str] = None) -> str: """Convert a JSON Schema type to a BigQuery type.""" if property_format == "date-time": return "timestamp" if property_format == "date": return "date" elif property_format == "time": return "time" elif "number" in property_type: return "float" elif "integer" in property_type and "string" in property_type: return "string" elif "integer" in property_type: return "integer" elif "boolean" in property_type: return "boolean" elif "object" in property_type: return "record" else: return "string" # Column name transforms are configurable and entirely opt-in. # This allows users to only use the transforms they need and not # become dependent on inconfigurable transforms outside their # realm of control which must be recreated if migrating loaders. @cache def transform_column_name( name: str, quote: bool = False, lower: bool = False, add_underscore_when_invalid: bool = False, snake_case: bool = False, ) -> str: """Transform a column name to a valid BigQuery column name.""" if snake_case and not lower: lower = True was_quoted = name.startswith("`") and name.endswith("`") name = name.strip("`") if snake_case: name = re.sub("((?!^)(?<!_)[A-Z][a-z]+|(?<=[a-z0-9])[A-Z])", r"_\1", name) if lower: name = "{}".format(name).lower() if add_underscore_when_invalid: if name[0].isdigit(): name = "_{}".format(name) if quote or was_quoted: name = "`{}`".format(name) return name
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/core.py
core.py
import hashlib import os from typing import Any, Dict, List, Optional, Type, cast import proto from google.cloud.bigquery import SchemaField from google.protobuf import descriptor_pb2, message_factory MAP = { # Limited scope of types as these are the only primitive types we can infer # from the JSON schema which incidentally simplifies the implementation "FLOAT": descriptor_pb2.FieldDescriptorProto.TYPE_DOUBLE, "INTEGER": descriptor_pb2.FieldDescriptorProto.TYPE_INT64, "BOOLEAN": descriptor_pb2.FieldDescriptorProto.TYPE_BOOL, "STRING": descriptor_pb2.FieldDescriptorProto.TYPE_STRING, # On ingestion, JSON is expected to be a string "JSON": descriptor_pb2.FieldDescriptorProto.TYPE_STRING, # BigQuery coerces these to the correct format on ingestion "TIMESTAMP": descriptor_pb2.FieldDescriptorProto.TYPE_STRING, "DATE": descriptor_pb2.FieldDescriptorProto.TYPE_STRING, "TIME": descriptor_pb2.FieldDescriptorProto.TYPE_STRING, } def generate_field_v2(base: SchemaField, i: int = 1, pool: Optional[Any] = None) -> Dict[str, Any]: """Generate proto2 field properties from a SchemaField.""" name: str = base.name typ: str = cast(str, base.field_type).upper() if base.mode == "REPEATED": label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED else: label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL if typ.upper() == "RECORD": proto_cls = proto_schema_factory_v2(base.fields, pool) props = dict( name=name, number=i, label=label, type=descriptor_pb2.FieldDescriptorProto.TYPE_MESSAGE, type_name=proto_cls.DESCRIPTOR.full_name, json_name=name, ) else: props = dict( name=name, number=i, label=label, type=MAP[typ], json_name=name, ) return props def proto_schema_factory_v2( bigquery_schema: List[SchemaField], pool: Optional[Any] = None ) -> Type[proto.Message]: """Generate a proto2 Message from a BigQuery schema.""" fhash = hashlib.sha1() for f in bigquery_schema: fhash.update(hash(f).to_bytes(8, "big", signed=True)) fname = f"AnonymousProto_{fhash.hexdigest()}.proto" clsname = f"net.proto2.python.public.target_bigquery.AnonymousProto_{fhash.hexdigest()}" factory = message_factory.MessageFactory(pool=pool) try: proto_descriptor = factory.pool.FindMessageTypeByName(clsname) proto_cls = factory.GetPrototype(proto_descriptor) except KeyError: package, name = clsname.rsplit(".", 1) file_proto = descriptor_pb2.FileDescriptorProto() file_proto.name = os.path.join(package.replace(".", "/"), fname) file_proto.package = package desc_proto = file_proto.message_type.add() desc_proto.name = name for i, f in enumerate(bigquery_schema): field_proto = desc_proto.field.add() for k, v in generate_field_v2(f, i + 1, factory.pool).items(): setattr(field_proto, k, v) factory.pool.Add(file_proto) proto_descriptor = factory.pool.FindMessageTypeByName(clsname) proto_cls = factory.GetPrototype(proto_descriptor) return proto_cls def generate_field(base: SchemaField, i: int = 1) -> proto.Field: """Not intended for production use. Generate a proto.Field from a SchemaField.""" kwargs = {} name: str = base.name typ: str = cast(str, base.field_type).upper() if base.mode == "REPEATED": cls = proto.RepeatedField else: cls = proto.Field if typ.upper() == "RECORD": f = cls( proto_type=proto.MESSAGE, message=proto_schema_factory(base.fields), number=i, **kwargs, ) else: f = cls(proto_type=MAP[typ], number=i, **kwargs) return (f, name) def proto_schema_factory(bigquery_schema: List[SchemaField]) -> Type[proto.Message]: """Not intended for production use. Generate a proto.Message from a BigQuery schema.""" return type( f"Schema{abs(hash((f for f in bigquery_schema)))}", (proto.Message,), { name: f for f, name in (generate_field(field, i + 1) for i, field in enumerate(bigquery_schema)) }, )
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/proto_gen.py
proto_gen.py
import os from io import BytesIO from multiprocessing import Process from multiprocessing.dummy import Process as _Thread from queue import Empty from typing import Any, Dict, NamedTuple, Optional, Type, Union import orjson from google.cloud import bigquery from target_bigquery.core import ( BaseBigQuerySink, BaseWorker, Compressor, Denormalized, ParType, bigquery_client_factory, ) class Job(NamedTuple): table: str data: Union[bytes, memoryview] config: Dict[str, Any] attempt: int = 1 class BatchJobWorker(BaseWorker): """Worker that loads data into BigQuery via LoadJobs.""" def run(self) -> None: """Run the worker.""" client: bigquery.Client = bigquery_client_factory(self.credentials) while True: try: job: Optional[Job] = self.queue.get(timeout=30.0) except Empty: break if job is None: break try: client.load_table_from_file( BytesIO(job.data), job.table, num_retries=3, job_config=bigquery.LoadJobConfig(**job.config), ).result() except Exception as exc: job.attempt += 1 if job.attempt > 3: # TODO: add a metric for this + a DLQ & wrap exception type self.error_notifier.send((exc, self.serialize_exception(exc))) raise else: self.queue.put(job) else: self.job_notifier.send(True) self.log_notifier.send( f"[{self.ext_id}] Loaded {len(job.data)} bytes into {job.table}." ) finally: self.queue.task_done() class BatchJobThreadWorker(BatchJobWorker, _Thread): pass class BatchJobProcessWorker(BatchJobWorker, Process): pass class BigQueryBatchJobSink(BaseBigQuerySink): MAX_WORKERS = os.cpu_count() * 2 WORKER_CAPACITY_FACTOR = 1 WORKER_CREATION_MIN_INTERVAL = 10.0 @property def job_config(self) -> Dict[str, Any]: return { "schema": self.table.get_resolved_schema(), "source_format": bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, "write_disposition": bigquery.WriteDisposition.WRITE_APPEND, } def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.buffer = Compressor() @staticmethod def worker_cls_factory( worker_executor_cls: Type[Process], config: Dict[str, Any] ) -> Type[Union[BatchJobThreadWorker, BatchJobProcessWorker]]: Worker = type("Worker", (BatchJobWorker, worker_executor_cls), {}) return Worker def process_record(self, record: Dict[str, Any], context: Dict[str, Any]) -> None: self.buffer.write(orjson.dumps(record, option=orjson.OPT_APPEND_NEWLINE)) def process_batch(self, context: Dict[str, Any]) -> None: self.buffer.close() self.global_queue.put( Job( data=( self.buffer.getvalue() if self.global_par_typ is ParType.PROCESS else self.buffer.getbuffer() ), table=self.table.as_ref(), config=self.job_config, ), ) self.increment_jobs_enqueued() self.buffer = Compressor() class BigQueryBatchJobDenormalizedSink(Denormalized, BigQueryBatchJobSink): @property def job_config(self) -> Dict[str, Any]: return { "schema": self.table.get_resolved_schema(), "source_format": bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, "write_disposition": bigquery.WriteDisposition.WRITE_APPEND, "schema_update_options": [ bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION, ], "ignore_unknown_values": True, } # Defer schema evolution the the write disposition def evolve_schema(self: BaseBigQuerySink) -> None: pass
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/batch_job.py
batch_job.py
import os from time import sleep from multiprocessing import Process from multiprocessing.connection import Connection from multiprocessing.dummy import Process as _Thread from queue import Empty from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Type, Union, cast, ) import orjson from google.cloud.bigquery_storage_v1 import BigQueryWriteClient, types, writer from google.protobuf import json_format from proto import Message from tenacity import retry, stop_after_attempt, wait_fixed if TYPE_CHECKING: from target_bigquery.target import TargetBigQuery import logging from target_bigquery.core import BaseBigQuerySink, BaseWorker, Denormalized, storage_client_factory from target_bigquery.proto_gen import proto_schema_factory_v2 logger = logging.getLogger(__name__) # Stream specific constant MAX_IN_FLIGHT = 15 """Maximum number of concurrent requests per worker be processed by grpc before awaiting.""" Dispatcher = Callable[[types.AppendRowsRequest], writer.AppendRowsFuture] StreamComponents = Tuple[str, writer.AppendRowsStream, Dispatcher] def get_application_stream(client: BigQueryWriteClient, job: "Job") -> StreamComponents: """Get an application created stream for the parent. This stream must be finalized and committed.""" write_stream = types.WriteStream() write_stream.type_ = types.WriteStream.Type.PENDING write_stream = client.create_write_stream(parent=job.parent, write_stream=write_stream) job.template.write_stream = write_stream.name append_rows_stream = writer.AppendRowsStream(client, job.template) rv = (write_stream.name, append_rows_stream) job.stream_notifier.send(rv) return *rv, retry( append_rows_stream.send, wait=wait_fixed(2), stop=stop_after_attempt(5), reraise=True, ) def get_default_stream(client: BigQueryWriteClient, job: "Job") -> StreamComponents: """Get the default storage write API stream for the parent.""" job.template.write_stream = BigQueryWriteClient.write_stream_path( **BigQueryWriteClient.parse_table_path(job.parent), stream="_default" ) append_rows_stream = writer.AppendRowsStream(client, job.template) rv = (job.template.write_stream, append_rows_stream) job.stream_notifier.send(rv) return *rv, retry( append_rows_stream.send, wait=wait_fixed(2), stop=stop_after_attempt(5), reraise=True, ) def generate_request( payload: types.ProtoRows, offset: Optional[int] = None, path: Optional[str] = None, ) -> types.AppendRowsRequest: """Generate a request for the storage write API from a payload.""" request = types.AppendRowsRequest() if offset is not None: request.offset = int(offset) if path is not None: request.write_stream = path proto_data = types.AppendRowsRequest.ProtoData() proto_data.rows = payload request.proto_rows = proto_data return request def generate_template(message: Type[Message]): """Generate a template for the storage write API from a proto message class.""" from google.protobuf import descriptor_pb2 template, proto_schema, proto_descriptor, proto_data = ( types.AppendRowsRequest(), types.ProtoSchema(), descriptor_pb2.DescriptorProto(), types.AppendRowsRequest.ProtoData(), ) message.DESCRIPTOR.CopyToProto(proto_descriptor) proto_schema.proto_descriptor = proto_descriptor proto_data.writer_schema = proto_schema template.proto_rows = proto_data return template class Job(): parent: str template: types.AppendRowsRequest stream_notifier: Connection data: types.ProtoRows attempts: int = 1 def __init__(self, parent, template, stream_notifier, data): """Initialize the worker process.""" self.parent = parent self.template = template self.stream_notifier = stream_notifier self.data = data class StorageWriteBatchWorker(BaseWorker): """Worker process for the storage write API.""" def __init__(self, *args, **kwargs): """Initialize the worker process.""" super().__init__(*args, **kwargs) self.get_stream_components = get_application_stream self.awaiting: List[writer.AppendRowsFuture] = [] self.cache: Dict[str, StreamComponents] = {} self.max_errors_before_recycle = 5 self.offsets: Dict[str, int] = {} self.logger=logger def run(self): """Run the worker process.""" client: BigQueryWriteClient = storage_client_factory(self.credentials) if os.getenv("TARGET_BIGQUERY_DEBUG", "false").lower() == "true": bidi_logger = logging.getLogger("google.api_core.bidi") bidi_logger.setLevel(logging.DEBUG) while True: try: job: Optional[Job] = self.queue.get(timeout=30.0) except Empty: break if job is None: break if job.parent not in self.cache or self.cache[job.parent][1]._closed: self.cache[job.parent] = self.get_stream_components(client, job) self.offsets[job.parent] = 0 write_stream, _, dispatch = cast(StreamComponents, self.cache[job.parent]) try: kwargs = {} if write_stream.endswith("_default"): kwargs["offset"] = None kwargs["path"] = write_stream else: kwargs["offset"] = self.offsets[job.parent] self.awaiting.append(dispatch(generate_request(job.data, **kwargs))) except Exception as exc: job.attempts += 1 self.logger.info(f"job.attempts : {job.attempts}") self.max_errors_before_recycle -= 1 if job.attempts > 3: # TODO: add a metric for this + a DLQ & wrap exception type self.error_notifier.send((exc, self.serialize_exception(exc))) else: self.queue.put(job) # Track errors and recycle the stream if we hit a threshold # 1 bad payload 👆 is not indicative of a bad bidi stream as it _could_ # be a transient error or luck of the draw with the first payload. # 5 worker-specific errors is a good threshold to recycle the stream # and start fresh. This is an arbitrary number and can be adjusted. if self.max_errors_before_recycle == 0: self.wait(drain=True) self.close_cached_streams() raise else: self.log_notifier.send( f"[{self.ext_id}] Sent {len(job.data.serialized_rows)} rows to {write_stream}" f" with offset {self.offsets[job.parent]}." ) self.offsets[job.parent] += len(job.data.serialized_rows) if len(self.awaiting) > MAX_IN_FLIGHT: self.wait() finally: self.queue.task_done() # Wait for all in-flight requests to complete after poison pill self.logger.info(f"[{self.ext_id}] : {self.offsets}") self.wait(drain=True) self.close_cached_streams() self.logger.info("Worker process exiting.") self.log_notifier.send("Worker process exiting.") def close_cached_streams(self) -> None: """Close all cached streams.""" for _, stream, _ in self.cache.values(): try: stream.close() except Exception as exc: self.error_notifier.send((exc, self.serialize_exception(exc))) def wait(self, drain: bool = False) -> None: """Wait for in-flight requests to complete.""" while self.awaiting and ((len(self.awaiting) > MAX_IN_FLIGHT // 2) or drain): try: self.awaiting.pop(0).result() except Exception as exc: self.error_notifier.send((exc, self.serialize_exception(exc))) finally: self.job_notifier.send(True) class StorageWriteStreamWorker(StorageWriteBatchWorker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.get_stream_components = get_default_stream class StorageWriteThreadStreamWorker(StorageWriteStreamWorker, _Thread): pass class StorageWriteProcessStreamWorker(StorageWriteStreamWorker, Process): pass class StorageWriteThreadBatchWorker(StorageWriteBatchWorker, _Thread): pass class StorageWriteProcessBatchWorker(StorageWriteBatchWorker, Process): pass class BigQueryStorageWriteSink(BaseBigQuerySink): MAX_WORKERS = os.cpu_count() * 2 MAX_JOBS_QUEUED = MAX_WORKERS * 2 WORKER_CAPACITY_FACTOR = 10 WORKER_CREATION_MIN_INTERVAL = 1.0 @staticmethod def worker_cls_factory( worker_executor_cls: Type[Process], config: Dict[str, Any] ) -> Type[ Union[ StorageWriteThreadStreamWorker, StorageWriteProcessStreamWorker, StorageWriteThreadBatchWorker, StorageWriteProcessBatchWorker, ] ]: if config.get("options", {}).get("storage_write_batch_mode", False): Worker = type("Worker", (StorageWriteBatchWorker, worker_executor_cls), {}) else: Worker = type("Worker", (StorageWriteStreamWorker, worker_executor_cls), {}) return Worker def __init__( self, target: "TargetBigQuery", stream_name: str, schema: Dict[str, Any], key_properties: Optional[List[str]], ) -> None: super().__init__(target, stream_name, schema, key_properties) self.open_streams: Set[Tuple[str, writer.AppendRowsStream]] = set() self.parent = BigQueryWriteClient.table_path( self.table.project, self.table.dataset, self.table.name, ) self.stream_notification, self.stream_notifier = target.pipe_cls(False) self.template = generate_template(self.proto_schema) @property def proto_schema(self) -> Type[Message]: if not hasattr(self, "_proto_schema"): self._proto_schema = proto_schema_factory_v2( self.table.get_resolved_schema(self.apply_transforms) ) return self._proto_schema def start_batch(self, context: Dict[str, Any]) -> None: self.proto_rows = types.ProtoRows() def preprocess_record(self, record: dict, context: dict) -> dict: record = super().preprocess_record(record, context) record["data"] = orjson.dumps(record["data"]).decode("utf-8") return record def process_record(self, record: Dict[str, Any], context: Dict[str, Any]) -> None: self.proto_rows.serialized_rows.append( json_format.ParseDict(record, self.proto_schema()).SerializeToString() ) def process_batch(self, context: Dict[str, Any]) -> None: while self.global_queue.qsize() >= self.MAX_JOBS_QUEUED: self.logger.warn(f"Max jobs enqueued reached ({self.MAX_JOBS_QUEUED})") sleep(1) self.global_queue.put( Job( parent=self.parent, template=self.template, data=self.proto_rows, stream_notifier=self.stream_notifier, ) ) self.increment_jobs_enqueued() def commit_streams(self) -> None: while self.stream_notification.poll(): stream_payload = self.stream_notification.recv() self.logger.debug("Stream enqueued %s", stream_payload) self.open_streams.add(stream_payload) if not self.open_streams: return self.open_streams = [ (name, stream) for name, stream in self.open_streams if not name.endswith("_default") ] if self.open_streams: committer = storage_client_factory(self._credentials) for name, stream in self.open_streams: stream.close() committer.finalize_write_stream(name=name) write = committer.batch_commit_write_streams( types.BatchCommitWriteStreamsRequest( parent=self.parent, write_streams=[name for name, _ in self.open_streams], ) ) self.logger.info(f"Batch commit time: {write.commit_time}") self.logger.info(f"Batch commit errors: {write.stream_errors}") self.logger.info(f"Writes to streams: '{self.open_streams}' have been committed.") self.open_streams = set() def clean_up(self) -> None: self.commit_streams() super().clean_up() def pre_state_hook(self) -> None: self.commit_streams() class BigQueryStorageWriteDenormalizedSink(Denormalized, BigQueryStorageWriteSink): pass
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/storage_write.py
storage_write.py
import os import shutil import time from io import BytesIO from multiprocessing import Process from multiprocessing.connection import Connection from multiprocessing.dummy import Process as _Thread from queue import Empty from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Type, Union import orjson from google.api_core.exceptions import Conflict from google.cloud import bigquery, storage from target_bigquery.constants import DEFAULT_BUCKET_PATH from target_bigquery.core import ( BaseBigQuerySink, BaseWorker, BigQueryCredentials, Compressor, Denormalized, ParType, bigquery_client_factory, gcs_client_factory, ) if TYPE_CHECKING: from target_bigquery.target import TargetBigQuery class Job(NamedTuple): """Job to be processed by a worker.""" buffer: Union[memoryview, bytes] batch_id: str table: str dataset: str bucket: str gcs_notifier: Connection attempt: int = 1 class GcsStagingWorker(BaseWorker): """Worker that uploads data to GCS.""" def run(self) -> None: """Run the worker.""" client: storage.Client = gcs_client_factory(self.credentials) while True: try: job: Optional[Job] = self.queue.get(timeout=30.0) except Empty: break if job is None: break try: # TODO: consider configurability? path = DEFAULT_BUCKET_PATH.format( bucket=job.bucket, dataset=job.dataset, table=job.table, date=time.strftime("%Y-%m-%d"), batch_id=job.batch_id, ) blob = storage.Blob.from_string(path, client=client) # TODO: pass in timeout? # TODO: composite uploads with blob.open( "wb", if_generation_match=0, chunk_size=1024 * 1024 * 10, timeout=300, ) as fh: shutil.copyfileobj(BytesIO(job.buffer), fh) job.gcs_notifier.send(path) except Exception as exc: job.attempt += 1 if job.attempt > 3: # TODO: add a metric for this + a DLQ & wrap exception type self.error_notifier.send((exc, self.serialize_exception(exc))) raise else: self.queue.put(job) else: self.job_notifier.send(True) self.log_notifier.send( f"[{self.ext_id}] Successfully uploaded {len(job.buffer)} bytes to {path}" ) finally: self.queue.task_done() class GcsStagingThreadWorker(GcsStagingWorker, _Thread): pass class GcsStagingProcessWorker(GcsStagingWorker, Process): pass class BigQueryGcsStagingSink(BaseBigQuerySink): MAX_WORKERS = os.cpu_count() * 2 WORKER_CAPACITY_FACTOR = 1 WORKER_CREATION_MIN_INTERVAL = 10.0 def __init__( self, target: "TargetBigQuery", stream_name: str, schema: Dict[str, Any], key_properties: Optional[List[str]], ) -> None: super().__init__(target, stream_name, schema, key_properties) self.bucket_name = self.config["bucket"] self._credentials = BigQueryCredentials( self.config.get("credentials_path"), self.config.get("credentials_json"), self.config["project"], ) self.client = gcs_client_factory(self._credentials) self.create_bucket_if_not_exists() self.buffer = Compressor() self.buffer = Compressor() self.gcs_notification, self.gcs_notifier = target.pipe_cls(False) self.uris: List[str] = [] self.increment_jobs_enqueued = target.increment_jobs_enqueued @staticmethod def worker_cls_factory( worker_executor_cls: Type[Process], config: Dict[str, Any] ) -> Type[Union[GcsStagingThreadWorker, GcsStagingProcessWorker,]]: Worker = type("Worker", (GcsStagingWorker, worker_executor_cls), {}) return Worker @property def job_config(self) -> Dict[str, Any]: return { "schema": self.table.get_resolved_schema(), "source_format": bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, "write_disposition": bigquery.WriteDisposition.WRITE_APPEND, } def process_record(self, record: Dict[str, Any], context: Dict[str, Any]) -> None: self.buffer.write(orjson.dumps(record, option=orjson.OPT_APPEND_NEWLINE)) def process_batch(self, context: Dict[str, Any]) -> None: self.buffer.close() self.global_queue.put( Job( buffer=( self.buffer.getvalue() if self.global_par_typ is ParType.PROCESS else self.buffer.getbuffer() ), batch_id=context["batch_id"], table=self.table.name, dataset=self.table.dataset, bucket=self.bucket_name, gcs_notifier=self.gcs_notifier, ), ) self.increment_jobs_enqueued() self.buffer = Compressor() def clean_up(self) -> None: while self.gcs_notification.poll(): self.uris.append(self.gcs_notification.recv()) # Anything in the queue at this point can be considered now a DLQ if self.uris: self.logger.info("Loading data into BigQuery from GCS stage...") self.logger.info("URIs: %s", ", ".join(self.uris)) client = bigquery_client_factory(self._credentials) client.load_table_from_uri( self.uris, self.table.as_ref(), timeout=self.config.get("timeout", 600), job_config=bigquery.LoadJobConfig(**self.job_config), ).result() self.logger.info("Data loaded successfully") else: self.logger.info("No data to load") super().clean_up() def as_bucket(self, **kwargs) -> storage.Bucket: """Returns a Bucket instance for this GCS specification.""" bucket = storage.Bucket(client=self.client, name=self.bucket_name) config = {**self.default_bucket_options(), **kwargs} for option, value in config.items(): if option != "location": setattr(bucket, option, value) return bucket def create_bucket_if_not_exists(self) -> storage.Bucket: """Creates a cloud storage bucket. This is idempotent and will not create a new GCS bucket if one already exists.""" kwargs = {} storage_class: str = self.config.get("storage_class") if storage_class: kwargs["storage_class"] = storage_class location: str = self.config.get("location", self.default_bucket_options()["location"]) if not hasattr(self, "_gcs_bucket"): try: self._gcs_bucket = self.client.create_bucket(self.as_bucket(), location=location) except Conflict: gcs_bucket = self.client.get_bucket(self.as_bucket()) if gcs_bucket.location.lower() != location.lower(): raise Exception( "Location of existing GCS bucket " f"{self.bucket_name} ({gcs_bucket.location.lower()}) does not match " f"specified location: {location}" ) else: self._gcs_bucket = gcs_bucket else: # Wait for eventual consistency time.sleep(5) return self._gcs_bucket @staticmethod def default_bucket_options() -> Dict[str, str]: return {"storage_class": "STANDARD", "location": "US"} class BigQueryGcsStagingDenormalizedSink(Denormalized, BigQueryGcsStagingSink): @property def job_config(self) -> Dict[str, Any]: return { "schema": self.table.get_resolved_schema(), "source_format": bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, "write_disposition": bigquery.WriteDisposition.WRITE_APPEND, "schema_update_options": [ bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION, ], "ignore_unknown_values": True, } # Defer schema evolution to the write disposition def evolve_schema(self: BaseBigQuerySink) -> None: pass
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/gcs_stage.py
gcs_stage.py
import os from multiprocessing import Process from multiprocessing.dummy import Process as _Thread from queue import Empty from typing import Any, Dict, List, NamedTuple, Optional, Type, Union import orjson from google.api_core.exceptions import GatewayTimeout, NotFound from google.cloud import _http, bigquery from tenacity import retry, retry_if_exception_type, stop_after_delay, wait_fixed from target_bigquery.core import BaseBigQuerySink, BaseWorker, Denormalized, bigquery_client_factory class Job(NamedTuple): """Job to be processed by a worker.""" table: bigquery.TableReference records: List[Dict[str, Any]] attempt: int = 1 class StreamingInsertWorker(BaseWorker): """Worker that streams data into BigQuery.""" def run(self) -> None: """Run the worker.""" # A monkey patch since we can't override the default json encoder... _http.json = orjson client: bigquery.Client = bigquery_client_factory(self.credentials) while True: try: job: Optional[Job] = self.queue.get(timeout=20.0) except Empty: break if job is None: break try: _ = retry( client.insert_rows_json, retry=retry_if_exception_type( (ConnectionError, TimeoutError, NotFound, GatewayTimeout) ), wait=wait_fixed(1), stop=stop_after_delay(10), reraise=True, )(table=job.table, json_rows=job.records) except Exception as exc: job.attempt += 1 if job.attempt > 3: # TODO: add a metric for this + a DLQ & wrap exception type self.error_notifier.send((exc, self.serialize_exception(exc))) raise else: self.queue.put(job) else: self.job_notifier.send(True) self.log_notifier.send( f"[{self.ext_id}] Inserted {len(job.records)} records into {job.table}" ) finally: self.queue.task_done() class StreamingInsertThreadWorker(StreamingInsertWorker, _Thread): pass class StreamingInsertProcessWorker(StreamingInsertWorker, Process): pass class BigQueryStreamingInsertSink(BaseBigQuerySink): MAX_WORKERS = os.cpu_count() * 2 WORKER_CAPACITY_FACTOR = 10 WORKER_CREATION_MIN_INTERVAL = 1.0 @staticmethod def worker_cls_factory( worker_executor_cls: Type[Process], config: Dict[str, Any] ) -> Type[Union[StreamingInsertThreadWorker, StreamingInsertProcessWorker,]]: Worker = type("Worker", (StreamingInsertWorker, worker_executor_cls), {}) return Worker def preprocess_record(self, record: dict, context: dict) -> dict: record = super().preprocess_record(record, context) record["data"] = orjson.dumps(record["data"]).decode("utf-8") return record @property def max_size(self) -> int: return min(super().max_size, 500) def process_record(self, record: Dict[str, Any], context: Dict[str, Any]) -> None: self.records_to_drain.append(record) def process_batch(self, context: Dict[str, Any]) -> None: self.global_queue.put(Job(table=self.table.as_ref(), records=self.records_to_drain.copy())) self.increment_jobs_enqueued() self.records_to_drain = [] class BigQueryStreamingInsertDenormalizedSink(Denormalized, BigQueryStreamingInsertSink): pass
z3-target-bigquery
/z3_target_bigquery-0.6.8-py3-none-any.whl/target_bigquery/streaming_insert.py
streaming_insert.py
import json import os import sys import typing from ..version import __version__ as version from .default import DEFAULT, OVERWRITE __all__ = 'Config', 'config_directory' class ConfigOption(dict): ''' Single entry info for configuration file. Instance variables: name: name of the config option default: default value ''' def __init__( self, name: str, valtype: typing.Callable[[typing.Any], typing.Any], default: typing.Any): ''' Args: name: name of the config option valtype: type of the config option default: default value ''' super().__init__() self.name = name self.valtype = valtype self.default = default class Config(dict): ''' Program configuration. Instance variables: self: program configuration {'option': value} filename: full path to config filename ''' def __init__(self): super().__init__() self.filename = _config_filename() try: fid = open(self.filename, 'r') except FileNotFoundError: imported = None else: imported = fid.read() fid.close() try: imp_dict = {} if imported is None else json.loads(imported) except json.decoder.JSONDecodeError: imp_dict = {} for entry in imp_dict: self._insert_entry(entry, imp_dict[entry]) self._check_missing() self['version'] = version def _write_config(self) -> None: ''' Write current configuration to file. ''' self['version'] = version with open(self.filename, 'w') as fid: json.dump(self, fid) def _insert_entry(self, entry_name: str, entry_value: typing.Any) -> None: ''' Insert imported entry. Args: entry: config file entry read from file ''' if entry_name in DEFAULT: self[entry_name] = DEFAULT[entry_name][1](entry_value) def _check_missing(self) -> None: ''' Insert missing entries into configuration. ''' changed = False if 'version' not in self or self['version'] != version: for entry in OVERWRITE[version]: self[entry] = DEFAULT[entry][1](DEFAULT[entry][0]) changed = True for entry in DEFAULT: if entry not in self: self[entry] = DEFAULT[entry][1](DEFAULT[entry][0]) changed = True if changed: self._write_config() def update(self, entry: str, data: object) -> None: ''' Update config entry with new data. Args: entry: config entry data: new data ''' self[entry] = data self._write_config() def config_directory() -> str: ''' Return configuration directory. This will create said directory if it doesn't exist. Returns: str: full path to configuration directory ''' if sys.platform.startswith('win32'): configdir = os.path.join(os.getenv('LOCALAPPDATA'), 'z3-tracker') else: configdir = os.path.expanduser('~/.z3-tracker') if not os.path.isdir(configdir): os.mkdir(configdir) return configdir def _config_filename() -> str: ''' Return config file name. This will create the config directory if it doesn't exist. The config file itself, however, won't. Returns: str: fill path to config file ''' return os.path.join(config_directory(), 'config.json')
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/config/config.py
config.py
from . import storage __all__ = 'EntranceTracker', class EntranceTracker(dict): ''' Entrance tracker Instance variables: self: {'location': 'linked locations'} armed: True if entrance connection is armed worldtracker: world state tracker ''' def __init__(self, worldtracker): ''' Args: worldtracker: world state tracker ''' super().__init__(storage.load_entrances()) self.armed = False self.worldtracker = worldtracker def event(self, button: str) -> bool: ''' Entrance connection event Connection happens in two steps: first it's armed, then it's connected. Args: button: name of location Returns: bool: True if new connection was made ''' if ('retro' in self.worldtracker.settings and not 'entrance' in self.worldtracker.settings): return False if not self.armed: if button not in self: self.armed = button return False if button.replace(' (E)', ' (I)') in self.values(): self.armed = False return False interior = button.replace(' (E)', ' (I)') self[self.armed] = interior self[interior] = self.armed self.armed = False self.save() return True def abort(self, button: str = None) -> bool: ''' Abort or delete connection. Args: button: name of location ''' if ('retro' in self.worldtracker.settings and not 'entrance' in self.worldtracker.settings): return False self.armed = False if button is not None and button in self: del self[self[button]] del self[button] self.save() def update(self) -> None: ''' Update world tracker with new entrance information. ''' self.worldtracker.ruleset.disconnect_entrances() for location in self: self.worldtracker.ruleset[location].link[self[location]] = [] self.worldtracker.ruleset[self[location]].link[location] = [] self.worldtracker.rulecheck() def reset(self) -> None: ''' Remove all established connections. ''' for loc in tuple(self.keys()): del self[loc] self.armed = False def find_remote(self, start: str) -> list: ''' Find other interior conections. Args: start: starting entrance Returns: list: entrances connected via interiors ''' if start not in self: return [] reachable = [self[start]] done = {start} entrances = set() while reachable: loc = reachable.pop(0) done.add(loc) for link in self.worldtracker.ruleset[loc].link: if link in ('Ocarina', 'Pyramid', 'Castle Walls'): continue if not self.worldtracker.ruleset[link].type.startswith( 'entrance') and link not in done: reachable.append(link) elif self.worldtracker.ruleset[link].type.startswith( 'entrance') and link != start: entrances.add(link) return entrances def save(self) -> None: ''' Save current connections to file. ''' storage.store_entrances(self)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/entrances/entrances.py
entrances.py
import functools import importlib import tkinter as tk import tkinter.ttk as ttk import typing from ..config import CONFIG from ..config.images import image common = importlib.import_module( '..gui-common.maps', package=__package__) BUTTONTYPE = common.BUTTONTYPE from . import misc MAPSCALE = 1 __all__ = 'MapDisplay', 'make_symbol_coordinates' class MapDisplay(tk.Toplevel): ''' Map window Instance variables: identifier: map name scale: map scale imagefile: map image entrancetracker: entrance tracker other: other (dark/light world) map activelink: linked button currently artifically set to active button: ocation buttons tracker: location trackern ''' def __init__(self, spec: str): ''' Args: spec: map type ''' # General initialisation assert spec in ('light', 'dark') super().__init__(background=CONFIG['background']) self.identifier = spec self.scale = CONFIG['map_size'] self.title('Light World' if spec == 'light' else 'Dark World') self.button = {} self.entrancetracker = None self.other = None self.activelink = set() self.tracker = None # Set up bottom text label. self.helpertext = tk.StringVar() self.helper = ttk.Label( self, textvariable=self.helpertext, style='themed.TLabel') self.helper.grid(column=0, row=1, sticky=tk.S) # Set background image. imagefile = tk.PhotoImage( file=image('lightworld' if spec == 'light' else 'darkworld'), master=self) scaling = MAPSCALE * self.scale imgdim = (imagefile.width() * scaling, imagefile.height() * scaling) self.map = tk.Canvas( self, background=CONFIG['background'], height=imgdim[1], highlightbackground=CONFIG['background'], width=imgdim[0]) self.map.grid(column=0, row=0, sticky=misc.A) for up in range(1, 1000): if not (scaling * up) % 1: upscale = int(scaling * up) downscale = up break else: CONFIG['map_size'] = 1 self.scale = 1 assert False if upscale != 1: imagefile = imagefile.zoom(upscale, upscale) if downscale != 1: imagefile = imagefile.subsample(downscale, downscale) self.image = self.map.create_image( (0, 0), anchor=tk.NW, image=imagefile) self.map.bind('<ButtonRelease-3>', lambda _: self._rightclick_button()) self.imagefile = imagefile # Set-up entrance tracker display. self.map.bind('<Enter>', self._update_entrance_state) self.map.bind('<Leave>', lambda _: self.helper.configure( background='', foreground=CONFIG['foreground'])) # Only for Retro mode self.bind('<r>', lambda _: self._clear_retro()) def add_location_tracker(self, locationtracker) -> None: ''' Add location tracker. Args: locationtracker: location tracker ''' self.tracker = locationtracker def place_buttons(self, locations: dict) -> None: ''' Place buttons on map. Args: locations: { 'location name': {'map': str, 'coord': (int, int), 'type': str}} ''' for loc in locations: self.add_button( loc, locations[loc]['coord'], locations[loc]['type']) def add_button( self, name: str, coord: typing.Sequence[int], buttontype: str) -> None: ''' Add a button. Args: name: name of new button coord: coordinates for centre of button buttontype: type of button ''' # Dungeon buttons are different. if buttontype == 'dungeon': self._add_dungeon_button(name, coord) return # Make button. assert (buttontype in ('chest', 'item', 'cave', 'drop', 'ganon') or buttontype.startswith('entrance')) displaytext = name if buttontype == 'chest': buttonfunc = self._chest_icon elif buttontype == 'entrance_drop': buttonfunc = self._drop_entrance_icon displaytext = displaytext.replace(' Entrance (E)', '') elif buttontype.startswith('entrance'): buttonfunc = self._entrance_icon displaytext = displaytext.replace(' Entrance (E)', '') elif buttontype == 'item': buttonfunc = self._item_icon elif buttontype == 'cave': buttonfunc = self._cave_icon elif buttontype == 'drop': buttonfunc = self._drop_icon elif buttontype == 'ganon': buttonfunc = self._ganon_icon else: buttonfunc = self._item_icon new = buttonfunc(coord) self.button[name] = { 'id': new, 'type': buttontype, 'display': displaytext, 'available': 'unavailable', 'entrance': False} if name not in self.tracker: self.tracker[name] = True # Assign button functions. self.map.tag_bind( new, '<Enter>', lambda _: self._hover(name)) self.map.tag_bind( new, '<Leave>', lambda _: self._unhover(name)) self.map.tag_bind( new, '<ButtonRelease-1>', lambda _: self._leftclick_button(name)) if buttontype.startswith('entrance'): self.map.tag_bind( new, '<ButtonRelease-2>', lambda _: self._middleclick_button(name)) self.map.tag_bind( new, '<ButtonRelease-3>', lambda _: self._rightclick_button(name)) def _update_entrance_state(self, *args) -> None: ''' Update display of entrance linking. ''' self.helper.configure( background=('yellow' if self.entrancetracker.armed else ''), foreground=('black' if self.entrancetracker.armed else CONFIG['foreground'])) def _hover(self, button: str) -> None: ''' Set bottom display. Args: button: button under mouse ''' displaytext = self.button[button]['display'] if self.button[button]['type'].startswith('entrance'): # Entrance leading to itself. try: same = self.entrancetracker[button] == button.replace( ' (E)', ' (I)') except KeyError: same = False if button in self.entrancetracker and same: self.set_entrance_colour(button, 'default') # Entrances reachable from entrance. linked = self.entrancetracker.find_remote(button) for loc in linked: if loc in self.button: self.set_entrance_colour(loc, 'linked') else: self.other.set_entrance_colour(loc, 'linked') # Entrance leading to interior. if button in self.entrancetracker and not same: linked = self.entrancetracker[button].replace( ' Entrance (I)', '') displaytext = '{0:s} → {1:s}'.format(displaytext, linked) if displaytext != linked: linkbutton = '{0:s} Entrance (E)'.format(linked) if linkbutton in self.button: self.set_entrance_colour(linkbutton, 'interior') else: self.other.set_entrance_colour(linkbutton, 'interior') # Interior reached via entrance. interior = button.replace(' (E)', ' (I)') if interior in self.entrancetracker and not same: linked = self.entrancetracker[interior] if displaytext != linked.replace(' Entrance (E)', ''): if linked in self.button: self.set_entrance_colour(linked, 'entrance') else: self.other.set_entrance_colour(linked, 'entrance') self.helpertext.set(displaytext) def _unhover(self, button: str) -> None: ''' Set bottom display. Args: button: button under mouse ''' self.helpertext.set('') while self.activelink: self._set_colour(self.activelink.pop()) while self.other.activelink: self.other._set_colour(self.other.activelink.pop()) def _leftclick_button(self, name: str) -> None: ''' Event on left-clicking a button. Args: name: name of clicked-on button ''' self.tracker[name] = not self.tracker[name] self._set_colour(name) self.tracker.save() def _middleclick_button(self, name: str) -> None: ''' Event on middle-clicking a button. Args: name: name of clicked on button ''' if not CONFIG['entrance_randomiser']: return new = self.entrancetracker.event(name) if not new and self.entrancetracker.armed: self.helper.configure(background='yellow', foreground='black') else: self.helper.configure( background='', foreground=CONFIG['foreground']) if new: self.set_entrance() def _rightclick_button(self, name: str = None) -> None: ''' Event on right-clicking a button. Args: name: name of clicked on button ''' self.entrancetracker.abort(name) self.helper.configure(background='', foreground=CONFIG['foreground']) if CONFIG['entrance_randomiser'] and name: self.set_entrance() self._hover(name) def _add_dungeon_button( self, name: str, coord: typing.Sequence[int]) -> None: ''' Add dungeon button. Args: name: name of dungeon coord: location on map ''' shape = -13, -13, 13, 13 loc = make_symbol_coordinates(coord, shape, self.scale) new_outer = self.map.create_rectangle(*loc) shape = -7, -7, 7, 7 loc = make_symbol_coordinates(coord, shape, self.scale) new_inner = self.map.create_rectangle(*loc) self.button[name] = { 'id': (new_outer, new_inner), 'type': 'dungeon', 'display': name, 'available': ['unavailable', 'unavailable']} if name not in self.tracker: self.tracker[name] = [True, True] for new in (new_outer, new_inner): self.map.tag_bind( new, '<Enter>', lambda _: self.helpertext.set(name)) self.map.tag_bind( new, '<Leave>', lambda _: self.helpertext.set('')) def remove_buttons(self) -> None: ''' Remove all buttons from map. ''' for button in self.button.values(): if button['type'] == 'dungeon': self.map.delete(button['id'][0]) self.map.delete(button['id'][1]) else: self.map.delete(button['id']) self.button = {} def set_availability(self, name: str, availability: str) -> None: ''' Set whether given location is available. Args: name: location name availability: 'available', 'unavailable', 'visible', 'maybe', 'indirect' ''' assert availability in ( 'available', 'unavailable', 'visible', 'maybe', 'indirect') self.button[name]['available'] = availability self._set_colour(name) def set_dungeon_availability( self, name: str, availability: (str, str)) -> None: ''' Set whether given dungeon is available. Args: name: location name availability: two of 'available', 'unavailable', 'visible', 'maybe', 'indirect' ''' for idx, avail in enumerate(availability): assert avail in ( 'available', 'unavailable', 'visible', 'maybe', 'indirect') self.button[name]['available'][idx] = avail self._set_colour(name) self.tracker.save() def set_entrance(self) -> None: ''' Update entrance display. ''' for button in self.button: if self.button[button]['type'] == 'dungeon': continue if (button in self.entrancetracker and not self.button[button]['entrance']): self.button[button]['entrance'] = True self.entrancetracker.update() elif (button not in self.entrancetracker and self.button[button]['entrance']): self.button[button]['entrance'] = False self.entrancetracker.update() for button in self.other.button: if self.other.button[button]['type'] == 'dungeon': continue if (button in self.entrancetracker and not self.other.button[button]['entrance']): self.other.button[button]['entrance'] = True self.entrancetracker.update() elif (button not in self.entrancetracker and self.other.button[button]['entrance']): self.other.button[button]['entrance'] = False self.entrancetracker.update() def _set_colour(self, button: str) -> None: ''' Set button colour. Args: button: button name ''' if self.button[button]['type'] == 'dungeon': self._set_dungeon_colour(button) return if not self.tracker[button]: colour = 'checked' else: colour = self.button[button]['available'] if self.button[button]['type'] in BUTTONTYPE: colours = BUTTONTYPE[self.button[button]['type']]['colours'] else: colours = BUTTONTYPE['standard']['colours'] if self.button[button]['entrance']: activeoutline = 'black' activewidth = 3 outline = 3 else: activeoutline = 'black' activewidth = 1 outline = 1 self.map.itemconfigure( self.button[button]['id'], activefill=colours[colour]['active'], activeoutline=activeoutline, activewidth=activewidth, fill=colours[colour]['normal'], outline='black', width=outline) def set_entrance_colour(self, button: str, linktype: str) -> None: ''' Set colour of linked entrance button. Args: button: button name linktime: 'entrance', 'interior', 'linked' ''' if not CONFIG['entrance_randomiser']: return assert linktype in ('entrance', 'interior', 'linked', 'default') if not self.tracker[button]: colour = 'checked' else: colour = self.button[button]['available'] if self.button[button]['type'] in BUTTONTYPE: colours = BUTTONTYPE[self.button[button]['type']]['colours'] else: colours = BUTTONTYPE['standard']['colours'] if button in self.activelink: if linktype == 'interior': linkcolour = 'magenta' elif linktype == 'entrance': linkcolour = 'cyan' else: linkcolour = 'orange' self.map.itemconfigure( self.button[button]['id'], fill=colours[colour]['active'], outline=linkcolour, width=3) elif linktype == 'entrance': self.map.itemconfigure( self.button[button]['id'], fill=colours[colour]['active'], outline='yellow', width=3) elif linktype == 'interior': self.map.itemconfigure( self.button[button]['id'], fill=colours[colour]['active'], outline='red', width=3) elif linktype == 'linked': self.map.itemconfigure( self.button[button]['id'], fill=colours[colour]['active'], outline='blue', width=3) elif linktype == 'default': self.map.itemconfigure( self.button[button]['id'], activefill=colours[colour]['active'], activeoutline='white', activewidth=3) self.activelink.add(button) def _set_dungeon_colour(self, button: str) -> None: ''' Set colour of dungeon button. Args: button: dungeon name ''' for bpart in range(2): if not self.tracker[button][bpart]: colour = 'checked' else: colour = self.button[button]['available'][bpart] colours = BUTTONTYPE['standard']['colours'] self.map.itemconfigure( self.button[button]['id'][bpart], activefill=colours[colour]['normal'], fill=colours[colour]['normal'], outline='black', width=1) def reset(self) -> None: ''' Reset state of all buttons. ''' self.entrancetracker.reset() self.tracker.reset() self.set_entrance() for button in self.button: if self.button[button]['type'] == 'dungeon': self.tracker[button] = [True, True] else: self.tracker[button] = True self._set_colour(button) def add_entrance_tracker(self, entrancetracker) -> None: ''' Add entrance tracker. ''' self.entrancetracker = entrancetracker def _clear_retro(self) -> None: ''' Mark all Retro buttons. ''' if CONFIG['world_state'] == 'Retro': for button in self.button: if self.button[button]['type'] in ( 'entrance', 'entrance_shop'): self.tracker[button] = False self._set_colour(button) self.tracker.save() def _chest_icon(self, location: typing.Sequence[int]) -> int: shape = -7, -7, 7, 7 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_rectangle(*loc) return new def _entrance_icon(self, location: typing.Sequence[int]) -> int: shape = -5, -5, 5, 5 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_rectangle(*loc) return new def _item_icon(self, location: typing.Sequence[int]) -> int: shape = -7, -7, 7, 7 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_oval(*loc) return new def _cave_icon(self, location: typing.Sequence[int]) -> int: shape = -7, 7, 0, -7, 7, 7 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_polygon(*loc) return new def _drop_icon(self, location: typing.Sequence[int]) -> int: shape = -7, -7, 0, 7, 7, -7 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_polygon(*loc) return new def _drop_entrance_icon(self, location: typing.Sequence[int]) -> int: shape = -6, -6, 0, 6, 6, -6 loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_polygon(*loc) return new def _ganon_icon(self, location: typing.Sequence[int]) -> int: '''Go-mode symbol''' shape = (0, -20, 5, -5, 20, -5, 8, 5, 12, 20, 0, 11, -12, 20, -8, 5, -20, -5, -5, -5) loc = make_symbol_coordinates(location, shape, self.scale) new = self.map.create_polygon(*loc) return new def make_symbol_coordinates( location: typing.Sequence[int], shape: typing.Sequence[int], mapscale: float) -> list: ''' Create corner points for map symbol. Args: location: centre of symbol shape: symbol corners relative to centre point mapscale: additional map scaling factor Returns: list: flat list of coordinates for symbol creation ''' loc = list(location[:2]) * (len(shape) // 2) scaled = tuple(int(c * MAPSCALE * mapscale) for c in shape) loc = [loc[l] * mapscale + scaled[l] for l in range(len(scaled))] return loc
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/maps.py
maps.py
import logging as log import tkinter as tk import tkinter.ttk as ttk from ..config import CONFIG FOREGROUND = CONFIG['foreground'] FRAME = None INFOSTRING = None INFOTEXT = None REFRESH = None __all__ = ( 'FRAME', 'INFOSTRING', 'INFOTEXT', 'REFRESH', 'set_info', 'AutotrackToggle') def set_info(message: str, msgtype: str = None, tolog: bool = True, refreshbutton: bool = True) -> None: ''' Set autotracker status message. Args: message: status message msgtype: 'info' or 'error' or None tolog: if False, message won't be copied to stdout refreshbutton: True if refreshbutton should be shown ''' assert msgtype in ('info', 'error', None) if not message: if tolog: log.debug('Resetting info.') INFOSTRING.set('') FRAME.grid_remove() else: if refreshbutton: FRAME.refreshbutton.grid() else: FRAME.refreshbutton.grid_remove() if msgtype is not None: if tolog: if msgtype == 'error': log.warning('%s', message) else: log.info('%s', message) INFOSTRING.set('{0:s}{1:s}'.format( 'ERROR:\n' if msgtype == 'error' else '', message)) if msgtype == 'error': INFOTEXT.configure(foreground='#bb0000') elif msgtype is not None: INFOTEXT.configure(foreground='#000000') FRAME.grid() class AutotrackToggle(ttk.Label): ''' Switch allowing autotracker for specific display to be switched off. Instance variables: attext: button label toggle: True if autotracking is on ''' def __init__(self, *args, **kwargs): ''' Args: default: default state; True means autotracking enabled args, kwargs: arguments of ttk.Label() ''' self.toggle = kwargs['default'] self.attext = tk.StringVar() del kwargs['default'] kwargs.update({'borderwidth': 1, 'textvariable': self.attext}) super().__init__(*args, **kwargs) self.defaultcolour = CONFIG['background'] self.bind('<ButtonRelease-1>', lambda _: self.set_autotracking(not self.toggle)) self.disable() def disable(self) -> None: ''' Disable button. ''' self.attext.set('') self.configure(background=self.defaultcolour, relief=tk.FLAT) def enable(self) -> None: ''' Enable button. ''' self.configure(relief=tk.GROOVE) self.set_autotracking(self.toggle) def set_autotracking(self, autotrack: bool) -> None: ''' Set autotracker. Args: autotrack: True if autotracker should be switched on ''' self.toggle = autotrack if autotrack: self.attext.set(' Auto ') else: self.attext.set(' Manual ') self.configure( background=self.defaultcolour, foreground=FOREGROUND) def set_state(self, state: str) -> None: ''' Set autotracking status. Args: state: 'on', 'off' or 'error' ''' if not self.toggle: return assert state in ('on', 'off', 'error') colour = ( '#bb0000' if state == 'error' else '#bb6b00' if state == 'off' else '#0000bb') self.configure(background=colour, foreground='white')
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/autotracker.py
autotracker.py
import sys import tkinter as tk import tkinter.colorchooser as tkc import tkinter.ttk as ttk import tkinter.messagebox as tkmbox import typing from .. import autotracker from ..config import CONFIG from ..config.default import DEFAULT, CONFLICTS from . import misc SPACERWIDTH = -5 PADDING = 3 FONT = ('Arial', CONFIG['font_size']) FATFONT = ('Arial Black', int(round(CONFIG['font_size'] * CONFIG['icon_size'] * 1.33))) __all__ = 'start', class ConfigWindow(tk.Toplevel): ''' Config window Instance variables: tracker: world state tracker widgets: random collection of GUI widgets entries: current string config choices boolentries: current boolean config choices texts: texts display for config options hidden: handles of hidable widgets usb2snes: QUsb2snes device selection ''' def __init__(self, tracker): ''' Args: tracker: world state tracker ''' super().__init__() self.title('Settings') self.frame = ttk.Frame(self, padding=PADDING) self.frame.grid(column=0, row=0, sticky=misc.A) self.option_add('*TCombobox*Listbox.font', FONT) self.tracker = tracker self.widgets = [] self.entries = {} self.boolentries = {} self.texts = {} self.hidden = {} col = ttk.Frame(self.frame) col.grid(column=0, row=0, sticky=tk.E+tk.W+tk.N) self.widgets.append(col) sec = ttk.LabelFrame( col, padding=PADDING, text='Display settings (requires restart)') sec.grid(column=0, row=0, sticky=tk.E+tk.W) self.widgets.append(sec) self._make_entry(0, sec, 'Font size', 'font_size') self._make_entry(1, sec, 'Item/Dungeon tracker size', 'icon_size') self._make_entry(2, sec, 'Maps size', 'map_size') self._make_check(3, sec, 'Autotracker debug log', 'usb2snes_debug') self._make_colour(4, sec, 'Background colour', 'background') self._make_colour(5, sec, 'Text colour', 'foreground') sec = ttk.LabelFrame( col, padding=PADDING, text='Program settings') sec.grid(column=0, row=1, sticky=tk.E+tk.W) self.widgets.append(sec) self._make_check(0, sec, 'Autotracker', 'autotracking') self.usb2snes = self._make_option( 1, sec, 'Tracking source', (), 'usb2snes_device') self._update_usb2snes() self._make_multichoice( 2, sec, 'Autotrackers enabled by default', ('Items',), ('autodefault_items',), 3) sec = ttk.LabelFrame( col, padding=PADDING, text='File information') sec.grid(column=0, row=2, sticky=tk.E+tk.W) self.widgets.append(sec) self._make_display(0, sec, 'GUI module', 'gui') self._make_display(1, sec, 'Autosave', 'autosave') self._make_display( 2, sec, 'Item/Dungeon tracker layout', 'button_layout') self._make_display(3, sec, 'Window layout', 'window_layout') self._make_entry(4, sec, 'Path trace log', 'path_trace') self._make_display(5, sec, 'QUsb2snes address', 'usb2snes_server') col = ttk.Frame(self.frame) col.grid(column=1, row=0, sticky=tk.E+tk.W+tk.N) self.widgets.append(col) sec = ttk.LabelFrame( col, padding=PADDING, text='Game settings') sec.grid(column=0, row=0, sticky=tk.E+tk.W) self.widgets.append(sec) self._make_check(0, sec, 'Entrance Randomiser', 'entrance_randomiser') self._make_choice( 1, sec, 'World State', ('Standard', 'Open', 'Inverted', 'Retro'), 'world_state') self._make_choice( 2, sec, 'Glitches Required', ('None', 'Overworld Glitches', 'Major Glitches'), 'glitch_mode') self._make_choice( 3, sec, 'Item Placement', ('Basic', 'Advanced'), 'item_placement') self._make_multichoice( 5, sec, 'Shuffled dungeon items', ('Maps', 'Small Keys', 'Compasses', 'Big Keys'), ('shuffle_map', 'shuffle_smallkey', 'shuffle_compass', 'shuffle_bigkey'), 2) self._make_choice( 4, sec, 'Dungeon Items', ('Standard', 'Maps/Compasses', 'Maps/Compasses/Small Keys', 'Keysanity', 'Custom'), 'dungeon_items', linkwidget={'Custom': 'Shuffled dungeon items'}) if self.entries['dungeon_items'].get() != 'Custom': self.hidden['Shuffled dungeon items'].grid_remove() self._make_choice( 6, sec, 'Goal', ('Defeat Ganon', 'Fast Ganon', 'All Dungeons', 'Master Sword Pedestal', 'Triforce Hunt'), 'goal') self._make_choice( 7, sec, 'Swords', ('Randomised', 'Assured', 'Vanilla', 'Swordless'), 'swords') self._make_check(8, sec, 'Enemiser', 'enemiser') self._make_check(9, sec, 'Shop-sanity', 'shopsanity') sec = ttk.LabelFrame( col, padding=PADDING, text='Display settings') sec.grid(column=0, row=1, sticky=tk.E+tk.W) self.widgets.append(sec) self._make_check(0, sec, 'Major Locations Only', 'majoronly') buttonframe = ttk.Frame(self.frame) buttonframe.grid(column=0, columnspan=9, row=9, sticky=tk.E+tk.S) okbutton = ttk.Button(buttonframe, command=self.apply, text='Apply') cancelbutton = ttk.Button( buttonframe, command=self.withdraw, text='Cancel') col = 1 if sys.platform.startswith('win32') else 0 okbutton.grid(column=col, row=0, sticky=tk.E) cancelbutton.grid(column=1 - col, row=0, sticky=tk.E) self.widgets.extend((buttonframe, okbutton, cancelbutton)) def deiconify(self) -> None: ''' Update options when opening this window. ''' self._update_usb2snes() super().deiconify() def _make_entry( self, location: int, parent: ttk.LabelFrame, displaytext: str, configoption: str): ''' Make text box. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window configoption: corresponding config option ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label(parent, width=SPACERWIDTH) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.StringVar() entryvar.set(str(CONFIG[configoption])) entry = ttk.Entry(parent, font=FONT, textvariable=entryvar) entry.grid(column=2, row=location, sticky=tk.W) self.entries[configoption] = entryvar self.texts[configoption] = displaytext self.widgets.extend((name, spacer, entry)) def _make_display( self, location: int, parent: ttk.LabelFrame, displaytext: str, configoption: str) -> None: ''' Make info display. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window configoption: corresponding config option ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label(parent, width=SPACERWIDTH) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.StringVar() entryvar.set(str(CONFIG[configoption])) entry = ttk.Entry(parent, font=FONT, textvariable=entryvar) entry.configure(state='readonly') entry.grid(column=2, row=location, sticky=tk.W) self.widgets.extend((name, spacer, entryvar, entry)) def _make_check( self, location: int, parent: ttk.LabelFrame, displaytext: str, configoption: str, halfwidth: bool = False) -> None: ''' Make checkbox. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window configoption: corresponding config option ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label( parent, width=int(SPACERWIDTH / (2 if halfwidth else 1))) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.IntVar() entryvar.set(int(CONFIG[configoption])) entry = ttk.Checkbutton(parent, variable=entryvar) entry.grid(column=2, row=location, sticky=tk.W) self.boolentries[configoption] = entryvar self.texts[configoption] = displaytext self.widgets.extend((name, spacer, entry)) def _make_choice( self, location: int, parent: ttk.LabelFrame, displaytext: str, choices: typing.Sequence[str], configoption: str, linkwidget: dict = {}) -> None: ''' Make menu selection. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window choices: available selections configoption: corresponding config option halfwidth: only use half spacer width linkwidget: link visibility of widget to option ({option: widget}) ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label(parent, width=SPACERWIDTH) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.StringVar() entryvar.set(str(CONFIG[configoption])) entry = ttk.Combobox( parent, font=FONT, values=choices, textvariable=entryvar, width=max(len(s) for s in choices)) if linkwidget: def _check_hidden(*args) -> True: if entryvar.get() in linkwidget: self.hidden[linkwidget[entryvar.get()]].grid() for lw in linkwidget: if entryvar.get() != lw: self.hidden[linkwidget[lw]].grid_remove() entryvar.trace('w', _check_hidden) entry.configure(state='readonly') entry.grid(column=2, row=location, sticky=tk.W+tk.E) self.entries[configoption] = entryvar self.texts[configoption] = displaytext self.widgets.extend((name, spacer, entry)) def _make_option( self, location: int, parent: ttk.LabelFrame, displaytext: str, options: set, configoption: str) -> ttk.OptionMenu: ''' Make option menu selection. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window options: list of available options configoption: corresponding config option Returns: ttk.OptionMenu: created widget ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label(parent, width=SPACERWIDTH) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.StringVar() entryvar.set(str(CONFIG[configoption])) entry = ttk.OptionMenu(parent, entryvar, *options) entry['menu'].configure(font=FONT) entry.grid(column=2, row=location, sticky=tk.W+tk.E) self.entries[configoption] = entryvar self.texts[configoption] = displaytext self.widgets.extend((name, spacer, entry)) return entry def _make_multichoice( self, location: int, parent: ttk.LabelFrame, displaytext: str, options: tuple, configoptions: tuple, columns: int): ''' Make multiple choice frame. Args: location: row on GUI parent: parent widgets displaytext: text to show as frame header options: available options configoptions: configoptions corresponding to options columns: number of columns to use ''' outerframe = ttk.LabelFrame(parent, text=displaytext) outerframe.grid(column=0, columnspan=3, row=location, sticky=tk.W+tk.E) columnframes = [] for c in range(columns): columnframes.append(ttk.Frame(outerframe)) columnframes[-1].grid(column=2 * c, row=0, sticky=tk.W) columnspacers = [] for c in range(columns - 1): columnspacers.append(ttk.Label(outerframe, width=SPACERWIDTH)) columnspacers[-1].grid(column=2 * c + 1, row=0, sticky=tk.W) column = 0 row = 0 for idx, opt in enumerate(options): self._make_check(row, columnframes[column], opt, configoptions[idx], halfwidth=True) column += 1 if column >= columns: row += 1 column = 0 self.hidden[displaytext] = outerframe self.widgets.extend((outerframe, columnframes, columnspacers)) def _make_colour( self, location: int, parent: ttk.LabelFrame, displaytext: str, configoption: str) -> None: ''' Make colour selection button. Args: location: row on GUI parent: parent widgets displaytext: text to show in config window configoption: corresponding config option ''' name = ttk.Label(parent, text=displaytext) name.grid(column=0, row=location, sticky=tk.W) spacer = ttk.Label(parent, width=SPACERWIDTH) spacer.grid(column=1, row=location, sticky=tk.W) entryvar = tk.StringVar() entryvar.set(str(CONFIG[configoption])) def _set_colour() -> None: colour = tkc.askcolor(entryvar.get(), parent=self) if colour[1] is not None: entryvar.set(colour[1]) entry = ttk.Button(parent, command=_set_colour, textvariable=entryvar) entry.grid(column=2, row=location, sticky=tk.W) self.entries[configoption] = entryvar self.texts[configoption] = displaytext self.widgets.extend((name, spacer, entry)) def _update_usb2snes(self) -> None: ''' Update available QUsb2snes devices. ''' self.usb2snes['menu'].delete(0, 'end') devices = list(autotracker.DEVICES) devices.remove('') devices.extend(('SD2SNES', 'Retroarch', 'SNES9X', 'Bizhawk')) for dev in devices: self.usb2snes['menu'].add_command( label=dev, command=tk._setit(self.entries['usb2snes_device'], dev)) def withdraw(self) -> None: ''' Reset all entries before closing the window. ''' for entry in self.entries: self.entries[entry].set(str(CONFIG[entry])) for entry in self.boolentries: self.boolentries[entry].set(int(CONFIG[entry])) super().withdraw() def apply(self) -> None: ''' Apply changed config. ''' if self._check_conflicts(): return for entry in self.boolentries: CONFIG.update( entry, DEFAULT[entry][1](self.boolentries[entry].get())) for entry in self.entries: try: CONFIG.update( entry, DEFAULT[entry][1](self.entries[entry].get())) except ValueError: tkmbox.showerror( 'Invalid', "You have entered an incorrect value into '{0:s}'.".format( self.texts[entry]), parent=self) break else: self.tracker.reapply() self.dungeondisplay.redraw() super().withdraw() def _check_conflicts(self) -> bool: ''' Check config for conflicts. Returns: bool: True if conflicts are present ''' for conflict in CONFLICTS: notpassed = True for cond in conflict: if cond in self.boolentries: notpassed &= ( self.boolentries[cond].get() == conflict[cond][0]) else: notpassed &= self.entries[cond].get() == conflict[cond][0] if notpassed: message = [ '- {0:s}: {1:s}'.format( conflict[cond][1], str(conflict[cond][0])) for cond in conflict] tkmbox.showerror( 'Conflict', 'The following settings are conflicting:\n{0:s}'.format( '\n'.join(message)), parent=self) return True return False def start(tracker) -> None: ''' Open config window. Args: tracker: world state tracker ''' return ConfigWindow(tracker)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/config.py
config.py
import tkinter as tk import tkinter.ttk as ttk import typing from ..autotracker import AutotrackToggle from ..config import CONFIG from .. import items from . import misc BACKGROUND = CONFIG['background'] FOREGROUND = CONFIG['foreground'] __all__ = 'start', class ItemWindow(tk.Toplevel): ''' Inventory item display Instance variables: tracker: item tracker object layout: item layout in display helpertext: helper text variable scaling: scaling factor of individual buttons buttons: {'item identifier': button object} autotrack: True if autotracker is active ''' def __init__(self, tracker: items.ItemTracker): ''' Args: tracker: item tracker object ''' super().__init__() self.title('Items') self.tracker = tracker self.frame = ttk.Frame(self, style='themed.TFrame') self.frame.pack(side='top', fill='both', expand=True) self.bottomline = ttk.Frame(self, style='themed.TFrame') self.bottomline.pack(side='top', fill='x', expand=True) self.autotrack = AutotrackToggle( self.bottomline, default=CONFIG['autodefault_items']) self.autotrack.pack(side='left') self.helperframe = ttk.Frame(self.bottomline, style='themed.TFrame') self.helperframe.pack(side='right', fill='x', expand=True) self.helpertext = tk.StringVar() self.helper = ttk.Label( self.helperframe, anchor=tk.CENTER, style='themed.TLabel', textvariable=self.helpertext) self.helper.pack(side='right', fill='x', expand=True) self.scaling = _scale_factors() self.buttons = {} for item in self.tracker: if ( self.tracker[item].location and self.tracker[item].displayname and self.tracker[item].icon): self._item_display(self.tracker[item]) def _item_display(self, item) -> None: ''' Make and place single item display object. Args: item: item object Writes: buttons ''' button = ItemButton(item, self.frame, self.scaling) button.bind( '<Enter>', lambda _: self.helpertext.set(item.display())) button.bind( '<Leave>', lambda _: self.helpertext.set('')) button.bind('<ButtonRelease-1>', item.increase) button.bind('<ButtonRelease-3>', item.decrease) button.bind( '<ButtonRelease-1>', lambda _: self.helpertext.set(item.display()), add='+') button.bind( '<ButtonRelease-3>', lambda _: self.helpertext.set(item.display()), add='+') button.bind( '<ButtonRelease-1>', lambda _: self.tracker.save(), add='+') button.bind( '<ButtonRelease-3>', lambda _: self.tracker.save(), add='+') button.bind( '<ButtonRelease-1>', lambda _: button.check_state(item), add='+') button.bind( '<ButtonRelease-3>', lambda _: button.check_state(item), add='+') button.grid(column=item.location[1], row=item.location[0]) self.buttons[item.identifier] = button def set_all(self, stepping: dict) -> None: ''' Set all items in one sweep. Args: stepping: {'item identifier': required stepping} ''' self.tracker.restore(stepping) self.tracker.save() for item in self.tracker: if self.tracker[item].icon: self.buttons[item].check_state(self.tracker[item]) def reset(self) -> None: ''' Reset items to default. ''' self.tracker.reset() for item in self.tracker: if self.tracker[item].icon: self.buttons[item].check_state(self.tracker[item]) class ItemButton(tk.Canvas): ''' Single item display object. ''' def __init__( self, item, parent: ttk.Frame, scaling: (int, int)): ''' item: item object parent: parent widget for object scaling: button up- and downscale ''' super().__init__( parent, background=BACKGROUND, height=64 * scaling[0] / scaling[1], highlightbackground=BACKGROUND, width=64 * scaling[0] / scaling[1]) self.scaling = scaling self.img = None self.icon = None self.state = None self.check_state(item) def check_state(self, item) -> None: ''' Check button state and make adjustments if necessary. Args: item: item object ''' if self.state == item.inventory: return self.delete(self.img) icon = tk.PhotoImage( file=item.icon[item.index()], master=self.master) if self.scaling[0] != 1: icon = icon.zoom(self.scaling[0], self.scaling[0]) if self.scaling[1] != 1: icon = icon.subsample(self.scaling[1], self.scaling[1]) if not item.state(): for x in range(icon.width()): for y in range(icon.height()): bw = sum(icon.get(x, y)) // item.disabled[0] if bw in (0, 255): continue bw *= int( (item.disabled[1] - 1) * int(BACKGROUND[1:], 16) / 0xd9d9d9) + 1 bw = 255 if bw > 255 else int(bw) icon.put('#{0:02x}{0:02x}{0:02x}'.format(bw), (x, y)) self.img = self.create_image(0, 0, anchor=tk.NW, image=icon) self.icon = icon self.state = item.inventory def _scale_factors() -> (int, int): ''' Calculate up- and downscale factor. Returns: int: upscale factor int: downscale factor ''' scaling = CONFIG['icon_size'] for up in range(1, 1000): if not (scaling * up) % 1: upscale = int(scaling * up) downscale = up break else: CONFIG.set('icon_size', 1) assert False return upscale, downscale def start(worldtracker) -> ItemWindow: ''' Initialise item tracker window. Args: worldtracker: world state tracker ''' return ItemWindow(items.ItemTracker(worldtracker))
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/items.py
items.py
import importlib import math import os import re import threading import tkinter as tk import tkinter.filedialog as filedialog import tkinter.messagebox as tkmbox import tkinter.ttk as ttk import typing from .. import autotracker from ..config import CONFIGDIRECTORY, CONFIG common = importlib.import_module( '..gui-common.interface', package=__package__) from .. import update from .. import version from . import config from . import dark from . import dungeons from . import environ from . import help from . import items from . import light from . import misc from . import ttkstyle __all__ = 'GraphicalInterface', class GraphicalInterface(tk.Tk): ''' Main access point for everything GUI related. Instance variables: _gui_root: tkinter framework root object _menu: main menu _buttons: buttons in menu _tracker: world state tracker _windows: collection of child windows ''' def __init__(self): ''' Initialise GUI. ''' super().__init__() self.call('tk', 'scaling', 1) ttkstyle.init() self._init_menu() self._tracker = common.world_tracker() self._windows = {'menu': self} self._restore_windows() self._prepare_windows() self.protocol('WM_DELETE_WINDOW', self.quit) self._start_update_check() self._start_autotracker() def _restore_windows(self) -> None: ''' Restore previously stored window layout. ''' layout = common.load_window_cache() for window in layout: if window not in self._windows and window in environ.WINDOWLIST: self._start_window(window) if window in self._windows: self._windows[window].geometry( '+{0:d}+{1:d}'.format(*layout[window])) def _start_window(self, identifier: str) -> None: ''' Initialise a window. Args: identifier: name of window to open ''' if identifier == 'quit': self.quit() return if identifier == 'reset': self.reset() return if identifier == 'save': self.save() return if identifier == 'load': self.load() return if identifier in self._windows: self._windows[identifier].deiconify() return self._windows[identifier] = globals()[identifier].start(self._tracker) if identifier == 'config': self._windows[identifier].dungeondisplay = self._windows['dungeons'] self._windows[identifier].protocol( 'WM_DELETE_WINDOW', self._windows[identifier].withdraw) def run(self) -> None: ''' Run main GUI loop. ''' self.mainloop() def quit(self) -> None: ''' Quit program. ''' autotracker.STOP.set() common.save_window_cache(self._window_layout()) for window in self._windows: if window != 'menu': self._windows[window].withdraw() self._menu.quit() def _prepare_windows(self) -> None: ''' Preload windows without displaying them. I don't really want to deal with the hassle of non-existing windows/trackers, so I do this. ''' prepwindows = [] for window in environ.WINDOWLIST: if window not in self._windows: prepwindows.append(window) for window in prepwindows: self._start_window(window) for window in prepwindows: self._windows[window].withdraw() def _open_window(self, window: str) -> None: ''' Open a window. Args: window: name of existing window object creator: window creation routine ''' try: self._windows[window].deiconify() except (AttributeError, tk.TclError): self._start_window(window) self._windows[window].protocol( 'WM_DELETE_WINDOW', self._windows[window].withdraw) def _window_layout(self) -> dict: ''' Return current position of all windows. Returns: dict: {window name: (x, y)} ''' layout = {} for window in self._windows: if self._windows[window].state() == 'withdrawn': continue try: self._windows[window].deiconify() except (AttributeError, tk.TclError): continue layout[window] = tuple( int(c) for c in re.match( '(\d+)x(\d+)\+-?(\d+)\+-?(\d+)', self._windows[window].geometry()).groups()[2:]) return layout def _init_menu(self) -> None: ''' Create menu buttons. ''' self.title('z3-tracker') self._menu = ttk.Frame(self) self._menu.grid(column=0, row=0, sticky=misc.A) self._buttons = { 'items': self._make_button('items', (0, 0), 'Items'), 'dungeons': self._make_button('dungeons', (1, 0), 'Dungeons'), 'light': self._make_button('light', (0, 1), 'Light World'), 'dark': self._make_button('dark', (1, 1), 'Dark World'), 'config': self._make_button('config', (0, 3), 'Settings'), 'help': self._make_button('help', (1, 3), 'Help'), 'save': self._make_button('save', (0, 4), 'Save'), 'load': self._make_button('load', (1, 4), 'Load'), 'reset': self._make_button('reset', (0, 5), 'Reset'), 'quit': self._make_button('quit', (1, 5), 'Quit'), } def _make_button( self, identifier: str, loc: typing.Sequence[int], text: str or tk.StringVar) -> ttk.Button: ''' Shortcut to place buttons. Args: identifier: name of button loc: (column, row) of button on 2D grid text: text to display on button Returns: ttk.Button: created button ''' button = ttk.Button( self._menu, command=lambda: self._start_window(identifier)) if isinstance(text, tk.StringVar): button.configure(textvariable=text) else: assert isinstance(text, str) button.configure(text=text) button.grid(column=loc[0], row=loc[1], sticky=tk.N+tk.W+tk.E) return button def reset(self) -> None: ''' Reset tracker windows. ''' check = tkmbox.askokcancel( 'Reset', 'This will delete all stored progress.', default=tkmbox.CANCEL, icon=tkmbox.WARNING) if not check: return for window in self._windows: if window not in ('menu', 'config'): self._windows[window].reset() try: os.remove(os.path.join(CONFIGDIRECTORY, CONFIG['autosave'])) except FileNotFoundError: pass def save(self) -> None: ''' Save tracker state to file. ''' savefile = filedialog.asksaveasfilename( defaultextension='.json', filetypes=(('JSON', '*.json'),), parent=self, title='Save to file') if not savefile: return with open( os.path.join(CONFIGDIRECTORY, CONFIG['autosave']), 'r') as src: with open(savefile, 'w') as dst: dst.write(src.read()) def load(self) -> None: ''' Load save file. ''' loadfile = filedialog.askopenfilename( defaultextension='.json', filetypes=(('JSON', '*.json'),), parent=self, title='Load file') if not loadfile: return with open( os.path.join(CONFIGDIRECTORY, CONFIG['autosave']), 'w') as dst: with open(loadfile, 'r') as src: dst.write(src.read()) tkmbox.showinfo('Load file', 'Please restart z3-tracker.') self.quit() def _start_update_check(self) -> None: ''' Initiate update check. ''' check = threading.Thread( target=self._update_check, name='Update checker', daemon=True) check.start() def _start_autotracker(self) -> None: ''' Initiate autotracker. ''' autotracker.INTERFACES['items'] = self._windows['items'] infostring = tk.StringVar() atframe = ttk.LabelFrame(self, text='Autotracker') atframe.grid(column=0, row=2, sticky=misc.A) infotext = ttk.Label( atframe, textvariable=infostring, wraplength='{0:d}mm'.format( math.floor(55 * CONFIG['font_size'] / 16 + 5))) infotext.grid(column=0, row=0, sticky=misc.A) refresh = threading.Event() atframe.refreshbutton = ttk.Button( atframe, command=refresh.set, text='Refresh') atframe.refreshbutton.grid(column=0, row=1, sticky=tk.W+tk.E+tk.S) atframe.grid_remove() autotracker.register_gui(infostring, atframe, infotext, refresh) at = threading.Thread( target=autotracker.thread, name='Autotracker', kwargs={'windows': {'item': self._windows['items']}}) at.start() def _update_check(self) -> None: ''' Check for updates. ''' update_available = update.check_update_availability() if update_available: update_text='''Update available: - current: {0:s} - newest: {1:s}'''.format(version.__version__, update_available) update_frame = ttk.Frame(self) update_frame.grid(column=0, row=1, sticky=misc.A) update_label = ttk.Label( update_frame, text=update_text) update_label.grid(sticky=misc.A)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/interface.py
interface.py
import importlib import tkinter as tk import tkinter.ttk as ttk import typing from ..config import CONFIG from ..config.images import image, makebw from .. import dungeons common = importlib.import_module( '..gui-common.dungeons', package=__package__) BACKGROUND = CONFIG['background'] FOREGROUND = CONFIG['foreground'] REWARDS = common.REWARDS from .config import FATFONT from . import misc __all__ = 'DungeonWindow', class DungeonWindow(tk.Toplevel): ''' Dungeon check display. Instance variables: tracker: dungeon tracker object layout: dungeon layout in display helpertext: helper text variable scaling: up- and downscale factors for objects widgets: single dungeon button collections ''' def __init__(self, tracker): ''' Args: tracker: dungeon tracker object ''' super().__init__() self.title('Dungeons') self.tracker = tracker self.frame = ttk.Frame(self, style='themed.TFrame') self.frame.pack(side='top', fill='both', expand=True) self.bottomframe = ttk.Frame(self, style='themed.TFrame') self.bottomframe.pack(side='top', fill='x', expand=True) self.helperframe = ttk.Frame(self.bottomframe, style='themed.TFrame') self.helperframe.pack(side='left', fill='x', expand=True) self.helpertext = tk.StringVar() self.helper = ttk.Label( self.helperframe, anchor=tk.CENTER, style='themed.TLabel', textvariable=self.helpertext) self.helper.pack(side='left', fill='x', expand=True) self.scaling = _scale_factors() scale = self.scaling[0] / self.scaling[1] _icon_scale = lambda icon: icon.zoom( self.scaling[0], self.scaling[0]).subsample( self.scaling[1], self.scaling[1]) self.ganoncrystals = { 'icon': _icon_scale( tk.PhotoImage( file=image('ganonstower'), master=self.bottomframe)).subsample(2, 2), 'canvas': tk.Canvas( self.bottomframe, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=48 * scale), 'count': -1} self.ganoncrystals['image'] = self.ganoncrystals['canvas'].create_image( 0, 0, anchor=tk.NW, image=self.ganoncrystals['icon']) self.ganoncrystals['text'] = self.ganoncrystals['canvas'].create_text( 48 * scale, 32 * scale, anchor=tk.SE, text='?') self.ganoncrystals['canvas'].bind( '<Enter>', lambda _: self.helpertext.set("Ganon's Pyramid Access")) self.ganoncrystals['canvas'].bind( '<Leave>', lambda _: self.helpertext.set('')) self.ganoncrystals['canvas'].bind( '<ButtonRelease-1>', lambda _: self.set_crystal('ganon', +1)) self.ganoncrystals['canvas'].bind( '<ButtonRelease-3>', lambda _: self.set_crystal('ganon', -1)) self.ganoncrystals['canvas'].pack(side='right') self.set_crystal('ganon', 0) self.crystalspacer = ttk.Label( self.bottomframe, style='themed.TLabel', width=-2) self.crystalspacer.pack(side='right') self.towercrystals = { 'icon': _icon_scale( tk.PhotoImage( file=image('reward-crystal'), master=self.bottomframe)), 'canvas': tk.Canvas( self.bottomframe, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=48 * scale), 'count': -1} self.towercrystals['image'] = self.towercrystals['canvas'].create_image( 0, 0, anchor=tk.NW, image=self.towercrystals['icon']) self.towercrystals['text'] = self.towercrystals['canvas'].create_text( 48 * scale, 32 * scale, anchor=tk.SE, text='?') self.towercrystals['canvas'].bind( '<Enter>', lambda _: self.helpertext.set("Ganon's Tower Access")) self.towercrystals['canvas'].bind( '<Leave>', lambda _: self.helpertext.set('')) self.towercrystals['canvas'].bind( '<ButtonRelease-1>', lambda _: self.set_crystal('tower', +1)) self.towercrystals['canvas'].bind( '<ButtonRelease-3>', lambda _: self.set_crystal('tower', -1)) self.towercrystals['canvas'].pack(side='right') self.set_crystal('tower', 0) buttonstyle = ttk.Style() buttonstyle.configure('Dungeonbutton.TButton', relief=tk.FLAT) self.widgets = [] self.redraw() def _dungeon_display(self, dungeon) -> None: ''' Make and place single dungeons display object. Args: dungeon: dungeon object Writes: buttons ''' widget = Dungeon(dungeon, self.frame, self.scaling) widget.bind( '<Enter>', lambda _: self.helpertext.set(self._namestring(dungeon))) widget.bind( '<Leave>', lambda _: self.helpertext.set('')) for button in widget.buttons: button.bind('<ButtonRelease-1>', self.tracker.save, add='+') button.bind('<ButtonRelease-3>', self.tracker.save, add='+') button.bind( '<ButtonRelease-1>', lambda _: widget.check_state(dungeon), add='+') button.bind( '<ButtonRelease-3>', lambda _: widget.check_state(dungeon), add='+') widget.grid( column=dungeon.location[0], row=dungeon.location[1], sticky=misc.A) self.widgets.append(widget) def _namestring(self, dungeon) -> str: ''' Return helper string. Args: dungeon: dungeon object Returns: str: string to display on GUI ''' return '{0:s} ({1:s})'.format( dungeon.identifier, dungeon.idstr) def reset(self) -> None: ''' Reset dungeons to default. ''' for cobj in ('tower', 'ganon'): self.set_crystal(cobj, None) self.tracker.reset() self.redraw() def redraw(self) -> None: ''' Recreate dungeon display. ''' while self.widgets: self.widgets.pop().destroy() for dungeon in self.tracker: self._dungeon_display(self.tracker[dungeon]) def set_crystal(self, ctype: str, diff: int) -> None: ''' Set crystal requirements. Args: ctype: 'tower' or 'crystal' diff: -1, 0, +1 or None (for reset) ''' assert ctype in ('tower', 'ganon') assert diff in (-1, 0, +1, None) scale = self.scaling[0] / self.scaling[1] cobj = self.towercrystals if ctype == 'tower' else self.ganoncrystals cobj['count'] = self.tracker.set_crystal(ctype, diff) if cobj['count'] == -1: newtext = '?' else: newtext = str(cobj['count']) cobj['canvas'].delete(cobj['text']) cobj['text'] = cobj['canvas'].create_text( 48 * scale, 32 * scale, anchor=tk.SE, fill=FOREGROUND, font=FATFONT, text=newtext) class Dungeon(ttk.Frame): ''' Single dungeon display object. ''' def __init__( self, dungeon, parent: ttk.Frame, scaling: (int, int)): ''' dungeon: dungeon object parent: parent widget for object scaling: button scale ''' self.scaling = scaling scale = scaling[0] / scaling[1] super().__init__( parent, borderwidth=2, relief=tk.RIDGE, style='themed.TFrame') self.child = ttk.Label(self, style='themed.TLabel') self.child.grid(column=0, row=0, sticky=misc.A) icon = self._icon_scale( tk.PhotoImage(file=dungeon.icon, master=parent) if dungeon.icon else None) self.pic = ttk.Label( self.child, borderwidth=1, image=icon, relief=tk.RAISED, style='themed.TLabel') self.pic.grid(column=0, row=0, columnspan=2, rowspan=2) self.icon = icon self.rewardname = dungeon.get('reward') self.rewardimg = REWARDS[self.rewardname] self.rewardicon = self._icon_scale( tk.PhotoImage(file=image(self.rewardimg), master=self)) self.reward = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=32 * scale) if 'reward' in dungeon.features: self.rewardid = self.reward.create_image( 0, 0, anchor=tk.NW, image=self.rewardicon) self.reward.bind( '<ButtonRelease-1>', lambda _: dungeon.cycle_reward(True)) self.reward.bind( '<ButtonRelease-3>', lambda _: dungeon.cycle_reward(False)) self.reward.grid(column=2, row=0) self.complete = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=32 * scale) self.complete.create_rectangle( 4 * scale + 1, 4 * scale + 1, int(32 * scale) - 5, int(32 * scale) - 5, outline=FOREGROUND, width=int(round(4 * scale))) self.completeid = None self.complete.bind( '<ButtonRelease-1>', lambda _: dungeon.mark_complete(True)) self.complete.bind( '<ButtonRelease-3>', lambda _: dungeon.mark_complete(False)) self.complete.grid(column=2, row=1) self.medallionname = dungeon.medallion self.medallionicon = self._icon_scale( tk.PhotoImage( file=image('medallion-{0:s}'.format(self.medallionname)), master=self)) self.medallion = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=32 * scale) if 'medallion' in dungeon.features: self.medallionid = self.medallion.create_image( 0, 0, anchor=tk.NW, image=self.medallionicon) self.medallion.bind( '<ButtonRelease-1>', lambda _: dungeon.cycle_medallion(True)) self.medallion.bind( '<ButtonRelease-3>', lambda _: dungeon.cycle_medallion(False)) self.medallion.grid(column=3, row=0) self.bigkeyicon = self._icon_scale( tk.PhotoImage(file=image('bigkey'), master=parent)) self.bigkey = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=32 * scale) if ('bigkey' in dungeon.features and ( CONFIG['dungeon_items'] == 'Keysanity' or ( CONFIG['dungeon_items'] == 'Custom' and CONFIG['shuffle_bigkey']))): self.bigkeyid = self.bigkey.create_image( 0, 0, anchor=tk.NW, image=self.bigkeyicon) self.bigkey.bind('<ButtonRelease-1>', dungeon.toggle_bigkey) self.bigkey.bind('<ButtonRelease-3>', dungeon.toggle_bigkey) self.bigkey.grid(column=3, row=1, sticky=tk.E) self.keyicon = self._icon_scale( tk.PhotoImage(file=image('smallkey'), master=parent)) self.key = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=48 * scale) if (dungeon.totalkeys > 0 and ( CONFIG['dungeon_items'] in ( 'Maps/Compasses/Small Keys', 'Keysanity') or ( CONFIG['dungeon_items'] == 'Custom' and CONFIG['shuffle_smallkey'])) and CONFIG['world_state'] != 'Retro'): self.keyimg = self.key.create_image( 0, 0, anchor=tk.NW, image=self.keyicon) self.keytext = self.key.create_text( 48 * scale, 32 * scale, anchor=tk.SE, text='0') self.key.bind('<ButtonRelease-1>', dungeon.key_up) self.key.bind('<ButtonRelease-3>', dungeon.key_down) self.key.grid(column=4, columnspan=2, row=0) self.itemicon = self._icon_scale( tk.PhotoImage(file=image('chest_full'), master=parent)) self.item = tk.Canvas( self.child, background=BACKGROUND, height=32 * scale, highlightbackground=BACKGROUND, width=48 * scale) if dungeon.total_items() > 0: self.itemimg = self.item.create_image( 0, 0, anchor=tk.NW, image=self.itemicon) self.itemtext = self.item.create_text( 48 * scale, 32 * scale, anchor=tk.SE, text='0') self.item.bind('<ButtonRelease-1>', dungeon.item_up) self.item.bind('<ButtonRelease-3>', dungeon.item_down) if (CONFIG['dungeon_items'] in ( 'Maps/Compasses/Small Keys', 'Keysanity') or ( CONFIG['dungeon_items'] == 'Custom' and ( CONFIG['shuffle_smallkey'] or CONFIG['shuffle_bigkey']))): self.item.grid(column=4, columnspan=2, row=1) else: self.item.grid(column=3, columnspan=2, row=1) self.buttons = ( self.reward, self.complete, self.medallion, self.bigkey, self.key, self.item) self.check_state(dungeon) def check_state(self, dungeon) -> None: ''' Check button state and make adjustments if necessary. Args: dungeon: dungeon object ''' # Check whether reward image needs to be changed. if self.rewardname != dungeon.reward: self.rewardname = dungeon.reward self.rewardimg = REWARDS[dungeon.reward] self.rewardicon = self._icon_scale( tk.PhotoImage(file=image(self.rewardimg), master=self)) self.reward.delete(self.rewardid) self.rewardid = self.reward.create_image( 0, 0, anchor=tk.NW, image=self.rewardicon) # Check completion. icon = self._icon_scale(tk.PhotoImage(file=dungeon.icon, master=self)) if dungeon.completed: icon = makebw(icon) if dungeon.completed and self.completeid is None: self.completeid = self.complete.create_text( int(32 * self.scaling[0] / self.scaling[1] / 2), int(32 * self.scaling[0] / self.scaling[1] / 2), anchor=tk.CENTER, fill=FOREGROUND, font=(FATFONT[0], int(round(20 * self.scaling[0] / self.scaling[1]))), text='✔') elif not dungeon.completed and self.completeid is not None: self.complete.delete(self.completeid) self.completeid = None self.pic = ttk.Label( self.child, borderwidth=1, image=icon, relief=tk.RAISED, style='themed.TLabel') self.pic.grid(column=0, row=0, columnspan=2, rowspan=2) self.icon = icon # Check whether medallion image needs to be changed. if self.medallionname != dungeon.medallion: self.medallionname = dungeon.medallion self.medallionicon = self._icon_scale( tk.PhotoImage( file=image('medallion-{0:s}'.format(self.medallionname)), master=self)) self.medallion.delete(self.medallionid) self.medallionid - self.medallion.create_image( 0, 0, anchor=tk.NW, image=self.medallionicon) # Check whether the bigkey button should be disabled. try: self.bigkey.delete(self.bigkeyid) except AttributeError: pass else: self.bigkeyicon = self._icon_scale( tk.PhotoImage(file=image('bigkey'), master=self)) if not dungeon.bigkey: self.bigkeyicon = makebw(self.bigkeyicon) self.bigkey.create_image( 0, 0, anchor=tk.NW, image=self.bigkeyicon) # Check numbers (small keys). scale = self.scaling[0] / self.scaling[1] try: self.key.delete(self.keytext) except AttributeError: pass else: self.keytext = self.key.create_text( 48 * scale, 32 * scale, anchor=tk.SE, fill=FOREGROUND, font=FATFONT, text=str(dungeon.smallkeys)) # Check numbers (items). try: self.item.delete(self.itemtext) except AttributeError: pass else: itemfont = ( (FATFONT[0], int(FATFONT[1] / 2)) if dungeon.remaining() > 9 else FATFONT) self.itemtext = self.item.create_text( 48 * scale, 32 * scale, anchor=tk.SE, fill=FOREGROUND, font=itemfont, text=str(dungeon.remaining())) newchest = ( 'chest_full' if dungeon.remaining() > 0 else 'chest_empty') self.itemicon = self._icon_scale( tk.PhotoImage(file=image(newchest), master=self)) self.item.delete(self.itemimg) self.itemimg = self.item.create_image( 0, 0, anchor=tk.NW, image=self.itemicon) def _icon_scale(self, icon: tk.PhotoImage) -> tk.PhotoImage: ''' Rescale icon. Args: icon: icon to be rescaled Returns: tk.PhotoImage: rescaled icon ''' if self.scaling[0] != 1: icon = icon.zoom(self.scaling[0], self.scaling[0]) if self.scaling[1] != 1: icon = icon.subsample(self.scaling[1], self.scaling[1]) return icon def _scale_factors() -> (int, int): ''' Calculate up- and downscale factor. Returns: int: upscale factor int: downscale factor ''' scaling = CONFIG['icon_size'] for up in range(1, 1000): if not (scaling * up) % 1: upscale = int(scaling * up) downscale = up break else: CONFIG.set('icon_size', 1) assert False return upscale, downscale def start(worldtracker) -> DungeonWindow: ''' Initialise dungeon tracker window. Args: worldtracker: world state tracker ''' return DungeonWindow(dungeons.DungeonTracker(worldtracker))
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/dungeons.py
dungeons.py
import importlib import tkinter as tk import tkinter.ttk as ttk from ..config import CONFIG common = importlib.import_module( '..gui-common.maps', package=__package__) BUTTONTYPE = common.BUTTONTYPE from .maps import make_symbol_coordinates from . import misc __all__ = 'HelpWindow', class HelpWindow(tk.Toplevel): ''' Help window ''' def __init__(self): super().__init__() self.title('Help') self.frame = ttk.Frame(self) self.frame.grid(sticky=misc.A) self.widgets = [] self.leftframe = ttk.Frame(self) self.leftframe.grid(column=0, row=0, sticky=misc.A) self.middleframe = ttk.Frame(self) self.middleframe.grid(column=1, row=0, sticky=misc.A) self.rightframe = ttk.Frame(self) self.rightframe.grid(column=2, row=0, sticky=misc.A) self._item_buttons() self._dungeon_buttons() self._entrance_buttons() self._map_control() self._retro_mode() def _item_buttons(self) -> None: ''' Item colours ''' widget = ttk.LabelFrame(self.leftframe, text='Item locations') widget.grid(column=0, row=0, sticky=tk.N+tk.E+tk.W) shape = -7, -7, 7, 7 loc = make_symbol_coordinates((16, 16), shape, 1) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=0, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE['standard']['colours']['available']['active'], fill=BUTTONTYPE['standard']['colours']['available']['normal']) text = ttk.Label(widget, text='Available') text.grid(column=1, row=0, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=1, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE['standard']['colours']['indirect']['active'], fill=BUTTONTYPE['standard']['colours']['indirect']['normal']) text = ttk.Label( widget, text='Available, requires finishing dungeon(s)') text.grid(column=1, row=1, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=2, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE['standard']['colours']['maybe']['active'], fill=BUTTONTYPE['standard']['colours']['maybe']['normal']) text = ttk.Label(widget, text='Possibly available') text.grid(column=1, row=2, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=3, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE['standard']['colours']['checked']['active'], fill=BUTTONTYPE['standard']['colours']['checked']['normal']) text = ttk.Label(widget, text='Already checked') text.grid(column=1, row=3, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=4, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE[ 'standard']['colours']['unavailable']['active'], fill=BUTTONTYPE['standard']['colours']['unavailable']['normal']) text = ttk.Label(widget, text='Unavailable') text.grid(column=1, row=4, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=5, sticky=misc.A) button = canvas.create_oval(*loc) canvas.itemconfigure( button, activefill=BUTTONTYPE['standard']['colours']['visible']['active'], fill=BUTTONTYPE['standard']['colours']['visible']['normal']) text = ttk.Label(widget, text='Unavailable, but visible') text.grid(column=1, row=5, sticky=tk.W) self.widgets.extend((canvas, widget)) def _dungeon_buttons(self) -> None: ''' Dungeon colours ''' widget = ttk.LabelFrame(self.leftframe, text='Dungeon locations') widget.grid(column=0, row=1, sticky=tk.N+tk.E+tk.W) shape = -13, -13, 13, 13 loc = make_symbol_coordinates((16, 16), shape, 1) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=0, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['normal']) text = ttk.Label(widget, text='Entirely available') text.grid(column=1, row=0, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=1, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['indirect']['normal']) text = ttk.Label( widget, text='Available, requires finishing dungeon(s)') text.grid(column=1, row=1, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=2, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['maybe']['normal']) text = ttk.Label(widget, text='Available if accessible') text.grid(column=1, row=2, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=3, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['checked']['normal']) text = ttk.Label(widget, text='Fully checked') text.grid(column=1, row=3, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=4, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['unavailable']['normal']) text = ttk.Label(widget, text='All unavailable') text.grid(column=1, row=4, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=5, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['visible']['normal']) text = ttk.Label(widget, text='Possibly or partially available') text.grid(column=1, row=5, sticky=tk.W) self.widgets.extend((canvas, widget)) def _entrance_buttons(self): ''' Entrance button colours ''' widget = ttk.LabelFrame(self.middleframe, text='Entrances') widget.grid(column=0, row=0, sticky=tk.N) shape = -5, -5, 5, 5 loc = make_symbol_coordinates((16, 16), shape, 1) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=0, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='white', width=3) text = ttk.Label(widget, text='Entrance leads to default location') text.grid(column=1, row=0, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=1, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='red', width=3) text = ttk.Label(widget, text='Selected entrance leads here') text.grid(column=1, row=1, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=2, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='yellow', width=3) text = ttk.Label( widget, text='This entrance leads to selected location') text.grid(column=1, row=2, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=3, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='orange', width=3) text = ttk.Label( widget, text='Entrances are switched between this and selected location') text.grid(column=1, row=3, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=4, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='blue', width=3) text = ttk.Label( widget, text='This exit can be reached from selected entrance.') text.grid(column=1, row=4, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=5, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='magenta', width=3) text = ttk.Label( widget, text='Combination of red and blue.') text.grid(column=1, row=5, sticky=tk.W) self.widgets.extend((canvas, widget)) canvas = tk.Canvas(widget, height=32, width=32) canvas.grid(column=0, row=6, sticky=misc.A) button = canvas.create_rectangle(*loc) canvas.itemconfigure( button, fill=BUTTONTYPE['standard']['colours']['available']['active'], outline='cyan', width=3) text = ttk.Label( widget, text='Combination of yellow and blue.') text.grid(column=1, row=6, sticky=tk.W) self.widgets.extend((canvas, widget)) def _map_control(self) -> None: ''' Map controls ''' widget = ttk.LabelFrame(self.rightframe, text='Entrance map control') widget.grid(column=0, row=0, sticky=tk.N) button = ttk.Label(widget, text='Left-click:') button.grid(column=0, row=0, sticky=misc.A) spacer = ttk.Label(widget, width=1) spacer.grid(column=1, row=0, sticky=misc.A) text = ttk.Label(widget, text='Mark and unmark locations as checked') text.grid(column=2, row=0, sticky=tk.W) button = ttk.Label(widget, text='Middle-click:') button.grid(column=0, row=1, sticky=misc.A) spacer = ttk.Label(widget, width=1) spacer.grid(column=1, row=1, sticky=misc.A) text = ttk.Label(widget, text='Link entrances') text.grid(column=2, row=1, sticky=tk.W) button = ttk.Label(widget, text='Right-click:') button.grid(column=0, row=2, sticky=misc.A) spacer = ttk.Label(widget, width=1) spacer.grid(column=1, row=2, sticky=misc.A) text = ttk.Label(widget, text='Abort linking or unlink location') text.grid(column=2, row=2, sticky=tk.W) def _retro_mode(self) -> None: ''' Retro mode shortcut. ''' widget = ttk.LabelFrame(self.rightframe, text='Retro mode') widget.grid(column=0, row=1, sticky=tk.N+tk.E+tk.W) button = ttk.Label(widget, text='R-key:') button.grid(column=0, row=0, sticky=misc.A) spacer = ttk.Label(widget, width=1) spacer.grid(column=1, row=0, sticky=misc.A) text = ttk.Label( widget, text='Mark take-any caves and shops as checked') text.grid(column=2, row=0, sticky=tk.W) def reset(self) -> None: ''' Dummy method ''' pass def start(*args) -> tk.Toplevel: ''' Open help window. Returns: tk.Toplevel: help window ''' return HelpWindow()
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/gui-tkinter/help.py
help.py
import configparser import importlib import os.path import json from ..config.images import image layoutstorage = importlib.import_module( '..gui-common.items', package=__package__) from .itemobj import ItemObj from .lists import ITEMS from . import storage __all__ = 'ItemTracker', def get_layout() -> dict: ''' Load (or create) item layout. Returns: dict: item layout in format {identifier: (column, row)} ''' try: layout = layoutstorage.load_items() except (layoutstorage.NoConfig, configparser.Error): layout = {} for item in ITEMS: layout[item[0]] = item[1] layoutstorage.new_item(layout) layout = layoutstorage.load_items() return layout class ItemTracker(dict): ''' Inventory item tracker. ''' def __init__(self, worldtracker): ''' Args: worldtracker: world state tracker ''' layout = get_layout() super().__init__() delayed_link = [] for rawitem in ITEMS: item = ItemObj( rawitem[0], rawitem[1], rawitem[2], tuple(rawitem[4].keys()), tuple(rawitem[4].values()), rawitem[3], rawitem[5]['links'] if 'links' in rawitem[5] else {}, rawitem[5]['default'] if 'default' in rawitem[5] else 0, worldtracker) try: item.location = layout[item.identifier.lower()] except KeyError: pass self[item.identifier] = item for item in self: for linkitem in self[item].link: self[item].linkitems[linkitem] = self[linkitem] data = storage.load_items() self.restore(data) def reset(self) -> None: ''' Reset all items. ''' for item in self: self[item].reset() def save(self) -> dict: ''' Save current item setup. ''' storage.store_items(self.store()) def store(self) -> dict: ''' Return current item setup info for storage. Returns: inventory: item setup info ''' inventory = {} for item in self: inventory[item] = self[item].inventory return inventory def restore(self, inventory) -> None: ''' Restore current item setup from file. Args: inventory: information from file ''' for item in inventory: if item in self: self[item].restore_inventory(inventory[item])
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/items/items.py
items.py
import json import os.path import threading from ..config import CONFIG, CONFIGDIRECTORY from ..version import __version__ as version DATALOCK = threading.RLock() __all__ = ( 'load_items', 'load_dungeons', 'load_locations', 'load_entrances' 'store_items', 'store_dungeons', 'store_locations','store_entrances') def load_items() -> dict: ''' Load item tracker data from save file. Returns: dict: save data ''' try: ret = _load_save()['Items'] except KeyError: ret = {} return ret def load_dungeons() -> dict: ''' Load dungeon tracker data from save file. Returns: dict: save data ''' try: ret = _load_save()['Dungeons'] except KeyError: ret = {} return ret def load_locations() -> dict: ''' Load location tracker data from save file. Returns: dict: save data ''' try: ret = _load_save()['Locations'] except KeyError: ret = {} return ret def load_entrances() -> dict: ''' Load entrance tracker data from save file. Returns: dict: save data ''' try: ret = _load_save()['Entrances'] except KeyError: ret = {} return ret def _load_save() -> dict: ''' Load save file. Return: dict: save data ''' with DATALOCK: try: fid = open(os.path.join(CONFIGDIRECTORY, CONFIG['autosave']), 'r') except FileNotFoundError: return {} try: data = json.load(fid) except json.JSONDecodeError: return {} finally: fid.close() if data['version'] != version: return {} return data def store_items(data: dict) -> None: ''' Store item tracker state. Args: data: save data ''' _store_save({'Items': data}) def store_dungeons(data: dict) -> None: ''' Store dungeon tracker state. Args: data: save data ''' _store_save({'Dungeons': data}) def store_locations(data: dict) -> None: ''' Store location tracker state. Args: data: save data ''' _store_save({'Locations': data}) def store_entrances(data: dict) -> None: ''' Store location tracker state. Args: data: save data ''' _store_save({'Entrances': data}) def _store_save(data: dict) -> None: ''' Write save file. Args: data: save data ''' with DATALOCK: savedata = _load_save() for dtype in data: savedata[dtype] = data[dtype] savedata['version'] = version with open( os.path.join(CONFIGDIRECTORY, CONFIG['autosave']), 'w') as fid: json.dump(savedata, fid)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/items/storage.py
storage.py
import operator import os.path import typing from ..config.images import image __all__ = 'ItemObj', class ItemObj(object): ''' Inventory item Progressive items are listed as one. Instance variables: identifier: item identifier string location: (column, row) location on display length: number of item progressions displayname: name(s) displayed in UI icon: path to image file(s) associated with item disabled: black&white conversion link: items (and requirement) linked with this item linkitems: item objects linked to this item default: default numer of items in inventory inventory: current number of items in inventory tracker: world state tracker ''' def __init__(self, identifier: str, location: typing.Sequence[int], length: int, displayname: typing.Sequence[str], icon: typing.Sequence[str], disabled: typing.Sequence[int], links: typing.Mapping[str, typing.Sequence[int]], default: int, tracker): ''' Args: identifier: internal item name location: (row, column) of item on tracker GUI length: number of progressions in item displayname: name(s) of item displayed on tracker GUI icon: icon(s) used on tracker GUI disabled: black&white conversion links: items linked with posession of item default: initial item progression tracker: world state tracker ''' self.identifier = identifier self.location = location self.length = length self.displayname = displayname self.icon = tuple(image(i) for i in icon) self.disabled = disabled self.link = links self.linkitems = {} self.default = default self.inventory = default self.tracker = tracker self.restore_inventory(self.default) def index(self) -> int: ''' Return current displayname/image index. Returns: int: index used for sequence attributes ''' idx = self.inventory if self.inventory < 1 else self.inventory - 1 return idx def display(self) -> str: ''' Return currently applicable item display string. Returns: str: name to be displayed in application ''' idx = self.index() item_name = self.displayname[idx] return item_name def state(self) -> bool: ''' Return current state of item. Returns: str: True if item is active, else False ''' return self.inventory > 0 def increase(self, *args) -> None: ''' Left-click on item ''' if self.inventory < self.length: self.inventory += 1 self.update_links() self.tracker.set_item(self.identifier, self.inventory) def decrease(self, *args) -> None: ''' Right-click on item ''' if self.inventory > 0: self.inventory -= 1 self.update_links() self.tracker.set_item(self.identifier, self.inventory) def reset(self) -> None: ''' Reset item. ''' to_remove = self.inventory - self.default if to_remove > 0: for _ in range(to_remove): self.decrease(_) elif to_remove < 0: for _ in range(-to_remove): self.increase(_) def restore_inventory(self, quantity: int) -> None: ''' Set inventory number. Args: quantity: number to set inventory to ''' self.inventory = quantity self.update_links() self.tracker.set_item(self.identifier, quantity) def add_links(linkitems: typing.Sequence) -> None: ''' Register linked items. Args: linkitems: list of item objects ''' for li in linkitems: self.linkitems[li.identifier] = li def update_links(self) -> None: ''' Update state of linked items according to current inventory. ''' for li in self.linkitems: if self.inventory in self.link[li]: self.linkitems[li].restore_inventory(1) else: self.linkitems[li].restore_inventory(0)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/items/itemobj.py
itemobj.py
__all__ = 'ITEMS', ITEMS = ( ('bow', (0, 0), 2, (6, 5), {'Bow and Arrows': 'bow', 'Bow and Silver Arrows': 'bowandsilvers'}, {'links': {'silverarrows': (2,)}}), ('silverarrows', (), 1, (6, 4), {}, {}), ('boomerang', (0, 1), 3, (6, 4), {'Boomerang': 'blueboomerang', 'Magical Boomerang': 'redboomerang', 'Boomerangs': 'bothboomerangs'}, {'links': {'blueboomerang': (1, 3), 'redboomerang': (2, 3)}}), ('blueboomerang', (), 1, (6, 4), {}, {}), ('redboomerang', (), 1, (6, 4), {}, {}), ('hookshot', (0, 2), 1, (6, 6), {'Hookshot': 'hookshot'}, {}), ('bombs', (0, 3), 1, (6, 4), {'Bombs': 'bombs'}, {'default': 1}), ('mushroompowder', (0, 4), 3, (6, 4), {'Mushroom': 'mushroom', 'Magic Powder': 'powder', 'Mushroom/Magic Powder': 'mushroompowder'}, {'links': {'mushroom': (1, 3), 'powder': (2, 3)}}), ('mushroom', (), 1, (6, 4), {}, {}), ('powder', (), 1, (6, 4), {}, {}), ('firerod', (1, 0), 1, (6, 6), {'Fire Rod': 'firerod'}, {}), ('icerod', (1, 1), 1, (6, 6), {'Ice Rod': 'icerod'}, {}), ('bombos', (1, 2), 1, (6, 4), {'Bombos Medallion': 'bombos'}, {}), ('ether', (1, 3), 1, (6, 4), {'Ether Medallion': 'ether'}, {}), ('quake', (1, 4), 1, (6, 4), {'Quake Medallion': 'quake'}, {}), ('lantern', (2, 0), 1, (6, 6), {'Lantern': 'lantern'}, {}), ('hammer', (2, 1), 1, (6, 5), {'Magic Hammer': 'hammer'}, {}), ('shovelocarina', (2, 2), 3, (6, 5), {'Shovel': 'shovel', 'Ocarina': 'ocarina', 'Shovel/Ocarina': 'shovelocarina'}, {'links': {'shovel': (1, 3), 'ocarina': (2, 3)}}), ('shovel', (), 1, (6, 4), {}, {}), ('ocarina', (), 1, (6, 4), {}, {}), ('bugnet', (2, 3), 1, (6, 5), {'Bug-Catching Net': 'bugnet'}, {}), ('mudora', (2, 4), 1, (6, 6), {'Book of Mudora': 'mudora'}, {}), ('bottle', (3, 0), 1, (6, 8), {'Bottle': 'bottle'}, {}), ('somaria', (3, 1), 1, (6, 6), {'Cane of Somaria': 'somaria'}, {}), ('byrna', (3, 2), 1, (6, 6), {'Cane of Byrna': 'byrna'}, {}), ('cape', (3, 3), 1, (6, 6), {'Magic Cape': 'cape'}, {}), ('mirror', (3, 4), 1, (6, 5), {'Magic Mirror': 'mirror'}, {}), ('sword', (1, 5), 4, (6, 6), {"Fighter's Sword": 'sword0', 'Master Sword': 'sword1', 'Tempered Sword': 'sword2', 'Golden Sword': 'sword3'}, {'links': {'mastersword': (2, 3, 4), 'mastersword2': (3, 4)}}), ('mastersword', (), 1, (6, 4), {}, {}), ('mastersword2', (), 1, (6, 4), {}, {}), ('shield', (2, 5), 3, (6, 4), {"Fighter's Shield": 'shield1', 'Red Shield': 'shield2', 'Mirror Shield': 'shield3'}, {'links': {'mirrorshield': (3,)}}), ('mirrorshield', (), 1, (6, 4), {}, {}), ('armour', (3, 5), 3, (6, 4), {'Green Tunic': 'armour1', 'Blue Mail': 'armour2', 'Red Mail': 'armour3'}, {'default': 1, 'links': {'bluemail': (2, 3), 'redmail': (3,)}}), ('bluemail', (), 1, (6, 4), {}, {}), ('redmail', (), 1, (6, 4), {}, {}), ('pegasus', (4, 1), 1, (6, 6), {'Pegasus Shoes': 'pegasus'}, {}), ('glove', (4, 2), 2, (6, 6), {'Power Gloves': 'glove1', "Titan's Mitts": 'glove2'}, {'links': {'powerglove': (1, 2), 'titansmitts': (2,)}}), ('powerglove', (), 1, (6, 4), {}, {}), ('titansmitts', (), 1, (6, 4), {}, {}), ('flippers', (4, 3), 1, (6, 5), {"Zora's Flippers": 'flippers'}, {}), ('pearl', (4, 4), 1, (6, 4), {'Moon Pearl': 'pearl'}, {}), ('halfmagic', (4, 5), 1, (6, 6), {'Half-Magic': 'halfmagic'}, {}) )
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/items/lists.py
lists.py
import asyncio import importlib import logging as log import queue import threading from ..config import CONFIG from .exceptions import AutotrackerException, NoConnection, ParseError, NoDevice from . import usb2snes gui = importlib.import_module( '..{0:s}.autotracker'.format(CONFIG['gui']), package=__package__) DATA = {'items': queue.Queue()} INTERFACES = {'items': None} STOP = threading.Event() __all__ = 'DATA', 'INTERFACES', 'STOP', 'thread' async def _autotrack(memview: usb2snes.MemoryReader) -> None: ''' Run autotracker routines. Args: memview: console memory reader Raises: AutotrackerException: on connection loss ''' interval = 0 while not STOP.is_set(): # Check for config changes. for _ in range(interval): if not CONFIG['autotracking']: return if CONFIG['usb2snes_device'] not in memview.device: return if STOP.wait(timeout=0.33): return interval = 5 * 3 # Check whether Zelda 3 is running. ingame = await memview.check_game_status() if not ingame: for w in INTERFACES.values(): w.autotrack.set_state('off') continue for w in INTERFACES.values(): w.autotrack.set_state('on') # Check inventory. items = await memview.check_items() if INTERFACES['items'].autotrack.toggle: INTERFACES['items'].set_all(items) async def _main() -> None: ''' Autotracker loop ''' memview = usb2snes.MemoryReader() while not STOP.wait(timeout=0.3): if gui.INFOSTRING is None or gui.INFOTEXT is None or gui.FRAME is None: continue if not CONFIG['autotracking']: for w in INTERFACES.values(): w.autotrack.disable() continue else: for w in INTERFACES.values(): w.autotrack.enable() log.debug('Starting autotracker.') quick_retry = False try: await memview.connect() except (OSError, NoConnection): gui.set_info( "Could not connect to QUsb2snes server '{0:s}'.".format( CONFIG['usb2snes_server']), 'error') except ParseError: gui.set_info("Unexpected message from QUsb2snes server.", 'error') except NoDevice: pass else: gui.set_info( 'Connected to device: {0:s}'.format(memview.device), 'info', refreshbutton=False) for w in INTERFACES.values(): w.autotrack.enable() try: await _autotrack(memview) except AutotrackerException: log.error('Lost connection to QUsb2snes.') gui.set_info('Lost connection to QUsb2snes.', 'error') quick_retry = True else: if STOP.is_set(): log.info('Autotracker stopped.') return log.info( '%s autotracker.', 'Restarting' if CONFIG['autotracking'] else 'Stopping') gui.set_info('') continue finally: await memview.disconnect() for w in INTERFACES.values(): w.autotrack.set_state('error') infotxt = gui.INFOSTRING.get() if infotxt: infotxt += '\n\n' else: infotxt = 'Autotracker: ' counter = 5 if quick_retry else 20 while counter > 0: if not CONFIG['autotracking']: break gui.set_info(infotxt + 'Restarting in {0:d}s.'.format(counter)) subcounter = 0 for _ in range(5): if STOP.wait(timeout=0.2) or gui.REFRESH.is_set(): counter = 0 gui.REFRESH.clear() break counter -= 1 else: if STOP.is_set(): log.info('Autotracker stopped.') return log.debug('Restarting autotracker.') gui.set_info('') continue gui.set_info('') log.info('Autotracker stopped.') def thread(windows: dict) -> None: ''' Autotracker thread Args: windows: tracker windows ''' asyncloop = asyncio.new_event_loop() asyncio.set_event_loop(asyncloop) try: asyncio.run(_main()) except: gui.set_info( 'Autotracker has crashed. Please restart z3-tracker.', 'error') raise
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/autotracker/autotracker.py
autotracker.py
import importlib import json import logging as log import threading import websockets from ..config import CONFIG from . import addresses from .exceptions import AutotrackerException, NoConnection, ParseError, NoDevice from .items import ITEMS gui = importlib.import_module( '..{0:s}.autotracker'.format(CONFIG['gui']), package=__package__) CONNECTED = threading.Event() DEVICES = {''} __all__ = 'CONNECTED', 'DEVICES', 'MemoryReader' class MemoryReader(object): ''' Console memory reader Instance variables: device: currently connected device socket: websocket object ''' def __init__(self): ''' No arguments ''' self.device = '' self.socket = None async def connect(self) -> None: ''' Establish connection with USB2SNES server. Raises: NoConnection, ParseError: on failure ''' log.info("Connecting autotracker to server '%s'.", CONFIG['usb2snes_server']) asyncio = importlib.import_module('asyncio') serveraddr = ( 'ws://{0:s}'.format(CONFIG['usb2snes_server']) if not CONFIG['usb2snes_server'].startswith('ws://') else CONFIG['usb2snes_server']) try: self.socket = await asyncio.wait_for(websockets.connect( serveraddr, ping_timeout=None, ping_interval=None), 1) except (websockets.InvalidURI, websockets.InvalidHandshake) as err: CONNECTED.clear() log.error('Received %s: %s', type(err), str(err)) raise NoConnection() from err except asyncio.TimeoutError as err: CONNECTED.clear() log.error('Connection attempt timed out.') raise NoConnection() from err log.debug('Connection successful.') try: devices = await self._retrieve_devices() except AutotrackerException: await self.disconnect() raise if not CONFIG['usb2snes_device']: if devices: gui.set_info( 'Connected to server. Please specify device in settings.', 'info') else: gui.set_info( 'Connected to server. Could not find any devices.', 'error') await self.disconnect() raise NoDevice() try: await self._choose_device(CONFIG['usb2snes_device']) except NoDevice: gui.set_info( "Connected to server. Could not find device '{0:s}'.".format( CONFIG['usb2snes_device']), 'error') await self.disconnect() raise except AutotrackerException: await self.disconnect() raise async def disconnect(self) -> None: ''' Close connection with USB2SNES server. ''' CONNECTED.clear() self.device = '' try: await self.socket.close() except AttributeError: pass else: self.socket = None async def _reconnect(self) -> None: ''' Re-establish connection. Raises: NoConnection, ParseError: on failure ''' await self.disconnect() await self.connect() async def _retrieve_devices(self) -> list: ''' Retrieve devices found by USB2SNES. Returns: list: list of devices Raises: NoConnection: if connection to server failed ParseError: if server reply was not understood ''' log.debug('Retrieving available devices.') ret = await self._send('DeviceList') log.debug('Found devices: %s', str(ret)) DEVICES.clear() DEVICES.add('') DEVICES.update(ret) return ret async def _choose_device(self, device: str) -> None: ''' Select device to use as tracker source. Args: device: device identifier, taken from self._retrieve_devices() Raises: NoConnection: if connection to server failed ParseError: if server reply was not understood NoDevice: if chosen device could not be found ''' devices = await self._retrieve_devices() for dev in devices: if device.upper() in dev.upper(): device = dev break else: log.error("Could not find device '%s'.", device) raise NoDevice("Could not find device '{0:s}'.".format(device)) log.info("Connecting to device '%s'.", device) await self._send('Attach', [device], noreply=True) deviceinfo = await self._send('Info') if not deviceinfo: raise NoDevice( "Could not attach to device '{0:s}'.".format(device)) log.info('Connection established.') self.device = device CONNECTED.set() async def _send(self, query: str, args: object = None, noreply: bool = False, hexreply: bool = False) -> object: ''' Send message to server. Args: query: query to send to server args: query argument(s) noreply: if True, don't expect reply from server hexreply: if True, expect server reply as raw hex Returns: object: reply from server Raises: NoConnection: if server connection failed ''' sendobject = {'Opcode': query, 'Space': 'SNES'} if args: sendobject['Operands'] = args log.debug('Send: %s', str(sendobject)) await self.socket.send(json.dumps(sendobject)) if noreply: return try: reply = await self.socket.recv() except websockets.ConnectionClosed as err: log.debug('Connection closed unexpectedly.') raise NoConnection() from err try: reply = json.loads(reply) except (json.JSONDecodeError, KeyError, UnicodeDecodeError) as err: if not hexreply: log.debug('Malformed reply: %s', reply) raise NoConnection() from err log.debug('Received: %s', str(reply)) if hexreply: ret = reply else: try: ret = reply['Results'] except KeyError: log.debug('Missing reply: %s', reply) raise ParseError() return ret async def _read_memory(self, address: int, length: int) -> bytearray: ''' Read console memory. Args: address: address of first byte to read length: number of bytes to read Returns: bytearray: memory content ''' ret = await self._send( 'GetAddress', [hex(address), hex(length)], hexreply=True) return ret async def check_game_status(self) -> bool: ''' Check whether game is running. Returns: bool: True if game is running and ready for memory access ''' log.debug('Checking game status.') ret = await self._read_memory(*addresses.GAMEMODE) ingame = int.from_bytes(ret, 'big') log.debug('Game mode: %x', ingame) if ingame in (0x07, 0x09, 0x0b, 0x0e): return True return False async def check_items(self) -> dict: ''' Retrieve items currently in Link's possession. Returns: dict: {'item identifier': stepping} ''' log.debug('Checking items.') itemmem = await self._read_memory(*addresses.ITEMS) ret = {} for item in ITEMS: log.debug("Item '%s'", item) ret[item] = _parse_item(itemmem, ITEMS[item]) return ret def _parse_item(memory: bytearray, condition: object, sub: bool = False) -> int: ''' Parse entry from autotracker.items.ITEMS. Args: memory: CPU memory banks from 7ef340 to 7ef3b9 condition: member of autotracker.items.ITEMS sub: if True, is subcheck Returns: int: highest fulfilled item stepping ''' def soffset(a): return a - 0x340 if isinstance(condition, int): log.debug('Exists: %x:%x -> %d', condition, memory[soffset(condition)], int(bool(memory[soffset(condition)]))) return int(bool(memory[soffset(condition)])) if isinstance(condition, dict): dictionary = condition address = None check = True else: address, dictionary = condition log.debug('Exists: %x:%x -> %d', address, memory[soffset(address)], int(bool(memory[soffset(address)]))) if not sub: check = bool(memory[soffset(address)]) else: check = True if check and 'flag' in dictionary: log.debug( 'Flag: %x:%x & %x == %x -> %d', dictionary['flag'][0], memory[soffset(dictionary['flag'][0])], dictionary['flag'][1], memory[soffset(dictionary['flag'][0])] & dictionary['flag'][1], ((memory[soffset(dictionary['flag'][0])] & dictionary['flag'][1]) == dictionary['flag'][1])) check = ( (memory[soffset(dictionary['flag'][0])] & dictionary['flag'][1]) == dictionary['flag'][1]) if check and 'is' in dictionary: assert address is not None log.debug( 'IS: %x:%x == %x -> %d', address, memory[soffset(address)], dictionary['is'], memory[soffset(address)] == dictionary['is']) check = memory[soffset(address)] == dictionary['is'] if check and 'min' in dictionary: assert address is not None log.debug( 'MIN: %x:%x >= %x -> %d', address, memory[soffset(address)], dictionary['min'], memory[soffset(address)] >= dictionary['min']) check = memory[soffset(address)] >= dictionary['min'] if check and 'choice' in dictionary: c = False log.debug('Choice BEGIN') for ch in dictionary['choice']: c |= _parse_item(memory, ch) log.debug('Choice END -> %d', c) check = c if check and 'step' in dictionary: steps = list(dictionary['step'].keys()) steps.sort(reverse=True) for s in steps: log.debug('Step: %d', s) if dictionary['step'][s] is None: log.debug('Step always TRUE') check = s break if _parse_item(memory, dictionary['step'][s], sub=True): log.debug('Step RESULT -> %d', s) check = s break else: check = False return check
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/autotracker/usb2snes.py
usb2snes.py
import os.path import typing from ..config import CONFIG, CONFIGDIRECTORY from ..dungeons import lists as dungeonlists from .. import entrances from .. import maps from .. import ruleset __all__ = 'Tracker', class _DelayCheck(Exception): ''' Thrown by Tracker.parse_requirement() when a check should be delayed. ''' def __init__(self, delayclass: str): ''' Args: delayclass: 'common', 'smallkey', 'bigkey', 'reward', 'boss' ''' super().__init__() assert delayclass in ( 'common', 'smallkey', 'bigkey', 'reward', 'maybe', 'boss') self.delayclass = delayclass class _SmallKeyCheck(Exception): ''' Raised when small key door is encountered. ''' def __init__(self, dungeon: str): ''' Args: requirement: number of required key chests ''' super().__init__() self.dungeon = dungeon class _BigKeyCheck(Exception): ''' Raised when big key lock is encountered. ''' def __init__(self, dungeon): ''' Args: requirement: number of required key chests ''' super().__init__() self.dungeon = dungeon class _RewardCheck(Exception): ''' Raised when reward is required. ''' class Tracker(object): ''' World state tracker Instance variables: items: item inventory dungeons: dungeon state maps: {'light', 'dark'} world map displays locationtracker: location tracker ruleset: location rules settings: game settings startpoint: starting locations entrances: entrance tracker crystals: crystal requirements for {'tower', 'ganon'} keys = {'dungeon': {'small': int, 'big': bool}} ''' def __init__(self): self.items = {} self.dungeons = {} self.maps = {'light': None, 'dark': None} self.locationtracker = maps.LocationTracker() self.entrances = entrances.EntranceTracker(self) self.crystals = {'tower': -1, 'ganon': -1} self.keys = {} self.update_rules() def update_rules(self) -> None: ''' Retrieve location rules. ''' self.ruleset = ruleset.Ruleset() self._make_settings() for dungeon in self.ruleset.dungeons: if (dungeon not in self.keys or 'small' not in self.keys[dungeon] or 'big' not in self.keys[dungeon]): self.keys[dungeon] = {'small': 0, 'big': False} self.rulecheck() def _make_settings(self) -> None: ''' Build game settings. ''' self.settings = set() if CONFIG['entrance_randomiser']: self.settings.add('entrance') self.settings.add(CONFIG['world_state'].lower()) if 'standard' in self.settings: self.settings.add('open') self.settings.add('glitches_{0:s}'.format( {'None': 'none', 'Overworld Glitches': 'overworld', 'Major Glitches': 'major'}[CONFIG['glitch_mode']])) self.settings.add('placement_{0:s}'.format( CONFIG['item_placement'].lower())) if CONFIG['dungeon_items'] in ( 'Maps/Compasses', 'Maps/Compasses/Small Keys', 'Keysanity'): self.settings.update(('random_map', 'random_compass')) if CONFIG['dungeon_items'] in ( 'Maps/Compasses/Small Keys', 'Keysanity'): self.settings.add('random_smallkey') if CONFIG['dungeon_items'] == 'Keysanity': self.settings.add('random_bigkey') if CONFIG['dungeon_items'] == 'Custom': for di in ('map', 'compass', 'smallkey', 'bigkey'): if CONFIG[f'shuffle_{di:s}']: self.settings.add(f'random_{di:s}') self.settings.add('goal_{0:s}'.format( {'Defeat Ganon': 'ganon', 'Fast Ganon': 'fastganon', 'All Dungeons': 'dungeons', 'Master Sword Pedestal': 'pedestal', 'Triforce Hunt': 'triforce'}[CONFIG['goal']])) if CONFIG['swords'] == 'Swordless': self.settings.add('swordless') if CONFIG['enemiser']: self.settings.add('enemiser') if CONFIG['majoronly']: self.settings.add('majoronly') self._set_startpoint() def _set_startpoint(self) -> None: ''' Choose starting point. ''' self.startpoint = ["Link's House"] if 'inverted' in self.settings: self.startpoint.append('Dark Chapel Entrance (I)') else: self.startpoint.append('Sanctuary') def reapply(self) -> None: ''' Purge map and recreate with (possibly) updated settings. ''' self.update_rules() for maptype in self.maps: self.maps[maptype].remove_buttons() self.make_buttons(maptype) if 'entrance' in self.settings: self.ruleset.disconnect_entrances() self.maps['light'].set_entrance() else: self.ruleset = ruleset.Ruleset() self.rulecheck() def set_item(self, itemname: str, itemnumber: int) -> None: ''' Set item inventory. Args: itemname: item identifier inventory: new item inventory to overwrite old one ''' self.items[itemname] = itemnumber self.rulecheck() def set_dungeon(self, dungeonname: str, dungeondata: dict) -> None: ''' Set dungeon data. Args: dungeonname: dungeon name dungeondata: new dungeon data ''' self.dungeons[dungeonname] = dungeondata self.rulecheck() def add_map(self, maptype: str, mapdisplay) -> None: ''' Add map to tracker. Args: maptype: 'light' or 'dark' mapdisplay: map display object ''' assert maptype in ('light', 'dark') self.maps[maptype] = mapdisplay self.maps[maptype].add_location_tracker(self.locationtracker) if all(m is not None for m in self.maps.values()): self.maps['light'].other = self.maps['dark'] self.maps['dark'].other = self.maps['light'] self.make_buttons(maptype) if 'entrance' in self.settings: self.ruleset.disconnect_entrances() if self.maps['light'] and self.maps['dark']: self.maps['light'].set_entrance() self.maps[maptype].add_entrance_tracker(self.entrances) self.rulecheck() def make_buttons(self, maptype: str) -> None: ''' Send button data to map display. Args: maptype: 'light' or 'dark' ''' assert maptype in ('light', 'dark') if CONFIG['entrance_randomiser']: gametype = 'entrance' elif CONFIG['world_state'] == 'Retro': gametype = 'item_retro' elif CONFIG['shopsanity']: gametype = 'item_shop' else: gametype = 'item' self.maps[maptype].place_buttons( self.ruleset.locations( gametype, maptype, 'majoronly' in self.settings)) def update_buttons(self, available: typing.Mapping, visible: typing.Sequence[str]) -> None: ''' Send updated availability info to map displays. Args: available: {'available location': 'type of availability'} visible: list of visible locations ''' # Go through maps. for mapd in self.maps.values(): # Go through buttons: for button in mapd.button: # Check dungeon status. if mapd.button[button]['type'] == 'dungeon': dungeonchecks = [] for loc in self.ruleset.dungeons[button]: if (self.ruleset[loc].type.startswith('dungeonchest') and not loc.endswith(' Boss Item')): dungeonchecks.append(loc in available) if all(dungeonchecks): try: clearable = available[ '{0:s} Big Key'.format(button)] except KeyError: # Castle Tower clearable = available[ '{0:s} Second Chest'.format(button)] elif any(dungeonchecks): clearable = 'visible' else: clearable = 'unavailable' if '{0:s} Reward'.format(button) in available: finishable = available['{0:s} Boss'.format(button)] if (finishable == 'available' and clearable == 'indirect'): finishable = 'indirect' else: finishable = 'unavailable' state = [clearable, finishable] mapd.set_dungeon_availability(button, state) # Check location status. else: if button in available: state = available[button] elif button in visible: state = 'visible' else: state = 'unavailable' mapd.set_availability(button, state) def rulecheck(self) -> None: ''' Update availability of all locations. ''' # Don't run if both maps aren't yet available. if not all(self.maps.values()): return # Create fresh rules. for loc in self.ruleset.values(): loc.checked = False keys = {} for dungeon in self.ruleset.dungeons: if self.ruleset[dungeon].type == 'dungeon': keys[dungeon] = {'small': self.keys[dungeon]['small'], 'big': self.keys[dungeon]['big']} else: keys[dungeon] = {'small': 1, 'big': False} # Prepare rulecheck. available = {} reachable = [_Connection(s) for s in self.startpoint] visible = set() delayed = {'common': [], 'smallkey': [], 'bigkey': [], 'boss': [], 'reward': [], 'maybe': []} keychecked = {loc: set() for loc in self.ruleset.dungeons} hadkey = dict.fromkeys(self.ruleset.dungeons.keys(), False) maybedungeons = set() asrabbit = set() pathtrace = {s: [] for s in self.startpoint} # Go through locations. while reachable: # Retrieve next available location. current, state = reachable.pop(0).get() # Mark current location. if self.ruleset[current].checked is not None: if 'maybe' in state: available[current] = 'maybe' elif 'boss' in state: available[current] = 'indirect' else: available[current] = 'available' self.ruleset[current].checked = True if 'rabbit' in state: asrabbit.add(current) # Add fixed keys. if self.ruleset[current].type == 'dungeonkey': keys[self.ruleset[current].dungeon]['small'] += 1 hadkey[self.ruleset[current].dungeon] = True # Add chest keys. if ('random_smallkey' not in self.settings and self.ruleset[current].type.startswith('dungeonchest') and self.ruleset[self.ruleset[current].dungeon].type == 'dungeon'): keypools = self.ruleset[self.ruleset[current].dungeon].keypools spheres_defined = False for sphere in keypools: if (sphere['type'] != 'small' or current not in sphere['chests']): continue for s in sphere['settings']: if s not in self.settings: break else: spheres_defined = True remaining = sum( loc not in keychecked[self.ruleset[current].dungeon] for loc in sphere['chests']) if remaining <= sphere['keys']: keys[self.ruleset[current].dungeon]['small'] += 1 hadkey[self.ruleset[current].dungeon] = True break if not spheres_defined: total = self.ruleset.dungeons[ self.ruleset[current].dungeon].keylocations() if current in total: remaining = sum( loc not in keychecked[self.ruleset[current].dungeon] for loc in total) totalkeys = dungeonlists.DUNGEONS[ self.ruleset[current].dungeon][1] if remaining <= totalkeys: keys[self.ruleset[current].dungeon]['small'] += 1 hadkey[self.ruleset[current].dungeon] = True keychecked[self.ruleset[current].dungeon].add(current) # Go through links. for link in self.ruleset[current].link: # Don't recheck already visited locations. if self.ruleset[link].checked: if 'rabbit' in state or link not in asrabbit: continue # Add Moon Pearl check if going into overworld. reqs = self.ruleset[current].link[link][:] if (self.ruleset[current].type == 'interior' and self.ruleset[link].type.startswith('entrance')): if (('inverted' not in self.settings and self.ruleset[link].map == 'dark') or ('inverted' in self.settings and self.ruleset[link].map == 'light')): reqs = [ ('and', [('or', reqs), ('state', 'rabbit;add')])] else: reqs = [ ('and', [('or', reqs), ('state', 'rabbit;dis')])] # Parse requirement. newstate = state.copy() try: ret, addstate = self._parse_requirement( reqs, state, None, keys) except _DelayCheck as err: newlink = (link, _Connection( self.ruleset[current].link[link], state)) if newlink not in delayed[err.delayclass]: delayed[err.delayclass].append(newlink) if CONFIG['path_trace']: newpath = pathtrace[current][:] newpath.append((current, newstate)) pathtrace[link] = newpath ret = False if ret: for retstate in addstate: s = retstate.split(';') if len(s) > 1 and s[1] == 'add': newstate.add(s[0]) elif s[0] in newstate: newstate.remove(s[0]) elif not (len(s) > 1 and s[1] == 'dis'): newstate.add(s[0]) newlink = _Connection(link, newstate) if newlink not in reachable: reachable.append(newlink) if CONFIG['path_trace']: newpath = pathtrace[current][:] newpath.append((current, newstate)) pathtrace[link] = newpath if link in asrabbit: asrabbit.remove(link) # Check visible locations. for link in self.ruleset[current].visible: if self._parse_requirement( self.ruleset[current].visible[link], state, None, keys)[0]: visible.add(link) # Go though delayed checks. ret = False addstate = [] if not reachable: for delayclass in delayed: for idx, loc in enumerate(delayed[delayclass]): current, state = loc[1].get() newstate = state.copy() try: ret, addstate = self._parse_requirement( current, state, available, keys) except _SmallKeyCheck as err: ret = self._check_smallkeys( available, err.dungeon, keys) if not ret and hadkey[err.dungeon]: ret = True addstate = ('maybe;add',) maybedungeons.add(err.dungeon) except _BigKeyCheck as err: avail, maybe = self._check_bigkey( available, err.dungeon) ret = False if avail or maybe: ret = True if ((not avail and maybe) or err.dungeon in maybedungeons): addstate = ('maybe;add',) if ret: for retstate in addstate: s = retstate.split(';') if len(s) > 1 and s[1] == 'add': newstate.add(s[0]) elif s[0] in state: newstate.remove(s[0]) elif not (len(s) > 1 and s[1] == 'dis'): newstate.add(s[0]) newlink = _Connection( delayed[delayclass].pop(idx)[0], newstate) if newlink not in reachable: reachable.append(newlink) elif CONFIG['path_trace'] and link in pathtrace: del pathtrace[current] if link in asrabbit: asrabbit.remove(link) break if reachable: break # Send updated availability to map displays. self.update_buttons(available, visible) if CONFIG['path_trace']: _store_pathtrace(pathtrace) def _parse_requirement( self, req: typing.Sequence[typing.Sequence], state: typing.Sequence, nodelay: typing.Sequence[str], keys: dict = {}, collector=any) -> (bool, list): ''' Parse generic link requirement object. When more than one requirement is given, this function defaults to OR! Args: req: [('requirement type', requirement object)] state: current connection state nodelay: don't throw DelayCheck when encountering access requirement, instead check against this list of locations keys: current number of available keys collector: something like any() or all() Returns: bool: True if requirements are met list: list of state flags to toggle ''' if not req: return True, [] result = [] addstate = [] for rtype, robj in req: # OR if rtype == 'or': sub = self._parse_requirement(robj, state, nodelay, keys) result.append(sub[0]) if sub[0]: addstate.extend(sub[1]) # AND elif rtype == 'and': sub = self._parse_requirement(robj, state, nodelay, keys, all) result.append(sub[0]) if sub[0]: addstate.extend(sub[1]) # settings elif rtype == 'settings': result.append(robj in self.settings) # nosettings elif rtype == 'nosettings': result.append(robj not in self.settings) # item elif rtype == 'item': rabbititems = ( 'mushroom', 'lantern', 'mudora', 'bottle', 'mirror') if ('rabbit' in state and ( not 'pearl' in self.items or self.items['pearl'] == 0) and robj not in rabbititems): result.append(False) else: result.append(robj in self.items and self.items[robj] > 0) if robj == 'mirror': addstate.append('rabbit;dis') # access elif rtype == 'access': if not nodelay: raise _DelayCheck('common') result.append(robj in nodelay) if result[-1] and nodelay[robj] in ('maybe', 'indirect'): addstate.append('{0:s};add'.format( 'maybe' if nodelay[robj] == 'maybe' else 'boss')) # glitch elif rtype == 'glitch': if robj == 'overworld': result.append('glitches_overworld' in self.settings or 'glitches_major' in self.settings) elif robj == 'major': result.append('glitches_major' in self.settings) # medallion elif rtype == 'medallion': if 'rabbit' in state and not 'pearl' in self.items: result.append(False) res, maybe = self._check_medallion(robj) result.append(res) if maybe: addstate.append('maybe;add') # mudora elif rtype == 'mudora': assert robj in ('take', 'see') result.append( 'mudora' in self.items and self.items['mudora'] > 0 and (('swordless' in self.settings and 'hammer' in self.items and self.items['hammer'] > 0) or 'mastersword' in self.items and self.items['mastersword'] > 0)) # pendant/crystals elif rtype in ('pendant', 'crystals'): if not nodelay: raise _DelayCheck('reward') res, flag = self._reward_locations(robj, nodelay) result.append(res) if flag: addstate.append('{0:s};add'.format(flag)) # smallkey elif rtype == 'smallkey': if 'retro' in self.settings: result.append(True) elif not nodelay: raise _DelayCheck('smallkey') else: if 'random_smallkey' in self.settings: if keys[robj]['small'] > 0: keys[robj]['small'] -= 1 result.append(True) else: result.append(False) else: raise _SmallKeyCheck(robj) # bigkey elif rtype == 'bigkey': if not nodelay: raise _DelayCheck('bigkey') else: if 'random_bigkey' in self.settings: if keys[robj]['big']: result.append(True) else: result.append(False) else: raise _BigKeyCheck(robj) # macro elif rtype == 'macro': if robj == 'ganon': if 'goal_ganon' in self.settings: sub = self._parse_requirement( [('and', [ ('crystals', 'ganon'), ('macro', 'ganondrop')])], state, nodelay, keys, all) elif 'goal_fastganon' in self.settings: sub = self._parse_requirement( [('crystals', 'ganon')], state, nodelay, keys) elif 'goal_dungeons' in self.settings: sub = self._parse_requirement( [('and', [ ('crystals', 'ganon'), ('pendant', 'courage'), ('pendant', 'power'), ('pendant', 'wisdom')])], state, nodelay, keys, all) elif 'goal_pedestal' in self.settings: sub = self._parse_requirement( [('and', [ ('pendant', 'courage'), ('pendant', 'power'), ('pendant', 'wisdom')])], state, nodelay, keys, all) elif 'goal_triforce' in self.settings: sub = self._parse_requirement( [('and', [ ('crystals', 'ganon'), ('pendant', 'courage'), ('pendant', 'power'), ('pendant', 'wisdom')])], state, nodelay, keys, all) else: assert False elif robj == 'ganonstower': sub = self._parse_requirement( [('crystals', 'ganonstower')], state, nodelay, keys) elif robj == 'ganondrop': if not nodelay: raise _DelayCheck('reward') if self._check_dungeon_state("Ganon's Tower"): sub = (True, ()) else: sub = self._parse_requirement( [('access', "Ganon's Tower Reward")], state, nodelay, keys) sub[1].append('boss;add') else: print(rtype, robj) assert False result.append(sub[0]) if sub[0]: addstate.extend(sub[1]) # state elif rtype == 'state': statestr = robj.split(';') assert statestr[0] in ('rabbit', 'maybe') if statestr[0] == 'maybe' and not nodelay: raise _DelayCheck('maybe') addstate.append(robj) result.append(True) # rabbitbarrier elif rtype == 'rabbitbarrier': if 'rabbit' in state and not self._parse_requirement( [('item', 'pearl')], state, nodelay)[0]: result.append(False) else: result.append(True) # boss elif rtype == 'boss': if not nodelay: raise _DelayCheck('boss') if not self._check_dungeon_state(robj): addstate.append('boss;add') result.append(True) # error else: print(rtype, robj) assert False return collector(result), addstate def _check_smallkeys( self, availability: typing.Sequence[str], dungeon: str, keys: dict) -> bool: ''' Check number of available small keys. Args: availability: list of already available locations dungeon: dungeon name keys: {dungeon name: number of available keys} Returns: bool: True if key requirement is met ''' if 'random_smallkey' in self.settings: addkeys = self.keys[dungeon]['small'] else: addkeys = 0 if keys[dungeon]['small'] + addkeys > 0: keys[dungeon]['small'] -= 1 return True return False def _check_bigkey( self, availability: typing.Sequence[str], dungeon: str) -> (bool, bool): ''' Check number of available small keys. Args: availability: list of already available locations dungeon: dungeon name Returns: bool: True if key requirement is met bool: True if key requirement might be met ''' if 'random_bigkey' in self.settings: return self.keys[dungeon]['big'] for pool in self.ruleset[dungeon].keypools: if pool['type'] == 'big': bigpool = pool['chests'] break else: bigpool = { loc for loc in self.ruleset.dungeons[dungeon] if self.ruleset[loc].type == 'dungeonchest'} avail = tuple(loc in availability for loc in bigpool) ret = all(avail) maybe = any(avail) return ret, maybe def _check_medallion(self, dungeon) -> (bool, bool): ''' Check whether medallion requirement is sattisfied. Args: dungeon: 'Misery Mire' or 'Turtle Rock' Returns: bool: True if fight is finishable bool: True if 'maybe' state should be added ''' assert dungeon in ('Misery Mire', 'Turtle Rock') req = self.dungeons[dungeon]['medallion'] if req == 'unknown': res = (self.items['bombos'] > 0, self.items['ether'] > 0, self.items['quake'] > 0) if all(res): res = True, False elif any(res): res = True, True else: res = False, False else: res = self.items[req] > 0, False if not 'swordless' in self.settings and self.items['sword'] == 0: res = False, False return res def _reward_locations( self, reward: str, available: typing.Sequence[str]) -> (bool, str): ''' Retrieve required locations for reward. Args: reward: 'courage', 'power', 'wisdom', 'fairy', 'ganonstower', 'ganon' available: list of available locations Returns: bool: True if all required locations are available str: '', 'maybe' or 'boss' ''' # Sanity check assert reward in ( 'courage', 'power', 'wisdom', 'fairy', 'ganonstower', 'ganon') # Conversion between ruleset files and reward names. conversion = { 'courage': 'courage', 'power': 'powerwisdom', 'wisdom': 'powerwisdom', 'fairy': '56crystal', 'ganonstower': 'crystal', 'ganon': 'crystal'} # Get current dungeons for desired reward type. rewarddungeons = [] knowndungeons = [] for dungeon in self.dungeons: if not 'reward' in self.dungeons[dungeon]['features']: continue if self.dungeons[dungeon]['reward'] == conversion[reward]: rewarddungeons.append(dungeon) knowndungeons.append(dungeon) if (reward.startswith('ganon') and self.dungeons[dungeon]['reward'] == '56crystal'): rewarddungeons.append(dungeon) knowndungeons.append(dungeon) # Check whether all required reward locations are known. required = { 'courage': 1, 'power': 2, 'wisdom': 2, 'fairy': 2, 'ganonstower': self.crystals['tower'], 'ganon': self.crystals['ganon']} if required[reward] < 0: unknown_requirement = True else: unknown_requirement = False total = dict.fromkeys( ('courage', 'powerwisdom', '56crystal', 'crystal'), 0) for dungeon in self.dungeons: if self.dungeons[dungeon]['reward'] != 'unknown': total[self.dungeons[dungeon]['reward']] += 1 if self.dungeons[dungeon]['reward'] == '56crystal': total['crystal'] += 1 # Check if enough rewards are known. enough = len(rewarddungeons) >= required[reward] # If not enough, count including dungeons with unknown reward. if not enough: rewarddungeons = [] for dungeon in self.dungeons: if not 'reward' in self.dungeons[dungeon]['features']: continue if self.dungeons[dungeon]['reward'] in ( conversion[reward], 'unknown'): rewarddungeons.append(dungeon) if (reward.startswith('ganon') and self.dungeons[dungeon]['reward'] == '56crystal'): rewarddungeons.append(dungeon) # Check if there is enough now. locations = [] maybes = 0 boss_required = 0 for dungeon in rewarddungeons: if self._check_dungeon_state(dungeon): locations.append(True) continue res, add = self._parse_requirement( [('access', '{0:s} Reward'.format(dungeon))], [], available) locations.append(res) for retstate in add: if res and retstate.split(';')[0] == 'maybe': maybes += 1 break boss_required += 1 # Add all information together. addflag = '' if enough: ret = sum(locations) >= required[reward] if required[reward] + boss_required > total[conversion[reward]]: addflag = 'boss' if required[reward] + maybes > total[conversion[reward]]: addflag = 'maybe' if unknown_requirement: if sum(locations) - maybes < 7: addflag = 'maybe' elif boss_required: addflag = 'boss' else: ret = sum(locations) >= required[reward] if not ret: ret = unknown_requirement addflag = 'maybe' else: if all(locations): addflag = 'boss' else: addflag = 'maybe' return ret, addflag def total_chests(self, dungeon: str) -> int: ''' Retrieve number of chests available in dungeon. Args: dungeon: name of dungeon Returns: int: number of non-dungeon-specific items ''' total_chests = 0 for locname in self.ruleset.dungeons[dungeon]: majorcheck = ( 'majoronly' not in self.settings or locname in ruleset.MAJORLOCATIONS) loc = self.ruleset.dungeons[dungeon][locname] if loc.type.startswith('dungeonchest') and majorcheck: total_chests += 1 return total_chests def set_dungeon_state(self, dungeon: str, state: [bool, bool]) -> None: ''' Set whether dungeon has been checked or not. Args: dungeon: name of dungeon state: (all items collected, boss defeated) ''' assert isinstance(state, list) assert len(state) == 2 if dungeon in self.maps['light'].button: mapd = 'light' else: mapd = 'dark' self.maps[mapd].tracker[dungeon] = state self.rulecheck() def _check_dungeon_state(self, dungeon: str) -> bool: ''' Check whether dungeon reward has been collected or not. Args: dungeon: name of dungeon Returns: bool: True if dungeon reward has been picked up ''' try: ret = self.maps['dark'].tracker[dungeon][1] except KeyError: ret = self.maps['light'].tracker[dungeon][1] return not ret def set_crystal_requirement(self, tower: int, ganon: int) -> None: ''' Set crystal requirements for Tower and Ganon Fight access. Args: tower: crystals required for Ganon's Tower access ganon: crystals required for the Ganon Fight ''' self.crystals['tower'] = tower self.crystals['ganon'] = ganon self.rulecheck() class _Connection(object): ''' Connected location Instance variables: name: name of connected location state: list of states linked to connection ''' def __init__(self, init: str = '', state: typing.Sequence = set()): ''' Args: init: name of connected location state: list of states linked to connection ''' super().__init__() self.name = init self.state = state def __eq__(self, other): ''' Equality check This will raise an error if 'other' is not '_Connection' type. ''' return self.get() == other.get() def get(self) -> (str, tuple): ''' Unpack data. Returns: str: name of connected location state: list of states linked to connection ''' return self.name, self.state def _store_pathtrace(pathtrace: dict) -> None: ''' Store pathtrace in file. Args: pathtrace: path trace ''' assert CONFIG['path_trace'] output = [] for location in pathtrace: output.append('[{0:s}]\n'.format(location)) first = True for path, states in pathtrace[location]: output.append('{0:s}{1:s}{2:s}\n'.format( ' ' if first else '--> ', path, (' + {0:s}'.format(', '.join(s for s in states)) if states else ''))) first = False output.append('\n') del output[-1] with open(os.path.join(CONFIGDIRECTORY, CONFIG['path_trace']), 'w') as fid: fid.writelines(output)
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/world/world.py
world.py
import typing from ..config.images import image __all__ = 'DungeonObj', class DungeonObj(object): ''' Dungeon object Instance variables: identifier: name of dungeon location: (column, row) on dungeon display totalkeys: total number of small keys available for this dungeon icon: name of dungeon image features: additional features of dungeon tracker: world state tracker idstr: dungeon code smallkeys: number of collected small keys bigkey: whether big key is collected or not chests: number of collected chests reward: dungeon reward completed: True if dungeon has been completed medallion: medallion requirement ''' import_data = ( 'smallkeys', 'bigkey', 'chests', 'reward', 'completed', 'medallion') def __init__(self, name: str, location: (int, int), totalkeys: int, icon: str, features: typing.Sequence[str], tracker, idstr: str): ''' Args: name: name of dungeon location: (column, row) on dungeon display totalkeys: total number of randomly placed small keys icon: icon image of dungeon features: list of features of dungeon tracker: world state tracker idstr: dungeon code ''' self.identifier = name self.location = location self.totalkeys = totalkeys self.icon = image(icon) self.features = features self.tracker = tracker self.idstr = idstr self.reset() def reset(self) -> None: ''' Reset all values to default. ''' self.smallkeys = 0 self.bigkey = False self.tracker.keys[self.identifier] = {'small': 0, 'big': False} self.chests = 0 self.reward = 'unknown' self.completed = False self.medallion = 'unknown' self.tracker.set_dungeon(self.identifier, self.export()) def restore(self, data: dict) -> None: ''' Rebuild dungeon info from save. Args: data: dungeon save data ''' for attr in self.import_data: if attr in ('smallkeys', 'chests'): data[attr] = int(data[attr]) self.set(attr, data[attr]) self.tracker.keys[self.identifier]['small'] = data['smallkeys'] self.tracker.keys[self.identifier]['big'] = data['bigkey'] def save(self) -> dict: ''' Return non-static dungeon info. Returns: dict: dungeon save data ''' data = {} for attr in self.import_data: data[attr] = self.get(attr) return data def export(self) -> dict: ''' Retrieve dungeon info for world state tracker. Returns: dict: dungeon info ''' data = self.save() data['features'] = self.features return data def set(self, variable: str, value) -> None: ''' Set dungeon variable. Args: variable: name of dungeon variable to change value: value to set variable to ''' self.__setattr__(variable, value) self.tracker.set_dungeon(self.identifier, self.export()) def get(self, variable: str) -> object: ''' Get dungeon variable. Args: variable: name of dungeon variable Returns: object: current value of variable ''' return self.__getattribute__(variable) def total_items(self) -> int: ''' Retrieve number of items available in dungeon. Returns: int: number of non-dungeon-specific items ''' total_chests = self.tracker.total_chests(self.identifier) if 'majoronly' in self.tracker.settings: total_chests += self.totalkeys if 'random_map' not in self.tracker.settings and 'map' in self.features: total_chests -= 1 if ('random_compass' not in self.tracker.settings and 'compass' in self.features): total_chests -= 1 if ('random_bigkey' not in self.tracker.settings and 'bigkey' in self.features): total_chests -= 1 if ('random_smallkey' not in self.tracker.settings and 'retro' not in self.tracker.settings): total_chests -= self.totalkeys return total_chests def remaining(self) -> int: ''' Retrieve number of remaining items in dungeon. Returns: int: number of remaining items ''' return self.total_items() - self.chests def cycle_reward(self, direction: bool) -> None: ''' Cycle through dungeon reward. Args: direction: cycling direction ''' circle = ('unknown', 'courage', 'powerwisdom', 'crystal', '56crystal') newidx = circle.index(self.reward) newidx += 1 if direction else -1 if newidx >= len(circle): newidx = 0 self.set('reward', circle[newidx]) def mark_complete(self, complete: bool) -> None: ''' Mark dungeon as (in)complete. Args: complete: False if dungeon is to be marked as completed ''' self.set('completed', complete) self.tracker.set_dungeon_state( self.identifier, [bool(self.remaining()), not complete]) def cycle_medallion(self, direction) -> None: ''' Cycle through medallion requirement. Args: direction: cycling direction ''' circle = ('unknown', 'bombos', 'ether', 'quake') newidx = circle.index(self.medallion) newidx += 1 if direction else -1 if newidx >= len(circle): newidx = 0 self.set('medallion', circle[newidx]) def toggle_bigkey(self, *args) -> None: ''' Toggle possession of the Big Key. ''' self.tracker.keys[self.identifier]['big'] = not self.bigkey self.set('bigkey', not self.bigkey) def key_up(self, *args) -> None: ''' Add one small key. ''' before = self.get('smallkeys') after = min(self.smallkeys + 1, self.totalkeys) self.tracker.keys[self.identifier]['small'] += (after - before) self.set('smallkeys', after) def key_down(self, *args) -> None: ''' Remove one small key. ''' before = self.get('smallkeys') after = max(self.smallkeys - 1, 0) self.tracker.keys[self.identifier]['small'] += (after - before) self.set('smallkeys', after) def item_up(self, *args) -> None: ''' Add one collected item. ''' self.set('chests', min(self.chests + 1, self.total_items())) self.tracker.set_dungeon_state( self.identifier, [bool(self.remaining()), not self.completed]) def item_down(self, *args) -> None: ''' Remove one collected item. ''' self.set('chests', max(self.chests - 1, 0)) self.tracker.set_dungeon_state( self.identifier, [bool(self.remaining()), not self.completed])
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/dungeons/dungeonobj.py
dungeonobj.py
import configparser import importlib import os.path import json from ..config.images import image layoutstorage = importlib.import_module( '..gui-common.dungeons', package=__package__) from .dungeonobj import DungeonObj from .lists import DUNGEONS from . import storage __all__ = 'DungeonTracker', def get_layout() -> dict: ''' Load (or create) dungeon layout. Returns: dict: dungeon layout in format {identifier: (column, row)} ''' try: layout = layoutstorage.load_dungeons() except (layoutstorage.NoConfig, configparser.Error): layout = {} for dungeon in DUNGEONS: layout[dungeon] = DUNGEONS[dungeon] layoutstorage.new_dungeon(layout) layout = layoutstorage.load_dungeons() return layout class DungeonTracker(dict): ''' Dungeon info tracker. ''' def __init__(self, worldtracker): ''' Args: worldtracker: world state tracker ''' layout = get_layout() super().__init__() self.worldtracker = worldtracker self.crystal_requirement = {'tower': -1, 'ganon': -1} delayed_link = [] for rawdungeon in DUNGEONS: dungeon = DungeonObj( rawdungeon, DUNGEONS[rawdungeon][0], DUNGEONS[rawdungeon][1], DUNGEONS[rawdungeon][2], DUNGEONS[rawdungeon][3], worldtracker, DUNGEONS[rawdungeon][4]) try: dungeon.location = layout[dungeon] except KeyError: pass self[dungeon.identifier] = dungeon data = storage.load_dungeons() self.restore(data) def set_crystal(self, ctype: str, diff: int) -> int: ''' Set crystal requirements. Args: ctype: 'tower' or 'crystal' diff: -1, +1 or None (for reset) Returns: int: number of required crystals, -1 means unknown ''' if diff is None: self.crystal_requirement[ctype] = -1 else: self.crystal_requirement[ctype] += diff if self.crystal_requirement[ctype] < -1: self.crystal_requirement[ctype] = 7 elif self.crystal_requirement[ctype] > 7: self.crystal_requirement[ctype] = -1 self.worldtracker.set_crystal_requirement( self.crystal_requirement['tower'], self.crystal_requirement['ganon']) self.save() return self.crystal_requirement[ctype] def reset(self) -> None: ''' Reset all dungeons. ''' for dungeon in self: self[dungeon].reset() def save(self, *args) -> dict: ''' Save current dungeon setup. ''' storage.store_dungeons(self.store()) def store(self) -> dict: ''' Return current dungeon info for storage. Returns: dict: dungeon info ''' dungeoninfo = {} for dungeon in self: dungeoninfo[dungeon] = self[dungeon].save() dungeoninfo['crystal_requirements'] = self.crystal_requirement return dungeoninfo def restore(self, dungeoninfo) -> None: ''' Restore current dungeon info from file. Args: dungeoninfo: information from file ''' for dungeon in dungeoninfo: if dungeon in self: self[dungeon].restore(dungeoninfo[dungeon]) try: self.crystal_requirement.update(dungeoninfo['crystal_requirements']) except KeyError: pass
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/dungeons/dungeons.py
dungeons.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Swamp Palace Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (304, 621), 'link': { 'South Dark World': [], 'Swamp Palace Entrance (I)': []} }, 'Swamp Palace Entrance (I)': { 'type': 'interior', 'link': { 'Swamp Palace Entrance (E)': [], 'Swamp Palace Before Canal': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Swamp Palace Before Canal': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Entrance (I)': [], 'Swamp Palace Canal': [('and', [ ('access', 'Water Drain'), ('or', [('settings', 'entrance'), ('item', 'mirror')])])]} }, 'Swamp Palace Canal': { 'type': 'area', 'dungeon': 'Swamp Palace After Canal', 'link': { 'Swamp Palace Before Canal': [], 'Swamp Palace After Canal': [('item', 'flippers')]} }, 'Swamp Palace After Canal': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Canal': [('item', 'flippers')], 'Swamp Palace Key': [], 'Swamp Palace Water Hall': [('smallkey', 'Swamp Palace')]} }, 'Swamp Palace Key': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace After Canal': []} }, 'Swamp Palace Water Hall': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace After Canal': [], 'Swamp Palace Map': [('item', 'bombs')], 'Swamp Palace First Hidden Key': [], 'Swamp Palace East Basin': [('smallkey', 'Swamp Palace')]} }, 'Swamp Palace Map': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Water Hall': []} }, 'Swamp Palace First Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Water Hall': []} }, 'Swamp Palace East Basin': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Water Hall': [], 'Swamp Palace Second Hidden Key': [], 'Swamp Palace East Switch Room': [ ('smallkey', 'Swamp Palace')]} }, 'Swamp Palace Second Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace East Basin': []} }, 'Swamp Palace East Switch Room': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace East Basin': [], 'Swamp Palace East Switch': [('item', 'hammer')]} }, 'Swamp Palace East Switch': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace East Switch Room': [], 'Swamp Palace Water Hall': [('item', 'flippers')], 'Swamp Palace Main Hall': [('item', 'flippers')]} }, 'Swamp Palace Main Hall': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace East Switch': [], 'Swamp Palace Compass': [], 'Swamp Palace Third Hidden Key': [], 'Swamp Palace West Switch': [('smallkey', 'Swamp Palace')], 'Swamp Palace Treasure': [('bigkey', 'Swamp Palace')], 'Swamp Palace Fourth Hidden Key': [('item', 'hookshot')], 'Swamp Palace Gauntlet Entrance': [('item', 'hookshot')]} }, 'Swamp Palace Compass': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': []} }, 'Swamp Palace Third Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': []} }, 'Swamp Palace West Switch': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': [], 'Swamp Palace West Basin': [('item', 'flippers')]} }, 'Swamp Palace West Basin': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': [('item', 'flippers')], 'Swamp Palace Fake Big Key': [], 'Swamp Palace Big Key': []} }, 'Swamp Palace Fake Big Key': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace West Basin': []} }, 'Swamp Palace Big Key': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace West Basin': []} }, 'Swamp Palace Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': []} }, 'Swamp Palace Fourth Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': []} }, 'Swamp Palace Gauntlet Entrance': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Main Hall': [], 'Swamp Palace Gauntlet': [('smallkey', 'Swamp Palace')]} }, 'Swamp Palace Gauntlet': { 'type': 'area', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Gauntlet Entrance': [], 'Swamp Palace Left Treasury Chest': [], 'Swamp Palace Right Treasury Chest': [], 'Swamp Palace Hidden Chest': [], 'Swamp Palace Boss': [('item', 'flippers')]} }, 'Swamp Palace Left Treasury Chest': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Gauntlet': []} }, 'Swamp Palace Right Treasury Chest': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Gauntlet': []} }, 'Swamp Palace Hidden Chest': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Gauntlet': []} }, 'Swamp Palace Boss': { 'type': 'dungeonboss', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Boss Item': [('and', [ ('item', 'hookshot'), ('or', [ ('settings', 'placement_advanced'), ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('item', 'hammer'), ('item', 'sword'), ('and', [ ('or', [ ('item', 'halfmagic'), ('item', 'bottle'), ('item', 'bow')]), ('or', [ ('item', 'firerod'), ('item', 'icerod')])])])])]} }, 'Swamp Palace Boss Item': { 'type': 'dungeonchest', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Reward': []} }, 'Swamp Palace Reward': { 'type': 'dungeonreward', 'dungeon': 'Swamp Palace', 'link': { 'Swamp Palace Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/swamppalace.py
swamppalace.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Kakariko Portal (DW)': { 'type': 'area', 'link': { 'Kakariko Portal (LW)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Kakariko Portal': [('item', 'powerglove')], 'Skull Woods Surface': [('rabbitbarrier', None)], "Thieves' Town Surface": [('item', 'titansmitts')]} }, 'Skull Woods Surface': { 'type': 'area', 'link': { 'Lost Woods': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'Kakariko Portal (DW)': [], "Thieves' Town Surface": [], 'Skull Woods First Entrance Entrance (E)': [], 'Skull Woods West Drop Entrance (E)': [], 'Skull Woods East Drop Entrance (E)': [], 'Skull Woods Central Drop Entrance (E)': [('rabbitbarrier', None)], 'Skull Woods Second Entrance Entrance (E)': [], 'North Dark World': []} }, 'Skull Woods First Entrance Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (116, 98), 'link': { 'Skull Woods Surface': [], 'Skull Woods First Entrance Entrance (I)': []} }, 'Skull Woods First Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods First Entrance Entrance (E)': [], 'Skull Woods First Entrance': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods First Entrance': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods First Entrance Entrance (I)': [], 'Skull Woods Map': [('rabbitbarrier', None)], 'Skull Woods West Drop': [('smallkey', 'Skull Woods')]} }, 'Skull Woods Map': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods First Entrance': []} }, 'Skull Woods West Drop': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods First Entrance': [('smallkey', 'Skull Woods')], 'Skull Woods Front Key': [('rabbitbarrier', None)], 'Skull Woods Compass': [('rabbitbarrier', None)], 'Skull Woods East Drop': []} }, 'Skull Woods Front Key': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods West Drop': []} }, 'Skull Woods Compass': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods West Drop': []} }, 'Skull Woods East Drop': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods First Entrance': [('smallkey', 'Skull Woods')], 'Skull Woods Safety Key': [('rabbitbarrier', None)]} }, 'Skull Woods Safety Key': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods East Drop': []} }, 'Skull Woods West Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'dark', 'coord': (98, 117), 'link': { 'Skull Woods West Drop Entrance (I)': []} }, 'Skull Woods West Drop Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods West Drop': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods East Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'dark', 'coord': (124, 113), 'link': { 'Skull Woods East Drop Entrance (I)': []} }, 'Skull Woods East Drop Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods East Drop': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Central Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'dark', 'coord': (120, 83), 'link': { 'Skull Woods Central Drop Entrance (I)': []} }, 'Skull Woods Central Drop Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods Central Drop': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Central Drop': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods First Entrance': [], 'Skull Woods Treasure Access': [('rabbitbarrier', None)]} }, 'Skull Woods Treasure Access': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Central Drop': [], 'Skull Woods Treasure': [('bigkey', 'Skull Woods')]} }, 'Skull Woods Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Treasure Access': []} }, 'Skull Woods Second Entrance Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (90, 96), 'link': { 'Skull Woods Surface': [], 'Skull Woods Second Entrance Entrance (I)': []} }, 'Skull Woods Second Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods Second Entrance Entrance (E)': [], 'Skull Woods Connector': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Connector': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Second Entrance Entrance (I)': [], 'Skull Woods Big Key': [('rabbitbarrier', None)], 'Skull Woods Hidden Key': [('rabbitbarrier', None)], 'Skull Woods Third Entrance Entrance (I)': []} }, 'Skull Woods Big Key': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Connector': []} }, 'Skull Woods Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Connector': []} }, 'Skull Woods Third Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods Connector': [], 'Skull Woods Third Entrance Entrance (E)': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Third Entrance Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (33, 86), 'link': { 'Skull Woods Third Entrance Entrance (I)': [], 'Hidden Skull Woods': []} }, 'Hidden Skull Woods': { 'type': 'area', 'link': { 'Lost Woods': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Skull Woods Third Entrance Entrance (E)': [], 'Skull Woods North Drop Entrance (E)': [], 'Skull Woods Fourth Entrance Entrance (E)': [('item', 'firerod')]} }, 'Skull Woods North Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'dark', 'coord': (74, 60), 'link': { 'Skull Woods North Drop Entrance (I)': []} }, 'Skull Woods North Drop Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods Connector': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Fourth Entrance Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (20, 43), 'link': { 'Hidden Skull Woods': [], 'Skull Woods Fourth Entrance Entrance (I)': []} }, 'Skull Woods Fourth Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Skull Woods Fourth Entrance Entrance (E)': [], 'Skull Woods Gauntlet Entrance': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Skull Woods Gauntlet Entrance': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Fourth Entrance Entrance (I)': [], 'Skull Woods Gauntlet Key': [('rabbitbarrier', None)], 'Skull Woods Gauntlet 1': [('smallkey', 'Skull Woods')]} }, 'Skull Woods Gauntlet Key': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Gauntlet Entrance': []} }, 'Skull Woods Gauntlet 1': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Gauntlet Entrance': [], 'Skull Woods Gauntlet 2': [('and', [ ('item', 'firerod'), ('item', 'sword')])]} }, 'Skull Woods Gauntlet 2': { 'type': 'area', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Gauntlet 2': [], 'Skull Woods Gibdo Key': [], 'Skull Woods Boss': [('smallkey', 'Skull Woods')]} }, 'Skull Woods Gibdo Key': { 'type': 'dungeonkey', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Gauntlet 2': []} }, 'Skull Woods Boss': { 'type': 'dungeonboss', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Boss Item': [('and', [ ('or', [ ('settings', 'placement_advanced'), ('item', 'mastersword'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('item', 'firerod')])]), ('or', [ ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('or', [ ('item', 'firerod'), ('item', 'somaria'), ('item', 'byrna')])]), ('item', 'sword'), ('item', 'hammer')])])]} }, 'Skull Woods Boss Item': { 'type': 'dungeonchest', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Reward': []} }, 'Skull Woods Reward': { 'type': 'dungeonreward', 'dungeon': 'Skull Woods', 'link': { 'Skull Woods Fourth Entrance Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/skullwoods.py
skullwoods.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Kakariko': { 'type': 'area', 'link': { "Thieves' Town Surface": [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], "East Thieves' Town": [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Light Bottle Ocarina': [], "Blacksmiths' House Entrance (E)": [], 'Above The Bat': [ ('item', 'hammer'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], "Mad Batter's Cave Entrance Entrance (E)": [], 'South Light World': [], 'Tavern Front Entrance (E)': [], 'Kakariko Shop Entrance (E)': [], 'Secret House Entrance (E)': [('item', 'bombs')], 'Cucco House Entrance (E)': [], "Bug Child's House Entrance (E)": [], 'Tavern Back Entrance': [('rabbitbarrier', None)], 'Kakariko Blue House Entrance (E)': [('rabbitbarrier', None)], 'Kakariko East Red House Entrance (E)': [], 'Bottle Vendor': [], 'Kakariko West Red House Entrance (E)': [], 'Kakariko Cave Entrance Entrance (E)': [], 'Kakariko Cave Drop Entrance (E)': [], 'Lost Woods': [('rabbitbarrier', None)], 'Kakariko Portal (LW)': [('item', 'titansmitts')], "Blind's House Entrance (E)": [], "Sahasrahla's House West Entrance Entrance (E)": [], "Sahasrahla's House East Entrance Entrance (E)": [], 'North Light World': []} }, "Blacksmiths' House Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (202, 353), 'link': { 'Kakariko': [], "Blacksmiths' House Entrance (I)": []} }, "Blacksmiths' House Entrance (I)": { 'type': 'interior', 'link': { "Blacksmiths' House Entrance (E)": [], 'Blacksmiths': [('and', [ ('access', 'Frog Prison'), ('or', [ ('settings', 'placement_advanced'), ('item', 'mirror')])])]} }, 'Blacksmiths': { 'type': 'chest', 'map': 'light', 'coord': (202, 347), 'link': { "Blacksmiths' House Entrance (I)": []} }, 'Above The Bat': { 'type': 'area', 'link': { 'Kakariko': [('item', 'hammer')], "Mad Batter's Cave Drop Entrance (E)": []} }, "Mad Batter's Cave Drop Entrance (E)": { 'type': 'entrance_drop', 'map': 'light', 'coord': (224, 365), 'link': { "Mad Batter's Cave Drop Entrance (I)": []} }, "Mad Batter's Cave Drop Entrance (I)": { 'type': 'interior', 'link': { "Mad Batter's Cave": []} }, "Mad Batter's Cave": { 'type': 'area', 'link': { 'Mad Batter': [('item', 'powder')], "Mad Batter's Cave Front": []} }, 'Mad Batter': { 'type': 'drop', 'map': 'light', 'coord': (215, 373), 'link': { "Mad Batter's Cave": []} }, "Mad Batter's Cave Front": { 'type': 'area', 'link': { "Mad Batter's Cave Entrance Entrance (I)": []} }, "Mad Batter's Cave Entrance Entrance (I)": { 'type': 'interior', 'link': { "Mad Batter's Cave Front": [], "Mad Batter's Cave Entrance Entrance (E)": []}, }, "Mad Batter's Cave Entrance Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (210, 368), 'link': { "Mad Batter's Cave Entrance Entrance (I)": [], 'Kakariko': []} }, 'Tavern Front Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (106, 395), 'link': { 'Kakariko': [], 'Tavern Front Entrance (I)': []} }, 'Tavern Front Entrance (I)': { 'type': 'interior', 'link': { 'Tavern Front Entrance (E)': []} }, 'Kakariko Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'light', 'coord': (73, 387), 'link': { 'Kakariko': [], 'Kakariko Shop Entrance (I)': []} }, 'Kakariko Shop Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko Shop Entrance (E)': []} }, 'Secret House Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (18, 394), 'link': { 'Kakariko': [], 'Cucco House Entrance (I)': []} }, 'Secret House Entrance (I)': { 'type': 'interior', 'link': { 'Secret House Entrance (E)': []} }, 'Cucco House Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (65, 358), 'link': { 'Kakariko': [], 'Cucco House Entrance (E)': []} }, 'Cucco House Entrance (I)': { 'type': 'interior', 'link': { 'Cucco House Entrance (E)': [], 'Cucco House': [('item', 'bombs')]} }, 'Cucco House': { 'type': 'chest', 'map': 'light', 'coord': (65, 350), 'link': { 'Cucco House Entrance (I)': []} }, "Bug Child's House Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (104, 356), 'link': { 'Kakariko': [], "Bug Child's House Entrance (I)": []} }, "Bug Child's House Entrance (I)": { 'type': 'interior', 'link': { "Bug Child's House Entrance (E)": [], 'Bug Child': [('item', 'bottle')]} }, 'Bug Child': { 'type': 'chest', 'map': 'light', 'coord': (104, 351), 'link': { "Bug Child's House Entrance (I)": []} }, 'Tavern Back Entrance': { 'type': 'item', 'map': 'light', 'coord': (106, 376), 'link': { 'Kakariko': []} }, 'Kakariko Blue House Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (135, 353), 'link': { 'Kakariko': [], 'Kakariko Blue House Entrance (I)': []} }, 'Kakariko Blue House Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko Blue House Entrance (E)': []} }, 'Kakariko East Red House Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (137, 319), 'link': { 'Kakariko': [], 'Kakariko East Red House Entrance (I)': []} }, 'Kakariko East Red House Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko East Red House Entrance (E)': []} }, 'Bottle Vendor': { 'type': 'item', 'map': 'light', 'coord': (63, 308), 'link': { 'Kakariko': []} }, 'Kakariko West Red House Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (33, 309), 'link': { 'Kakariko': [], 'Kakariko West Red House Entrance (I)': []} }, 'Kakariko West Red House Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko West Red House Entrance (E)': []} }, 'Kakariko Cave Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'light', 'coord': (15, 282), 'link': { 'Kakariko Cave Drop Entrance (I)': []} }, 'Kakariko Cave Drop Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko Cave': [('item', 'bombs')], 'Kakariko Cave Bottom': []} }, 'Kakariko Cave': { 'type': 'drop', 'map': 'light', 'coord': (15, 282), 'link': { 'Kakariko Cave Bottom': []} }, 'Kakariko Cave Bottom': { 'type': 'area', 'link': { 'Kakariko Cave Entrance Entrance (I)': []} }, 'Kakariko Cave Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko Cave Bottom': [], 'Kakariko Cave Entrance Entrance (E)': []} }, 'Kakariko Cave Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (31, 283), 'link': { 'Kakariko Cave Entrance Entrance (I)': [], 'Kakariko': []} }, 'Kakariko Portal (LW)': { 'type': 'area', 'link': { 'Kakariko Portal (DW)': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Kakariko Portal': [('item', 'powerglove')], 'Kakariko': [('item', 'titansmitts')], 'Lost Woods': [('item', 'hammer')]} }, 'Kakariko Portal': { 'type': 'area', 'link': { 'Kakariko Portal (LW)': [('and', [ ('settings', 'inverted'), ('state', 'rabbit')])], 'Kakariko Portal (DW)': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit')])]} }, "Blind's House Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (85, 279), 'link': { 'Kakariko': [], "Blind's House Entrance (I)": []} }, "Blind's House Entrance (I)": { 'type': 'interior', 'link': { "Blind's House Entrance (E)": [], "Blind's House": [('item', 'bombs')]} }, "Blind's House": { 'type': 'chest', 'map': 'light', 'coord': (85, 272), 'link': { "Blind's House Entrance (I)": []} }, "Sahasrahla's House East Entrance Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (115, 279), 'link': { 'Kakariko': [], "Sahasrahla's House East Entrance Entrance (I)": []} }, "Sahasrahla's House East Entrance Entrance (I)": { 'type': 'interior', 'link': { "Sahasrahla's House East Entrance Entrance (E)": [], "Sahasrahla's House West Entrance Entrance (I)": []} }, "Sahasrahla's House West Entrance Entrance (I)": { 'type': 'interior', 'link': { "Sahasrahla's House East Entrance Entrance (I)": [], "Sahasrahla's House West Entrance Entrance (E)": []} }, "Sahasrahla's House West Entrance Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (101, 279), 'link': { "Sahasrahla's House West Entrance Entrance (I)": [], 'Kakariko': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/kakariko.py
kakariko.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Dark River': { 'type': 'area', 'link': { 'Little River': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Witch Hut River': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'River Shop Area': [], 'Dark World Waterway': []} }, 'River Shop Area': { 'type': 'area', 'link': { 'East Light World': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'East Dark World': [('item', 'hammer'), ('item', 'powerglove')], 'Dark River': [('item', 'flippers')], 'North Dark World': [('item', 'hookshot')], 'River Shop Entrance (E)': [], 'Catfish Approach': [('item', 'powerglove')]} }, 'River Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'dark', 'coord': (528, 224), 'link': { 'River Shop Area': [], 'River Shop Entrance (I)': []} }, 'River Shop Entrance (I)': { 'type': 'interior', 'link': { 'River Shop Entrance (E)': []} }, 'Catfish Approach': { 'type': 'area', 'link': { "Zora's River": [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'River Shop Area': [('item', 'powerglove')], 'Dark River': [('item', 'flippers')], 'Catfish': [('rabbitbarrier', None)]} }, 'Catfish': { 'type': 'item', 'map': 'dark', 'coord': (587, 114), 'link': { 'Catfish Approach': []} }, 'East Dark World': { 'type': 'area', 'link': { 'East Light World': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'River Shop Area': [ ('item', 'hammer'), ('item', 'powerglove'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'Dark River': [('item', 'flippers')], 'Pyramid': [], 'South Dark World': [('item', 'hammer')], 'Frozen Lake': [('item', 'flippers')], 'Dark Fairy Cave Entrance (E)': [], 'Fake Dark Palace Entrance (E)': [], 'East Portal (DW)': [('item', 'hammer')], 'Dark Fairy Pond Entrance (E)': [], 'Dark Palace Entrance (E)': [('rabbitbarrier', None)]} }, 'Dark Fairy Cave Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (540, 427), 'link': { 'East Dark World': [], 'Dark Fairy Cave Entrance (I)': []} }, 'Dark Fairy Cave Entrance (I)': { 'type': 'interior', 'link': { 'Dark Fairy Cave Entrance (E)': []} }, 'Fake Dark Palace Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (557, 332), 'link': { 'East Dark World': [], 'Fake Dark Palace Entrance (I)': []} }, 'Fake Dark Palace Entrance (I)': { 'type': 'interior', 'link': { 'Fake Dark Palace Entrance (E)': []} }, 'East Portal (DW)': { 'type': 'area', 'link': { 'East Portal (LW)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'East Portal': [('item', 'powerglove')], 'East Dark World': [('item', 'hammer')]} }, 'Dark Fairy Pond Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (644, 464), 'link': { 'East Dark World': [], 'Dark Fairy Pond Entrance (I)': []} }, 'Dark Fairy Pond Entrance (I)': { 'type': 'interior', 'link': { 'Dark Fairy Pond Entrance (I)': []} }, 'Pyramid': { 'type': 'area', 'link': { 'Hyrule Castle': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Castle Walls': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'East Dark World': [], 'Pyramid Item': [], 'Pyramid Fairy Entrance (E)': [('and', [ ('access', 'Bomb Shop Entrance (I)'), ('crystals', 'fairy'), ('rabbitbarrier', None), ('or', [ ('and', [ ('settings', 'open'), ('nosettings', 'entrance'), ('item', 'hammer')]), ('and', [ ('settings', 'inverted'), ('nosettings', 'entrance'), ('item', 'mirror')]), ('and', [ ('or', [ ('and', [ ('nosettings', 'open'), ('nosettings', 'standard'), ('nosettings', 'inverted')]), ('settings', 'entrance')]), ('state', 'maybe;add')])])])], 'Ganon Drop Entrance (E)': [('and', [ ('nosettings', 'inverted'), ('or', [ ('and', [ ('nosettings', 'entrance'), ('settings', 'fastganon')]), ('macro', 'ganondrop')])])]} }, 'Pyramid Item': { 'type': 'item', 'map': 'dark', 'coord': (379, 297), 'link': { 'Pyramid': []} }, 'Pyramid Fairy Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (305, 321), 'link': { 'Pyramid': [], 'Pyramid Fairy Entrance (I)': []} }, 'Pyramid Fairy Entrance (I)': { 'type': 'interior', 'link': { 'Pyramid Fairy Entrance (E)': [], 'Pyramid Fairy': []} }, 'Pyramid Fairy': { 'type': 'cave', 'map': 'dark', 'coord': (305, 321), 'link': { 'Pyramid Fairy Entrance (I)': []} }, 'Ganon Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'dark', 'coord': (324, 270), 'link': { 'Ganon Drop Entrance (I)': []} }, 'Ganon Drop Entrance (I)': { 'type': 'interior', 'link': { 'Ganon': [('and', [ ('macro', 'ganon'), ('item', 'mastersword'), ('item', 'bow'), ('or', [('item', 'firerod'), ('item', 'lantern')]), ('or', [ ('item', 'silverarrows'), ('settings', 'placement_advanced')])])]} }, 'Ganon': { 'type': 'ganon', 'map': 'dark', 'coord': (324, 240), 'link': {} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/darkworld_east.py
darkworld_east.py
__all__ = 'LOCATIONS', LOCATIONS = { 'North Dark World': { 'type': 'area', 'link': { 'North Light World': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], "Thieves' Town Surface": [], 'Skull Woods Surface': [], "Thieves' Town Fortune Teller Entrance (E)": [], 'South Specialty Shop Entrance (E)': [], 'Bumper Cave Bottom Entrance Entrance (E)': [ ('item', 'powerglove')], 'Bumper Cave Top': [ ('glitch', 'major'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'North Specialty Shop Entrance (E)': [], 'Dark Chapel Entrance (E)': [], 'Haunted Graveyard': [('rabbitbarrier', None)], 'Dark River': [ ('item', 'flippers'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])]}, 'visible': {'Bumper Cave': []} }, "Thieves' Town Fortune Teller Entrance (E)": { 'type': 'entrance', 'map': 'dark', 'coord': (119, 214), 'link': { 'North Dark World': [], "Thieves' Town Fortune Teller Entrance (I)": []} }, "Thieves' Town Fortune Teller Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Fortune Teller Entrance (E)": []} }, 'South Specialty Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'dark', 'coord': (214, 302), 'link': { 'North Dark World': [], 'South Specialty Shop Entrance (I)': []} }, 'South Specialty Shop Entrance (I)': { 'type': 'interior', 'link': { 'South Specialty Shop Entrance (E)': []} }, 'Bumper Cave Bottom Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (236, 116), 'link': { 'North Dark World': [], 'Bumper Cave Bottom Entrance Entrance (I)': [ ('nosettings', 'inverted')], 'Hebra Ascent (Bottom) Entrance (I)': [('settings', 'inverted')]} }, 'Bumper Cave Bottom Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Bumper Cave Bottom Entrance Entrance (E)': [ ('nosettings', 'inverted')], 'Hebra Ascent (Bottom) Entrance (E)': [('settings', 'inverted')], 'Bumper Cave 1': []} }, 'Bumper Cave 1': { 'type': 'area', 'link': { 'Bumper Cave Bottom Entrance Entrance (I)': [], 'Bumper Cave 2': [ ('and', [ ('settings', 'placement_advanced'), ('rabbitbarrier', None)]), ('item', 'hookshot')]} }, 'Bumper Cave 2': { 'type': 'area', 'link': { 'Bumper Cave 1': [], 'Bumper Cave 3': [('item', 'cape')]} }, 'Bumper Cave 3': { 'type': 'area', 'link': { 'Bumper Cave 2': [('item', 'cape')], 'Bumper Cave Top Entrance Entrance (I)': []} }, 'Bumper Cave Top Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Bumper Cave 3': [], 'Bumper Cave Top Entrance Entrance (E)': [ ('nosettings', 'inverted')], 'Hebra Descent (Bottom) Entrance (E)': [('settings', 'inverted')]} }, 'Bumper Cave Top Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (238, 101), 'link': { 'Bumper Cave Top Entrance Entrance (I)': [ ('nosettings', 'inverted')], 'Hebra Descent (Bottom) Entrance (I)': [('settings', 'inverted')], 'Bumper Cave Top': []} }, 'Bumper Cave Top': { 'type': 'area', 'link': { 'Hebra Descent End': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Bumper Cave Top Entrance Entrance (E)': [], 'Bumper Cave': [], 'North Dark World': []} }, 'Bumper Cave': { 'type': 'item', 'map': 'dark', 'coord': (223, 101), 'link': { 'Bumper Cave Top': []} }, 'North Specialty Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'dark', 'coord': (217, 37), 'link': { 'North Dark World': [], 'North Specialty Shop Entrance (I)': []} }, 'North Specialty Shop Entrance (I)': { 'type': 'interior', 'link': { 'North Specialty Shop Entrance (E)': []} }, 'Dark Chapel Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (300, 181), 'link': { 'North Dark World': [], 'Dark Chapel Entrance (I)': []} }, 'Haunted Graveyard': { 'type': 'area', 'link': { 'North Dark World': [('rabbitbarrier', None)], 'Graveyard Cave Entrance (E)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], "King's Tomb Exterior": [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])]} }, 'Dark Chapel Entrance (I)': { 'type': 'interior', 'link': { 'Dark Chapel Entrance (E)': []} } }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/darkworld_north.py
darkworld_north.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Turtle Rock Entrance Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (618, 54), 'link': { 'Turtle Rock Entrance Entrance (I)': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('settings', 'bottle'), ('item', 'bluemail')])])]} }, 'Turtle Rock Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Turtle Rock Entrance Entrance (E)': [], 'Turtle Rock Big Hole': [('item', 'somaria')]} }, 'Turtle Rock Big Hole': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Entrance Entrance (I)': [], 'Turtle Rock Compass': [], 'Turtle Rock Rolling Spikes': [('and', [ ('item', 'somaria'), ('item', 'firerod')])], 'Turtle Rock Trapped Stalfos': []} }, 'Turtle Rock Compass': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Big Hole': [('item', 'somaria')]} }, 'Turtle Rock Rolling Spikes': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Big Hole': [('item', 'somaria')], 'Turtle Rock Map': [], 'Turtle Rock Map Key': []} }, 'Turtle Rock Map': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Rolling Spikes': []} }, 'Turtle Rock Map Key': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Rolling Spikes': []} }, 'Turtle Rock Trapped Stalfos': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Big Hole': [('item', 'somaria')], 'Turtle Rock Hokkubokku Key Room': [('smallkey', 'Turtle Rock')]}, }, 'Turtle Rock Hokkubokku Key Room': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Trapped Stalfos': [('smallkey', 'Turtle Rock')], 'Turtle Rock Chain Chomp Room': [('smallkey', 'Turtle Rock')], 'Turtle Rock First Hokkubokku Key': []} }, 'Turtle Rock First Hokkubokku Key': { 'type': 'dungeonkey', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Hokkubokku Key Room': []} }, 'Turtle Rock Chain Chomp Room': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Hokkubokku Key Room': [('smallkey', 'Turtle Rock')], 'Turtle Rock Chain Chomp Key': [], 'Turtle Rock Pipe Rooms': [('smallkey', 'Turtle Rock')]} }, 'Turtle Rock Chain Chomp Key': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Chain Chomp Room': []} }, 'Turtle Rock Pipe Rooms': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Chain Chomp Room': [('smallkey', 'Turtle Rock')], 'Turtle Rock Second Hokkubokku Key': [], 'Turtle Rock Big Key': [('smallkey', 'Turtle Rock')], 'Turtle Rock Hokkubokku Room': []} }, 'Turtle Rock Second Hokkubokku Key': { 'type': 'dungeonkey', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Pipe Rooms': []} }, 'Turtle Rock Big Key': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Pipe Rooms': []} }, 'Turtle Rock Hokkubokku Room': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Pipe Rooms': [], 'Turtle Rock Laser Eye Exit Entrance (I)': [], 'Turtle Rock Zoro Room': [('bigkey', 'Turtle Rock')]} }, 'Turtle Rock Laser Eye Exit Entrance (I)': { 'type': 'interior', 'link': { 'Turtle Rock Hokkubokku Room': [('and', [ ('rabbitbarrier', None), ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('settings', 'bottle'), ('item', 'bluemail')])])])])], 'Turtle Rock Laser Eye Exit Entrance (E)': []} }, 'Turtle Rock Laser Eye Exit Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (522, 60), 'link': { 'Turtle Rock Laser Eye Exit Entrance (I)': [], 'Turtle Rock Balcony': []} }, 'Turtle Rock Balcony': { 'type': 'area', 'link': { 'Spiral Cave Top Entrance Entrance (E)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Goriya Cave Entrance (E)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Turtle Rock Laser Eye Exit Entrance (E)': [], 'Turtle Rock Big Chest Exit Entrance (E)': []} }, 'Turtle Rock Big Chest Exit Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (553, 60), 'link': { 'Turtle Rock Balcony': [], 'Turtle Rock Big Chest Exit Entrance (I)': []} }, 'Turtle Rock Big Chest Exit Entrance (I)': { 'type': 'interior', 'link': { 'Turtle Rock Big Chest Exit Entrance (E)': [], 'Turtle Rock Treasure': [('and', [ ('or', [ ('item', 'hookshot'), ('item', 'somaria')]), ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('settings', 'bottle'), ('item', 'bluemail')])])])])], 'Turtle Rock Hokkubokku Room': [('and', [ ('item', 'pegasus'), ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('settings', 'bottle'), ('item', 'bluemail')])])])])]} }, 'Turtle Rock Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Big Chest Exit Entrance (I)': [('item', 'somaria')], 'Turtle Rock Hokkubokku Room': []} }, 'Turtle Rock Zoro Room': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Hokkubokku Room': [], 'Turtle Rock Switch Room': [('item', 'bombs'), ('item', 'pegasus')]} }, 'Turtle Rock Switch Room': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Zoro Room': [], 'Turtle Rock Switch Key': [], 'Turtle Rock Dark Room North': [('smallkey', 'Turtle Rock')]} }, 'Turtle Rock Switch Key': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Switch Room': []} }, 'Turtle Rock Dark Room North': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Switch Room': [('smallkey', 'Turtle Rock')], 'Turtle Rock Dark Room Maze': [('and', [ ('item', 'lantern'), ('item', 'somaria')])]} }, 'Turtle Rock Dark Room Maze': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Dark Room North': [], 'Turtle Rock Dark Room South': []} }, 'Turtle Rock Dark Room South': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Dark Room Maze': [('and', [ ('item', 'lantern'), ('item', 'somaria')])], 'Turtle Rock Treasury': []} }, 'Turtle Rock Treasury': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Dark Room South': [], 'Turtle Rock Treasury Chest 1': [ ('item', 'mirrorshield'), ('item', 'byrna'), ('item', 'cape'), ('settings', 'placement_advanced')], 'Turtle Rock Treasury Chest 2': [ ('item', 'mirrorshield'), ('item', 'byrna'), ('item', 'cape'), ('settings', 'placement_advanced')], 'Turtle Rock Treasury Chest 3': [ ('item', 'mirrorshield'), ('item', 'byrna'), ('item', 'cape'), ('settings', 'placement_advanced')], 'Turtle Rock Treasury Chest 4': [ ('item', 'mirrorshield'), ('item', 'byrna'), ('item', 'cape'), ('settings', 'placement_advanced')], 'Turtle Rock Fairy Exit Entrance (I)': [('item', 'bombs')], 'Turtle Rock Boss Maze': [('smallkey', 'Turtle Rock')]} }, 'Turtle Rock Treasury Chest 1': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Treasury': []} }, 'Turtle Rock Treasury Chest 2': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Treasury': []} }, 'Turtle Rock Treasury Chest 3': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Treasury': []} }, 'Turtle Rock Treasury Chest 4': { 'type': 'dungeonchest', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Treasury': []} }, 'Turtle Rock Fairy Exit Entrance (I)': { 'type': 'interior', 'link': { 'Turtle Rock Treasury': [('and', [ ('rabbitbarrier', None), ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('settings', 'bottle'), ('item', 'bluemail')])])])])], 'Turtle Rock Fairy Exit Entrance (E)': []} }, 'Turtle Rock Fairy Exit Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (538, 76), 'link': { 'Turtle Rock Fairy Exit Entrance (I)': [], 'Turtle Rock Fairy Exit': []} }, 'Turtle Rock Fairy Exit': { 'type': 'area', 'link': { 'Fairy Maze Top Entrance Entrance (E)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Turtle Rock Fairy Exit Entrance (E)': []} }, 'Turtle Rock Boss Maze': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Treasury': [], 'Turtle Rock Boss Door': [('item', 'somaria')]} }, 'Turtle Rock Boss Door': { 'type': 'area', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Boss Maze': [('item', 'somaria')], 'Turtle Rock Boss': [('bigkey', 'Turtle Rock')]} }, 'Turtle Rock Boss': { 'type': 'dungeonboss', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Boss Item': [('and', [ ('item', 'firerod'), ('item', 'icerod'), ('or', [ ('settings', 'placement_advanced'), ('settings', 'swordless'), ('settings', 'mastersword2'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('item', 'mastersword')])]), ('or', [ ('item', 'mastersword3'), ('item', 'hammer'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('item', 'sword')])])])]} }, 'Turtle Rock Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Reward': []} }, 'Turtle Rock Reward': { 'type': 'dungeonreward', 'dungeon': 'Turtle Rock', 'link': { 'Turtle Rock Entrance Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/turtlerock.py
turtlerock.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Mountain Tower Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'light', 'coord': (372, 35), 'link': { 'West Upper Mount Hebra': [], 'Mountain Tower Entrance (I)': []} }, 'Mountain Tower Entrance (I)': { 'type': 'interior', 'link': { 'Mountain Tower Entrance (E)': [], 'Mountain Tower Interior': [('rabbitbarrier', None)]} }, 'Mountain Tower Interior': { 'type': 'area', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Small Key': [], 'Mountain Tower Map': [], 'Mountain Tower Big Key Descent': [('smallkey', 'Mountain Tower')], 'Mountain Tower Ascent': [('bigkey', 'Mountain Tower')]} }, 'Mountain Tower Small Key': { 'type': 'dungeonchest', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Interior': []} }, 'Mountain Tower Map': { 'type': 'dungeonchest', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Interior': []} }, 'Mountain Tower Big Key Descent': { 'type': 'area', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Interior': [], 'Mountain Tower Big Key': [ ('item', 'lantern'), ('item', 'firerod')]} }, 'Mountain Tower Big Key': { 'type': 'dungeonchest', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Big Key Descent': []} }, 'Mountain Tower Ascent': { 'type': 'area', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Interior': [], 'Mountain Tower Compass': [], 'Mountain Tower Treasure': [], 'Mountain Tower Boss': []} }, 'Mountain Tower Compass': { 'type': 'dungeonchest', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Ascent': []} }, 'Mountain Tower Treasure': { 'type': 'dungeonchest', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Ascent': []} }, 'Mountain Tower Boss': { 'type': 'dungeonboss', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Boss Item': [('item', 'sword'), ('item', 'hammer')]} }, 'Mountain Tower Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Reward': []} }, 'Mountain Tower Reward': { 'type': 'dungeonreward', 'dungeon': 'Mountain Tower', 'link': { 'Mountain Tower Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/mountaintower.py
mountaintower.py
__all__ = 'LOCATIONS', LOCATIONS = { 'East Light World': { 'type': 'area', 'link': { 'River Shop Area': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'East Dark World': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Light Bottle Ocarina': [], 'Witch Hut River': [ ('item', 'flippers'), ('and', [('glitch', 'overworld'), ('rabbitbarrier', None)])], 'Witch Hut Entrance (E)': [('rabbitbarrier', None)], 'Witch': [('rabbitbarrier', None)], "Zora's River": [ ('item', 'powerglove'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'North Light World': [], 'Hyrule Castle': [('item', 'powerglove')], 'South Light World': [], 'East Fairy Cave Entrance (E)': [], 'Lake Hylia': [('item', 'flippers')], 'East Fairy Pond Entrance (E)': [], 'East Portal (LW)': [('item', 'hammer')], "Sahasrahla's Hideout Entrance (E)": [], 'East Palace Entrance (E)': []} }, 'Witch Hut River': { 'type': 'area', 'link': { 'Dark River': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'East Light World': [], 'North Light World': [], 'Witch Hut Waterway': []} }, 'Witch Hut Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (531, 224), 'link': { 'East Light World': [('rabbitbarrier', None)], 'Witch Hut Entrance (I)': []} }, 'Witch Hut Entrance (I)': { 'type': 'interior', 'link': { 'Witch Hut Entrance (E)': [], 'Witch Hut': [('and', [('access', 'Witch'), ('item', 'mushroom')])]} }, 'Witch Hut': { 'type': 'chest', 'map': 'light', 'coord': (531, 215), 'link': { 'Witch Hut Entrance (I)': []} }, 'Witch': { 'type': 'area', 'link': { 'East Light World': [('rabbitbarrier', None)]} }, 'East Fairy Cave Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (546, 428), 'link': { 'East Light World': [], 'East Fairy Cave Entrance (I)': []} }, 'East Fairy Cave Entrance (I)': { 'type': 'interior', 'link': { 'East Fairy Cave Entrance (E)': []} }, 'East Fairy Pond Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (650, 464), 'link': { 'East Light World': [], 'East Fairy Pond Entrance (I)': []} }, 'East Fairy Pond Entrance (I)': { 'type': 'interior', 'link': { 'East Fairy Pond Entrance (E)': []} }, 'East Portal (LW)': { 'type': 'area', 'link': { 'East Portal (DW)': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'East Light World': [('item', 'hammer')], 'East Portal': [('item', 'powerglove')]} }, 'East Portal': { 'type': 'area', 'link': { 'East Portal (DW)': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit')])], 'East Portal (LW)': [('and', [ ('settings', 'inverted'), ('state', 'rabbit')])]} }, "Sahasrahla's Hideout Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (537, 300), 'link': { 'East Light World': [], "Sahasrahla's Hideout Entrance (I)": []} }, "Sahasrahla's Hideout Entrance (I)": { 'type': 'interior', 'link': { "Sahasrahla's Hideout Entrance (E)": [], "Sahasrahla's Hideout": []} }, "Sahasrahla's Hideout": { 'type': 'area', 'link': { "Sahasrahla's Hideout Entrance (I)": [], "Sahasrahla's Reward": [('pendant', 'courage')], "Sahasrahla's Treasure": [('item', 'bombs'), ('item', 'pegasus')]} }, "Sahasrahla's Reward": { 'type': 'chest', 'map': 'light', 'coord': (537, 300), 'link': { "Sahasrahla's Hideout": []} }, "Sahasrahla's Treasure": { 'type': 'cave', 'map': 'light', 'coord': (537, 284), 'link': { "Sahasrahla's Hideout": []} }, "Zora's River": { 'type': 'area', 'link': { 'Catfish Approach': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'East Light World': [('item', 'powerglove')], 'Waterfall Lake': [('item', 'flippers')], 'King Zora': [], 'Zora River Viewpoint': [ ('item', 'flippers'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])]}, 'visible': {'Zora River Viewpoint': []} }, 'Waterfall Lake': { 'type': 'area', 'link': { 'Zora River Waterway': [], "Zora's River": [], 'Waterfall Fairy Entrance (E)': [ ('item', 'flippers'), ('and', [ ('glitch', 'overworld'), ('or', [ ('item', 'pearl'), ('item', 'pegasus')])])]} }, 'Waterfall Fairy Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (597, 89), 'link': { 'Waterfall Lake': [('item', 'flippers')], 'Waterfall Fairy Entrance (I)': []} }, 'Waterfall Fairy Entrance (I)': { 'type': 'interior', 'link': { 'Waterfall Fairy Entrance (E)': [], 'Waterfall Fairy': []} }, 'Waterfall Fairy': { 'type': 'cave', 'map': 'light', 'coord': (597, 89), 'link': { 'Waterfall Fairy Entrance (E)': []} }, 'King Zora': { 'type': 'item', 'map': 'light', 'coord': (640, 100), 'link': { "Zora's River": []} }, 'Zora River Viewpoint': { 'type': 'item', 'map': 'light', 'coord': (640, 120), 'link': { "Zora's River": [('item', 'flippers')]} }, 'East Palace Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'light', 'coord': (636, 272), 'link': { 'East Palace Entrance (E)': [], 'East Palace Entrance (I)': []} }, 'East Palace Entrance (I)': { 'type': 'interior', 'link': { 'East Palace Entrance (E)': [], 'East Palace Interior': [('rabbitbarrier', None)]} }, 'East Palace Interior': { 'type': 'area', 'dungeon': 'East Palace', 'link': { 'East Palace Entrance (I)': [], 'East Palace Rupee': [], 'East Palace Map': [], 'East Palace Compass': [], 'East Palace Treasure': [('bigkey', 'East Palace')], 'East Palace Dark Room': [('item', 'lantern')], 'East Palace Boss Door': [('bigkey', 'East Palace')]} }, 'East Palace Rupee': { 'type': 'dungeonchest', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': []} }, 'East Palace Map': { 'type': 'dungeonchest', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': []} }, 'East Palace Compass': { 'type': 'dungeonchest', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': []} }, 'East Palace Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': []} }, 'East Palace Dark Room': { 'type': 'area', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': [], 'East Palace Hidden Key': [], 'East Palace Big Key': [('smallkey', 'East Palace')]} }, 'East Palace Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'East Palace', 'link': { 'East Palace Dark Room': []} }, 'East Palace Big Key': { 'type': 'dungeonchest', 'dungeon': 'East Palace', 'link': { 'East Palace Dark Room': []} }, 'East Palace Boss Door': { 'type': 'area', 'dungeon': 'East Palace', 'link': { 'East Palace Interior': [], 'East Palace Gauntlet Entrance': [ ('item', 'lantern'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])]} }, 'East Palace Gauntlet Entrance': { 'type': 'area', 'dungeon': 'East Palace', 'link': { 'East Palace Boss Door': [], 'East Palace Eyegore Key': [], 'East Palace Gauntlet': [('smallkey', 'East Palace')]} }, 'East Palace Eyegore Key': { 'type': 'dungeonkey', 'dungeon': 'East Palace', 'link': { 'East Palace Gauntlet Entrance': []} }, 'East Palace Gauntlet': { 'type': 'area', 'dungeon': 'East Palace', 'link': { 'East Palace Gauntlet Entrance': [ ('item', 'lantern'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])], 'East Palace Boss': [('item', 'bow'), ('settings', 'enemiser')]} }, 'East Palace Boss': { 'type': 'dungeonboss', 'dungeon': 'East Palace', 'link': { 'East Palace Boss Item': [ ('item', 'sword'), ('item', 'hammer'), ('item', 'bow'), ('item', 'boomerang'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('or', [ ('item', 'firerod'), ('item', 'icerod'), ('item', 'byrna'), ('item', 'somaria')])])]} }, 'East Palace Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'East Palace', 'link': { 'East Palace Reward': []} }, 'East Palace Reward': { 'type': 'dungeonreward', 'dungeon': 'East Palace', 'link': { 'East Palace Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/lightworld_east.py
lightworld_east.py
__all__ = 'LOCATIONS', LOCATIONS = { "Thieves' Town Surface": { 'type': 'area', 'link': { 'Kakariko': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'South Light World': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'South Dark World': [], 'Frog Prison': [('item', 'titansmitts')], "East Thieves' Town": [ ('item', 'titansmitts'), ('or', [ ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')]), ('glitch', 'major')])], "Thieves' Town Southern House Entrance (E)": [('item', 'bombs')], "Thieves' Town Shop Entrance (E)": [('item', 'hammer')], "Thieves' Town Eastern House Entrance (E)": [], "Thieves' Town Underground Entrance (E)": [('rabbitbarrier', None)], "Thieves' Town Western House Entrance (E)": [], 'Skull Woods Surface': [], 'Kakariko Portal (DW)': [('item', 'titansmitts')], 'North Dark World': []} }, 'Frog Prison': { 'type': 'area', 'link': { 'South Light World': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], "Thieves' Town Surface": [('item', 'titansmitts')]} }, "Thieves' Town Southern House Entrance (E)": { 'type': 'entrance_unique', 'map': 'dark', 'coord': (67, 386), 'link': { "Thieves' Town Surface": [], "Thieves' Town Southern House Entrance (I)": []} }, "Thieves' Town Southern House Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Southern House Entrance (E)": [], 'Sealed House': []} }, 'Sealed House': { 'type': 'chest', 'map': 'dark', 'coord': (67, 383), 'link': { "Thieves' Town Southern House Entrance (E)": []} }, "Thieves' Town Shop Entrance (E)": { 'type': 'entrance_shop', 'map': 'dark', 'coord': (129, 353), 'link': { "Thieves' Town Surface": [('item', 'hammer')], "Thieves' Town Shop Entrance (I)": []} }, "Thieves' Town Shop Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Shop Entrance (E)": []} }, "Thieves' Town Eastern House Entrance (E)": { 'type': 'entrance_unique', 'map': 'dark', 'coord': (131, 320), 'link': { "Thieves' Town Surface": [], "Thieves' Town Eastern House Entrance (I)": []} }, "Thieves' Town Eastern House Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Eastern House Entrance (E)": [], 'Deserted House': []} }, 'Deserted House': { 'type': 'chest', 'map': 'dark', 'coord': (131, 314), 'link': { "Thieves' Town Eastern House Entrance (I)": []} }, "Thieves' Town Western House Entrance (E)": { 'type': 'entrance_unique', 'map': 'dark', 'coord': (28, 310), 'link': { "Thieves' Town Surface": [], "Thieves' Town Western House Entrance (I)": []} }, "Thieves' Town Western House Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Western House Entrance (E)": [], 'Chest Game': []} }, 'Chest Game': { 'type': 'chest', 'map': 'dark', 'coord': (28, 304), 'link': { "Thieves' Town Western House Entrance (I)": []} }, "East Thieves' Town": { 'type': 'area', 'link': { 'Kakariko': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Above The Bat': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], "Thieves' Town Surface": [('item', 'titansmitts')], 'Locked Chest': [('access', 'Blacksmiths')], 'Stake Cave Entrance (E)': [('item', 'hammer')]} }, 'Locked Chest': { 'type': 'area', 'link': { "East Thieves' Town": []} }, 'Stake Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (204, 401), 'link': { "East Thieves' Town": [], 'Stake Cave Entrance (I)': []} }, 'Stake Cave Entrance (I)': { 'type': 'interior', 'link': { 'Stake Cave Entrance (E)': [], 'Stake Cave': []} }, 'Stake Cave': { 'type': 'drop', 'map': 'dark', 'coord': (204, 401), 'link': { 'Stake Cave Entrance (I)': []} }, "Thieves' Town Underground Entrance (E)": { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (77, 322), 'link': { "Thieves' Town Surface": [], "Thieves' Town Underground Entrance (I)": []} }, "Thieves' Town Underground Entrance (I)": { 'type': 'interior', 'link': { "Thieves' Town Underground Entrance (E)": [], "Thieves' Town Underground": [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, "Thieves' Town Underground": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground Entrance (I)": [], "Thieves' Town Map": [('rabbitbarrier', None)], "Thieves' Town Rupees": [('rabbitbarrier', None)], "Thieves' Town Compass": [('rabbitbarrier', None)], "Thieves' Town Big Key": [('rabbitbarrier', None)], "Thieves' Town Boss Hall": [('bigkey', "Thieves' Town")]} }, "Thieves' Town Map": { 'type': 'dungeonchest', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground": []} }, "Thieves' Town Rupees": { 'type': 'dungeonchest', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground": []} }, "Thieves' Town Compass": { 'type': 'dungeonchest', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground": []} }, "Thieves' Town Big Key": { 'type': 'dungeonchest', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground": []} }, "Thieves' Town Boss Hall": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground": [], "Thieves' Town First Hidden Key": [('rabbitbarrier', None)], "Thieves' Town Boss": [('and', [ ('access', "Thieves' Town Attic"), ('access', "Thieves' Town Blind's Cell")])], "Thieves' Town Gauntlet": [('smallkey', "Thieves' Town")]} }, "Thieves' Town First Hidden Key": { 'type': 'dungeonkey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Boss Hall": []} }, "Thieves' Town Gauntlet": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Boss Hall": [('rabbitbarrier', None)], "Thieves' Town Second Hidden Key": [('rabbitbarrier', None)], "Thieves' Town Attic": [('smallkey', "Thieves' Town")], "Thieves' Town Dungeons": []} }, "Thieves' Town Second Hidden Key": { 'type': 'dungeonkey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Gauntlet": []} }, "Thieves' Town Attic": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Gauntlet": [], "Thieves' Town Bombs": [('rabbitbarrier', None)]} }, "Thieves' Town Bombs": { 'type': 'dungeonchest_nokey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Attic": []} }, "Thieves' Town Dungeons": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Gauntlet": [], "Thieves' Town Treasure Room": [('smallkey', "Thieves' Town")], "Thieves' Town Blind's Cell": [('bigkey', "Thieves' Town")]} }, "Thieves' Town Treasure Room": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Dungeons": [], "Thieves' Town Treasure": [('item', 'hammer')]} }, "Thieves' Town Treasure": { 'type': 'dungeonchest_nokey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Treasure Room": [('item', 'hammer')]} }, "Thieves' Town Blind's Cell": { 'type': 'area', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Dungeons": [], "Thieves' Town Blind's Key": []} }, "Thieves' Town Blind's Key": { 'type': 'dungeonchest_nokey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Blind's Cell": []} }, "Thieves' Town Boss": { 'type': 'dungeonboss', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Boss Item": [('and', [ ('or', [ ('settings', 'placement_advanced'), ('settings', 'swordless'), ('and', [ ('item', 'sword'), ('or', [ ('item', 'cape'), ('item', 'byrna')])])]), ('or', [ ('item', 'sword'), ('item', 'hammer'), ('item', 'byrna'), ('item', 'somaria')])])]} }, "Thieves' Town Boss Item": { 'type': 'dungeonchest_nokey', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Reward": []} }, "Thieves' Town Reward": { 'type': 'dungeonreward', 'dungeon': "Thieves' Town", 'link': { "Thieves' Town Underground Entrance (I)": []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/thievestown.py
thievestown.py
__all__ = 'LOCATIONS', LOCATIONS= { 'Lost Woods': { 'type': 'area', 'link': { 'Skull Woods': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Hidden Skull Woods': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Light Bottle Ocarina': [], 'Kakariko': [('rabbitbarrier', None)], 'Kakariko Portal (LW)': [('item', 'hammer')], 'North Light World': [], 'Master Sword Pedestal': [('and', [ ('pendant', 'courage'), ('pendant', 'power'), ('pendant', 'wisdom'), ('or', [ ('settings', 'placement_advanced'), ('item', 'mudora')])])], 'Mushroom': [('rabbitbarrier', None)], "Thief's Cave Drop Entrance (E)": [('rabbitbarrier', None)], "Thief's Cave Entrance Entrance (E)": [], 'Northern Chest Game Entrance (E)': []}, 'visible': { 'Master Sword Pedestal': [('item', 'mudora')]} }, 'Master Sword Pedestal': { 'type': 'item', 'map': 'light', 'coord': (27, 33), 'link': { 'Lost Woods': []} }, 'Mushroom': { 'type': 'item', 'map': 'light', 'coord': (79, 57), 'link': { 'Lost Woods': [('rabbitbarrier', None)]} }, "Thief's Cave Drop Entrance (E)": { 'type': 'entrance_drop', 'map': 'light', 'coord': (125, 84), 'link': { "Thief's Cave Drop Entrance (I)": []} }, "Thief's Cave Drop Entrance (I)": { 'type': 'interior', 'link': { "Thief's Cave": []} }, "Thief's Cave": { 'type': 'drop', 'map': 'light', 'coord': (125, 87), 'link': { "Thief's Cave Entrance": []} }, "Thief's Cave Entrance": { 'type': 'area', 'link': { "Thief's Cave Entrance Entrance (I)": []}, 'visible': {"Thief's Cave": []} }, "Thief's Cave Entrance Entrance (I)": { 'type': 'interior', 'link': { "Thief's Cave Entrance": [], "Thief's Cave Entrance Entrance (I)": []} }, "Thief's Cave Entrance Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (122, 99), 'link': { "Thief's Cave Entrance": [], 'Lost Woods': []} }, 'Northern Chest Game Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (123, 10), 'link': { 'Lost Woods': [], 'Northern Chest Game Entrance (I)': []} }, 'Northern Chest Game Entrance (I)': { 'type': 'interior', 'link': { 'Northern Chest Game Entrance (E)': []} }, 'North Light World': { 'type': 'area', 'link': { 'North Dark World': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Kakariko': [], 'Lost Woods': [], 'Kakariko Fortune Teller Entrance (E)': [], 'Hyrule Castle': [], 'Crossworld Waterway': [('item', 'flippers')], "Lumberjacks' House Entrance (E)": [], 'Cut Tree Drop Entrance (E)': [('and', [ ('access', 'Castle Tower Reward'), ('item', 'pegasus')])], 'Cut Tree Cave Entrance (E)': [], 'Hebra Ascent (Bottom) Entrance (E)': [('item', 'powerglove')], 'Pegasus Cave Entrance (E)': [('item', 'pegasus')], 'Sanctuary Entrance Entrance (E)': [], 'Sanctuary Drop Entrance (E)': [('item', 'powerglove')], 'Graveyard Cave Entrance': [ ('and', [('settings', 'inverted'), ('rabbitbarrier', None)]), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], "King's Tomb Exterior": [('item', 'titansmitts')], 'North Fairy Pond Drop Entrance (E)': [('rabbitbarrier', None)], 'North Fairy Pond Cave Entrance (E)': [], 'Witch Hut River': [('item', 'flippers')], 'Little River': [('item', 'flippers')], 'East Light World': [], 'West Lower Mount Hebra': [ ('glitch', 'major'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])]} }, 'Kakariko Fortune Teller Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (125, 214), 'link': { 'North Light World': [], 'Kakariko Fortune Teller Entrance (I)': []} }, 'Kakariko Fortune Teller Entrance (I)': { 'type': 'interior', 'link': { 'Kakariko Fortune Teller Entrance (E)': []} }, 'Crossworld Waterway': { 'type': 'area', 'link': { 'Lake Hylia': [], 'North Light World': []} }, "Lumberjacks' House Entrance (E)": { 'type': 'entrance', 'map': 'light', 'coord': (223, 40), 'link': { 'North Light World': [], "Lumberjacks' House Entrance (I)": []} }, "Lumberjacks' House Entrance (I)": { 'type': 'interior', 'link': { "Lumberjacks' House Entrance (E)": []} }, 'Cut Tree Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'light', 'coord': (200, 49), 'link': { 'Cut Tree Drop Entrance (I)': []} }, 'Cut Tree Drop Entrance (I)': { 'type': 'interior', 'link': { 'Cut Tree': []} }, 'Cut Tree': { 'type': 'drop', 'map': 'light', 'coord': (200, 49), 'link': { 'Cut Tree Viewpoint': []} }, 'Cut Tree Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (220, 21), 'link': { 'North Light World': [], 'Cut Tree Cave Entrance (I)': []} }, 'Cut Tree Cave Entrance (I)': { 'type': 'interior', 'link': { 'Cut Tree Cave Entrance (E)': [], 'Cut Tree Viewpoint': []} }, 'Cut Tree Viewpoint': { 'type': 'area', 'link': { 'Cut Tree Cave Entrance (I)': []}, 'visible': {'Cut Tree': []} }, 'Hebra Ascent (Bottom) Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (236, 116), 'link': { 'North Light World': [], 'Hebra Ascent (Bottom) Entrance (I)': [('nosettings', 'inverted')], 'Bumper Cave Bottom Entrance Entrance (I)': [ ('settings', 'inverted')]} }, 'Hebra Ascent (Bottom) Entrance (I)': { 'type': 'interior', 'link': { 'Hebra Ascent (Bottom) Entrance (E)': [('nosettings', 'inverted')], 'Bumper Cave Bottom Entrance Entrance (E)': [ ('settings', 'inverted')], 'Hebra Ascent': []} }, 'Hebra Descent (Bottom) Entrance (I)': { 'type': 'interior', 'link': { 'Hebra Descent': [], 'Hebra Descent (Bottom) Entrance (E)': [('nosettings', 'inverted')], 'Bumper Cave Bottom Entrance Entrance (E)': [ ('settings', 'inverted')]} }, 'Hebra Descent (Bottom) Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (238, 101), 'link': { 'Hebra Descent (Bottom) Entrance (I)': [('nosettings', 'inverted')], 'Bumper Cave Top Entrance Entrance (I)': [ ('settings', 'inverted')], 'Hebra Descent End': []} }, 'Hebra Descent End': { 'type': 'area', 'link': { 'Bumper Cave Top': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Hebra Descent (Bottom) Entrance (E)': [], 'North Light World': []} }, 'Pegasus Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (259, 194), 'link': { 'North Light World': [], 'Pegasus Cave Entrance (I)': []} }, 'Pegasus Cave Entrance (I)': { 'type': 'interior', 'link': { 'Pegasus Cave Entrance (E)': [], 'Pegasus Cave': []} }, 'Pegasus Cave': { 'type': 'drop', 'map': 'light', 'coord': (259, 194), 'link': { 'Pegasus Cave Entrance (I)': []} }, 'Sanctuary Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (306, 176), 'link': { 'North Light World': [], 'Sanctuary Entrance Entrance (I)': []} }, 'Sanctuary Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Sanctuary Entrance Entrance (E)': [], 'Sanctuary': [('rabbitbarrier', None)]} }, 'Sanctuary Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'light', 'coord': (345, 194), 'link': { 'Sanctuary Drop Entrance (I)': []} }, 'Sanctuary Drop Entrance (I)': { 'type': 'interior', 'link': { 'Sewers Last Hall': []} }, 'Graveyard Cave Entrance': { 'type': 'area', 'link': { 'North Light World': [], 'Graveyard Cave Entrance (E)': []} }, 'Graveyard Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (378, 181), 'link': { 'Graveyard Cave Entrance': [], 'Graveyard Cave Entrance (I)': []} }, 'Graveyard Cave Entrance (I)': { 'type': 'interior', 'link': { 'Graveyard Cave Entrance (E)': [], 'Graveyard Cave Front': []} }, 'Graveyard Cave Front': { 'type': 'area', 'link': { 'Graveyard Cave Entrance (I)': [], 'Graveyard Cave': [('item', 'bombs')]} }, 'Graveyard Cave': { 'type': 'cave', 'map': 'light', 'coord': (378, 181), 'link': { 'Graveyard Cave Front': []} }, "King's Tomb Exterior": { 'type': 'area', 'link': { 'Haunted Graveyard': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'North Light World': [('item', 'titansmitts')], "King's Tomb Entrance (E)": [('item', 'pegasus')]} }, "King's Tomb Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (399, 197), 'link': { "King's Tomb Exterior": [], "King's Tomb Entrance (I)": []} }, "King's Tomb Entrance (I)": { 'type': 'interior', 'link': { "King's Tomb Entrance (E)": [], "King's Tomb": []} }, "King's Tomb": { 'type': 'drop', 'map': 'light', 'coord': (399, 197), 'link': { "King's Tomb Entrance (I)": []} }, 'North Fairy Pond Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'light', 'coord': (426, 206), 'link': { 'North Fairy Pond Drop Entrance (I)': []} }, 'North Fairy Pond Drop Entrance (I)': { 'type': 'interior', 'link': { 'North Fairy Pond': []} }, 'North Fairy Pond': { 'type': 'area', 'link': { 'North Fairy Pond Cave': []} }, 'North Fairy Pond Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (443, 181), 'link': { 'North Light World': [], 'North Fairy Pond Cave Entrance (I)': []} }, 'North Fairy Pond Cave Entrance (I)': { 'type': 'interior', 'link': { 'North Fairy Pond Cave Entrance (E)': [], 'North Fairy Pond Cave': []} }, 'North Fairy Pond Cave': { 'type': 'area', 'link': { 'North Fairy Pond Cave Entrance (I)': []} }, 'Little River': { 'type': 'area', 'link': { 'Dark River': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'North Light World': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/lightworld_north.py
lightworld_north.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Hyrule Castle': { 'type': 'area', 'link': { 'Pyramid': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'North Light World': [], 'South Light World': [], 'East Light World': [('item', 'powerglove')], 'Secret Path Drop Entrance (E)': [('rabbitbarrier', None)], 'Gate Portal': [('and', [ ('access', 'Castle Tower Reward'), ('nosettings', 'inverted')])], 'Secret Path Exit Entrance (E)': [('rabbitbarrier', None)], 'Castle Gates Entrance (E)': []} }, 'Gate Portal': { 'type': 'area', 'link': { 'Pyramid': [('state', 'rabbit')]} }, 'Secret Path Drop Entrance (E)': { 'type': 'entrance_drop', 'map': 'light', 'coord': (395, 276), 'link': { 'Secret Path Drop Entrance (I)': []} }, 'Secret Path Drop Entrance (I)': { 'type': 'interior', 'link': { 'Secret Path': []} }, 'Secret Path': { 'type': 'drop', 'map': 'light', 'coord': (365, 284), 'link': { 'Secret Path Exit Entrance (I)': []} }, 'Secret Path Exit Entrance (I)': { 'type': 'interior', 'link': { 'Secret Path': [], 'Secret Path Exit Entrance (E)': []} }, 'Secret Path Exit Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (365, 284), 'link': { 'Secret Path Exit Entrance (I)': [], 'Hyrule Castle': []} }, 'Castle Gates Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (332, 291), 'link': { 'Hyrule Castle': [], 'Castle Gates Entrance (I)': []} }, 'Castle Gates Entrance (I)': { 'type': 'interior', 'link': { 'Castle Gates Entrance (E)': [], 'Hyrule Castle Interior': []} }, 'Hyrule Castle Interior': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Castle Gates Entrance (I)': [], 'Western Wall Access Entrance (I)': [], 'Eastern Wall Access Entrance (I)': [], 'Secret Escape': [ ('and', [('access', 'Zelda'), ('rabbitbarrier', None)]), ('nosettings', 'standard')], 'Dungeons Descent 1': []} }, 'Dungeons Descent 1': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Hyrule Castle Interior': [], 'Dungeons Map': [], 'Dungeons First Soldier Key': [('rabbitbarrier', None)], 'Dungeons Descent 2': [('smallkey', 'Castle Dungeons')]} }, 'Dungeons Map': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 1': []} }, 'Dungeons First Soldier Key': { 'type': 'dungeonkey', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 1': []} }, 'Dungeons Descent 2': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 1': [], 'Dungeons Second Soldier Key': [], 'Dungeons Treasure': [], 'Dungeons Cells': [('smallkey', 'Castle Dungeons')]} }, 'Dungeons Second Soldier Key': { 'type': 'dungeonkey', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 2': []} }, 'Dungeons Treasure': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 2': []} }, 'Dungeons Cells': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Descent 2': [], 'Dungeons Big Key': []} }, 'Dungeons Big Key': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Cells': [], 'Zelda': []} }, 'Zelda': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Dungeons Cells': [], "Zelda's Treasure": []} }, "Zelda's Treasure": { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Zelda': [], 'Castle Dungeons': [('rabbitbarrier', None)]} }, 'Secret Escape': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Hyrule Castle Interior': [], 'Sewers': [ ('item', 'lantern'), ('settings', 'standard'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])]} }, 'Sewers': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Chest': [('rabbitbarrier', None)], 'Sewers Rat Key': [], 'Sewers Locked Door': [('smallkey', 'Castle Dungeons')]} }, 'Sewers Chest': { 'type': 'drop', 'map': 'light', 'coord': (344, 223), 'link': { 'Sewers': [], 'Sewers Dungeon Chest': []} }, 'Sewers Dungeon Chest': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Chest': []} }, 'Sewers Rat Key': { 'type': 'dungeonkey', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers': []} }, 'Sewers Locked Door': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers': [ ('item', 'lantern'), ('settings', 'standard'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])], 'Sewers Last Hall': [('state', 'maybe;add')]} }, 'Sewers Last Hall': { 'type': 'area', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Locked Door': [('state', 'maybe;add')], 'Sewers Treasure': [('item', 'bombs'), ('item', 'pegasus')], 'Sanctuary': [('rabbitbarrier', None)]} }, 'Sewers Treasure': { 'type': 'drop', 'map': 'light', 'coord': (344, 193), 'link': { 'Sewers Last Hall': [], 'Sewers Treasure Chest 1': [], 'Sewers Treasure Chest 2': [], 'Sewers Treasure Chest 3': []} }, 'Sewers Treasure Chest 1': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Treasure': []} }, 'Sewers Treasure Chest 2': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Treasure': []} }, 'Sewers Treasure Chest 3': { 'type': 'dungeonchest', 'dungeon': 'Castle Dungeons', 'link': { 'Sewers Treasure': []} }, 'Sanctuary': { 'type': 'chest', 'map': 'light', 'coord': (306, 172), 'link': { 'Sanctuary Entrance Entrance (I)': []} }, 'Western Wall Access Entrance (I)': { 'type': 'interior', 'link': { 'Hyrule Castle Interior': [], 'Western Wall Access Entrance (E)': []} }, 'Eastern Wall Access Entrance (I)': { 'type': 'interior', 'link': { 'Hyrule Castle Interior': [], 'Eastern Wall Access Entrance (E)': []} }, 'Western Wall Access Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (298, 257), 'link': { 'Western Wall Access Entrance (I)': [], 'Castle Walls': []} }, 'Eastern Wall Access Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (365, 257), 'link': { 'Eastern Wall Access Entrance (I)': [], 'Castle Walls': []} }, 'Castle Walls': { 'type': 'area', 'link': { 'Pyramid': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Western Wall Access Entrance (E)': [], 'Eastern Wall Access Entrance (E)': [], 'Hyrule Castle': [], 'Castle Tower Entrance (E)': [ ('and', [ ('nosettings', 'inverted'), ('or', [ ('item', 'mastersword'), ('item', 'cape'), ('and', [ ('settings', 'swordless'), ('item', 'hammer')])])]), ('and', [ ('settings', 'inverted'), ('macro', 'ganonstower')])], 'Ganon Drop Entrance (E)': [('and', [ ('settings', 'inverted'), ('or', [ ('and', [ ('nosettings', 'entrance'), ('settings', 'fastganon')]), ('macro', 'ganondrop')])])]} }, 'Castle Tower Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'light', 'coord': (332, 265), 'link': { 'Castle Walls': [], 'Castle Tower Entrance (I)': [('nosettings', 'inverted')], "Ganon's Tower Entrance (I)": [('settings', 'inverted')]} }, 'Castle Tower Entrance (I)': { 'type': 'interior', 'link': { 'Castle Tower Entrance (E)': [('nosettings', 'inverted')], "Ganon's Tower Entrance (E)": [('settings', 'inverted')], 'Castle Tower Ascent 1': [('rabbitbarrier', None)]} }, 'Castle Tower Ascent 1': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Entrance (I)': [], 'Castle Tower First Chest': [], 'Castle Tower Ascent Stairs': [('smallkey', 'Castle Tower')]} }, 'Castle Tower First Chest': { 'type': 'dungeonchest', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Ascent 1': []} }, 'Castle Tower Ascent Stairs': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower First Chest': [], 'Castle Tower Ascent 2': [ ('item', 'lantern'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])]} }, 'Castle Tower Ascent 2': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Ascent Stairs': [], 'Castle Tower Second Chest': [], 'Castle Tower Ascent 3': [('smallkey', 'Castle Tower')]} }, 'Castle Tower Second Chest': { 'type': 'dungeonchest', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Ascent 2': []} }, 'Castle Tower Ascent 3': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Ascent 2': [ ('item', 'lantern'), ('and', [ ('settings', 'placement_advanced'), ('item', 'firerod')])], 'Castle Tower Boss': [('item', 'sword'), ('settings', 'swordless')]} }, 'Castle Tower Boss': { 'type': 'dungeonboss', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Boss Item': [ ('item', 'sword'), ('and', [ ('settings', 'swordless'), ('item', 'hammer')]), ('item', 'bugnet')]} }, 'Castle Tower Boss Item': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Castle Tower Reward': [('boss', 'Castle Tower')]} }, 'Castle Tower Reward': { 'type': 'area', 'dungeon': 'Castle Tower', 'link': { 'Pyramid': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit')])], 'Castle Walls': [('and', [ ('settings', 'inverted'), ('state', 'rabbit')])]} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/castle.py
castle.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Dark Palace Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (629, 262), 'link': { 'East Dark World': [], 'Dark Palace Entrance (I)': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])]} }, 'Dark Palace Entrance (I)': { 'type': 'interior', 'link': { 'Dark Palace Entrance (E)': [], 'Dark Palace Front': [('and', [ ('rabbitbarrier', None), ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'sword')]), ('item', 'bottle')])])])]} }, 'Dark Palace Front': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Entrance (I)': [], 'Dark Palace First Key': [], 'Dark Palace Centre': [('smallkey', 'Dark Palace')], 'Dark Palace Hidden Path': [ ('item', 'bombs'), ('item', 'pegasus')]} }, 'Dark Palace First Key': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Front': []} }, 'Dark Palace Hidden Path': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Front': [('item', 'bombs'), ('item', 'pegasus')], 'Dark Palace Moving Floor': [ ('item', 'bow'), ('settings', 'enemiser')]} }, 'Dark Palace Moving Floor': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Hidden Path': [], 'Dark Palace Key With A View': [('item', 'bombs')], 'Dark Palace Map': [], 'Dark Palace Centre': [('item', 'hammer')]} }, 'Dark Palace Key With A View': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Moving Floor': []} }, 'Dark Palace Map': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Moving Floor': []} }, 'Dark Palace Centre': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Front': [], 'Dark Palace Gauntlet Entrance': [('bigkey', 'Dark Palace')], 'Dark Palace Big Key Drop': [('item', 'bombs')], 'Dark Palace Stalfos Arena': [], 'Dark Palace Targetting Chest': [], 'Dark Palace Back': [('smallkey', 'Dark Palace')]} }, 'Dark Palace Big Key Drop': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Stalfos Arena': [], 'Dark Palace Big Key': [('smallkey', 'Dark Palace')]} }, 'Dark Palace Big Key': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Big Key Drop': [], 'Dark Palace Big Key': []} }, 'Dark Palace Stalfos Arena': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Stalfos Key': [], 'Dark Palace Front': []} }, 'Dark Palace Stalfos Key': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Stalfos Arena': []} }, 'Dark Palace Targetting Chest': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Centre': []} }, 'Dark Palace Back': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Maze Entrance': [('smallkey', 'Dark Palace')], 'Dark Palace Treasury': [ ('item', 'lantern'), ('and', [ ('settings', 'placement_advanded'), ('item', 'firerod')])], 'Dark Palace Compass': [], 'Dark Palace Return Path': []} }, 'Dark Palace Maze Entrance': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Back': [], 'Dark Palace Maze': [('item', 'lantern')]} }, 'Dark Palace Maze': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Maze Entrance': [], 'Dark Palace Maze Bombs': [], 'Dark Palace Maze Key': [], 'Dark Palace Treasure': [('item', 'bombs')]}, }, 'Dark Palace Maze Bombs': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Maze': []} }, 'Dark Palace Maze Key': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Maze': []} }, 'Dark Palace Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Maze': [('item', 'lantern')]} }, 'Dark Palace Treasury': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Back': [], 'Dark Palace Treasury Left Chest': [], 'Dark Palace Treasury Right Chest': []} }, 'Dark Palace Treasury Left Chest': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Treasury': []} }, 'Dark Palace Treasury Right Chest': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Treasury': []} }, 'Dark Palace Compass': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Back': []} }, 'Dark Palace Return Path': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Back': [], 'Dark Palace Return Chest': [], 'Dark Palace Centre': []} }, 'Dark Palace Return Chest': { 'type': 'dungeonchest', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Return Path': []} }, 'Dark Palace Gauntlet Entrance': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Centre': [], 'Dark Palace Gauntlet Door': [('item', 'bow')]} }, 'Dark Palace Gauntlet Door': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Gauntlet Entrance': [], 'Dark Palace Gauntlet': [('and', [ ('item', 'lantern'), ('item', 'hammer')])]} }, 'Dark Palace Gauntlet': { 'type': 'area', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Gauntlet Door': [('item', 'hammer')], 'Dark Palace Boss': [('smallkey', 'Dark Palace')]} }, 'Dark Palace Boss': { 'type': 'dungeonboss', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Boss Item': [('and', [ ('or', [ ('item', 'bombs'), ('item', 'hammer')]), ('or', [ ('item', 'mastersword'), ('item', 'bow')])])]} }, 'Dark Palace Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Reward': []} }, 'Dark Palace Reward': { 'type': 'dungeonreward', 'dungeon': 'Dark Palace', 'link': { 'Dark Palace Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/darkpalace.py
darkpalace.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Ice Palace Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (523, 573), 'link': { 'Ice Palace Exterior': [], 'Ice Palace Entrance (I)': []} }, 'Ice Palace Entrance (I)': { 'type': 'interior', 'link': { 'Ice Palace Entrance (E)': [], 'Ice Palace Floor 1 Room 1': []} }, 'Ice Palace Floor 1 Room 1': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Entrance (I)': [], 'Ice Palace Floor 1 Room 2': [ ('item', 'firerod'), ('and', [ ('item', 'bombos'), ('or', [ ('settings', 'swordless'), ('item', 'sword')])])]} }, 'Ice Palace Floor 1 Room 2': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 1 Room 1': [], 'Ice Palace First Bari Key': [], 'Ice Palace Floor 2': [('smallkey', 'Ice Palace')]} }, 'Ice Palace First Bari Key': { 'type': 'dungeonkey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 1 Room 2': []} }, 'Ice Palace Floor 2': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 1 Room 2': [], 'Ice Palace Compass': [], 'Ice Palace Floor 3': [('item', 'bombs')]} }, 'Ice Palace Compass': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 2': []} }, 'Ice Palace Floor 3': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 2': [], 'Ice Palace Second Bari Key': [], 'Ice Palace Floor 4': [('smallkey', 'Ice Palace')]} }, 'Ice Palace Second Bari Key': { 'type': 'dungeonkey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 3': []} }, 'Ice Palace Floor 4': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 3': [], 'Ice Palace Lower Ascent': [('smallkey', 'Ice Palace')], 'Ice Palace Big Ice Floor': [], 'Ice Palace Freezor Room': []} }, 'Ice Palace Lower Ascent': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 4': [], 'Ice Palace Ascent Key': [], 'Ice Palace Map': [], 'Ice Palace Upper Ascent': [('and', [ ('item', 'hammer'), ('item', 'powerglove'), ('item', 'bombs')])]} }, 'Ice Palace Ascent Key': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Lower Ascent': []} }, 'Ice Palace Map': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Lower Ascent': []} }, 'Ice Palace Upper Ascent': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Lower Ascent': [], 'Ice Palace Upper Hidden Key': [], # Generally speaking, the bottom key can be reached without using a # small key via. But this is not what we're after, therefore this # 'virtual keydoor' is placed here. 'Ice Palace Big Key': [('smallkey', 'Ice Palace')], 'Ice Palace Floor 2': []} }, 'Ice Palace Upper Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Upper Ascent': []} }, 'Ice Palace Big Key': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Upper Ascent': []} }, 'Ice Palace Big Ice Floor': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Lower Ascent': [('item', 'hookshot')], 'Ice Palace Bottom Key': [('smallkey', 'Ice Palace')], 'Ice Palace Boss Puzzle': []}, }, 'Ice Palace Freezor Room': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Floor 4': [], 'Ice Palace Freezor Chest': [ ('item', 'firerod'), ('and', [ ('item', 'bombos'), ('or', [ ('item', 'sword'), ('settings', 'swordless')])])], 'Ice Palace Treasure Drop': [('item', 'bombs')], 'Ice Palace Boss Puzzle': []} }, 'Ice Palace Freezor Chest': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Freezor Room': []} }, 'Ice Palace Treasure Drop': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Treasure': [('bigkey', 'Ice Palace')], 'Ice Palace Boss Puzzle': []} }, 'Ice Palace Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Treasure Drop': []} }, 'Ice Palace Boss Puzzle': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Boss Puzzle Solution': [('bigkey', 'Ice Palace')], 'Ice Palace Babusu Room': []} }, 'Ice Palace Babusu Room': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Boss Puzzle': [], 'Ice Palace Lower Hidden Key': [], 'Ice Palace Ice Bridge': [('smallkey', 'Ice Palace')]} }, 'Ice Palace Lower Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Babusu Room': []} }, 'Ice Palace Ice Bridge': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Babusu Room': [], # Another 'virtual door'. Ice Palace sure is special. 'Ice Palace Bottom Key': [('smallkey', 'Ice Palace')]} }, 'Ice Palace Bottom Key': { 'type': 'dungeonchest', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Ice Bridge': [], 'Ice Palace Big Ice Floor': []} }, 'Ice Palace Boss Puzzle Solution': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Above Boss': [('smallkey', 'Ice Palace')], 'Ice Palace Somaria Puzzle': [ ('settings', 'placement_basic'), ('item', 'somaria')], 'Ice Palace Boss Puzzle': []} }, 'Ice Palace Somaria Puzzle': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Boss Puzzle Solution': [], 'Ice Palace Above Boss': []} }, 'Ice Palace Above Boss': { 'type': 'area', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Boss Puzzle Solution': [], 'Ice Palace Boss': [('and', [ ('item', 'hammer'), ('item', 'powerglove')])]} }, 'Ice Palace Boss': { 'type': 'dungeonboss', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Boss Item': [('and', [ ('or', [ ('item', 'firerod'), ('and', [ ('item', 'bombos'), ('or', [ ('settings', 'swordless'), ('item', 'sword')])])]), ('or', [ ('item', 'sword'), ('item', 'hammer'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('or', [ ('item', 'firerod'), ('item', 'bombos')])])]), ('or', [ ('settings', 'placement_advanced'), ('item', 'mastersword'), ('and', [ ('or', [ ('item', 'bottle'), ('item', 'halfmagic')]), ('item', 'firerod')])])])]} }, 'Ice Palace Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Reward': []} }, 'Ice Palace Reward': { 'type': 'dungeonreward', 'dungeon': 'Ice Palace', 'link': { 'Ice Palace Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/icepalace.py
icepalace.py
__all__ = 'LOCATIONS', LOCATIONS = { 'Misery Mire Surface': { 'type': 'area', 'link': { 'Desert': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Desert Ridge': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Misery Mire Treasury Entrance (E)': [], 'Misery Mire Fairy Entrance (E)': [], 'Desert Cave Valley': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Misery Mire Cave Entrance (E)': [], 'Misery Mire Dungeon Entrance (E)': [('and', [ ('medallion', 'Misery Mire'), ('item', 'sword')])]} }, 'Misery Mire Treasury Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (20, 531), 'link': { 'Misery Mire Surface': [], 'Misery Mire Treasury Entrance (I)': []} }, 'Misery Mire Treasury Entrance (I)': { 'type': 'interior', 'link': { 'Misery Mire Treasury Entrance (E)': [], 'Misery Mire Treasury': [('rabbitbarrier', None)]} }, 'Misery Mire Treasury': { 'type': 'chest', 'map': 'dark', 'coord': (20, 528), 'link': { 'Misery Mire Treasury Entrance (I)': []} }, 'Misery Mire Fairy Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (66, 531), 'link': { 'Misery Mire Surface': [], 'Misery Mire Fairy Entrance (I)': []} }, 'Misery Mire Fairy Entrance (I)': { 'type': 'interior', 'link': { 'Misery Mire Fairy Entrance (E)': []} }, 'Misery Mire Cave Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (126, 547), 'link': { 'Misery Mire Surface': [], 'Misery Mire Cave Entrance (I)': []} }, 'Misery Mire Cave Entrance (I)': { 'type': 'interior', 'link': { 'Misery Mire Cave Entrance (E)': []} }, 'Desert Portal (DW)': { 'type': 'area', 'link': { 'Desert Portal (LW)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Desert Portal': [('item', 'titansmitts')], 'Misery Mire Surface': []} }, 'Misery Mire Dungeon Entrance (E)': { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (43, 553), 'link': { 'Misery Mire Surface': [], 'Misery Mire Dungeon Entrance (I)': []} }, 'Misery Mire Dungeon Entrance (I)': { 'type': 'interior', 'link': { 'Misery Mire Dungeon Entrance (E)': [], 'Misery Mire Descent': [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('item', 'bottle'), ('item', 'bluemail')])])]} }, 'Misery Mire Descent': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Dungeon Entrance (I)': [], 'Misery Mire Interior': [ ('item', 'hookshot'), ('and', [ ('item', 'pegasus'), ('settings', 'placement_advanced')])]} }, 'Misery Mire Interior': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Descent': [ ('item', 'hookshot'), ('item', 'pegasus'), ('item', 'mirror')], 'Misery Mire Bridge Key': [], 'Misery Mire Hidden Key': [], 'Misery Mire Spike Key': [], 'Misery Mire Map': [('smallkey', 'Misery Mire')], 'Misery Mire Treasure Room': [ ('item', 'hookshot'), ('item', 'pegasus')], 'Misery Mire Upper Key': [], 'Misery Mire Switch Room': [('smallkey', 'Misery Mire')], 'Misery Mire Gauntlet Bridge': [('bigkey', 'Misery Mire')]} }, 'Misery Mire Bridge Key': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []} }, 'Misery Mire Hidden Key': { 'type': 'dungeonkey', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []} }, 'Misery Mire Spike Key': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []} }, 'Misery Mire Map': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []}, }, 'Misery Mire Treasure Room': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': [], 'Misery Mire Treasure': [('bigkey', 'Misery Mire')]} }, 'Misery Mire Treasure': { 'type': 'dungeonchest_nokey', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []}, }, 'Misery Mire Upper Key': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []}, }, 'Misery Mire Switch Room': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': [], 'Misery Mire Bari Key': [], 'Misery Mire Torch Room': [('smallkey', 'Misery Mire')]} }, 'Misery Mire Bari Key': { 'type': 'dungeonkey', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Switch Room': []} }, 'Misery Mire Torch Room': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Switch Room': [], 'Misery Mire Compass': [('item', 'lantern'), ('item', 'firerod')], 'Misery Mire Big Key': [('item', 'lantern'), ('item', 'firerod')]} }, 'Misery Mire Compass': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Torch Room': [], 'Misery Mire Interior': []} }, 'Misery Mire Big Key': { 'type': 'dungeonchest', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': []} }, 'Misery Mire Gauntlet Bridge': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Interior': [], 'Misery Mire Gauntlet': [('and', [ ('item', 'lantern'), ('item', 'somaria')])]} }, 'Misery Mire Gauntlet': { 'type': 'area', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Gauntlet Bridge': [], 'Misery Mire Boss': [('item', 'bombs')]} }, 'Misery Mire Boss': { 'type': 'dungeonboss', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Boss Item': [('and', [ ('or', [ ('settings', 'placement_advanced'), ('item', 'mastersword'), ('item', 'bow')]), ('or', [ ('item', 'hammer'), ('item', 'sword'), ('item', 'bow')])])]} }, 'Misery Mire Boss Item': { 'type': 'dungeonchest_nokey', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Reward': []}, }, 'Misery Mire Reward': { 'type': 'dungeonreward', 'dungeon': 'Misery Mire', 'link': { 'Misery Mire Dungeon Entrance (I)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/miserymire.py
miserymire.py
__all__ = 'LOCATIONS', LOCATIONS = { 'South Light World': { 'type': 'area', 'link': { 'South Dark World': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Light Bottle Ocarina': [], "Link's House Entrance (E)": [], 'Hyrule Castle': [], 'Fairy Pond Under Rocks (LW) Entrance (E)': [('item', 'pegasus')], 'Haunted Grove': [('item', 'shovel')], 'Southern Chest Game Entrance (E)': [], 'Kakariko': [], "Thieves' Town Surface": [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Frog Prison': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Library Entrance (E)': [], "Quarrelling Brothers' House East Entrance (E)": [], 'Cave Near Haunted Grove Entrance (E)': [ ('settings', 'inverted'), ('glitch', 'major'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'Southern Shores': [], 'Lake Hylia Fortune Teller Entrance (E)': [], 'Lake Hylia': [('item', 'flippers')], 'Lake Hylia Shop Entrance (E)': [], 'East Light World': [], 'Small Lake Hylia Island': [ ('glitch', 'major'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])]}, 'visible': {'Running Game': [], 'Small Lake Hylia Island': []} }, "Link's House Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (363, 456), 'link': { 'South Light World': [], "Link's House Entrance (I)": [('nosettings', 'inverted')], 'Bomb Shop Entrance (I)': [('settings', 'inverted')]} }, "Link's House Entrance (I)": { 'type': 'interior', 'link': { "Link's House Entrance (E)": [('nosettings', 'inverted')], 'Bomb Shop Entrance (E)': [('settings', 'inverted')], "Link's House": [('rabbitbarrier', None)]} }, "Link's House": { 'type': 'chest', 'map': 'light', 'coord': (363, 448), 'link': { "Link's House Entrance (I)": [], 'Ocarina': [('and', [ ('item', 'ocarina'), ('access', 'Kakariko')])]} }, 'Fairy Pond Under Rocks (LW) Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (313, 433), 'link': { 'South Light World': [], 'Fairy Pond Under Rocks (LW) Entrance (I)': []} }, 'Fairy Pond Under Rocks (LW) Entrance (I)': { 'type': 'interior', 'link': { 'Fairy Pond Under Rocks (LW) Entrance (E)': []} }, 'Haunted Grove': { 'type': 'item', 'map': 'light', 'coord': (190, 438), 'link': { 'South Light World': []} }, 'Southern Chest Game Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (143, 465), 'link': { 'South Light World': [], 'Southern Chest Game Entrance (I)': []} }, 'Southern Chest Game Entrance (I)': { 'type': 'interior', 'link': { 'Southern Chest Game Entrance (E)': []} }, 'Library Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (104, 436), 'link': { 'South Light World': [], 'Library Entrance (I)': []} }, 'Library Entrance (I)': { 'type': 'interior', 'link': { 'Library Entrance (E)': [], 'Library': [('item', 'pegasus')]}, 'visible': {'Library': []} }, 'Library': { 'type': 'chest', 'map': 'light', 'coord': (104, 432), 'link': { 'Library Entrance (I)': []} }, "Quarrelling Brothers' House East Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (93, 476), 'link': { 'South Light World': [], "Quarrelling Brothers' House East Entrance (I)": []} }, "Quarrelling Brothers' House East Entrance (I)": { 'type': 'interior', 'link': { "Quarrelling Brothers' House East Entrance (E)": [], "Quarrelling Brothers' House West Entrance (I)": [ ('item', 'bombs')]} }, "Quarrelling Brothers' House West Entrance (I)": { 'type': 'interior', 'link': { "Quarrelling Brothers' House East Entrance (I)": [ ('item', 'bombs')], "Quarrelling Brothers' House West Entrance (E)": []} }, "Quarrelling Brothers' House West Entrance (E)": { 'type': 'entrance_unique', 'map': 'light', 'coord': (73, 476), 'link': { "Quarrelling Brothers' House West Entrance (I)": [], 'Running Game': [('rabbitbarrier', None)]} }, 'Running Game': { 'type': 'item', 'map': 'light', 'coord': (22, 463), 'link': { "Quarrelling Brothers' House West Entrance (E)": [], 'South Light World': []}, }, 'Cave Near Haunted Grove Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (177, 546), 'link': { 'South Light World': [], 'Cave Near Haunted Grove Entrance (I)': []} }, 'Cave Near Haunted Grove Entrance (I)': { 'type': 'interior', 'link': { 'Cave Near Haunted Grove Entrance (E)': [], 'Cave Near Haunted Grove': [('rabbitbarrier', None)]} }, 'Cave Near Haunted Grove': { 'type': 'cave', 'map': 'light', 'coord': (177, 546), 'link': { 'Cave Near Haunted Grove Entrance (I)': []} }, 'Lake Hylia Fortune Teller Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (433, 530), 'link': { 'South Light World': [], 'Lake Hylia Fortune Teller Entrance (I)': []} }, 'Lake Hylia Fortune Teller Entrance (I)': { 'type': 'interior', 'link': { 'Lake Hylia Fortune Teller Entrance (E)': []} }, 'Lake Hylia Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'light', 'coord': (482, 508), 'link': { 'South Light World': [], 'Lake Hylia Shop Entrance (I)': []} }, 'Lake Hylia Shop Entrance (I)': { 'type': 'interior', 'link': { 'Lake Hylia Shop Entrance (E)': []} }, 'Southern Shores': { 'type': 'area', 'link': { 'South Dark World': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Light Bottle Ocarina': [], 'South Light World': [], 'South Portal (LW)': [('item', 'hammer')], 'Witch Hut Waterway': [('item', 'flippers')], 'Locksmith': [('access', 'Locked Chest')], 'Desert Fairy Entrance (E)': [], 'Bombos Stone Mountain': [ ('settings', 'inverted'), ('glitch', 'major'), ('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'Desert': [], 'Rich Thief Entrance (E)': [('item', 'powerglove')], 'Item Under Water': [('access', 'Water Drain')], 'Water Drain Entrance (E)': [], 'South Fairy Entrance (E)': [('item', 'bombs')], 'Moldorm Cave Entrance (E)': [('item', 'bombs')], 'Lake Hylia': [ ('item', 'flippers'), ('and', [('glitch', 'overworld'), ('rabbitbarrier', None)])], 'Poor Thief Entrance (E)': [('item', 'powerglove')], 'Ice Cave Main Entrance Entrance (E)': [], 'Ice Cave Secret Entrance Entrance (E)': [('item', 'bombs')], 'Eastern Shores': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])]} }, 'South Portal (LW)': { 'type': 'area', 'link': { 'South Portal (DW)': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Southern Shores': [('item', 'hammer')], 'South Portal': [('item', 'powerglove')]}, }, 'South Portal': { 'type': 'area', 'link': { 'South Portal (LW)': [('and', [ ('settings', 'inverted'), ('state', 'rabbit')])], 'South Portal (DW)': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit')])]} }, 'Witch Hut Waterway': { 'type': 'area', 'link': { 'Southern Shores': [], 'Witch Hut River': []} }, 'Locksmith': { 'type': 'item', 'map': 'light', 'coord': (224, 594), 'link': { 'Southern Shores': []} }, 'Desert Fairy Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (184, 590), 'link': { 'Southern Shores': [], 'Desert Fairy Entrance (I)': []} }, 'Desert Fairy Entrance (I)': { 'type': 'interior', 'link': { 'Desert Fairy Entrance (E)': []} }, 'Bombos Stone Mountain': { 'type': 'area', 'link': { 'Southern Shores': [], 'Desert': [], 'Bombos Stone': [('mudora', 'take')]}, 'visible': {'Bombos Stone': [('item', 'mudora')]} }, 'Bombos Stone': { 'type': 'item', 'map': 'light', 'coord': (145, 610), 'link': { 'Bombos Stone Mountain': []} }, 'Rich Thief Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (207, 634), 'link': { 'Southern Shores': [], 'Rich Thief Entrance (I)': []} }, 'Rich Thief Entrance (I)': { 'type': 'interior', 'link': { 'Rich Thief Entrance (E)': []} }, 'Item Under Water': { 'type': 'item', 'map': 'light', 'coord': (296, 616), 'link': { 'Southern Shores': []} }, 'Water Drain Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (311, 620), 'link': { 'Southern Shores': [], 'Water Drain Entrance (I)': []} }, 'Water Drain Entrance (I)': { 'type': 'interior', 'link': { 'Water Drain Entrance (E)': [], 'Water Drain': [('rabbitbarrier', None)]} }, 'Water Drain': { 'type': 'chest', 'map': 'light', 'coord': (311, 616), 'link': { 'Water Drain Entrance (I)': []}, }, 'South Fairy Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (396, 517), 'link': { 'Southern Shores': [], 'South Fairy Entrance (I)': []} }, 'South Fairy Entrance (I)': { 'type': 'interior', 'link': { 'South Fairy Entrance (E)': []} }, 'Moldorm Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (433, 621), 'link': { 'Southern Shores': [], 'Moldorm Cave Entrance (I)': []} }, 'Moldorm Cave Entrance (I)': { 'type': 'interior', 'link': { 'Moldorm Cave Entrance (E)': [], 'Moldorm Cave': [('rabbitbarrier', None)]} }, 'Moldorm Cave': { 'type': 'cave', 'map': 'light', 'coord': (433, 621), 'link': { 'Moldorm Cave Entrance (I)': []} }, 'Poor Thief Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (599, 525), 'link': { 'Southern Shores': [], 'Poor Thief Entrance (I)': []} }, 'Poor Thief Entrance (I)': { 'type': 'interior', 'link': { 'Poor Thief Entrance (E)': []} }, 'Ice Cave Main Entrance Entrance (E)': { 'type': 'entrance', 'map': 'light', 'coord': (607, 511), 'link': { 'Southern Shores': [], 'Ice Cave Main Entrance Entrance (I)': []} }, 'Ice Cave Main Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Ice Cave Main Entrance Entrance (E)': []} }, 'Ice Cave Secret Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'light', 'coord': (593, 511), 'link': { 'Southern Shores': [], 'Ice Cave Secret Entrance Entrance (I)': []} }, 'Ice Cave Secret Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Ice Cave Secret Entrance Entrance (E)': [], 'Ice Cave': []} }, 'Ice Cave': { 'type': 'cave', 'map': 'light', 'coord': (593, 511), 'link': { 'Ice Cave Secret Entrance Entrance (I)': []} }, 'Lake Hylia': { 'type': 'area', 'link': { 'Frozen Lake': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Southern Shores': [], 'Crossworld Waterway': [], 'Zora River Waterway': [], 'Large Lake Hylia Island': [], 'Small Lake Hylia Island': [('settings', 'inverted')], 'South Light World': [], 'East Light World': [], 'Under The Bridge': []}, 'visible': {'Small Lake Hylia Island': []} }, 'Zora River Waterway': { 'type': 'area', 'link': { 'Lake Hylia': [], 'Waterfall Lake': []} }, 'Under The Bridge': { 'type': 'item', 'map': 'light', 'coord': (469, 462), 'link': { 'Lake Hylia': []} }, 'Small Lake Hylia Island': { 'type': 'item', 'map': 'light', 'coord': (483, 552), 'link': { 'Frozen Lake': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Lake Hylia': [('item', 'flippers')]} }, 'Large Lake Hylia Island': { 'type': 'area', 'link': { 'Ice Palace Exterior': [('and', [ ('settings', 'inverted'), ('item', 'mirror')])], 'Ice Palace Portal': [('item', 'titansmitts')], 'Fairy Queen Cave Entrance (E)': []}, }, 'Ice Palace Portal': { 'type': 'area', 'link': { 'Ice Palace Exterior': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit')])], 'Large Lake Hylia Island': [('and', [ ('settings', 'inverted'), ('state', 'rabbit')])]} }, 'Fairy Queen Cave Entrance (E)': { 'type': 'entrance_shop', 'map': 'light', 'coord': (526, 564), 'link': { 'Large Lake Hylia Island': [], 'Fairy Queen Cave Entrance (I)': []} }, 'Fairy Queen Cave Entrance (I)': { 'type': 'interior', 'link': { 'Fairy Queen Cave Entrance (E)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/lightworld_south.py
lightworld_south.py
__all__ = 'LOCATIONS', LOCATIONS = { 'West Lower Death Mountain': { 'type': 'area', 'link': { 'West Lower Mount Hebra': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Heart Rock': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'West Death Mountain Fairy Entrance (E)': [], 'Cave of Byrna Entrance (E)': [], 'Hebra Portal': [], 'West Upper Death Mountain': [('settings', 'inverted')], 'East Lower Death Mountain': [ ('and', [ ('glitch', 'overworld'), ('item', 'pegasus'), ('or', [ ('item', 'pearl'), ('item', 'hammer')])]), ('glitch', 'major')], 'East Dark World': [('and', [ ('glitch', 'overworld'), ('item', 'mirror'), ('item', 'pegasus'), ('or', [ ('item', 'sword'), ('item', 'hookshot')])])]} }, 'West Death Mountain Fairy Entrance (E)': { 'type': 'entrance', 'map': 'dark', 'coord': (264, 125), 'link': { 'West Lower Death Mountain': [], 'West Death Mountain Fairy Entrance (I)': [ ('nosettings', 'inverted')], 'Hebra Ascent (Top) Entrance (I)': [('settings', 'inverted')]} }, 'West Death Mountain Fairy Entrance (I)': { 'type': 'interior', 'link': { 'West Death Mountain Fairy Entrance (E)': [ ('nosettings', 'inverted')], 'Hebra Ascent (Top) Entrance (E)': [('settings', 'inverted')]} }, 'Cave of Byrna Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (375, 96), 'link': { 'West Lower Death Mountain': [], 'Cave of Byrna Entrance (I)': []} }, 'Cave of Byrna Entrance (I)': { 'type': 'interior', 'link': { 'Cave of Byrna Entrance (E)': [], 'Cave of Byrna': [('and', [ ('item', 'hammer'), ('or', [ ('and', [ ('item', 'cape'), ('or', [ ('item', 'halfmagic'), ('item', 'bottle')])]), ('item', 'byrna')]), ('item', 'powerglove')])]} }, 'Cave of Byrna': { 'type': 'cave', 'map': 'dark', 'coord': (375, 96), 'link': { 'Cave of Byrna Entrance (I)': [('and', [ ('item', 'hammer'), ('or', [ ('and', [ ('item', 'cape'), ('or', [ ('item', 'halfmagic'), ('item', 'bottle')])]), ('item', 'byrna')]), ('item', 'powerglove')])]} }, 'West Upper Death Mountain': { 'type': 'area', 'link': { 'West Upper Mount Hebra': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'West Lower Death Mountain': [], "Ganon's Tower Entrance (E)": [ ('and', [ ('nosettings', 'inverted'), ('macro', 'ganonstower')]), ('settings', 'inverted')], 'East Upper Death Mountain': []} }, "Ganon's Tower Entrance (E)": { 'type': 'entrance_dungeon', 'map': 'dark', 'coord': (367, 35), 'link': { 'West Upper Death Mountain': [], "Ganon's Tower Entrance (I)": [('nosettings', 'inverted')], 'Castle Tower Entrance (I)': [('settings', 'inverted')]} }, 'East Lower Death Mountain': { 'type': 'area', 'link': { 'East Lower Mount Hebra': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Death Mountain Shop Entrance (E)': [], 'Death Mountain Cave Bottom Entrance Entrance (E)': [], 'East Hebra Portal': [('item', 'titansmitts')]} }, 'Death Mountain Shop Entrance (E)': { 'type': 'entrance_shop', 'map': 'dark', 'coord': (571, 96), 'link': { 'East Lower Death Mountain': [], 'Death Mountain Shop Entrance (I)': []} }, 'Death Mountain Shop Entrance (I)': { 'type': 'interior', 'link': { 'Death Mountain Shop Entrance (E)': []} }, 'Death Mountain Cave Bottom Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (557, 96), 'link': { 'East Lower Death Mountain': [], 'Death Mountain Cave Bottom Entrance Entrance (I)': []} }, 'Death Mountain Cave Bottom Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Death Mountain Cave Bottom Entrance Entrance (E)': [], 'Death Mountain Cave': [('rabbitbarrier', None)], 'Death Mountain Cave Top Entrance Entrance (I)': []} }, 'Death Mountain Cave': { 'type': 'cave', 'map': 'dark', 'coord': (557, 96), 'link': { 'Death Mountain Cave Top Entrance Entrance (I)': []} }, 'Death Mountain Cave Top Entrance Entrance (I)': { 'type': 'interior', 'link': { 'Death Mountain Cave': [('rabbitbarrier', None)], 'Death Mountain Cave Top Entrance Entrance (E)': []} }, 'Death Mountain Cave Top Entrance Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (564, 41), 'link': { 'Death Mountain Cave Top Entrance Entrance (I)': [], 'East Upper Death Mountain': []} }, 'East Upper Death Mountain': { 'type': 'area', 'link': { 'East Upper Mount Hebra': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Dark Bottle Ocarina': [], 'West Upper Death Mountain': [], 'East Lower Death Mountain': [], 'Death Mountain Cave Top Entrance Entrance (E)': [], 'Pit Cave Entrance (E)': [('item', 'powerglove')], 'Turtle Rock Portal (DW)': [('settings', 'inverted')], 'Turtle Rock Entrance Entrance (E)': [ ('access', 'Open Turtle Rock')], 'Pit Cave Peak': [('and', [ ('glitch', 'overworld'), ('item', 'pegasus')])], 'Turtle Rock Balcony': [ ('and', [ ('glitch', 'overworld'), ('or', [ ('item', 'mirror'), ('item', 'pegasus')])])], 'Turtle Rock Fairy Exit': [ ('and', [ ('glitch', 'overworld'), ('or', [ ('item', 'mirror'), ('item', 'pegasus')])]), ('glitch', 'major')]} }, 'Pit Cave Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (546, 44), 'link': { 'East Upper Death Mountain': [], 'Pit Cave Entrance (I)': []} }, 'Pit Cave Entrance (I)': { 'type': 'interior', 'link': { 'Pit Cave Entrance (E)': [], 'Pit Cave': []} }, 'Pit Cave': { 'type': 'area', 'link': { 'Pit Cave Entrance (I)': [], 'Pit Cave Pegasus Chest': [ ('and', [ ('item', 'pegasus'), ('settings', 'placement_advanced')]), ('item', 'hookshot')], 'Pit Cave Hookshot Chests': [('item', 'hookshot')], 'Pit Cave Back Exit Entrance (I)': [('item', 'bombs')]} }, 'Pit Cave Pegasus Chest': { 'type': 'drop', 'map': 'dark', 'coord': (546, 51), 'link': { 'Pit Cave': []} }, 'Pit Cave Hookshot Chests': { 'type': 'drop', 'map': 'dark', 'coord': (546, 37), 'link': { 'Pit Cave': []} }, 'Pit Cave Back Exit Entrance (I)': { 'type': 'interior', 'link': { 'Pit Cave': [('item', 'bombs')], 'Pit Cave Back Exit Entrance (E)': []} }, 'Pit Cave Back Exit Entrance (E)': { 'type': 'entrance_unique', 'map': 'dark', 'coord': (524, 10), 'link': { 'Pit Cave Back Exit Entrance (I)': [], 'Pit Cave Peak': []} }, 'Pit Cave Peak': { 'type': 'area', 'link': { 'Heart Peak': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'Pit Cave Back Exit Entrance (E)': [], 'East Upper Death Mountain': []} }, 'Turtle Rock Portal (DW)': { 'type': 'area', 'link': { 'Turtle Rock Portal (LW)': [('and', [ ('nosettings', 'inverted'), ('item', 'mirror')])], 'East Upper Death Mountain': [], 'Turtle Rock Portal': [('item', 'titansmitts')], 'Open Turtle Rock': [('medallion', 'Turtle Rock')]} }, 'Open Turtle Rock': { 'type': 'area', 'link': { 'Turtle Rock Portal (DW)': []} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/deathmountain.py
deathmountain.py
__all__ = 'LOCATIONS', LOCATIONS = { "Ganon's Tower Entrance (I)": { 'type': 'interior', 'link': { 'Castle Tower Entrance (E)': [('settings', 'inverted')], "Ganon's Tower Entrance (E)": [('nosettings', 'inverted')], "Ganon's Tower Lobby": [('and', [ ('or', [ ('settings', 'placement_advanced'), ('and', [ ('or', [ ('settings', 'swordless'), ('item', 'mastersword')]), ('or', [ ('item', 'bottle'), ('item', 'bluemail')])])]), ('rabbitbarrier', None)])]} }, "Ganon's Tower Lobby": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Entrance (I)": [], "Ganon's Tower Torch Key Room": [], "Ganon's Tower Trap Room": [], "Ganon's Tower Ascent 1": [('bigkey', "Ganon's Tower")]} }, "Ganon's Tower Torch Key Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Lobby": [], "Ganon's Tower Trap Room": [('smallkey', "Ganon's Tower")], "Ganon's Tower Torch Key": [('item', 'pegasus')], "Ganon's Tower Moving Bumper Key": []} }, "Ganon's Tower Torch Key": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Torch Key Room": []} }, "Ganon's Tower Moving Bumper Key": { 'type': 'dungeonkey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Torch Key Room": [], "Ganon's Tower Pit Room": [('item', 'hammer')]} }, "Ganon's Tower Pit Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Moving Bumper Key": [('item', 'hookshot')], "Ganon's Tower Stalfos Room": [('item', 'hookshot')], "Ganon's Tower Map Room": [ ('item', 'hookshot'), ('item', 'pegasus')]} }, "Ganon's Tower Stalfos Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Pit Room": [ ('item', 'hookshot'), ('item', 'pegasus')], "Ganon's Tower Stalfos Room Chest 1": [], "Ganon's Tower Stalfos Room Chest 2": [], "Ganon's Tower Stalfos Room Chest 3": [], "Ganon's Tower Stalfos Room Chest 4": []} }, "Ganon's Tower Stalfos Room Chest 1": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Stalfos Room": []} }, "Ganon's Tower Stalfos Room Chest 2": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Stalfos Room": []} }, "Ganon's Tower Stalfos Room Chest 3": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Stalfos Room": []} }, "Ganon's Tower Stalfos Room Chest 4": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Stalfos Room": []} }, "Ganon's Tower Map Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Pit Room": [('item', 'hookshot')], "Ganon's Tower Map": [('smallkey', "Ganon's Tower")], "Ganon's Tower Double Switch": []} }, "Ganon's Tower Map": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Map Room": []} }, "Ganon's Tower Double Switch": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Map Room": [], "Ganon's Tower Switch Key": [], "Ganon's Tower Winder Room": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Switch Key": { 'type': 'dungeonkey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Double Switch": []} }, "Ganon's Tower Winder Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Winder Room Key": [('item', 'hookshot')]} }, "Ganon's Tower Winder Room Key": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Teleport Maze": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Teleport Maze": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Treasure": [('item', 'bombs')], "Ganon's Tower Convergence": []} }, "Ganon's Tower Secret Treasure": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Chest 1": [], "Ganon's Tower Secret Chest 2": [], "Ganon's Tower Secret Chest 3": [], "Ganon's Tower Secret Chest 4": [], "Ganon's Tower Convergence": []} }, "Ganon's Tower Secret Chest 1": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Treasure": []} }, "Ganon's Tower Secret Chest 2": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Treasure": []} }, "Ganon's Tower Secret Chest 3": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Treasure": []} }, "Ganon's Tower Secret Chest 4": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Secret Treasure": []} }, "Ganon's Tower Trap Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Lobby": [], "Ganon's Tower Torch Key Room": [('smallkey', "Ganon's Tower")], "Ganon's Tower Trap Chest 1": [], "Ganon's Tower Trap Chest 2": [], "Ganon's Tower Tile Room": [('item', 'somaria')]} }, "Ganon's Tower Trap Chest 1": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Trap Room": []} }, "Ganon's Tower Trap Chest 2": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Trap Room": []} }, "Ganon's Tower Tile Room": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Trap Room": [], "Ganon's Tower Torch Race": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Torch Race": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Tile Room": [], "Ganon's Tower Compass Room": [('item', 'firerod')]} }, "Ganon's Tower Compass Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Torch Race": [], "Ganon's Tower Compass Chest 1": [], "Ganon's Tower Compass Chest 2": [], "Ganon's Tower Compass Chest 3": [], "Ganon's Tower Compass Chest 4": [], "Ganon's Tower Obstacle Course Key": []} }, "Ganon's Tower Compass Chest 1": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Compass Room": []} }, "Ganon's Tower Compass Chest 2": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Compass Room": []} }, "Ganon's Tower Compass Chest 3": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Compass Room": []} }, "Ganon's Tower Compass Chest 4": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Compass Room": []} }, "Ganon's Tower Obstacle Course Key": { 'type': 'dungeonkey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Convergence": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Convergence": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Anti-Fairy Room": [], "Ganon's Tower Treasure Room": []} }, "Ganon's Tower Anti-Fairy Room": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Convergence": [], "Ganon's Tower Armos On Ice": [('item', 'bombs')]} }, "Ganon's Tower Armos On Ice": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Big Key Room": [], "Ganon's Tower Treasure Room": []} }, "Ganon's Tower Big Key Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Armos On Ice": [], "Ganon's Tower Big Key": [], "Ganon's Tower Big Key Chest Left": [], "Ganon's Tower Big Key Chest Right": []} }, "Ganon's Tower Big Key": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Big Key Room": []} }, "Ganon's Tower Big Key Chest Left": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Big Key Room": []} }, "Ganon's Tower Big Key Chest Right": { 'type': 'dungeonchest', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Big Key Room": []} }, "Ganon's Tower Treasure Room": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Treasure": [('bigkey', "Ganon's Tower")], "Ganon's Tower Convergence": [], "Ganon's Tower Torch Key Room": []} }, "Ganon's Tower Treasure": { 'type': 'dungeonchest_nokey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Treasure Room": []} }, "Ganon's Tower Ascent 1": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Lobby": [], "Ganon's Tower Ascent 2": [ ('item', 'bow'), ('settings', 'enemiser')]} }, "Ganon's Tower Ascent 2": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 1": [ ('item', 'bow'), ('settings', 'enemiser')], "Ganon's Tower Ascent 3": [ ('item', 'lantern'), ('item', 'firerod')]} }, "Ganon's Tower Ascent 3": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 2": [], "Ganon's Tower Helmasaur Key": [], "Ganon's Tower Helmasaur Chest 1": [], "Ganon's Tower Helmasaur Chest 2": [], "Ganon's Tower Ascent 4": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Helmasaur Key": { 'type': 'dungeonkey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 3": []} }, "Ganon's Tower Helmasaur Chest 1": { 'type': 'dungeonchest_nokey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 3": []} }, "Ganon's Tower Helmasaur Chest 2": { 'type': 'dungeonchest_nokey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 3": []} }, "Ganon's Tower Ascent 4": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 3": [], "Ganon's Tower Rabbit Beam Chest": [], "Ganon's Tower Ascent 5": [('smallkey', "Ganon's Tower")]} }, "Ganon's Tower Rabbit Beam Chest": { 'type': 'dungeonchest_nokey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 4": []} }, "Ganon's Tower Ascent 5": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 4": [], "Ganon's Tower Ascent 6": [('item', 'hookshot')]} }, "Ganon's Tower Ascent 6": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Last Chest": [], "Ganon's Tower Boss": []} }, "Ganon's Tower Last Chest": { 'type': 'dungeonchest_nokey', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Ascent 6": []} }, "Ganon's Tower Boss": { 'type': 'dungeonboss', "dungeon": "Ganon's Tower", 'link': { "Ganon's Tower Boss Item": [ ('item', 'sword'), ('and', [ ('settings', 'swordless'), ('item', 'hammer')]), ('item', 'bugnet')]} }, "Ganon's Tower Boss Item": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { "Ganon's Tower Reward": []} }, "Ganon's Tower Reward": { 'type': 'area', 'dungeon': "Ganon's Tower", 'link': { 'Pyramid': [('and', [ ('nosettings', 'inverted'), ('state', 'rabbit;add')])], 'Castle Walls': [('and', [ ('settings', 'inverted'), ('state', 'rabbit;add')])]} }, }
z3-tracker
/z3_tracker-0.9.12-py3-none-any.whl/z3tracker/ruleset/vt8/ganonstower.py
ganonstower.py