Z3
z3py.py
Go to the documentation of this file.
1 
2 
3 
10 
11 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
12 
13 Several online tutorials for Z3Py are available at:
14 http://rise4fun.com/Z3Py/tutorial/guide
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
17 
18 Small example:
19 
20 >>> x = Int('x')
21 >>> y = Int('y')
22 >>> s = Solver()
23 >>> s.add(x > 0)
24 >>> s.add(x < 2)
25 >>> s.add(y == x + 1)
26 >>> s.check()
27 sat
28 >>> m = s.model()
29 >>> m[x]
30 1
31 >>> m[y]
32 2
33 
34 Z3 exceptions:
35 
36 >>> try:
37 ... x = BitVec('x', 32)
38 ... y = Bool('y')
39 ... # the expression x + y is type incorrect
40 ... n = x + y
41 ... except Z3Exception as ex:
42 ... print("failed: %s" % ex)
43 failed: sort mismatch
44 """
45 from . import z3core
46 from .z3core import *
47 from .z3types import *
48 from .z3consts import *
49 from .z3printer import *
50 from fractions import Fraction
51 import sys
52 import io
53 import math
54 import copy
55 
56 if sys.version < '3':
57  def _is_int(v):
58  return isinstance(v, (int, long))
59 else:
60  def _is_int(v):
61  return isinstance(v, int)
62 
63 def enable_trace(msg):
64  Z3_enable_trace(msg)
65 
66 def disable_trace(msg):
67  Z3_disable_trace(msg)
68 
70  major = ctypes.c_uint(0)
71  minor = ctypes.c_uint(0)
72  build = ctypes.c_uint(0)
73  rev = ctypes.c_uint(0)
74  Z3_get_version(major, minor, build, rev)
75  return "%s.%s.%s" % (major.value, minor.value, build.value)
76 
78  major = ctypes.c_uint(0)
79  minor = ctypes.c_uint(0)
80  build = ctypes.c_uint(0)
81  rev = ctypes.c_uint(0)
82  Z3_get_version(major, minor, build, rev)
83  return (major.value, minor.value, build.value, rev.value)
84 
86  return Z3_get_full_version()
87 
88 # We use _z3_assert instead of the assert command because we want to
89 # produce nice error messages in Z3Py at rise4fun.com
90 def _z3_assert(cond, msg):
91  if not cond:
92  raise Z3Exception(msg)
93 
94 def _z3_check_cint_overflow(n, name):
95  _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
96 
97 def open_log(fname):
98  """Log interaction to a file. This function must be invoked immediately after init(). """
99  Z3_open_log(fname)
100 
101 def append_log(s):
102  """Append user-defined string to interaction log. """
103  Z3_append_log(s)
104 
105 def to_symbol(s, ctx=None):
106  """Convert an integer or string into a Z3 symbol."""
107  if _is_int(s):
108  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
109  else:
110  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
111 
112 def _symbol2py(ctx, s):
113  """Convert a Z3 symbol back into a Python object. """
114  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
115  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
116  else:
117  return Z3_get_symbol_string(ctx.ref(), s)
118 
119 # Hack for having nary functions that can receive one argument that is the
120 # list of arguments.
121 # Use this when function takes a single list of arguments
122 def _get_args(args):
123  try:
124  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
125  return args[0]
126  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
127  return [arg for arg in args[0]]
128  else:
129  return args
130  except: # len is not necessarily defined when args is not a sequence (use reflection?)
131  return args
132 
133 # Use this when function takes multiple arguments
134 def _get_args_ast_list(args):
135  try:
136  if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
137  return [arg for arg in args]
138  else:
139  return args
140  except:
141  return args
142 
143 def _to_param_value(val):
144  if isinstance(val, bool):
145  if val == True:
146  return "true"
147  else:
148  return "false"
149  else:
150  return str(val)
151 
153  # Do nothing error handler, just avoid exit(0)
154  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
155  return
156 
157 class Context:
158  """A Context manages all other Z3 objects, global configuration options, etc.
159 
160  Z3Py uses a default global context. For most applications this is sufficient.
161  An application may use multiple Z3 contexts. Objects created in one context
162  cannot be used in another one. However, several objects may be "translated" from
163  one context to another. It is not safe to access Z3 objects from multiple threads.
164  The only exception is the method `interrupt()` that can be used to interrupt() a long
165  computation.
166  The initialization method receives global configuration options for the new context.
167  """
168  def __init__(self, *args, **kws):
169  if __debug__:
170  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
171  conf = Z3_mk_config()
172  for key in kws:
173  value = kws[key]
174  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
175  prev = None
176  for a in args:
177  if prev is None:
178  prev = a
179  else:
180  Z3_set_param_value(conf, str(prev), _to_param_value(a))
181  prev = None
182  self.ctx = Z3_mk_context_rc(conf)
183  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
184  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
185  Z3_del_config(conf)
186 
187  def __del__(self):
188  Z3_del_context(self.ctx)
189  self.ctx = None
190  self.eh = None
191 
192  def ref(self):
193  """Return a reference to the actual C pointer to the Z3 context."""
194  return self.ctx
195 
196  def interrupt(self):
197  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
198 
199  This method can be invoked from a thread different from the one executing the
200  interruptible procedure.
201  """
202  Z3_interrupt(self.ref())
203 
204 
205 # Global Z3 context
206 _main_ctx = None
207 def main_ctx():
208  """Return a reference to the global Z3 context.
209 
210  >>> x = Real('x')
211  >>> x.ctx == main_ctx()
212  True
213  >>> c = Context()
214  >>> c == main_ctx()
215  False
216  >>> x2 = Real('x', c)
217  >>> x2.ctx == c
218  True
219  >>> eq(x, x2)
220  False
221  """
222  global _main_ctx
223  if _main_ctx is None:
224  _main_ctx = Context()
225  return _main_ctx
226 
227 def _get_ctx(ctx):
228  if ctx is None:
229  return main_ctx()
230  else:
231  return ctx
232 
233 def set_param(*args, **kws):
234  """Set Z3 global (or module) parameters.
235 
236  >>> set_param(precision=10)
237  """
238  if __debug__:
239  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
240  new_kws = {}
241  for k in kws:
242  v = kws[k]
243  if not set_pp_option(k, v):
244  new_kws[k] = v
245  for key in new_kws:
246  value = new_kws[key]
247  Z3_global_param_set(str(key).upper(), _to_param_value(value))
248  prev = None
249  for a in args:
250  if prev is None:
251  prev = a
252  else:
253  Z3_global_param_set(str(prev), _to_param_value(a))
254  prev = None
255 
257  """Reset all global (or module) parameters.
258  """
260 
261 def set_option(*args, **kws):
262  """Alias for 'set_param' for backward compatibility.
263  """
264  return set_param(*args, **kws)
265 
266 def get_param(name):
267  """Return the value of a Z3 global (or module) parameter
268 
269  >>> get_param('nlsat.reorder')
270  'true'
271  """
272  ptr = (ctypes.c_char_p * 1)()
273  if Z3_global_param_get(str(name), ptr):
274  r = z3core._to_pystr(ptr[0])
275  return r
276  raise Z3Exception("failed to retrieve value for '%s'" % name)
277 
278 
283 
284 # Mark objects that use pretty printer
286  """Superclass for all Z3 objects that have support for pretty printing."""
287  def use_pp(self):
288  return True
289 
291  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
292  def __init__(self, ast, ctx=None):
293  self.ast = ast
294  self.ctx = _get_ctx(ctx)
295  Z3_inc_ref(self.ctx.ref(), self.as_ast())
296 
297  def __del__(self):
298  if self.ctx.ref() is not None:
299  Z3_dec_ref(self.ctx.ref(), self.as_ast())
300 
301  def __deepcopy__(self, memo={}):
302  return _to_ast_ref(self.ast, self.ctx)
303 
304  def __str__(self):
305  return obj_to_string(self)
306 
307  def __repr__(self):
308  return obj_to_string(self)
309 
310  def __eq__(self, other):
311  return self.eq(other)
312 
313  def __hash__(self):
314  return self.hash()
315 
316  def __nonzero__(self):
317  return self.__bool__()
318 
319  def __bool__(self):
320  if is_true(self):
321  return True
322  elif is_false(self):
323  return False
324  elif is_eq(self) and self.num_args() == 2:
325  return self.arg(0).eq(self.arg(1))
326  else:
327  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
328 
329  def sexpr(self):
330  """Return a string representing the AST node in s-expression notation.
331 
332  >>> x = Int('x')
333  >>> ((x + 1)*x).sexpr()
334  '(* (+ x 1) x)'
335  """
336  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
337 
338  def as_ast(self):
339  """Return a pointer to the corresponding C Z3_ast object."""
340  return self.ast
341 
342  def get_id(self):
343  """Return unique identifier for object. It can be used for hash-tables and maps."""
344  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
345 
346  def ctx_ref(self):
347  """Return a reference to the C context where this AST node is stored."""
348  return self.ctx.ref()
349 
350  def eq(self, other):
351  """Return `True` if `self` and `other` are structurally identical.
352 
353  >>> x = Int('x')
354  >>> n1 = x + 1
355  >>> n2 = 1 + x
356  >>> n1.eq(n2)
357  False
358  >>> n1 = simplify(n1)
359  >>> n2 = simplify(n2)
360  >>> n1.eq(n2)
361  True
362  """
363  if __debug__:
364  _z3_assert(is_ast(other), "Z3 AST expected")
365  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
366 
367  def translate(self, target):
368  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
369 
370  >>> c1 = Context()
371  >>> c2 = Context()
372  >>> x = Int('x', c1)
373  >>> y = Int('y', c2)
374  >>> # Nodes in different contexts can't be mixed.
375  >>> # However, we can translate nodes from one context to another.
376  >>> x.translate(c2) + y
377  x + y
378  """
379  if __debug__:
380  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
381  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
382 
383  def __copy__(self):
384  return self.translate(self.ctx)
385 
386  def hash(self):
387  """Return a hashcode for the `self`.
388 
389  >>> n1 = simplify(Int('x') + 1)
390  >>> n2 = simplify(2 + Int('x') - 1)
391  >>> n1.hash() == n2.hash()
392  True
393  """
394  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
395 
396 def is_ast(a):
397  """Return `True` if `a` is an AST node.
398 
399  >>> is_ast(10)
400  False
401  >>> is_ast(IntVal(10))
402  True
403  >>> is_ast(Int('x'))
404  True
405  >>> is_ast(BoolSort())
406  True
407  >>> is_ast(Function('f', IntSort(), IntSort()))
408  True
409  >>> is_ast("x")
410  False
411  >>> is_ast(Solver())
412  False
413  """
414  return isinstance(a, AstRef)
415 
416 def eq(a, b):
417  """Return `True` if `a` and `b` are structurally identical AST nodes.
418 
419  >>> x = Int('x')
420  >>> y = Int('y')
421  >>> eq(x, y)
422  False
423  >>> eq(x + 1, x + 1)
424  True
425  >>> eq(x + 1, 1 + x)
426  False
427  >>> eq(simplify(x + 1), simplify(1 + x))
428  True
429  """
430  if __debug__:
431  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
432  return a.eq(b)
433 
434 def _ast_kind(ctx, a):
435  if is_ast(a):
436  a = a.as_ast()
437  return Z3_get_ast_kind(ctx.ref(), a)
438 
439 def _ctx_from_ast_arg_list(args, default_ctx=None):
440  ctx = None
441  for a in args:
442  if is_ast(a) or is_probe(a):
443  if ctx is None:
444  ctx = a.ctx
445  else:
446  if __debug__:
447  _z3_assert(ctx == a.ctx, "Context mismatch")
448  if ctx is None:
449  ctx = default_ctx
450  return ctx
451 
452 def _ctx_from_ast_args(*args):
453  return _ctx_from_ast_arg_list(args)
454 
455 def _to_func_decl_array(args):
456  sz = len(args)
457  _args = (FuncDecl * sz)()
458  for i in range(sz):
459  _args[i] = args[i].as_func_decl()
460  return _args, sz
461 
462 def _to_ast_array(args):
463  sz = len(args)
464  _args = (Ast * sz)()
465  for i in range(sz):
466  _args[i] = args[i].as_ast()
467  return _args, sz
468 
469 def _to_ref_array(ref, args):
470  sz = len(args)
471  _args = (ref * sz)()
472  for i in range(sz):
473  _args[i] = args[i].as_ast()
474  return _args, sz
475 
476 def _to_ast_ref(a, ctx):
477  k = _ast_kind(ctx, a)
478  if k == Z3_SORT_AST:
479  return _to_sort_ref(a, ctx)
480  elif k == Z3_FUNC_DECL_AST:
481  return _to_func_decl_ref(a, ctx)
482  else:
483  return _to_expr_ref(a, ctx)
484 
485 
490 
491 def _sort_kind(ctx, s):
492  return Z3_get_sort_kind(ctx.ref(), s)
493 
495  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
496  def as_ast(self):
497  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
498 
499  def get_id(self):
500  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
501 
502  def kind(self):
503  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
504 
505  >>> b = BoolSort()
506  >>> b.kind() == Z3_BOOL_SORT
507  True
508  >>> b.kind() == Z3_INT_SORT
509  False
510  >>> A = ArraySort(IntSort(), IntSort())
511  >>> A.kind() == Z3_ARRAY_SORT
512  True
513  >>> A.kind() == Z3_INT_SORT
514  False
515  """
516  return _sort_kind(self.ctx, self.ast)
517 
518  def subsort(self, other):
519  """Return `True` if `self` is a subsort of `other`.
520 
521  >>> IntSort().subsort(RealSort())
522  True
523  """
524  return False
525 
526  def cast(self, val):
527  """Try to cast `val` as an element of sort `self`.
528 
529  This method is used in Z3Py to convert Python objects such as integers,
530  floats, longs and strings into Z3 expressions.
531 
532  >>> x = Int('x')
533  >>> RealSort().cast(x)
534  ToReal(x)
535  """
536  if __debug__:
537  _z3_assert(is_expr(val), "Z3 expression expected")
538  _z3_assert(self.eq(val.sort()), "Sort mismatch")
539  return val
540 
541  def name(self):
542  """Return the name (string) of sort `self`.
543 
544  >>> BoolSort().name()
545  'Bool'
546  >>> ArraySort(IntSort(), IntSort()).name()
547  'Array'
548  """
549  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
550 
551  def __eq__(self, other):
552  """Return `True` if `self` and `other` are the same Z3 sort.
553 
554  >>> p = Bool('p')
555  >>> p.sort() == BoolSort()
556  True
557  >>> p.sort() == IntSort()
558  False
559  """
560  if other is None:
561  return False
562  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
563 
564  def __ne__(self, other):
565  """Return `True` if `self` and `other` are not the same Z3 sort.
566 
567  >>> p = Bool('p')
568  >>> p.sort() != BoolSort()
569  False
570  >>> p.sort() != IntSort()
571  True
572  """
573  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
574 
575  def __hash__(self):
576  """ Hash code. """
577  return AstRef.__hash__(self)
578 
579 def is_sort(s):
580  """Return `True` if `s` is a Z3 sort.
581 
582  >>> is_sort(IntSort())
583  True
584  >>> is_sort(Int('x'))
585  False
586  >>> is_expr(Int('x'))
587  True
588  """
589  return isinstance(s, SortRef)
590 
591 def _to_sort_ref(s, ctx):
592  if __debug__:
593  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
594  k = _sort_kind(ctx, s)
595  if k == Z3_BOOL_SORT:
596  return BoolSortRef(s, ctx)
597  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
598  return ArithSortRef(s, ctx)
599  elif k == Z3_BV_SORT:
600  return BitVecSortRef(s, ctx)
601  elif k == Z3_ARRAY_SORT:
602  return ArraySortRef(s, ctx)
603  elif k == Z3_DATATYPE_SORT:
604  return DatatypeSortRef(s, ctx)
605  elif k == Z3_FINITE_DOMAIN_SORT:
606  return FiniteDomainSortRef(s, ctx)
607  elif k == Z3_FLOATING_POINT_SORT:
608  return FPSortRef(s, ctx)
609  elif k == Z3_ROUNDING_MODE_SORT:
610  return FPRMSortRef(s, ctx)
611  return SortRef(s, ctx)
612 
613 def _sort(ctx, a):
614  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
615 
616 def DeclareSort(name, ctx=None):
617  """Create a new uninterpreted sort named `name`.
618 
619  If `ctx=None`, then the new sort is declared in the global Z3Py context.
620 
621  >>> A = DeclareSort('A')
622  >>> a = Const('a', A)
623  >>> b = Const('b', A)
624  >>> a.sort() == A
625  True
626  >>> b.sort() == A
627  True
628  >>> a == b
629  a == b
630  """
631  ctx = _get_ctx(ctx)
632  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
633 
634 
639 
641  """Function declaration. Every constant and function have an associated declaration.
642 
643  The declaration assigns a name, a sort (i.e., type), and for function
644  the sort (i.e., type) of each of its arguments. Note that, in Z3,
645  a constant is a function with 0 arguments.
646  """
647  def as_ast(self):
648  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
649 
650  def get_id(self):
651  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
652 
653  def as_func_decl(self):
654  return self.ast
655 
656  def name(self):
657  """Return the name of the function declaration `self`.
658 
659  >>> f = Function('f', IntSort(), IntSort())
660  >>> f.name()
661  'f'
662  >>> isinstance(f.name(), str)
663  True
664  """
665  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
666 
667  def arity(self):
668  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
669 
670  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
671  >>> f.arity()
672  2
673  """
674  return int(Z3_get_arity(self.ctx_ref(), self.ast))
675 
676  def domain(self, i):
677  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
678 
679  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
680  >>> f.domain(0)
681  Int
682  >>> f.domain(1)
683  Real
684  """
685  if __debug__:
686  _z3_assert(i < self.arity(), "Index out of bounds")
687  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
688 
689  def range(self):
690  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
691 
692  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
693  >>> f.range()
694  Bool
695  """
696  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
697 
698  def kind(self):
699  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
700 
701  >>> x = Int('x')
702  >>> d = (x + 1).decl()
703  >>> d.kind() == Z3_OP_ADD
704  True
705  >>> d.kind() == Z3_OP_MUL
706  False
707  """
708  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
709 
710  def params(self):
711  ctx = self.ctx
712  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
713  result = [ None for i in range(n) ]
714  for i in range(n):
715  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
716  if k == Z3_PARAMETER_INT:
717  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
718  elif k == Z3_PARAMETER_DOUBLE:
719  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
720  elif k == Z3_PARAMETER_RATIONAL:
721  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
722  elif k == Z3_PARAMETER_SYMBOL:
723  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
724  elif k == Z3_PARAMETER_SORT:
725  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
726  elif k == Z3_PARAMETER_AST:
727  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
728  elif k == Z3_PARAMETER_FUNC_DECL:
729  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
730  else:
731  assert(False)
732  return result
733 
734  def __call__(self, *args):
735  """Create a Z3 application expression using the function `self`, and the given arguments.
736 
737  The arguments must be Z3 expressions. This method assumes that
738  the sorts of the elements in `args` match the sorts of the
739  domain. Limited coercion is supported. For example, if
740  args[0] is a Python integer, and the function expects a Z3
741  integer, then the argument is automatically converted into a
742  Z3 integer.
743 
744  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
745  >>> x = Int('x')
746  >>> y = Real('y')
747  >>> f(x, y)
748  f(x, y)
749  >>> f(x, x)
750  f(x, ToReal(x))
751  """
752  args = _get_args(args)
753  num = len(args)
754  if __debug__:
755  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
756  _args = (Ast * num)()
757  saved = []
758  for i in range(num):
759  # self.domain(i).cast(args[i]) may create a new Z3 expression,
760  # then we must save in 'saved' to prevent it from being garbage collected.
761  tmp = self.domain(i).cast(args[i])
762  saved.append(tmp)
763  _args[i] = tmp.as_ast()
764  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
765 
767  """Return `True` if `a` is a Z3 function declaration.
768 
769  >>> f = Function('f', IntSort(), IntSort())
770  >>> is_func_decl(f)
771  True
772  >>> x = Real('x')
773  >>> is_func_decl(x)
774  False
775  """
776  return isinstance(a, FuncDeclRef)
777 
778 def Function(name, *sig):
779  """Create a new Z3 uninterpreted function with the given sorts.
780 
781  >>> f = Function('f', IntSort(), IntSort())
782  >>> f(f(0))
783  f(f(0))
784  """
785  sig = _get_args(sig)
786  if __debug__:
787  _z3_assert(len(sig) > 0, "At least two arguments expected")
788  arity = len(sig) - 1
789  rng = sig[arity]
790  if __debug__:
791  _z3_assert(is_sort(rng), "Z3 sort expected")
792  dom = (Sort * arity)()
793  for i in range(arity):
794  if __debug__:
795  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
796  dom[i] = sig[i].ast
797  ctx = rng.ctx
798  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
799 
800 def _to_func_decl_ref(a, ctx):
801  return FuncDeclRef(a, ctx)
802 
803 def RecFunction(name, *sig):
804  """Create a new Z3 recursive with the given sorts."""
805  sig = _get_args(sig)
806  if __debug__:
807  _z3_assert(len(sig) > 0, "At least two arguments expected")
808  arity = len(sig) - 1
809  rng = sig[arity]
810  if __debug__:
811  _z3_assert(is_sort(rng), "Z3 sort expected")
812  dom = (Sort * arity)()
813  for i in range(arity):
814  if __debug__:
815  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
816  dom[i] = sig[i].ast
817  ctx = rng.ctx
818  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
819 
820 def RecAddDefinition(f, args, body):
821  """Set the body of a recursive function.
822  Recursive definitions are only unfolded during search.
823  >>> ctx = Context()
824  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
825  >>> n = Int('n', ctx)
826  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
827  >>> simplify(fac(5))
828  fac(5)
829  >>> s = Solver(ctx=ctx)
830  >>> s.add(fac(n) < 3)
831  >>> s.check()
832  sat
833  >>> s.model().eval(fac(5))
834  120
835  """
836  if is_app(args):
837  args = [args]
838  ctx = body.ctx
839  args = _get_args(args)
840  n = len(args)
841  _args = (Ast * n)()
842  for i in range(n):
843  _args[i] = args[i].ast
844  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
845 
846 
851 
853  """Constraints, formulas and terms are expressions in Z3.
854 
855  Expressions are ASTs. Every expression has a sort.
856  There are three main kinds of expressions:
857  function applications, quantifiers and bounded variables.
858  A constant is a function application with 0 arguments.
859  For quantifier free problems, all expressions are
860  function applications.
861  """
862  def as_ast(self):
863  return self.ast
864 
865  def get_id(self):
866  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
867 
868  def sort(self):
869  """Return the sort of expression `self`.
870 
871  >>> x = Int('x')
872  >>> (x + 1).sort()
873  Int
874  >>> y = Real('y')
875  >>> (x + y).sort()
876  Real
877  """
878  return _sort(self.ctx, self.as_ast())
879 
880  def sort_kind(self):
881  """Shorthand for `self.sort().kind()`.
882 
883  >>> a = Array('a', IntSort(), IntSort())
884  >>> a.sort_kind() == Z3_ARRAY_SORT
885  True
886  >>> a.sort_kind() == Z3_INT_SORT
887  False
888  """
889  return self.sort().kind()
890 
891  def __eq__(self, other):
892  """Return a Z3 expression that represents the constraint `self == other`.
893 
894  If `other` is `None`, then this method simply returns `False`.
895 
896  >>> a = Int('a')
897  >>> b = Int('b')
898  >>> a == b
899  a == b
900  >>> a is None
901  False
902  """
903  if other is None:
904  return False
905  a, b = _coerce_exprs(self, other)
906  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
907 
908  def __hash__(self):
909  """ Hash code. """
910  return AstRef.__hash__(self)
911 
912  def __ne__(self, other):
913  """Return a Z3 expression that represents the constraint `self != other`.
914 
915  If `other` is `None`, then this method simply returns `True`.
916 
917  >>> a = Int('a')
918  >>> b = Int('b')
919  >>> a != b
920  a != b
921  >>> a is not None
922  True
923  """
924  if other is None:
925  return True
926  a, b = _coerce_exprs(self, other)
927  _args, sz = _to_ast_array((a, b))
928  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
929 
930  def params(self):
931  return self.decl().params()
932 
933  def decl(self):
934  """Return the Z3 function declaration associated with a Z3 application.
935 
936  >>> f = Function('f', IntSort(), IntSort())
937  >>> a = Int('a')
938  >>> t = f(a)
939  >>> eq(t.decl(), f)
940  True
941  >>> (a + 1).decl()
942  +
943  """
944  if __debug__:
945  _z3_assert(is_app(self), "Z3 application expected")
946  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
947 
948  def num_args(self):
949  """Return the number of arguments of a Z3 application.
950 
951  >>> a = Int('a')
952  >>> b = Int('b')
953  >>> (a + b).num_args()
954  2
955  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
956  >>> t = f(a, b, 0)
957  >>> t.num_args()
958  3
959  """
960  if __debug__:
961  _z3_assert(is_app(self), "Z3 application expected")
962  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
963 
964  def arg(self, idx):
965  """Return argument `idx` of the application `self`.
966 
967  This method assumes that `self` is a function application with at least `idx+1` arguments.
968 
969  >>> a = Int('a')
970  >>> b = Int('b')
971  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
972  >>> t = f(a, b, 0)
973  >>> t.arg(0)
974  a
975  >>> t.arg(1)
976  b
977  >>> t.arg(2)
978  0
979  """
980  if __debug__:
981  _z3_assert(is_app(self), "Z3 application expected")
982  _z3_assert(idx < self.num_args(), "Invalid argument index")
983  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
984 
985  def children(self):
986  """Return a list containing the children of the given expression
987 
988  >>> a = Int('a')
989  >>> b = Int('b')
990  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
991  >>> t = f(a, b, 0)
992  >>> t.children()
993  [a, b, 0]
994  """
995  if is_app(self):
996  return [self.arg(i) for i in range(self.num_args())]
997  else:
998  return []
999 
1000 def _to_expr_ref(a, ctx):
1001  if isinstance(a, Pattern):
1002  return PatternRef(a, ctx)
1003  ctx_ref = ctx.ref()
1004  k = Z3_get_ast_kind(ctx_ref, a)
1005  if k == Z3_QUANTIFIER_AST:
1006  return QuantifierRef(a, ctx)
1007  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1008  if sk == Z3_BOOL_SORT:
1009  return BoolRef(a, ctx)
1010  if sk == Z3_INT_SORT:
1011  if k == Z3_NUMERAL_AST:
1012  return IntNumRef(a, ctx)
1013  return ArithRef(a, ctx)
1014  if sk == Z3_REAL_SORT:
1015  if k == Z3_NUMERAL_AST:
1016  return RatNumRef(a, ctx)
1017  if _is_algebraic(ctx, a):
1018  return AlgebraicNumRef(a, ctx)
1019  return ArithRef(a, ctx)
1020  if sk == Z3_BV_SORT:
1021  if k == Z3_NUMERAL_AST:
1022  return BitVecNumRef(a, ctx)
1023  else:
1024  return BitVecRef(a, ctx)
1025  if sk == Z3_ARRAY_SORT:
1026  return ArrayRef(a, ctx)
1027  if sk == Z3_DATATYPE_SORT:
1028  return DatatypeRef(a, ctx)
1029  if sk == Z3_FLOATING_POINT_SORT:
1030  if k == Z3_APP_AST and _is_numeral(ctx, a):
1031  return FPNumRef(a, ctx)
1032  else:
1033  return FPRef(a, ctx)
1034  if sk == Z3_FINITE_DOMAIN_SORT:
1035  if k == Z3_NUMERAL_AST:
1036  return FiniteDomainNumRef(a, ctx)
1037  else:
1038  return FiniteDomainRef(a, ctx)
1039  if sk == Z3_ROUNDING_MODE_SORT:
1040  return FPRMRef(a, ctx)
1041  if sk == Z3_SEQ_SORT:
1042  return SeqRef(a, ctx)
1043  if sk == Z3_RE_SORT:
1044  return ReRef(a, ctx)
1045  return ExprRef(a, ctx)
1046 
1047 def _coerce_expr_merge(s, a):
1048  if is_expr(a):
1049  s1 = a.sort()
1050  if s is None:
1051  return s1
1052  if s1.eq(s):
1053  return s
1054  elif s.subsort(s1):
1055  return s1
1056  elif s1.subsort(s):
1057  return s
1058  else:
1059  if __debug__:
1060  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1061  _z3_assert(False, "sort mismatch")
1062  else:
1063  return s
1064 
1065 def _coerce_exprs(a, b, ctx=None):
1066  if not is_expr(a) and not is_expr(b):
1067  a = _py2expr(a, ctx)
1068  b = _py2expr(b, ctx)
1069  s = None
1070  s = _coerce_expr_merge(s, a)
1071  s = _coerce_expr_merge(s, b)
1072  a = s.cast(a)
1073  b = s.cast(b)
1074  return (a, b)
1075 
1076 
1077 def _reduce(f, l, a):
1078  r = a
1079  for e in l:
1080  r = f(r, e)
1081  return r
1082 
1083 def _coerce_expr_list(alist, ctx=None):
1084  has_expr = False
1085  for a in alist:
1086  if is_expr(a):
1087  has_expr = True
1088  break
1089  if not has_expr:
1090  alist = [ _py2expr(a, ctx) for a in alist ]
1091  s = _reduce(_coerce_expr_merge, alist, None)
1092  return [ s.cast(a) for a in alist ]
1093 
1094 def is_expr(a):
1095  """Return `True` if `a` is a Z3 expression.
1096 
1097  >>> a = Int('a')
1098  >>> is_expr(a)
1099  True
1100  >>> is_expr(a + 1)
1101  True
1102  >>> is_expr(IntSort())
1103  False
1104  >>> is_expr(1)
1105  False
1106  >>> is_expr(IntVal(1))
1107  True
1108  >>> x = Int('x')
1109  >>> is_expr(ForAll(x, x >= 0))
1110  True
1111  >>> is_expr(FPVal(1.0))
1112  True
1113  """
1114  return isinstance(a, ExprRef)
1115 
1116 def is_app(a):
1117  """Return `True` if `a` is a Z3 function application.
1118 
1119  Note that, constants are function applications with 0 arguments.
1120 
1121  >>> a = Int('a')
1122  >>> is_app(a)
1123  True
1124  >>> is_app(a + 1)
1125  True
1126  >>> is_app(IntSort())
1127  False
1128  >>> is_app(1)
1129  False
1130  >>> is_app(IntVal(1))
1131  True
1132  >>> x = Int('x')
1133  >>> is_app(ForAll(x, x >= 0))
1134  False
1135  """
1136  if not isinstance(a, ExprRef):
1137  return False
1138  k = _ast_kind(a.ctx, a)
1139  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1140 
1141 def is_const(a):
1142  """Return `True` if `a` is Z3 constant/variable expression.
1143 
1144  >>> a = Int('a')
1145  >>> is_const(a)
1146  True
1147  >>> is_const(a + 1)
1148  False
1149  >>> is_const(1)
1150  False
1151  >>> is_const(IntVal(1))
1152  True
1153  >>> x = Int('x')
1154  >>> is_const(ForAll(x, x >= 0))
1155  False
1156  """
1157  return is_app(a) and a.num_args() == 0
1158 
1159 def is_var(a):
1160  """Return `True` if `a` is variable.
1161 
1162  Z3 uses de-Bruijn indices for representing bound variables in
1163  quantifiers.
1164 
1165  >>> x = Int('x')
1166  >>> is_var(x)
1167  False
1168  >>> is_const(x)
1169  True
1170  >>> f = Function('f', IntSort(), IntSort())
1171  >>> # Z3 replaces x with bound variables when ForAll is executed.
1172  >>> q = ForAll(x, f(x) == x)
1173  >>> b = q.body()
1174  >>> b
1175  f(Var(0)) == Var(0)
1176  >>> b.arg(1)
1177  Var(0)
1178  >>> is_var(b.arg(1))
1179  True
1180  """
1181  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1182 
1184  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1185 
1186  >>> x = Int('x')
1187  >>> y = Int('y')
1188  >>> is_var(x)
1189  False
1190  >>> is_const(x)
1191  True
1192  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1193  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1194  >>> q = ForAll([x, y], f(x, y) == x + y)
1195  >>> q.body()
1196  f(Var(1), Var(0)) == Var(1) + Var(0)
1197  >>> b = q.body()
1198  >>> b.arg(0)
1199  f(Var(1), Var(0))
1200  >>> v1 = b.arg(0).arg(0)
1201  >>> v2 = b.arg(0).arg(1)
1202  >>> v1
1203  Var(1)
1204  >>> v2
1205  Var(0)
1206  >>> get_var_index(v1)
1207  1
1208  >>> get_var_index(v2)
1209  0
1210  """
1211  if __debug__:
1212  _z3_assert(is_var(a), "Z3 bound variable expected")
1213  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1214 
1215 def is_app_of(a, k):
1216  """Return `True` if `a` is an application of the given kind `k`.
1217 
1218  >>> x = Int('x')
1219  >>> n = x + 1
1220  >>> is_app_of(n, Z3_OP_ADD)
1221  True
1222  >>> is_app_of(n, Z3_OP_MUL)
1223  False
1224  """
1225  return is_app(a) and a.decl().kind() == k
1226 
1227 def If(a, b, c, ctx=None):
1228  """Create a Z3 if-then-else expression.
1229 
1230  >>> x = Int('x')
1231  >>> y = Int('y')
1232  >>> max = If(x > y, x, y)
1233  >>> max
1234  If(x > y, x, y)
1235  >>> simplify(max)
1236  If(x <= y, y, x)
1237  """
1238  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1239  return Cond(a, b, c, ctx)
1240  else:
1241  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1242  s = BoolSort(ctx)
1243  a = s.cast(a)
1244  b, c = _coerce_exprs(b, c, ctx)
1245  if __debug__:
1246  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1247  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1248 
1249 def Distinct(*args):
1250  """Create a Z3 distinct expression.
1251 
1252  >>> x = Int('x')
1253  >>> y = Int('y')
1254  >>> Distinct(x, y)
1255  x != y
1256  >>> z = Int('z')
1257  >>> Distinct(x, y, z)
1258  Distinct(x, y, z)
1259  >>> simplify(Distinct(x, y, z))
1260  Distinct(x, y, z)
1261  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1262  And(Not(x == y), Not(x == z), Not(y == z))
1263  """
1264  args = _get_args(args)
1265  ctx = _ctx_from_ast_arg_list(args)
1266  if __debug__:
1267  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1268  args = _coerce_expr_list(args, ctx)
1269  _args, sz = _to_ast_array(args)
1270  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1271 
1272 def _mk_bin(f, a, b):
1273  args = (Ast * 2)()
1274  if __debug__:
1275  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1276  args[0] = a.as_ast()
1277  args[1] = b.as_ast()
1278  return f(a.ctx.ref(), 2, args)
1279 
1280 def Const(name, sort):
1281  """Create a constant of the given sort.
1282 
1283  >>> Const('x', IntSort())
1284  x
1285  """
1286  if __debug__:
1287  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1288  ctx = sort.ctx
1289  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1290 
1291 def Consts(names, sort):
1292  """Create a several constants of the given sort.
1293 
1294  `names` is a string containing the names of all constants to be created.
1295  Blank spaces separate the names of different constants.
1296 
1297  >>> x, y, z = Consts('x y z', IntSort())
1298  >>> x + y + z
1299  x + y + z
1300  """
1301  if isinstance(names, str):
1302  names = names.split(" ")
1303  return [Const(name, sort) for name in names]
1304 
1305 def FreshConst(sort, prefix='c'):
1306  """Create a fresh constant of a specified sort"""
1307  ctx = _get_ctx(sort.ctx)
1308  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1309 
1310 def Var(idx, s):
1311  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1312 
1313  >>> Var(0, IntSort())
1314  Var(0)
1315  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1316  False
1317  """
1318  if __debug__:
1319  _z3_assert(is_sort(s), "Z3 sort expected")
1320  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1321 
1322 def RealVar(idx, ctx=None):
1323  """
1324  Create a real free variable. Free variables are used to create quantified formulas.
1325  They are also used to create polynomials.
1326 
1327  >>> RealVar(0)
1328  Var(0)
1329  """
1330  return Var(idx, RealSort(ctx))
1331 
1332 def RealVarVector(n, ctx=None):
1333  """
1334  Create a list of Real free variables.
1335  The variables have ids: 0, 1, ..., n-1
1336 
1337  >>> x0, x1, x2, x3 = RealVarVector(4)
1338  >>> x2
1339  Var(2)
1340  """
1341  return [ RealVar(i, ctx) for i in range(n) ]
1342 
1343 
1348 
1350  """Boolean sort."""
1351  def cast(self, val):
1352  """Try to cast `val` as a Boolean.
1353 
1354  >>> x = BoolSort().cast(True)
1355  >>> x
1356  True
1357  >>> is_expr(x)
1358  True
1359  >>> is_expr(True)
1360  False
1361  >>> x.sort()
1362  Bool
1363  """
1364  if isinstance(val, bool):
1365  return BoolVal(val, self.ctx)
1366  if __debug__:
1367  if not is_expr(val):
1368  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1369  if not self.eq(val.sort()):
1370  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1371  return val
1372 
1373  def subsort(self, other):
1374  return isinstance(other, ArithSortRef)
1375 
1376  def is_int(self):
1377  return True
1378 
1379  def is_bool(self):
1380  return True
1381 
1382 
1384  """All Boolean expressions are instances of this class."""
1385  def sort(self):
1386  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1387 
1388  def __rmul__(self, other):
1389  return self * other
1390 
1391  def __mul__(self, other):
1392  """Create the Z3 expression `self * other`.
1393  """
1394  if other == 1:
1395  return self
1396  if other == 0:
1397  return 0
1398  return If(self, other, 0)
1399 
1400 
1401 def is_bool(a):
1402  """Return `True` if `a` is a Z3 Boolean expression.
1403 
1404  >>> p = Bool('p')
1405  >>> is_bool(p)
1406  True
1407  >>> q = Bool('q')
1408  >>> is_bool(And(p, q))
1409  True
1410  >>> x = Real('x')
1411  >>> is_bool(x)
1412  False
1413  >>> is_bool(x == 0)
1414  True
1415  """
1416  return isinstance(a, BoolRef)
1417 
1418 def is_true(a):
1419  """Return `True` if `a` is the Z3 true expression.
1420 
1421  >>> p = Bool('p')
1422  >>> is_true(p)
1423  False
1424  >>> is_true(simplify(p == p))
1425  True
1426  >>> x = Real('x')
1427  >>> is_true(x == 0)
1428  False
1429  >>> # True is a Python Boolean expression
1430  >>> is_true(True)
1431  False
1432  """
1433  return is_app_of(a, Z3_OP_TRUE)
1434 
1435 def is_false(a):
1436  """Return `True` if `a` is the Z3 false expression.
1437 
1438  >>> p = Bool('p')
1439  >>> is_false(p)
1440  False
1441  >>> is_false(False)
1442  False
1443  >>> is_false(BoolVal(False))
1444  True
1445  """
1446  return is_app_of(a, Z3_OP_FALSE)
1447 
1448 def is_and(a):
1449  """Return `True` if `a` is a Z3 and expression.
1450 
1451  >>> p, q = Bools('p q')
1452  >>> is_and(And(p, q))
1453  True
1454  >>> is_and(Or(p, q))
1455  False
1456  """
1457  return is_app_of(a, Z3_OP_AND)
1458 
1459 def is_or(a):
1460  """Return `True` if `a` is a Z3 or expression.
1461 
1462  >>> p, q = Bools('p q')
1463  >>> is_or(Or(p, q))
1464  True
1465  >>> is_or(And(p, q))
1466  False
1467  """
1468  return is_app_of(a, Z3_OP_OR)
1469 
1470 def is_implies(a):
1471  """Return `True` if `a` is a Z3 implication expression.
1472 
1473  >>> p, q = Bools('p q')
1474  >>> is_implies(Implies(p, q))
1475  True
1476  >>> is_implies(And(p, q))
1477  False
1478  """
1479  return is_app_of(a, Z3_OP_IMPLIES)
1480 
1481 def is_not(a):
1482  """Return `True` if `a` is a Z3 not expression.
1483 
1484  >>> p = Bool('p')
1485  >>> is_not(p)
1486  False
1487  >>> is_not(Not(p))
1488  True
1489  """
1490  return is_app_of(a, Z3_OP_NOT)
1491 
1492 def is_eq(a):
1493  """Return `True` if `a` is a Z3 equality expression.
1494 
1495  >>> x, y = Ints('x y')
1496  >>> is_eq(x == y)
1497  True
1498  """
1499  return is_app_of(a, Z3_OP_EQ)
1500 
1502  """Return `True` if `a` is a Z3 distinct expression.
1503 
1504  >>> x, y, z = Ints('x y z')
1505  >>> is_distinct(x == y)
1506  False
1507  >>> is_distinct(Distinct(x, y, z))
1508  True
1509  """
1510  return is_app_of(a, Z3_OP_DISTINCT)
1511 
1512 def BoolSort(ctx=None):
1513  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1514 
1515  >>> BoolSort()
1516  Bool
1517  >>> p = Const('p', BoolSort())
1518  >>> is_bool(p)
1519  True
1520  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1521  >>> r(0, 1)
1522  r(0, 1)
1523  >>> is_bool(r(0, 1))
1524  True
1525  """
1526  ctx = _get_ctx(ctx)
1527  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1528 
1529 def BoolVal(val, ctx=None):
1530  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1531 
1532  >>> BoolVal(True)
1533  True
1534  >>> is_true(BoolVal(True))
1535  True
1536  >>> is_true(True)
1537  False
1538  >>> is_false(BoolVal(False))
1539  True
1540  """
1541  ctx = _get_ctx(ctx)
1542  if val == False:
1543  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1544  else:
1545  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1546 
1547 def Bool(name, ctx=None):
1548  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1549 
1550  >>> p = Bool('p')
1551  >>> q = Bool('q')
1552  >>> And(p, q)
1553  And(p, q)
1554  """
1555  ctx = _get_ctx(ctx)
1556  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1557 
1558 def Bools(names, ctx=None):
1559  """Return a tuple of Boolean constants.
1560 
1561  `names` is a single string containing all names separated by blank spaces.
1562  If `ctx=None`, then the global context is used.
1563 
1564  >>> p, q, r = Bools('p q r')
1565  >>> And(p, Or(q, r))
1566  And(p, Or(q, r))
1567  """
1568  ctx = _get_ctx(ctx)
1569  if isinstance(names, str):
1570  names = names.split(" ")
1571  return [Bool(name, ctx) for name in names]
1572 
1573 def BoolVector(prefix, sz, ctx=None):
1574  """Return a list of Boolean constants of size `sz`.
1575 
1576  The constants are named using the given prefix.
1577  If `ctx=None`, then the global context is used.
1578 
1579  >>> P = BoolVector('p', 3)
1580  >>> P
1581  [p__0, p__1, p__2]
1582  >>> And(P)
1583  And(p__0, p__1, p__2)
1584  """
1585  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1586 
1587 def FreshBool(prefix='b', ctx=None):
1588  """Return a fresh Boolean constant in the given context using the given prefix.
1589 
1590  If `ctx=None`, then the global context is used.
1591 
1592  >>> b1 = FreshBool()
1593  >>> b2 = FreshBool()
1594  >>> eq(b1, b2)
1595  False
1596  """
1597  ctx = _get_ctx(ctx)
1598  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1599 
1600 def Implies(a, b, ctx=None):
1601  """Create a Z3 implies expression.
1602 
1603  >>> p, q = Bools('p q')
1604  >>> Implies(p, q)
1605  Implies(p, q)
1606  >>> simplify(Implies(p, q))
1607  Or(Not(p), q)
1608  """
1609  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1610  s = BoolSort(ctx)
1611  a = s.cast(a)
1612  b = s.cast(b)
1613  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1614 
1615 def Xor(a, b, ctx=None):
1616  """Create a Z3 Xor expression.
1617 
1618  >>> p, q = Bools('p q')
1619  >>> Xor(p, q)
1620  Xor(p, q)
1621  >>> simplify(Xor(p, q))
1622  Not(p) == q
1623  """
1624  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1625  s = BoolSort(ctx)
1626  a = s.cast(a)
1627  b = s.cast(b)
1628  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1629 
1630 def Not(a, ctx=None):
1631  """Create a Z3 not expression or probe.
1632 
1633  >>> p = Bool('p')
1634  >>> Not(Not(p))
1635  Not(Not(p))
1636  >>> simplify(Not(Not(p)))
1637  p
1638  """
1639  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1640  if is_probe(a):
1641  # Not is also used to build probes
1642  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1643  else:
1644  s = BoolSort(ctx)
1645  a = s.cast(a)
1646  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1647 
1648 def _has_probe(args):
1649  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1650  for arg in args:
1651  if is_probe(arg):
1652  return True
1653  return False
1654 
1655 def And(*args):
1656  """Create a Z3 and-expression or and-probe.
1657 
1658  >>> p, q, r = Bools('p q r')
1659  >>> And(p, q, r)
1660  And(p, q, r)
1661  >>> P = BoolVector('p', 5)
1662  >>> And(P)
1663  And(p__0, p__1, p__2, p__3, p__4)
1664  """
1665  last_arg = None
1666  if len(args) > 0:
1667  last_arg = args[len(args)-1]
1668  if isinstance(last_arg, Context):
1669  ctx = args[len(args)-1]
1670  args = args[:len(args)-1]
1671  elif len(args) == 1 and isinstance(args[0], AstVector):
1672  ctx = args[0].ctx
1673  args = [a for a in args[0]]
1674  else:
1675  ctx = main_ctx()
1676  args = _get_args(args)
1677  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1678  if __debug__:
1679  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1680  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1681  if _has_probe(args):
1682  return _probe_and(args, ctx)
1683  else:
1684  args = _coerce_expr_list(args, ctx)
1685  _args, sz = _to_ast_array(args)
1686  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1687 
1688 def Or(*args):
1689  """Create a Z3 or-expression or or-probe.
1690 
1691  >>> p, q, r = Bools('p q r')
1692  >>> Or(p, q, r)
1693  Or(p, q, r)
1694  >>> P = BoolVector('p', 5)
1695  >>> Or(P)
1696  Or(p__0, p__1, p__2, p__3, p__4)
1697  """
1698  last_arg = None
1699  if len(args) > 0:
1700  last_arg = args[len(args)-1]
1701  if isinstance(last_arg, Context):
1702  ctx = args[len(args)-1]
1703  args = args[:len(args)-1]
1704  else:
1705  ctx = main_ctx()
1706  args = _get_args(args)
1707  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1708  if __debug__:
1709  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1710  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1711  if _has_probe(args):
1712  return _probe_or(args, ctx)
1713  else:
1714  args = _coerce_expr_list(args, ctx)
1715  _args, sz = _to_ast_array(args)
1716  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1717 
1718 #########################################
1719 #
1720 # Patterns
1721 #
1722 #########################################
1723 
1724 class PatternRef(ExprRef):
1725  """Patterns are hints for quantifier instantiation.
1726 
1727  """
1728  def as_ast(self):
1729  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1730 
1731  def get_id(self):
1732  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1733 
1734 def is_pattern(a):
1735  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1736 
1737  >>> f = Function('f', IntSort(), IntSort())
1738  >>> x = Int('x')
1739  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1740  >>> q
1741  ForAll(x, f(x) == 0)
1742  >>> q.num_patterns()
1743  1
1744  >>> is_pattern(q.pattern(0))
1745  True
1746  >>> q.pattern(0)
1747  f(Var(0))
1748  """
1749  return isinstance(a, PatternRef)
1750 
1751 def MultiPattern(*args):
1752  """Create a Z3 multi-pattern using the given expressions `*args`
1753 
1754  >>> f = Function('f', IntSort(), IntSort())
1755  >>> g = Function('g', IntSort(), IntSort())
1756  >>> x = Int('x')
1757  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1758  >>> q
1759  ForAll(x, f(x) != g(x))
1760  >>> q.num_patterns()
1761  1
1762  >>> is_pattern(q.pattern(0))
1763  True
1764  >>> q.pattern(0)
1765  MultiPattern(f(Var(0)), g(Var(0)))
1766  """
1767  if __debug__:
1768  _z3_assert(len(args) > 0, "At least one argument expected")
1769  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1770  ctx = args[0].ctx
1771  args, sz = _to_ast_array(args)
1772  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1773 
1774 def _to_pattern(arg):
1775  if is_pattern(arg):
1776  return arg
1777  else:
1778  return MultiPattern(arg)
1779 
1780 #########################################
1781 #
1782 # Quantifiers
1783 #
1784 #########################################
1785 
1786 class QuantifierRef(BoolRef):
1787  """Universally and Existentially quantified formulas."""
1788 
1789  def as_ast(self):
1790  return self.ast
1791 
1792  def get_id(self):
1793  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1794 
1795  def sort(self):
1796  """Return the Boolean sort or sort of Lambda."""
1797  if self.is_lambda():
1798  return _sort(self.ctx, self.as_ast())
1799  return BoolSort(self.ctx)
1800 
1801  def is_forall(self):
1802  """Return `True` if `self` is a universal quantifier.
1803 
1804  >>> f = Function('f', IntSort(), IntSort())
1805  >>> x = Int('x')
1806  >>> q = ForAll(x, f(x) == 0)
1807  >>> q.is_forall()
1808  True
1809  >>> q = Exists(x, f(x) != 0)
1810  >>> q.is_forall()
1811  False
1812  """
1813  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1814 
1815  def is_exists(self):
1816  """Return `True` if `self` is an existential quantifier.
1817 
1818  >>> f = Function('f', IntSort(), IntSort())
1819  >>> x = Int('x')
1820  >>> q = ForAll(x, f(x) == 0)
1821  >>> q.is_exists()
1822  False
1823  >>> q = Exists(x, f(x) != 0)
1824  >>> q.is_exists()
1825  True
1826  """
1827  return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1828 
1829  def is_lambda(self):
1830  """Return `True` if `self` is a lambda expression.
1831 
1832  >>> f = Function('f', IntSort(), IntSort())
1833  >>> x = Int('x')
1834  >>> q = Lambda(x, f(x))
1835  >>> q.is_lambda()
1836  True
1837  >>> q = Exists(x, f(x) != 0)
1838  >>> q.is_lambda()
1839  False
1840  """
1841  return Z3_is_lambda(self.ctx_ref(), self.ast)
1842 
1843  def weight(self):
1844  """Return the weight annotation of `self`.
1845 
1846  >>> f = Function('f', IntSort(), IntSort())
1847  >>> x = Int('x')
1848  >>> q = ForAll(x, f(x) == 0)
1849  >>> q.weight()
1850  1
1851  >>> q = ForAll(x, f(x) == 0, weight=10)
1852  >>> q.weight()
1853  10
1854  """
1855  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1856 
1857  def num_patterns(self):
1858  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1859 
1860  >>> f = Function('f', IntSort(), IntSort())
1861  >>> g = Function('g', IntSort(), IntSort())
1862  >>> x = Int('x')
1863  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1864  >>> q.num_patterns()
1865  2
1866  """
1867  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1868 
1869  def pattern(self, idx):
1870  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1871 
1872  >>> f = Function('f', IntSort(), IntSort())
1873  >>> g = Function('g', IntSort(), IntSort())
1874  >>> x = Int('x')
1875  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1876  >>> q.num_patterns()
1877  2
1878  >>> q.pattern(0)
1879  f(Var(0))
1880  >>> q.pattern(1)
1881  g(Var(0))
1882  """
1883  if __debug__:
1884  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1885  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1886 
1887  def num_no_patterns(self):
1888  """Return the number of no-patterns."""
1889  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1890 
1891  def no_pattern(self, idx):
1892  """Return a no-pattern."""
1893  if __debug__:
1894  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1895  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1896 
1897  def body(self):
1898  """Return the expression being quantified.
1899 
1900  >>> f = Function('f', IntSort(), IntSort())
1901  >>> x = Int('x')
1902  >>> q = ForAll(x, f(x) == 0)
1903  >>> q.body()
1904  f(Var(0)) == 0
1905  """
1906  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1907 
1908  def num_vars(self):
1909  """Return the number of variables bounded by this quantifier.
1910 
1911  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1912  >>> x = Int('x')
1913  >>> y = Int('y')
1914  >>> q = ForAll([x, y], f(x, y) >= x)
1915  >>> q.num_vars()
1916  2
1917  """
1918  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1919 
1920  def var_name(self, idx):
1921  """Return a string representing a name used when displaying the quantifier.
1922 
1923  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1924  >>> x = Int('x')
1925  >>> y = Int('y')
1926  >>> q = ForAll([x, y], f(x, y) >= x)
1927  >>> q.var_name(0)
1928  'x'
1929  >>> q.var_name(1)
1930  'y'
1931  """
1932  if __debug__:
1933  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1934  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1935 
1936  def var_sort(self, idx):
1937  """Return the sort of a bound variable.
1938 
1939  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1940  >>> x = Int('x')
1941  >>> y = Real('y')
1942  >>> q = ForAll([x, y], f(x, y) >= x)
1943  >>> q.var_sort(0)
1944  Int
1945  >>> q.var_sort(1)
1946  Real
1947  """
1948  if __debug__:
1949  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1950  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1951 
1952  def children(self):
1953  """Return a list containing a single element self.body()
1954 
1955  >>> f = Function('f', IntSort(), IntSort())
1956  >>> x = Int('x')
1957  >>> q = ForAll(x, f(x) == 0)
1958  >>> q.children()
1959  [f(Var(0)) == 0]
1960  """
1961  return [ self.body() ]
1962 
1963 def is_quantifier(a):
1964  """Return `True` if `a` is a Z3 quantifier.
1965 
1966  >>> f = Function('f', IntSort(), IntSort())
1967  >>> x = Int('x')
1968  >>> q = ForAll(x, f(x) == 0)
1969  >>> is_quantifier(q)
1970  True
1971  >>> is_quantifier(f(x))
1972  False
1973  """
1974  return isinstance(a, QuantifierRef)
1975 
1976 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1977  if __debug__:
1978  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
1979  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1980  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1981  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1982  if is_app(vs):
1983  ctx = vs.ctx
1984  vs = [vs]
1985  else:
1986  ctx = vs[0].ctx
1987  if not is_expr(body):
1988  body = BoolVal(body, ctx)
1989  num_vars = len(vs)
1990  if num_vars == 0:
1991  return body
1992  _vs = (Ast * num_vars)()
1993  for i in range(num_vars):
1994  ## TODO: Check if is constant
1995  _vs[i] = vs[i].as_ast()
1996  patterns = [ _to_pattern(p) for p in patterns ]
1997  num_pats = len(patterns)
1998  _pats = (Pattern * num_pats)()
1999  for i in range(num_pats):
2000  _pats[i] = patterns[i].ast
2001  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2002  qid = to_symbol(qid, ctx)
2003  skid = to_symbol(skid, ctx)
2004  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2005  num_vars, _vs,
2006  num_pats, _pats,
2007  num_no_pats, _no_pats,
2008  body.as_ast()), ctx)
2009 
2010 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2011  """Create a Z3 forall formula.
2012 
2013  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2014 
2015  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2016  >>> x = Int('x')
2017  >>> y = Int('y')
2018  >>> ForAll([x, y], f(x, y) >= x)
2019  ForAll([x, y], f(x, y) >= x)
2020  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2021  ForAll([x, y], f(x, y) >= x)
2022  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2023  ForAll([x, y], f(x, y) >= x)
2024  """
2025  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2026 
2027 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2028  """Create a Z3 exists formula.
2029 
2030  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2031 
2032 
2033  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2034  >>> x = Int('x')
2035  >>> y = Int('y')
2036  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2037  >>> q
2038  Exists([x, y], f(x, y) >= x)
2039  >>> is_quantifier(q)
2040  True
2041  >>> r = Tactic('nnf')(q).as_expr()
2042  >>> is_quantifier(r)
2043  False
2044  """
2045  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2046 
2047 def Lambda(vs, body):
2048  """Create a Z3 lambda expression.
2049 
2050  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2051  >>> mem0 = Array('mem0', IntSort(), IntSort())
2052  >>> lo, hi, e, i = Ints('lo hi e i')
2053  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2054  >>> mem1
2055  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2056  """
2057  ctx = body.ctx
2058  if is_app(vs):
2059  vs = [vs]
2060  num_vars = len(vs)
2061  _vs = (Ast * num_vars)()
2062  for i in range(num_vars):
2063  ## TODO: Check if is constant
2064  _vs[i] = vs[i].as_ast()
2065  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2066 
2067 #########################################
2068 #
2069 # Arithmetic
2070 #
2071 #########################################
2072 
2073 class ArithSortRef(SortRef):
2074  """Real and Integer sorts."""
2075 
2076  def is_real(self):
2077  """Return `True` if `self` is of the sort Real.
2078 
2079  >>> x = Real('x')
2080  >>> x.is_real()
2081  True
2082  >>> (x + 1).is_real()
2083  True
2084  >>> x = Int('x')
2085  >>> x.is_real()
2086  False
2087  """
2088  return self.kind() == Z3_REAL_SORT
2089 
2090  def is_int(self):
2091  """Return `True` if `self` is of the sort Integer.
2092 
2093  >>> x = Int('x')
2094  >>> x.is_int()
2095  True
2096  >>> (x + 1).is_int()
2097  True
2098  >>> x = Real('x')
2099  >>> x.is_int()
2100  False
2101  """
2102  return self.kind() == Z3_INT_SORT
2103 
2104  def subsort(self, other):
2105  """Return `True` if `self` is a subsort of `other`."""
2106  return self.is_int() and is_arith_sort(other) and other.is_real()
2107 
2108  def cast(self, val):
2109  """Try to cast `val` as an Integer or Real.
2110 
2111  >>> IntSort().cast(10)
2112  10
2113  >>> is_int(IntSort().cast(10))
2114  True
2115  >>> is_int(10)
2116  False
2117  >>> RealSort().cast(10)
2118  10
2119  >>> is_real(RealSort().cast(10))
2120  True
2121  """
2122  if is_expr(val):
2123  if __debug__:
2124  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2125  val_s = val.sort()
2126  if self.eq(val_s):
2127  return val
2128  if val_s.is_int() and self.is_real():
2129  return ToReal(val)
2130  if val_s.is_bool() and self.is_int():
2131  return If(val, 1, 0)
2132  if val_s.is_bool() and self.is_real():
2133  return ToReal(If(val, 1, 0))
2134  if __debug__:
2135  _z3_assert(False, "Z3 Integer/Real expression expected" )
2136  else:
2137  if self.is_int():
2138  return IntVal(val, self.ctx)
2139  if self.is_real():
2140  return RealVal(val, self.ctx)
2141  if __debug__:
2142  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2143 
2144 def is_arith_sort(s):
2145  """Return `True` if s is an arithmetical sort (type).
2146 
2147  >>> is_arith_sort(IntSort())
2148  True
2149  >>> is_arith_sort(RealSort())
2150  True
2151  >>> is_arith_sort(BoolSort())
2152  False
2153  >>> n = Int('x') + 1
2154  >>> is_arith_sort(n.sort())
2155  True
2156  """
2157  return isinstance(s, ArithSortRef)
2158 
2159 class ArithRef(ExprRef):
2160  """Integer and Real expressions."""
2161 
2162  def sort(self):
2163  """Return the sort (type) of the arithmetical expression `self`.
2164 
2165  >>> Int('x').sort()
2166  Int
2167  >>> (Real('x') + 1).sort()
2168  Real
2169  """
2170  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2171 
2172  def is_int(self):
2173  """Return `True` if `self` is an integer expression.
2174 
2175  >>> x = Int('x')
2176  >>> x.is_int()
2177  True
2178  >>> (x + 1).is_int()
2179  True
2180  >>> y = Real('y')
2181  >>> (x + y).is_int()
2182  False
2183  """
2184  return self.sort().is_int()
2185 
2186  def is_real(self):
2187  """Return `True` if `self` is an real expression.
2188 
2189  >>> x = Real('x')
2190  >>> x.is_real()
2191  True
2192  >>> (x + 1).is_real()
2193  True
2194  """
2195  return self.sort().is_real()
2196 
2197  def __add__(self, other):
2198  """Create the Z3 expression `self + other`.
2199 
2200  >>> x = Int('x')
2201  >>> y = Int('y')
2202  >>> x + y
2203  x + y
2204  >>> (x + y).sort()
2205  Int
2206  """
2207  a, b = _coerce_exprs(self, other)
2208  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2209 
2210  def __radd__(self, other):
2211  """Create the Z3 expression `other + self`.
2212 
2213  >>> x = Int('x')
2214  >>> 10 + x
2215  10 + x
2216  """
2217  a, b = _coerce_exprs(self, other)
2218  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2219 
2220  def __mul__(self, other):
2221  """Create the Z3 expression `self * other`.
2222 
2223  >>> x = Real('x')
2224  >>> y = Real('y')
2225  >>> x * y
2226  x*y
2227  >>> (x * y).sort()
2228  Real
2229  """
2230  if isinstance(other, BoolRef):
2231  return If(other, self, 0)
2232  a, b = _coerce_exprs(self, other)
2233  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2234 
2235  def __rmul__(self, other):
2236  """Create the Z3 expression `other * self`.
2237 
2238  >>> x = Real('x')
2239  >>> 10 * x
2240  10*x
2241  """
2242  a, b = _coerce_exprs(self, other)
2243  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2244 
2245  def __sub__(self, other):
2246  """Create the Z3 expression `self - other`.
2247 
2248  >>> x = Int('x')
2249  >>> y = Int('y')
2250  >>> x - y
2251  x - y
2252  >>> (x - y).sort()
2253  Int
2254  """
2255  a, b = _coerce_exprs(self, other)
2256  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2257 
2258  def __rsub__(self, other):
2259  """Create the Z3 expression `other - self`.
2260 
2261  >>> x = Int('x')
2262  >>> 10 - x
2263  10 - x
2264  """
2265  a, b = _coerce_exprs(self, other)
2266  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2267 
2268  def __pow__(self, other):
2269  """Create the Z3 expression `self**other` (** is the power operator).
2270 
2271  >>> x = Real('x')
2272  >>> x**3
2273  x**3
2274  >>> (x**3).sort()
2275  Real
2276  >>> simplify(IntVal(2)**8)
2277  256
2278  """
2279  a, b = _coerce_exprs(self, other)
2280  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2281 
2282  def __rpow__(self, other):
2283  """Create the Z3 expression `other**self` (** is the power operator).
2284 
2285  >>> x = Real('x')
2286  >>> 2**x
2287  2**x
2288  >>> (2**x).sort()
2289  Real
2290  >>> simplify(2**IntVal(8))
2291  256
2292  """
2293  a, b = _coerce_exprs(self, other)
2294  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2295 
2296  def __div__(self, other):
2297  """Create the Z3 expression `other/self`.
2298 
2299  >>> x = Int('x')
2300  >>> y = Int('y')
2301  >>> x/y
2302  x/y
2303  >>> (x/y).sort()
2304  Int
2305  >>> (x/y).sexpr()
2306  '(div x y)'
2307  >>> x = Real('x')
2308  >>> y = Real('y')
2309  >>> x/y
2310  x/y
2311  >>> (x/y).sort()
2312  Real
2313  >>> (x/y).sexpr()
2314  '(/ x y)'
2315  """
2316  a, b = _coerce_exprs(self, other)
2317  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2318 
2319  def __truediv__(self, other):
2320  """Create the Z3 expression `other/self`."""
2321  return self.__div__(other)
2322 
2323  def __rdiv__(self, other):
2324  """Create the Z3 expression `other/self`.
2325 
2326  >>> x = Int('x')
2327  >>> 10/x
2328  10/x
2329  >>> (10/x).sexpr()
2330  '(div 10 x)'
2331  >>> x = Real('x')
2332  >>> 10/x
2333  10/x
2334  >>> (10/x).sexpr()
2335  '(/ 10.0 x)'
2336  """
2337  a, b = _coerce_exprs(self, other)
2338  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2339 
2340  def __rtruediv__(self, other):
2341  """Create the Z3 expression `other/self`."""
2342  return self.__rdiv__(other)
2343 
2344  def __mod__(self, other):
2345  """Create the Z3 expression `other%self`.
2346 
2347  >>> x = Int('x')
2348  >>> y = Int('y')
2349  >>> x % y
2350  x%y
2351  >>> simplify(IntVal(10) % IntVal(3))
2352  1
2353  """
2354  a, b = _coerce_exprs(self, other)
2355  if __debug__:
2356  _z3_assert(a.is_int(), "Z3 integer expression expected")
2357  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2358 
2359  def __rmod__(self, other):
2360  """Create the Z3 expression `other%self`.
2361 
2362  >>> x = Int('x')
2363  >>> 10 % x
2364  10%x
2365  """
2366  a, b = _coerce_exprs(self, other)
2367  if __debug__:
2368  _z3_assert(a.is_int(), "Z3 integer expression expected")
2369  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2370 
2371  def __neg__(self):
2372  """Return an expression representing `-self`.
2373 
2374  >>> x = Int('x')
2375  >>> -x
2376  -x
2377  >>> simplify(-(-x))
2378  x
2379  """
2380  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2381 
2382  def __pos__(self):
2383  """Return `self`.
2384 
2385  >>> x = Int('x')
2386  >>> +x
2387  x
2388  """
2389  return self
2390 
2391  def __le__(self, other):
2392  """Create the Z3 expression `other <= self`.
2393 
2394  >>> x, y = Ints('x y')
2395  >>> x <= y
2396  x <= y
2397  >>> y = Real('y')
2398  >>> x <= y
2399  ToReal(x) <= y
2400  """
2401  a, b = _coerce_exprs(self, other)
2402  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2403 
2404  def __lt__(self, other):
2405  """Create the Z3 expression `other < self`.
2406 
2407  >>> x, y = Ints('x y')
2408  >>> x < y
2409  x < y
2410  >>> y = Real('y')
2411  >>> x < y
2412  ToReal(x) < y
2413  """
2414  a, b = _coerce_exprs(self, other)
2415  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2416 
2417  def __gt__(self, other):
2418  """Create the Z3 expression `other > self`.
2419 
2420  >>> x, y = Ints('x y')
2421  >>> x > y
2422  x > y
2423  >>> y = Real('y')
2424  >>> x > y
2425  ToReal(x) > y
2426  """
2427  a, b = _coerce_exprs(self, other)
2428  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2429 
2430  def __ge__(self, other):
2431  """Create the Z3 expression `other >= self`.
2432 
2433  >>> x, y = Ints('x y')
2434  >>> x >= y
2435  x >= y
2436  >>> y = Real('y')
2437  >>> x >= y
2438  ToReal(x) >= y
2439  """
2440  a, b = _coerce_exprs(self, other)
2441  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2442 
2443 def is_arith(a):
2444  """Return `True` if `a` is an arithmetical expression.
2445 
2446  >>> x = Int('x')
2447  >>> is_arith(x)
2448  True
2449  >>> is_arith(x + 1)
2450  True
2451  >>> is_arith(1)
2452  False
2453  >>> is_arith(IntVal(1))
2454  True
2455  >>> y = Real('y')
2456  >>> is_arith(y)
2457  True
2458  >>> is_arith(y + 1)
2459  True
2460  """
2461  return isinstance(a, ArithRef)
2462 
2463 def is_int(a):
2464  """Return `True` if `a` is an integer expression.
2465 
2466  >>> x = Int('x')
2467  >>> is_int(x + 1)
2468  True
2469  >>> is_int(1)
2470  False
2471  >>> is_int(IntVal(1))
2472  True
2473  >>> y = Real('y')
2474  >>> is_int(y)
2475  False
2476  >>> is_int(y + 1)
2477  False
2478  """
2479  return is_arith(a) and a.is_int()
2480 
2481 def is_real(a):
2482  """Return `True` if `a` is a real expression.
2483 
2484  >>> x = Int('x')
2485  >>> is_real(x + 1)
2486  False
2487  >>> y = Real('y')
2488  >>> is_real(y)
2489  True
2490  >>> is_real(y + 1)
2491  True
2492  >>> is_real(1)
2493  False
2494  >>> is_real(RealVal(1))
2495  True
2496  """
2497  return is_arith(a) and a.is_real()
2498 
2499 def _is_numeral(ctx, a):
2500  return Z3_is_numeral_ast(ctx.ref(), a)
2501 
2502 def _is_algebraic(ctx, a):
2503  return Z3_is_algebraic_number(ctx.ref(), a)
2504 
2505 def is_int_value(a):
2506  """Return `True` if `a` is an integer value of sort Int.
2507 
2508  >>> is_int_value(IntVal(1))
2509  True
2510  >>> is_int_value(1)
2511  False
2512  >>> is_int_value(Int('x'))
2513  False
2514  >>> n = Int('x') + 1
2515  >>> n
2516  x + 1
2517  >>> n.arg(1)
2518  1
2519  >>> is_int_value(n.arg(1))
2520  True
2521  >>> is_int_value(RealVal("1/3"))
2522  False
2523  >>> is_int_value(RealVal(1))
2524  False
2525  """
2526  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2527 
2528 def is_rational_value(a):
2529  """Return `True` if `a` is rational value of sort Real.
2530 
2531  >>> is_rational_value(RealVal(1))
2532  True
2533  >>> is_rational_value(RealVal("3/5"))
2534  True
2535  >>> is_rational_value(IntVal(1))
2536  False
2537  >>> is_rational_value(1)
2538  False
2539  >>> n = Real('x') + 1
2540  >>> n.arg(1)
2541  1
2542  >>> is_rational_value(n.arg(1))
2543  True
2544  >>> is_rational_value(Real('x'))
2545  False
2546  """
2547  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2548 
2549 def is_algebraic_value(a):
2550  """Return `True` if `a` is an algebraic value of sort Real.
2551 
2552  >>> is_algebraic_value(RealVal("3/5"))
2553  False
2554  >>> n = simplify(Sqrt(2))
2555  >>> n
2556  1.4142135623?
2557  >>> is_algebraic_value(n)
2558  True
2559  """
2560  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2561 
2562 def is_add(a):
2563  """Return `True` if `a` is an expression of the form b + c.
2564 
2565  >>> x, y = Ints('x y')
2566  >>> is_add(x + y)
2567  True
2568  >>> is_add(x - y)
2569  False
2570  """
2571  return is_app_of(a, Z3_OP_ADD)
2572 
2573 def is_mul(a):
2574  """Return `True` if `a` is an expression of the form b * c.
2575 
2576  >>> x, y = Ints('x y')
2577  >>> is_mul(x * y)
2578  True
2579  >>> is_mul(x - y)
2580  False
2581  """
2582  return is_app_of(a, Z3_OP_MUL)
2583 
2584 def is_sub(a):
2585  """Return `True` if `a` is an expression of the form b - c.
2586 
2587  >>> x, y = Ints('x y')
2588  >>> is_sub(x - y)
2589  True
2590  >>> is_sub(x + y)
2591  False
2592  """
2593  return is_app_of(a, Z3_OP_SUB)
2594 
2595 def is_div(a):
2596  """Return `True` if `a` is an expression of the form b / c.
2597 
2598  >>> x, y = Reals('x y')
2599  >>> is_div(x / y)
2600  True
2601  >>> is_div(x + y)
2602  False
2603  >>> x, y = Ints('x y')
2604  >>> is_div(x / y)
2605  False
2606  >>> is_idiv(x / y)
2607  True
2608  """
2609  return is_app_of(a, Z3_OP_DIV)
2610 
2611 def is_idiv(a):
2612  """Return `True` if `a` is an expression of the form b div c.
2613 
2614  >>> x, y = Ints('x y')
2615  >>> is_idiv(x / y)
2616  True
2617  >>> is_idiv(x + y)
2618  False
2619  """
2620  return is_app_of(a, Z3_OP_IDIV)
2621 
2622 def is_mod(a):
2623  """Return `True` if `a` is an expression of the form b % c.
2624 
2625  >>> x, y = Ints('x y')
2626  >>> is_mod(x % y)
2627  True
2628  >>> is_mod(x + y)
2629  False
2630  """
2631  return is_app_of(a, Z3_OP_MOD)
2632 
2633 def is_le(a):
2634  """Return `True` if `a` is an expression of the form b <= c.
2635 
2636  >>> x, y = Ints('x y')
2637  >>> is_le(x <= y)
2638  True
2639  >>> is_le(x < y)
2640  False
2641  """
2642  return is_app_of(a, Z3_OP_LE)
2643 
2644 def is_lt(a):
2645  """Return `True` if `a` is an expression of the form b < c.
2646 
2647  >>> x, y = Ints('x y')
2648  >>> is_lt(x < y)
2649  True
2650  >>> is_lt(x == y)
2651  False
2652  """
2653  return is_app_of(a, Z3_OP_LT)
2654 
2655 def is_ge(a):
2656  """Return `True` if `a` is an expression of the form b >= c.
2657 
2658  >>> x, y = Ints('x y')
2659  >>> is_ge(x >= y)
2660  True
2661  >>> is_ge(x == y)
2662  False
2663  """
2664  return is_app_of(a, Z3_OP_GE)
2665 
2666 def is_gt(a):
2667  """Return `True` if `a` is an expression of the form b > c.
2668 
2669  >>> x, y = Ints('x y')
2670  >>> is_gt(x > y)
2671  True
2672  >>> is_gt(x == y)
2673  False
2674  """
2675  return is_app_of(a, Z3_OP_GT)
2676 
2677 def is_is_int(a):
2678  """Return `True` if `a` is an expression of the form IsInt(b).
2679 
2680  >>> x = Real('x')
2681  >>> is_is_int(IsInt(x))
2682  True
2683  >>> is_is_int(x)
2684  False
2685  """
2686  return is_app_of(a, Z3_OP_IS_INT)
2687 
2688 def is_to_real(a):
2689  """Return `True` if `a` is an expression of the form ToReal(b).
2690 
2691  >>> x = Int('x')
2692  >>> n = ToReal(x)
2693  >>> n
2694  ToReal(x)
2695  >>> is_to_real(n)
2696  True
2697  >>> is_to_real(x)
2698  False
2699  """
2700  return is_app_of(a, Z3_OP_TO_REAL)
2701 
2702 def is_to_int(a):
2703  """Return `True` if `a` is an expression of the form ToInt(b).
2704 
2705  >>> x = Real('x')
2706  >>> n = ToInt(x)
2707  >>> n
2708  ToInt(x)
2709  >>> is_to_int(n)
2710  True
2711  >>> is_to_int(x)
2712  False
2713  """
2714  return is_app_of(a, Z3_OP_TO_INT)
2715 
2716 class IntNumRef(ArithRef):
2717  """Integer values."""
2718 
2719  def as_long(self):
2720  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2721 
2722  >>> v = IntVal(1)
2723  >>> v + 1
2724  1 + 1
2725  >>> v.as_long() + 1
2726  2
2727  """
2728  if __debug__:
2729  _z3_assert(self.is_int(), "Integer value expected")
2730  return int(self.as_string())
2731 
2732  def as_string(self):
2733  """Return a Z3 integer numeral as a Python string.
2734  >>> v = IntVal(100)
2735  >>> v.as_string()
2736  '100'
2737  """
2738  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2739 
2740 class RatNumRef(ArithRef):
2741  """Rational values."""
2742 
2743  def numerator(self):
2744  """ Return the numerator of a Z3 rational numeral.
2745 
2746  >>> is_rational_value(RealVal("3/5"))
2747  True
2748  >>> n = RealVal("3/5")
2749  >>> n.numerator()
2750  3
2751  >>> is_rational_value(Q(3,5))
2752  True
2753  >>> Q(3,5).numerator()
2754  3
2755  """
2756  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2757 
2758  def denominator(self):
2759  """ Return the denominator of a Z3 rational numeral.
2760 
2761  >>> is_rational_value(Q(3,5))
2762  True
2763  >>> n = Q(3,5)
2764  >>> n.denominator()
2765  5
2766  """
2767  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2768 
2769  def numerator_as_long(self):
2770  """ Return the numerator as a Python long.
2771 
2772  >>> v = RealVal(10000000000)
2773  >>> v
2774  10000000000
2775  >>> v + 1
2776  10000000000 + 1
2777  >>> v.numerator_as_long() + 1 == 10000000001
2778  True
2779  """
2780  return self.numerator().as_long()
2781 
2782  def denominator_as_long(self):
2783  """ Return the denominator as a Python long.
2784 
2785  >>> v = RealVal("1/3")
2786  >>> v
2787  1/3
2788  >>> v.denominator_as_long()
2789  3
2790  """
2791  return self.denominator().as_long()
2792 
2793  def is_int(self):
2794  return False
2795 
2796  def is_real(self):
2797  return True
2798 
2799  def is_int_value(self):
2800  return self.denominator().is_int() and self.denominator_as_long() == 1
2801 
2802  def as_long(self):
2803  _z3_assert(self.is_int(), "Expected integer fraction")
2804  return self.numerator_as_long()
2805 
2806  def as_decimal(self, prec):
2807  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2808 
2809  >>> v = RealVal("1/5")
2810  >>> v.as_decimal(3)
2811  '0.2'
2812  >>> v = RealVal("1/3")
2813  >>> v.as_decimal(3)
2814  '0.333?'
2815  """
2816  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2817 
2818  def as_string(self):
2819  """Return a Z3 rational numeral as a Python string.
2820 
2821  >>> v = Q(3,6)
2822  >>> v.as_string()
2823  '1/2'
2824  """
2825  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2826 
2827  def as_fraction(self):
2828  """Return a Z3 rational as a Python Fraction object.
2829 
2830  >>> v = RealVal("1/5")
2831  >>> v.as_fraction()
2832  Fraction(1, 5)
2833  """
2834  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2835 
2836 class AlgebraicNumRef(ArithRef):
2837  """Algebraic irrational values."""
2838 
2839  def approx(self, precision=10):
2840  """Return a Z3 rational number that approximates the algebraic number `self`.
2841  The result `r` is such that |r - self| <= 1/10^precision
2842 
2843  >>> x = simplify(Sqrt(2))
2844  >>> x.approx(20)
2845  6838717160008073720548335/4835703278458516698824704
2846  >>> x.approx(5)
2847  2965821/2097152
2848  """
2849  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2850  def as_decimal(self, prec):
2851  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2852 
2853  >>> x = simplify(Sqrt(2))
2854  >>> x.as_decimal(10)
2855  '1.4142135623?'
2856  >>> x.as_decimal(20)
2857  '1.41421356237309504880?'
2858  """
2859  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2860 
2861 def _py2expr(a, ctx=None):
2862  if isinstance(a, bool):
2863  return BoolVal(a, ctx)
2864  if _is_int(a):
2865  return IntVal(a, ctx)
2866  if isinstance(a, float):
2867  return RealVal(a, ctx)
2868  if is_expr(a):
2869  return a
2870  if __debug__:
2871  _z3_assert(False, "Python bool, int, long or float expected")
2872 
2873 def IntSort(ctx=None):
2874  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2875 
2876  >>> IntSort()
2877  Int
2878  >>> x = Const('x', IntSort())
2879  >>> is_int(x)
2880  True
2881  >>> x.sort() == IntSort()
2882  True
2883  >>> x.sort() == BoolSort()
2884  False
2885  """
2886  ctx = _get_ctx(ctx)
2887  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2888 
2889 def RealSort(ctx=None):
2890  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2891 
2892  >>> RealSort()
2893  Real
2894  >>> x = Const('x', RealSort())
2895  >>> is_real(x)
2896  True
2897  >>> is_int(x)
2898  False
2899  >>> x.sort() == RealSort()
2900  True
2901  """
2902  ctx = _get_ctx(ctx)
2903  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2904 
2905 def _to_int_str(val):
2906  if isinstance(val, float):
2907  return str(int(val))
2908  elif isinstance(val, bool):
2909  if val:
2910  return "1"
2911  else:
2912  return "0"
2913  elif _is_int(val):
2914  return str(val)
2915  elif isinstance(val, str):
2916  return val
2917  if __debug__:
2918  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2919 
2920 def IntVal(val, ctx=None):
2921  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2922 
2923  >>> IntVal(1)
2924  1
2925  >>> IntVal("100")
2926  100
2927  """
2928  ctx = _get_ctx(ctx)
2929  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2930 
2931 def RealVal(val, ctx=None):
2932  """Return a Z3 real value.
2933 
2934  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2935  If `ctx=None`, then the global context is used.
2936 
2937  >>> RealVal(1)
2938  1
2939  >>> RealVal(1).sort()
2940  Real
2941  >>> RealVal("3/5")
2942  3/5
2943  >>> RealVal("1.5")
2944  3/2
2945  """
2946  ctx = _get_ctx(ctx)
2947  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2948 
2949 def RatVal(a, b, ctx=None):
2950  """Return a Z3 rational a/b.
2951 
2952  If `ctx=None`, then the global context is used.
2953 
2954  >>> RatVal(3,5)
2955  3/5
2956  >>> RatVal(3,5).sort()
2957  Real
2958  """
2959  if __debug__:
2960  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2961  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2962  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2963 
2964 def Q(a, b, ctx=None):
2965  """Return a Z3 rational a/b.
2966 
2967  If `ctx=None`, then the global context is used.
2968 
2969  >>> Q(3,5)
2970  3/5
2971  >>> Q(3,5).sort()
2972  Real
2973  """
2974  return simplify(RatVal(a, b))
2975 
2976 def Int(name, ctx=None):
2977  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2978 
2979  >>> x = Int('x')
2980  >>> is_int(x)
2981  True
2982  >>> is_int(x + 1)
2983  True
2984  """
2985  ctx = _get_ctx(ctx)
2986  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2987 
2988 def Ints(names, ctx=None):
2989  """Return a tuple of Integer constants.
2990 
2991  >>> x, y, z = Ints('x y z')
2992  >>> Sum(x, y, z)
2993  x + y + z
2994  """
2995  ctx = _get_ctx(ctx)
2996  if isinstance(names, str):
2997  names = names.split(" ")
2998  return [Int(name, ctx) for name in names]
2999 
3000 def IntVector(prefix, sz, ctx=None):
3001  """Return a list of integer constants of size `sz`.
3002 
3003  >>> X = IntVector('x', 3)
3004  >>> X
3005  [x__0, x__1, x__2]
3006  >>> Sum(X)
3007  x__0 + x__1 + x__2
3008  """
3009  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
3010 
3011 def FreshInt(prefix='x', ctx=None):
3012  """Return a fresh integer constant in the given context using the given prefix.
3013 
3014  >>> x = FreshInt()
3015  >>> y = FreshInt()
3016  >>> eq(x, y)
3017  False
3018  >>> x.sort()
3019  Int
3020  """
3021  ctx = _get_ctx(ctx)
3022  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3023 
3024 def Real(name, ctx=None):
3025  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3026 
3027  >>> x = Real('x')
3028  >>> is_real(x)
3029  True
3030  >>> is_real(x + 1)
3031  True
3032  """
3033  ctx = _get_ctx(ctx)
3034  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3035 
3036 def Reals(names, ctx=None):
3037  """Return a tuple of real constants.
3038 
3039  >>> x, y, z = Reals('x y z')
3040  >>> Sum(x, y, z)
3041  x + y + z
3042  >>> Sum(x, y, z).sort()
3043  Real
3044  """
3045  ctx = _get_ctx(ctx)
3046  if isinstance(names, str):
3047  names = names.split(" ")
3048  return [Real(name, ctx) for name in names]
3049 
3050 def RealVector(prefix, sz, ctx=None):
3051  """Return a list of real constants of size `sz`.
3052 
3053  >>> X = RealVector('x', 3)
3054  >>> X
3055  [x__0, x__1, x__2]
3056  >>> Sum(X)
3057  x__0 + x__1 + x__2
3058  >>> Sum(X).sort()
3059  Real
3060  """
3061  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
3062 
3063 def FreshReal(prefix='b', ctx=None):
3064  """Return a fresh real constant in the given context using the given prefix.
3065 
3066  >>> x = FreshReal()
3067  >>> y = FreshReal()
3068  >>> eq(x, y)
3069  False
3070  >>> x.sort()
3071  Real
3072  """
3073  ctx = _get_ctx(ctx)
3074  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3075 
3076 def ToReal(a):
3077  """ Return the Z3 expression ToReal(a).
3078 
3079  >>> x = Int('x')
3080  >>> x.sort()
3081  Int
3082  >>> n = ToReal(x)
3083  >>> n
3084  ToReal(x)
3085  >>> n.sort()
3086  Real
3087  """
3088  if __debug__:
3089  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3090  ctx = a.ctx
3091  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3092 
3093 def ToInt(a):
3094  """ Return the Z3 expression ToInt(a).
3095 
3096  >>> x = Real('x')
3097  >>> x.sort()
3098  Real
3099  >>> n = ToInt(x)
3100  >>> n
3101  ToInt(x)
3102  >>> n.sort()
3103  Int
3104  """
3105  if __debug__:
3106  _z3_assert(a.is_real(), "Z3 real expression expected.")
3107  ctx = a.ctx
3108  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3109 
3110 def IsInt(a):
3111  """ Return the Z3 predicate IsInt(a).
3112 
3113  >>> x = Real('x')
3114  >>> IsInt(x + "1/2")
3115  IsInt(x + 1/2)
3116  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3117  [x = 1/2]
3118  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3119  no solution
3120  """
3121  if __debug__:
3122  _z3_assert(a.is_real(), "Z3 real expression expected.")
3123  ctx = a.ctx
3124  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3125 
3126 def Sqrt(a, ctx=None):
3127  """ Return a Z3 expression which represents the square root of a.
3128 
3129  >>> x = Real('x')
3130  >>> Sqrt(x)
3131  x**(1/2)
3132  """
3133  if not is_expr(a):
3134  ctx = _get_ctx(ctx)
3135  a = RealVal(a, ctx)
3136  return a ** "1/2"
3137 
3138 def Cbrt(a, ctx=None):
3139  """ Return a Z3 expression which represents the cubic root of a.
3140 
3141  >>> x = Real('x')
3142  >>> Cbrt(x)
3143  x**(1/3)
3144  """
3145  if not is_expr(a):
3146  ctx = _get_ctx(ctx)
3147  a = RealVal(a, ctx)
3148  return a ** "1/3"
3149 
3150 #########################################
3151 #
3152 # Bit-Vectors
3153 #
3154 #########################################
3155 
3156 class BitVecSortRef(SortRef):
3157  """Bit-vector sort."""
3158 
3159  def size(self):
3160  """Return the size (number of bits) of the bit-vector sort `self`.
3161 
3162  >>> b = BitVecSort(32)
3163  >>> b.size()
3164  32
3165  """
3166  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3167 
3168  def subsort(self, other):
3169  return is_bv_sort(other) and self.size() < other.size()
3170 
3171  def cast(self, val):
3172  """Try to cast `val` as a Bit-Vector.
3173 
3174  >>> b = BitVecSort(32)
3175  >>> b.cast(10)
3176  10
3177  >>> b.cast(10).sexpr()
3178  '#x0000000a'
3179  """
3180  if is_expr(val):
3181  if __debug__:
3182  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3183  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3184  return val
3185  else:
3186  return BitVecVal(val, self)
3187 
3188 def is_bv_sort(s):
3189  """Return True if `s` is a Z3 bit-vector sort.
3190 
3191  >>> is_bv_sort(BitVecSort(32))
3192  True
3193  >>> is_bv_sort(IntSort())
3194  False
3195  """
3196  return isinstance(s, BitVecSortRef)
3197 
3198 class BitVecRef(ExprRef):
3199  """Bit-vector expressions."""
3200 
3201  def sort(self):
3202  """Return the sort of the bit-vector expression `self`.
3203 
3204  >>> x = BitVec('x', 32)
3205  >>> x.sort()
3206  BitVec(32)
3207  >>> x.sort() == BitVecSort(32)
3208  True
3209  """
3210  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3211 
3212  def size(self):
3213  """Return the number of bits of the bit-vector expression `self`.
3214 
3215  >>> x = BitVec('x', 32)
3216  >>> (x + 1).size()
3217  32
3218  >>> Concat(x, x).size()
3219  64
3220  """
3221  return self.sort().size()
3222 
3223  def __add__(self, other):
3224  """Create the Z3 expression `self + other`.
3225 
3226  >>> x = BitVec('x', 32)
3227  >>> y = BitVec('y', 32)
3228  >>> x + y
3229  x + y
3230  >>> (x + y).sort()
3231  BitVec(32)
3232  """
3233  a, b = _coerce_exprs(self, other)
3234  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3235 
3236  def __radd__(self, other):
3237  """Create the Z3 expression `other + self`.
3238 
3239  >>> x = BitVec('x', 32)
3240  >>> 10 + x
3241  10 + x
3242  """
3243  a, b = _coerce_exprs(self, other)
3244  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3245 
3246  def __mul__(self, other):
3247  """Create the Z3 expression `self * other`.
3248 
3249  >>> x = BitVec('x', 32)
3250  >>> y = BitVec('y', 32)
3251  >>> x * y
3252  x*y
3253  >>> (x * y).sort()
3254  BitVec(32)
3255  """
3256  a, b = _coerce_exprs(self, other)
3257  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3258 
3259  def __rmul__(self, other):
3260  """Create the Z3 expression `other * self`.
3261 
3262  >>> x = BitVec('x', 32)
3263  >>> 10 * x
3264  10*x
3265  """
3266  a, b = _coerce_exprs(self, other)
3267  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3268 
3269  def __sub__(self, other):
3270  """Create the Z3 expression `self - other`.
3271 
3272  >>> x = BitVec('x', 32)
3273  >>> y = BitVec('y', 32)
3274  >>> x - y
3275  x - y
3276  >>> (x - y).sort()
3277  BitVec(32)
3278  """
3279  a, b = _coerce_exprs(self, other)
3280  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3281 
3282  def __rsub__(self, other):
3283  """Create the Z3 expression `other - self`.
3284 
3285  >>> x = BitVec('x', 32)
3286  >>> 10 - x
3287  10 - x
3288  """
3289  a, b = _coerce_exprs(self, other)
3290  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3291 
3292  def __or__(self, other):
3293  """Create the Z3 expression bitwise-or `self | other`.
3294 
3295  >>> x = BitVec('x', 32)
3296  >>> y = BitVec('y', 32)
3297  >>> x | y
3298  x | y
3299  >>> (x | y).sort()
3300  BitVec(32)
3301  """
3302  a, b = _coerce_exprs(self, other)
3303  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3304 
3305  def __ror__(self, other):
3306  """Create the Z3 expression bitwise-or `other | self`.
3307 
3308  >>> x = BitVec('x', 32)
3309  >>> 10 | x
3310  10 | x
3311  """
3312  a, b = _coerce_exprs(self, other)
3313  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3314 
3315  def __and__(self, other):
3316  """Create the Z3 expression bitwise-and `self & other`.
3317 
3318  >>> x = BitVec('x', 32)
3319  >>> y = BitVec('y', 32)
3320  >>> x & y
3321  x & y
3322  >>> (x & y).sort()
3323  BitVec(32)
3324  """
3325  a, b = _coerce_exprs(self, other)
3326  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3327 
3328  def __rand__(self, other):
3329  """Create the Z3 expression bitwise-or `other & self`.
3330 
3331  >>> x = BitVec('x', 32)
3332  >>> 10 & x
3333  10 & x
3334  """
3335  a, b = _coerce_exprs(self, other)
3336  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3337 
3338  def __xor__(self, other):
3339  """Create the Z3 expression bitwise-xor `self ^ other`.
3340 
3341  >>> x = BitVec('x', 32)
3342  >>> y = BitVec('y', 32)
3343  >>> x ^ y
3344  x ^ y
3345  >>> (x ^ y).sort()
3346  BitVec(32)
3347  """
3348  a, b = _coerce_exprs(self, other)
3349  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3350 
3351  def __rxor__(self, other):
3352  """Create the Z3 expression bitwise-xor `other ^ self`.
3353 
3354  >>> x = BitVec('x', 32)
3355  >>> 10 ^ x
3356  10 ^ x
3357  """
3358  a, b = _coerce_exprs(self, other)
3359  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3360 
3361  def __pos__(self):
3362  """Return `self`.
3363 
3364  >>> x = BitVec('x', 32)
3365  >>> +x
3366  x
3367  """
3368  return self
3369 
3370  def __neg__(self):
3371  """Return an expression representing `-self`.
3372 
3373  >>> x = BitVec('x', 32)
3374  >>> -x
3375  -x
3376  >>> simplify(-(-x))
3377  x
3378  """
3379  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3380 
3381  def __invert__(self):
3382  """Create the Z3 expression bitwise-not `~self`.
3383 
3384  >>> x = BitVec('x', 32)
3385  >>> ~x
3386  ~x
3387  >>> simplify(~(~x))
3388  x
3389  """
3390  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3391 
3392  def __div__(self, other):
3393  """Create the Z3 expression (signed) division `self / other`.
3394 
3395  Use the function UDiv() for unsigned division.
3396 
3397  >>> x = BitVec('x', 32)
3398  >>> y = BitVec('y', 32)
3399  >>> x / y
3400  x/y
3401  >>> (x / y).sort()
3402  BitVec(32)
3403  >>> (x / y).sexpr()
3404  '(bvsdiv x y)'
3405  >>> UDiv(x, y).sexpr()
3406  '(bvudiv x y)'
3407  """
3408  a, b = _coerce_exprs(self, other)
3409  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3410 
3411  def __truediv__(self, other):
3412  """Create the Z3 expression (signed) division `self / other`."""
3413  return self.__div__(other)
3414 
3415  def __rdiv__(self, other):
3416  """Create the Z3 expression (signed) division `other / self`.
3417 
3418  Use the function UDiv() for unsigned division.
3419 
3420  >>> x = BitVec('x', 32)
3421  >>> 10 / x
3422  10/x
3423  >>> (10 / x).sexpr()
3424  '(bvsdiv #x0000000a x)'
3425  >>> UDiv(10, x).sexpr()
3426  '(bvudiv #x0000000a x)'
3427  """
3428  a, b = _coerce_exprs(self, other)
3429  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3430 
3431  def __rtruediv__(self, other):
3432  """Create the Z3 expression (signed) division `other / self`."""
3433  return self.__rdiv__(other)
3434 
3435  def __mod__(self, other):
3436  """Create the Z3 expression (signed) mod `self % other`.
3437 
3438  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3439 
3440  >>> x = BitVec('x', 32)
3441  >>> y = BitVec('y', 32)
3442  >>> x % y
3443  x%y
3444  >>> (x % y).sort()
3445  BitVec(32)
3446  >>> (x % y).sexpr()
3447  '(bvsmod x y)'
3448  >>> URem(x, y).sexpr()
3449  '(bvurem x y)'
3450  >>> SRem(x, y).sexpr()
3451  '(bvsrem x y)'
3452  """
3453  a, b = _coerce_exprs(self, other)
3454  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3455 
3456  def __rmod__(self, other):
3457  """Create the Z3 expression (signed) mod `other % self`.
3458 
3459  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3460 
3461  >>> x = BitVec('x', 32)
3462  >>> 10 % x
3463  10%x
3464  >>> (10 % x).sexpr()
3465  '(bvsmod #x0000000a x)'
3466  >>> URem(10, x).sexpr()
3467  '(bvurem #x0000000a x)'
3468  >>> SRem(10, x).sexpr()
3469  '(bvsrem #x0000000a x)'
3470  """
3471  a, b = _coerce_exprs(self, other)
3472  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3473 
3474  def __le__(self, other):
3475  """Create the Z3 expression (signed) `other <= self`.
3476 
3477  Use the function ULE() for unsigned less than or equal to.
3478 
3479  >>> x, y = BitVecs('x y', 32)
3480  >>> x <= y
3481  x <= y
3482  >>> (x <= y).sexpr()
3483  '(bvsle x y)'
3484  >>> ULE(x, y).sexpr()
3485  '(bvule x y)'
3486  """
3487  a, b = _coerce_exprs(self, other)
3488  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3489 
3490  def __lt__(self, other):
3491  """Create the Z3 expression (signed) `other < self`.
3492 
3493  Use the function ULT() for unsigned less than.
3494 
3495  >>> x, y = BitVecs('x y', 32)
3496  >>> x < y
3497  x < y
3498  >>> (x < y).sexpr()
3499  '(bvslt x y)'
3500  >>> ULT(x, y).sexpr()
3501  '(bvult x y)'
3502  """
3503  a, b = _coerce_exprs(self, other)
3504  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3505 
3506  def __gt__(self, other):
3507  """Create the Z3 expression (signed) `other > self`.
3508 
3509  Use the function UGT() for unsigned greater than.
3510 
3511  >>> x, y = BitVecs('x y', 32)
3512  >>> x > y
3513  x > y
3514  >>> (x > y).sexpr()
3515  '(bvsgt x y)'
3516  >>> UGT(x, y).sexpr()
3517  '(bvugt x y)'
3518  """
3519  a, b = _coerce_exprs(self, other)
3520  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3521 
3522  def __ge__(self, other):
3523  """Create the Z3 expression (signed) `other >= self`.
3524 
3525  Use the function UGE() for unsigned greater than or equal to.
3526 
3527  >>> x, y = BitVecs('x y', 32)
3528  >>> x >= y
3529  x >= y
3530  >>> (x >= y).sexpr()
3531  '(bvsge x y)'
3532  >>> UGE(x, y).sexpr()
3533  '(bvuge x y)'
3534  """
3535  a, b = _coerce_exprs(self, other)
3536  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3537 
3538  def __rshift__(self, other):
3539  """Create the Z3 expression (arithmetical) right shift `self >> other`
3540 
3541  Use the function LShR() for the right logical shift
3542 
3543  >>> x, y = BitVecs('x y', 32)
3544  >>> x >> y
3545  x >> y
3546  >>> (x >> y).sexpr()
3547  '(bvashr x y)'
3548  >>> LShR(x, y).sexpr()
3549  '(bvlshr x y)'
3550  >>> BitVecVal(4, 3)
3551  4
3552  >>> BitVecVal(4, 3).as_signed_long()
3553  -4
3554  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3555  -2
3556  >>> simplify(BitVecVal(4, 3) >> 1)
3557  6
3558  >>> simplify(LShR(BitVecVal(4, 3), 1))
3559  2
3560  >>> simplify(BitVecVal(2, 3) >> 1)
3561  1
3562  >>> simplify(LShR(BitVecVal(2, 3), 1))
3563  1
3564  """
3565  a, b = _coerce_exprs(self, other)
3566  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3567 
3568  def __lshift__(self, other):
3569  """Create the Z3 expression left shift `self << other`
3570 
3571  >>> x, y = BitVecs('x y', 32)
3572  >>> x << y
3573  x << y
3574  >>> (x << y).sexpr()
3575  '(bvshl x y)'
3576  >>> simplify(BitVecVal(2, 3) << 1)
3577  4
3578  """
3579  a, b = _coerce_exprs(self, other)
3580  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3581 
3582  def __rrshift__(self, other):
3583  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3584 
3585  Use the function LShR() for the right logical shift
3586 
3587  >>> x = BitVec('x', 32)
3588  >>> 10 >> x
3589  10 >> x
3590  >>> (10 >> x).sexpr()
3591  '(bvashr #x0000000a x)'
3592  """
3593  a, b = _coerce_exprs(self, other)
3594  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3595 
3596  def __rlshift__(self, other):
3597  """Create the Z3 expression left shift `other << self`.
3598 
3599  Use the function LShR() for the right logical shift
3600 
3601  >>> x = BitVec('x', 32)
3602  >>> 10 << x
3603  10 << x
3604  >>> (10 << x).sexpr()
3605  '(bvshl #x0000000a x)'
3606  """
3607  a, b = _coerce_exprs(self, other)
3608  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3609 
3610 class BitVecNumRef(BitVecRef):
3611  """Bit-vector values."""
3612 
3613  def as_long(self):
3614  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3615 
3616  >>> v = BitVecVal(0xbadc0de, 32)
3617  >>> v
3618  195936478
3619  >>> print("0x%.8x" % v.as_long())
3620  0x0badc0de
3621  """
3622  return int(self.as_string())
3623 
3624  def as_signed_long(self):
3625  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3626 
3627  >>> BitVecVal(4, 3).as_signed_long()
3628  -4
3629  >>> BitVecVal(7, 3).as_signed_long()
3630  -1
3631  >>> BitVecVal(3, 3).as_signed_long()
3632  3
3633  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3634  -1
3635  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3636  -1
3637  """
3638  sz = self.size()
3639  val = self.as_long()
3640  if val >= 2**(sz - 1):
3641  val = val - 2**sz
3642  if val < -2**(sz - 1):
3643  val = val + 2**sz
3644  return int(val)
3645 
3646  def as_string(self):
3647  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3648 
3649 def is_bv(a):
3650  """Return `True` if `a` is a Z3 bit-vector expression.
3651 
3652  >>> b = BitVec('b', 32)
3653  >>> is_bv(b)
3654  True
3655  >>> is_bv(b + 10)
3656  True
3657  >>> is_bv(Int('x'))
3658  False
3659  """
3660  return isinstance(a, BitVecRef)
3661 
3662 def is_bv_value(a):
3663  """Return `True` if `a` is a Z3 bit-vector numeral value.
3664 
3665  >>> b = BitVec('b', 32)
3666  >>> is_bv_value(b)
3667  False
3668  >>> b = BitVecVal(10, 32)
3669  >>> b
3670  10
3671  >>> is_bv_value(b)
3672  True
3673  """
3674  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3675 
3676 def BV2Int(a, is_signed=False):
3677  """Return the Z3 expression BV2Int(a).
3678 
3679  >>> b = BitVec('b', 3)
3680  >>> BV2Int(b).sort()
3681  Int
3682  >>> x = Int('x')
3683  >>> x > BV2Int(b)
3684  x > BV2Int(b)
3685  >>> x > BV2Int(b, is_signed=False)
3686  x > BV2Int(b)
3687  >>> x > BV2Int(b, is_signed=True)
3688  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3689  >>> solve(x > BV2Int(b), b == 1, x < 3)
3690  [b = 1, x = 2]
3691  """
3692  if __debug__:
3693  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3694  ctx = a.ctx
3695  ## investigate problem with bv2int
3696  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3697 
3698 def Int2BV(a, num_bits):
3699  """Return the z3 expression Int2BV(a, num_bits).
3700  It is a bit-vector of width num_bits and represents the
3701  modulo of a by 2^num_bits
3702  """
3703  ctx = a.ctx
3704  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3705 
3706 def BitVecSort(sz, ctx=None):
3707  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3708 
3709  >>> Byte = BitVecSort(8)
3710  >>> Word = BitVecSort(16)
3711  >>> Byte
3712  BitVec(8)
3713  >>> x = Const('x', Byte)
3714  >>> eq(x, BitVec('x', 8))
3715  True
3716  """
3717  ctx = _get_ctx(ctx)
3718  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3719 
3720 def BitVecVal(val, bv, ctx=None):
3721  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3722 
3723  >>> v = BitVecVal(10, 32)
3724  >>> v
3725  10
3726  >>> print("0x%.8x" % v.as_long())
3727  0x0000000a
3728  """
3729  if is_bv_sort(bv):
3730  ctx = bv.ctx
3731  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3732  else:
3733  ctx = _get_ctx(ctx)
3734  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3735 
3736 def BitVec(name, bv, ctx=None):
3737  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3738  If `ctx=None`, then the global context is used.
3739 
3740  >>> x = BitVec('x', 16)
3741  >>> is_bv(x)
3742  True
3743  >>> x.size()
3744  16
3745  >>> x.sort()
3746  BitVec(16)
3747  >>> word = BitVecSort(16)
3748  >>> x2 = BitVec('x', word)
3749  >>> eq(x, x2)
3750  True
3751  """
3752  if isinstance(bv, BitVecSortRef):
3753  ctx = bv.ctx
3754  else:
3755  ctx = _get_ctx(ctx)
3756  bv = BitVecSort(bv, ctx)
3757  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3758 
3759 def BitVecs(names, bv, ctx=None):
3760  """Return a tuple of bit-vector constants of size bv.
3761 
3762  >>> x, y, z = BitVecs('x y z', 16)
3763  >>> x.size()
3764  16
3765  >>> x.sort()
3766  BitVec(16)
3767  >>> Sum(x, y, z)
3768  0 + x + y + z
3769  >>> Product(x, y, z)
3770  1*x*y*z
3771  >>> simplify(Product(x, y, z))
3772  x*y*z
3773  """
3774  ctx = _get_ctx(ctx)
3775  if isinstance(names, str):
3776  names = names.split(" ")
3777  return [BitVec(name, bv, ctx) for name in names]
3778 
3779 def Concat(*args):
3780  """Create a Z3 bit-vector concatenation expression.
3781 
3782  >>> v = BitVecVal(1, 4)
3783  >>> Concat(v, v+1, v)
3784  Concat(Concat(1, 1 + 1), 1)
3785  >>> simplify(Concat(v, v+1, v))
3786  289
3787  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3788  121
3789  """
3790  args = _get_args(args)
3791  sz = len(args)
3792  if __debug__:
3793  _z3_assert(sz >= 2, "At least two arguments expected.")
3794 
3795  ctx = None
3796  for a in args:
3797  if is_expr(a):
3798  ctx = a.ctx
3799  break
3800  if is_seq(args[0]) or isinstance(args[0], str):
3801  args = [_coerce_seq(s, ctx) for s in args]
3802  if __debug__:
3803  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3804  v = (Ast * sz)()
3805  for i in range(sz):
3806  v[i] = args[i].as_ast()
3807  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3808 
3809  if is_re(args[0]):
3810  if __debug__:
3811  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3812  v = (Ast * sz)()
3813  for i in range(sz):
3814  v[i] = args[i].as_ast()
3815  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3816 
3817  if __debug__:
3818  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3819  r = args[0]
3820  for i in range(sz - 1):
3821  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3822  return r
3823 
3824 def Extract(high, low, a):
3825  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3826 
3827  >>> x = BitVec('x', 8)
3828  >>> Extract(6, 2, x)
3829  Extract(6, 2, x)
3830  >>> Extract(6, 2, x).sort()
3831  BitVec(5)
3832  >>> simplify(Extract(StringVal("abcd"),2,1))
3833  "c"
3834  """
3835  if isinstance(high, str):
3836  high = StringVal(high)
3837  if is_seq(high):
3838  s = high
3839  offset, length = _coerce_exprs(low, a, s.ctx)
3840  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3841  if __debug__:
3842  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3843  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3844  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3845  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3846 
3847 def _check_bv_args(a, b):
3848  if __debug__:
3849  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3850 
3851 def ULE(a, b):
3852  """Create the Z3 expression (unsigned) `other <= self`.
3853 
3854  Use the operator <= for signed less than or equal to.
3855 
3856  >>> x, y = BitVecs('x y', 32)
3857  >>> ULE(x, y)
3858  ULE(x, y)
3859  >>> (x <= y).sexpr()
3860  '(bvsle x y)'
3861  >>> ULE(x, y).sexpr()
3862  '(bvule x y)'
3863  """
3864  _check_bv_args(a, b)
3865  a, b = _coerce_exprs(a, b)
3866  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3867 
3868 def ULT(a, b):
3869  """Create the Z3 expression (unsigned) `other < self`.
3870 
3871  Use the operator < for signed less than.
3872 
3873  >>> x, y = BitVecs('x y', 32)
3874  >>> ULT(x, y)
3875  ULT(x, y)
3876  >>> (x < y).sexpr()
3877  '(bvslt x y)'
3878  >>> ULT(x, y).sexpr()
3879  '(bvult x y)'
3880  """
3881  _check_bv_args(a, b)
3882  a, b = _coerce_exprs(a, b)
3883  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3884 
3885 def UGE(a, b):
3886  """Create the Z3 expression (unsigned) `other >= self`.
3887 
3888  Use the operator >= for signed greater than or equal to.
3889 
3890  >>> x, y = BitVecs('x y', 32)
3891  >>> UGE(x, y)
3892  UGE(x, y)
3893  >>> (x >= y).sexpr()
3894  '(bvsge x y)'
3895  >>> UGE(x, y).sexpr()
3896  '(bvuge x y)'
3897  """
3898  _check_bv_args(a, b)
3899  a, b = _coerce_exprs(a, b)
3900  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3901 
3902 def UGT(a, b):
3903  """Create the Z3 expression (unsigned) `other > self`.
3904 
3905  Use the operator > for signed greater than.
3906 
3907  >>> x, y = BitVecs('x y', 32)
3908  >>> UGT(x, y)
3909  UGT(x, y)
3910  >>> (x > y).sexpr()
3911  '(bvsgt x y)'
3912  >>> UGT(x, y).sexpr()
3913  '(bvugt x y)'
3914  """
3915  _check_bv_args(a, b)
3916  a, b = _coerce_exprs(a, b)
3917  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3918 
3919 def UDiv(a, b):
3920  """Create the Z3 expression (unsigned) division `self / other`.
3921 
3922  Use the operator / for signed division.
3923 
3924  >>> x = BitVec('x', 32)
3925  >>> y = BitVec('y', 32)
3926  >>> UDiv(x, y)
3927  UDiv(x, y)
3928  >>> UDiv(x, y).sort()
3929  BitVec(32)
3930  >>> (x / y).sexpr()
3931  '(bvsdiv x y)'
3932  >>> UDiv(x, y).sexpr()
3933  '(bvudiv x y)'
3934  """
3935  _check_bv_args(a, b)
3936  a, b = _coerce_exprs(a, b)
3937  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3938 
3939 def URem(a, b):
3940  """Create the Z3 expression (unsigned) remainder `self % other`.
3941 
3942  Use the operator % for signed modulus, and SRem() for signed remainder.
3943 
3944  >>> x = BitVec('x', 32)
3945  >>> y = BitVec('y', 32)
3946  >>> URem(x, y)
3947  URem(x, y)
3948  >>> URem(x, y).sort()
3949  BitVec(32)
3950  >>> (x % y).sexpr()
3951  '(bvsmod x y)'
3952  >>> URem(x, y).sexpr()
3953  '(bvurem x y)'
3954  """
3955  _check_bv_args(a, b)
3956  a, b = _coerce_exprs(a, b)
3957  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3958 
3959 def SRem(a, b):
3960  """Create the Z3 expression signed remainder.
3961 
3962  Use the operator % for signed modulus, and URem() for unsigned remainder.
3963 
3964  >>> x = BitVec('x', 32)
3965  >>> y = BitVec('y', 32)
3966  >>> SRem(x, y)
3967  SRem(x, y)
3968  >>> SRem(x, y).sort()
3969  BitVec(32)
3970  >>> (x % y).sexpr()
3971  '(bvsmod x y)'
3972  >>> SRem(x, y).sexpr()
3973  '(bvsrem x y)'
3974  """
3975  _check_bv_args(a, b)
3976  a, b = _coerce_exprs(a, b)
3977  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3978 
3979 def LShR(a, b):
3980  """Create the Z3 expression logical right shift.
3981 
3982  Use the operator >> for the arithmetical right shift.
3983 
3984  >>> x, y = BitVecs('x y', 32)
3985  >>> LShR(x, y)
3986  LShR(x, y)
3987  >>> (x >> y).sexpr()
3988  '(bvashr x y)'
3989  >>> LShR(x, y).sexpr()
3990  '(bvlshr x y)'
3991  >>> BitVecVal(4, 3)
3992  4
3993  >>> BitVecVal(4, 3).as_signed_long()
3994  -4
3995  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3996  -2
3997  >>> simplify(BitVecVal(4, 3) >> 1)
3998  6
3999  >>> simplify(LShR(BitVecVal(4, 3), 1))
4000  2
4001  >>> simplify(BitVecVal(2, 3) >> 1)
4002  1
4003  >>> simplify(LShR(BitVecVal(2, 3), 1))
4004  1
4005  """
4006  _check_bv_args(a, b)
4007  a, b = _coerce_exprs(a, b)
4008  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4009 
4010 def RotateLeft(a, b):
4011  """Return an expression representing `a` rotated to the left `b` times.
4012 
4013  >>> a, b = BitVecs('a b', 16)
4014  >>> RotateLeft(a, b)
4015  RotateLeft(a, b)
4016  >>> simplify(RotateLeft(a, 0))
4017  a
4018  >>> simplify(RotateLeft(a, 16))
4019  a
4020  """
4021  _check_bv_args(a, b)
4022  a, b = _coerce_exprs(a, b)
4023  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4024 
4025 def RotateRight(a, b):
4026  """Return an expression representing `a` rotated to the right `b` times.
4027 
4028  >>> a, b = BitVecs('a b', 16)
4029  >>> RotateRight(a, b)
4030  RotateRight(a, b)
4031  >>> simplify(RotateRight(a, 0))
4032  a
4033  >>> simplify(RotateRight(a, 16))
4034  a
4035  """
4036  _check_bv_args(a, b)
4037  a, b = _coerce_exprs(a, b)
4038  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4039 
4040 def SignExt(n, a):
4041  """Return a bit-vector expression with `n` extra sign-bits.
4042 
4043  >>> x = BitVec('x', 16)
4044  >>> n = SignExt(8, x)
4045  >>> n.size()
4046  24
4047  >>> n
4048  SignExt(8, x)
4049  >>> n.sort()
4050  BitVec(24)
4051  >>> v0 = BitVecVal(2, 2)
4052  >>> v0
4053  2
4054  >>> v0.size()
4055  2
4056  >>> v = simplify(SignExt(6, v0))
4057  >>> v
4058  254
4059  >>> v.size()
4060  8
4061  >>> print("%.x" % v.as_long())
4062  fe
4063  """
4064  if __debug__:
4065  _z3_assert(_is_int(n), "First argument must be an integer")
4066  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4067  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4068 
4069 def ZeroExt(n, a):
4070  """Return a bit-vector expression with `n` extra zero-bits.
4071 
4072  >>> x = BitVec('x', 16)
4073  >>> n = ZeroExt(8, x)
4074  >>> n.size()
4075  24
4076  >>> n
4077  ZeroExt(8, x)
4078  >>> n.sort()
4079  BitVec(24)
4080  >>> v0 = BitVecVal(2, 2)
4081  >>> v0
4082  2
4083  >>> v0.size()
4084  2
4085  >>> v = simplify(ZeroExt(6, v0))
4086  >>> v
4087  2
4088  >>> v.size()
4089  8
4090  """
4091  if __debug__:
4092  _z3_assert(_is_int(n), "First argument must be an integer")
4093  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4094  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4095 
4096 def RepeatBitVec(n, a):
4097  """Return an expression representing `n` copies of `a`.
4098 
4099  >>> x = BitVec('x', 8)
4100  >>> n = RepeatBitVec(4, x)
4101  >>> n
4102  RepeatBitVec(4, x)
4103  >>> n.size()
4104  32
4105  >>> v0 = BitVecVal(10, 4)
4106  >>> print("%.x" % v0.as_long())
4107  a
4108  >>> v = simplify(RepeatBitVec(4, v0))
4109  >>> v.size()
4110  16
4111  >>> print("%.x" % v.as_long())
4112  aaaa
4113  """
4114  if __debug__:
4115  _z3_assert(_is_int(n), "First argument must be an integer")
4116  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4117  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4118 
4119 def BVRedAnd(a):
4120  """Return the reduction-and expression of `a`."""
4121  if __debug__:
4122  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4123  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4124 
4125 def BVRedOr(a):
4126  """Return the reduction-or expression of `a`."""
4127  if __debug__:
4128  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4129  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4130 
4131 def BVAddNoOverflow(a, b, signed):
4132  """A predicate the determines that bit-vector addition does not overflow"""
4133  _check_bv_args(a, b)
4134  a, b = _coerce_exprs(a, b)
4135  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4136 
4137 def BVAddNoUnderflow(a, b):
4138  """A predicate the determines that signed bit-vector addition does not underflow"""
4139  _check_bv_args(a, b)
4140  a, b = _coerce_exprs(a, b)
4141  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4142 
4143 def BVSubNoOverflow(a, b):
4144  """A predicate the determines that bit-vector subtraction does not overflow"""
4145  _check_bv_args(a, b)
4146  a, b = _coerce_exprs(a, b)
4147  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4148 
4149 
4150 def BVSubNoUnderflow(a, b, signed):
4151  """A predicate the determines that bit-vector subtraction does not underflow"""
4152  _check_bv_args(a, b)
4153  a, b = _coerce_exprs(a, b)
4154  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4155 
4156 def BVSDivNoOverflow(a, b):
4157  """A predicate the determines that bit-vector signed division does not overflow"""
4158  _check_bv_args(a, b)
4159  a, b = _coerce_exprs(a, b)
4160  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4161 
4162 def BVSNegNoOverflow(a):
4163  """A predicate the determines that bit-vector unary negation does not overflow"""
4164  if __debug__:
4165  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4166  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4167 
4168 def BVMulNoOverflow(a, b, signed):
4169  """A predicate the determines that bit-vector multiplication does not overflow"""
4170  _check_bv_args(a, b)
4171  a, b = _coerce_exprs(a, b)
4172  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4173 
4174 
4175 def BVMulNoUnderflow(a, b):
4176  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4177  _check_bv_args(a, b)
4178  a, b = _coerce_exprs(a, b)
4179  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4180 
4181 
4182 
4183 #########################################
4184 #
4185 # Arrays
4186 #
4187 #########################################
4188 
4189 class ArraySortRef(SortRef):
4190  """Array sorts."""
4191 
4192  def domain(self):
4193  """Return the domain of the array sort `self`.
4194 
4195  >>> A = ArraySort(IntSort(), BoolSort())
4196  >>> A.domain()
4197  Int
4198  """
4199  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4200 
4201  def range(self):
4202  """Return the range of the array sort `self`.
4203 
4204  >>> A = ArraySort(IntSort(), BoolSort())
4205  >>> A.range()
4206  Bool
4207  """
4208  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4209 
4210 class ArrayRef(ExprRef):
4211  """Array expressions. """
4212 
4213  def sort(self):
4214  """Return the array sort of the array expression `self`.
4215 
4216  >>> a = Array('a', IntSort(), BoolSort())
4217  >>> a.sort()
4218  Array(Int, Bool)
4219  """
4220  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4221 
4222  def domain(self):
4223  """Shorthand for `self.sort().domain()`.
4224 
4225  >>> a = Array('a', IntSort(), BoolSort())
4226  >>> a.domain()
4227  Int
4228  """
4229  return self.sort().domain()
4230 
4231  def range(self):
4232  """Shorthand for `self.sort().range()`.
4233 
4234  >>> a = Array('a', IntSort(), BoolSort())
4235  >>> a.range()
4236  Bool
4237  """
4238  return self.sort().range()
4239 
4240  def __getitem__(self, arg):
4241  """Return the Z3 expression `self[arg]`.
4242 
4243  >>> a = Array('a', IntSort(), BoolSort())
4244  >>> i = Int('i')
4245  >>> a[i]
4246  a[i]
4247  >>> a[i].sexpr()
4248  '(select a i)'
4249  """
4250  arg = self.domain().cast(arg)
4251  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4252 
4253  def default(self):
4254  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4255 
4256 
4257 def is_array(a):
4258  """Return `True` if `a` is a Z3 array expression.
4259 
4260  >>> a = Array('a', IntSort(), IntSort())
4261  >>> is_array(a)
4262  True
4263  >>> is_array(Store(a, 0, 1))
4264  True
4265  >>> is_array(a[0])
4266  False
4267  """
4268  return isinstance(a, ArrayRef)
4269 
4270 def is_const_array(a):
4271  """Return `True` if `a` is a Z3 constant array.
4272 
4273  >>> a = K(IntSort(), 10)
4274  >>> is_const_array(a)
4275  True
4276  >>> a = Array('a', IntSort(), IntSort())
4277  >>> is_const_array(a)
4278  False
4279  """
4280  return is_app_of(a, Z3_OP_CONST_ARRAY)
4281 
4282 def is_K(a):
4283  """Return `True` if `a` is a Z3 constant array.
4284 
4285  >>> a = K(IntSort(), 10)
4286  >>> is_K(a)
4287  True
4288  >>> a = Array('a', IntSort(), IntSort())
4289  >>> is_K(a)
4290  False
4291  """
4292  return is_app_of(a, Z3_OP_CONST_ARRAY)
4293 
4294 def is_map(a):
4295  """Return `True` if `a` is a Z3 map array expression.
4296 
4297  >>> f = Function('f', IntSort(), IntSort())
4298  >>> b = Array('b', IntSort(), IntSort())
4299  >>> a = Map(f, b)
4300  >>> a
4301  Map(f, b)
4302  >>> is_map(a)
4303  True
4304  >>> is_map(b)
4305  False
4306  """
4307  return is_app_of(a, Z3_OP_ARRAY_MAP)
4308 
4309 def is_default(a):
4310  """Return `True` if `a` is a Z3 default array expression.
4311  >>> d = Default(K(IntSort(), 10))
4312  >>> is_default(d)
4313  True
4314  """
4315  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4316 
4317 def get_map_func(a):
4318  """Return the function declaration associated with a Z3 map array expression.
4319 
4320  >>> f = Function('f', IntSort(), IntSort())
4321  >>> b = Array('b', IntSort(), IntSort())
4322  >>> a = Map(f, b)
4323  >>> eq(f, get_map_func(a))
4324  True
4325  >>> get_map_func(a)
4326  f
4327  >>> get_map_func(a)(0)
4328  f(0)
4329  """
4330  if __debug__:
4331  _z3_assert(is_map(a), "Z3 array map expression expected.")
4332  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4333 
4334 def ArraySort(*sig):
4335  """Return the Z3 array sort with the given domain and range sorts.
4336 
4337  >>> A = ArraySort(IntSort(), BoolSort())
4338  >>> A
4339  Array(Int, Bool)
4340  >>> A.domain()
4341  Int
4342  >>> A.range()
4343  Bool
4344  >>> AA = ArraySort(IntSort(), A)
4345  >>> AA
4346  Array(Int, Array(Int, Bool))
4347  """
4348  sig = _get_args(sig)
4349  if __debug__:
4350  _z3_assert(len(sig) > 1, "At least two arguments expected")
4351  arity = len(sig) - 1
4352  r = sig[arity]
4353  d = sig[0]
4354  if __debug__:
4355  for s in sig:
4356  _z3_assert(is_sort(s), "Z3 sort expected")
4357  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4358  ctx = d.ctx
4359  if len(sig) == 2:
4360  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4361  dom = (Sort * arity)()
4362  for i in range(arity):
4363  dom[i] = sig[i].ast
4364  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4365 
4366 def Array(name, dom, rng):
4367  """Return an array constant named `name` with the given domain and range sorts.
4368 
4369  >>> a = Array('a', IntSort(), IntSort())
4370  >>> a.sort()
4371  Array(Int, Int)
4372  >>> a[0]
4373  a[0]
4374  """
4375  s = ArraySort(dom, rng)
4376  ctx = s.ctx
4377  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4378 
4379 def Update(a, i, v):
4380  """Return a Z3 store array expression.
4381 
4382  >>> a = Array('a', IntSort(), IntSort())
4383  >>> i, v = Ints('i v')
4384  >>> s = Update(a, i, v)
4385  >>> s.sort()
4386  Array(Int, Int)
4387  >>> prove(s[i] == v)
4388  proved
4389  >>> j = Int('j')
4390  >>> prove(Implies(i != j, s[j] == a[j]))
4391  proved
4392  """
4393  if __debug__:
4394  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4395  i = a.domain().cast(i)
4396  v = a.range().cast(v)
4397  ctx = a.ctx
4398  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4399 
4400 def Default(a):
4401  """ Return a default value for array expression.
4402  >>> b = K(IntSort(), 1)
4403  >>> prove(Default(b) == 1)
4404  proved
4405  """
4406  if __debug__:
4407  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4408  return a.default()
4409 
4410 
4411 def Store(a, i, v):
4412  """Return a Z3 store array expression.
4413 
4414  >>> a = Array('a', IntSort(), IntSort())
4415  >>> i, v = Ints('i v')
4416  >>> s = Store(a, i, v)
4417  >>> s.sort()
4418  Array(Int, Int)
4419  >>> prove(s[i] == v)
4420  proved
4421  >>> j = Int('j')
4422  >>> prove(Implies(i != j, s[j] == a[j]))
4423  proved
4424  """
4425  return Update(a, i, v)
4426 
4427 def Select(a, i):
4428  """Return a Z3 select array expression.
4429 
4430  >>> a = Array('a', IntSort(), IntSort())
4431  >>> i = Int('i')
4432  >>> Select(a, i)
4433  a[i]
4434  >>> eq(Select(a, i), a[i])
4435  True
4436  """
4437  if __debug__:
4438  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4439  return a[i]
4440 
4441 
4442 def Map(f, *args):
4443  """Return a Z3 map array expression.
4444 
4445  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4446  >>> a1 = Array('a1', IntSort(), IntSort())
4447  >>> a2 = Array('a2', IntSort(), IntSort())
4448  >>> b = Map(f, a1, a2)
4449  >>> b
4450  Map(f, a1, a2)
4451  >>> prove(b[0] == f(a1[0], a2[0]))
4452  proved
4453  """
4454  args = _get_args(args)
4455  if __debug__:
4456  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4457  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4458  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4459  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4460  _args, sz = _to_ast_array(args)
4461  ctx = f.ctx
4462  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4463 
4464 def K(dom, v):
4465  """Return a Z3 constant array expression.
4466 
4467  >>> a = K(IntSort(), 10)
4468  >>> a
4469  K(Int, 10)
4470  >>> a.sort()
4471  Array(Int, Int)
4472  >>> i = Int('i')
4473  >>> a[i]
4474  K(Int, 10)[i]
4475  >>> simplify(a[i])
4476  10
4477  """
4478  if __debug__:
4479  _z3_assert(is_sort(dom), "Z3 sort expected")
4480  ctx = dom.ctx
4481  if not is_expr(v):
4482  v = _py2expr(v, ctx)
4483  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4484 
4485 def Ext(a, b):
4486  """Return extensionality index for arrays.
4487  """
4488  if __debug__:
4489  _z3_assert(is_array(a) and is_array(b))
4490  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
4491 
4492 def is_select(a):
4493  """Return `True` if `a` is a Z3 array select application.
4494 
4495  >>> a = Array('a', IntSort(), IntSort())
4496  >>> is_select(a)
4497  False
4498  >>> i = Int('i')
4499  >>> is_select(a[i])
4500  True
4501  """
4502  return is_app_of(a, Z3_OP_SELECT)
4503 
4504 def is_store(a):
4505  """Return `True` if `a` is a Z3 array store application.
4506 
4507  >>> a = Array('a', IntSort(), IntSort())
4508  >>> is_store(a)
4509  False
4510  >>> is_store(Store(a, 0, 1))
4511  True
4512  """
4513  return is_app_of(a, Z3_OP_STORE)
4514 
4515 #########################################
4516 #
4517 # Sets
4518 #
4519 #########################################
4520 
4521 
4522 def SetSort(s):
4523  """ Create a set sort over element sort s"""
4524  return ArraySort(s, BoolSort())
4525 
4526 def EmptySet(s):
4527  """Create the empty set
4528  >>> EmptySet(IntSort())
4529  K(Int, False)
4530  """
4531  ctx = s.ctx
4532  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4533 
4534 def FullSet(s):
4535  """Create the full set
4536  >>> FullSet(IntSort())
4537  K(Int, True)
4538  """
4539  ctx = s.ctx
4540  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4541 
4542 def SetUnion(*args):
4543  """ Take the union of sets
4544  >>> a = Const('a', SetSort(IntSort()))
4545  >>> b = Const('b', SetSort(IntSort()))
4546  >>> SetUnion(a, b)
4547  union(a, b)
4548  """
4549  args = _get_args(args)
4550  ctx = _ctx_from_ast_arg_list(args)
4551  _args, sz = _to_ast_array(args)
4552  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4553 
4554 def SetIntersect(*args):
4555  """ Take the union of sets
4556  >>> a = Const('a', SetSort(IntSort()))
4557  >>> b = Const('b', SetSort(IntSort()))
4558  >>> SetIntersect(a, b)
4559  intersect(a, b)
4560  """
4561  args = _get_args(args)
4562  ctx = _ctx_from_ast_arg_list(args)
4563  _args, sz = _to_ast_array(args)
4564  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4565 
4566 def SetAdd(s, e):
4567  """ Add element e to set s
4568  >>> a = Const('a', SetSort(IntSort()))
4569  >>> SetAdd(a, 1)
4570  Store(a, 1, True)
4571  """
4572  ctx = _ctx_from_ast_arg_list([s,e])
4573  e = _py2expr(e, ctx)
4574  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4575 
4576 def SetDel(s, e):
4577  """ Remove element e to set s
4578  >>> a = Const('a', SetSort(IntSort()))
4579  >>> SetDel(a, 1)
4580  Store(a, 1, False)
4581  """
4582  ctx = _ctx_from_ast_arg_list([s,e])
4583  e = _py2expr(e, ctx)
4584  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4585 
4586 def SetComplement(s):
4587  """ The complement of set s
4588  >>> a = Const('a', SetSort(IntSort()))
4589  >>> SetComplement(a)
4590  complement(a)
4591  """
4592  ctx = s.ctx
4593  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4594 
4595 def SetDifference(a, b):
4596  """ The set difference of a and b
4597  >>> a = Const('a', SetSort(IntSort()))
4598  >>> b = Const('b', SetSort(IntSort()))
4599  >>> SetDifference(a, b)
4600  difference(a, b)
4601  """
4602  ctx = _ctx_from_ast_arg_list([a, b])
4603  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4604 
4605 def IsMember(e, s):
4606  """ Check if e is a member of set s
4607  >>> a = Const('a', SetSort(IntSort()))
4608  >>> IsMember(1, a)
4609  a[1]
4610  """
4611  ctx = _ctx_from_ast_arg_list([s,e])
4612  e = _py2expr(e, ctx)
4613  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4614 
4615 def IsSubset(a, b):
4616  """ Check if a is a subset of b
4617  >>> a = Const('a', SetSort(IntSort()))
4618  >>> b = Const('b', SetSort(IntSort()))
4619  >>> IsSubset(a, b)
4620  subset(a, b)
4621  """
4622  ctx = _ctx_from_ast_arg_list([a, b])
4623  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4624 
4625 
4626 #########################################
4627 #
4628 # Datatypes
4629 #
4630 #########################################
4631 
4632 def _valid_accessor(acc):
4633  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4634  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4635 
4636 class Datatype:
4637  """Helper class for declaring Z3 datatypes.
4638 
4639  >>> List = Datatype('List')
4640  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4641  >>> List.declare('nil')
4642  >>> List = List.create()
4643  >>> # List is now a Z3 declaration
4644  >>> List.nil
4645  nil
4646  >>> List.cons(10, List.nil)
4647  cons(10, nil)
4648  >>> List.cons(10, List.nil).sort()
4649  List
4650  >>> cons = List.cons
4651  >>> nil = List.nil
4652  >>> car = List.car
4653  >>> cdr = List.cdr
4654  >>> n = cons(1, cons(0, nil))
4655  >>> n
4656  cons(1, cons(0, nil))
4657  >>> simplify(cdr(n))
4658  cons(0, nil)
4659  >>> simplify(car(n))
4660  1
4661  """
4662  def __init__(self, name, ctx=None):
4663  self.ctx = _get_ctx(ctx)
4664  self.name = name
4665  self.constructors = []
4666 
4667  def __deepcopy__(self, memo={}):
4668  r = Datatype(self.name, self.ctx)
4669  r.constructors = copy.deepcopy(self.constructors)
4670  return r
4671 
4672  def declare_core(self, name, rec_name, *args):
4673  if __debug__:
4674  _z3_assert(isinstance(name, str), "String expected")
4675  _z3_assert(isinstance(rec_name, str), "String expected")
4676  _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)")
4677  self.constructors.append((name, rec_name, args))
4678 
4679  def declare(self, name, *args):
4680  """Declare constructor named `name` with the given accessors `args`.
4681  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.
4682 
4683  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4684  declares the constructor named `cons` that builds a new List using an integer and a List.
4685  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4686  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4687  the actual datatype in Z3.
4688 
4689  >>> List = Datatype('List')
4690  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4691  >>> List.declare('nil')
4692  >>> List = List.create()
4693  """
4694  if __debug__:
4695  _z3_assert(isinstance(name, str), "String expected")
4696  _z3_assert(name != "", "Constructor name cannot be empty")
4697  return self.declare_core(name, "is-" + name, *args)
4698 
4699  def __repr__(self):
4700  return "Datatype(%s, %s)" % (self.name, self.constructors)
4701 
4702  def create(self):
4703  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4704 
4705  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4706 
4707  >>> List = Datatype('List')
4708  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4709  >>> List.declare('nil')
4710  >>> List = List.create()
4711  >>> List.nil
4712  nil
4713  >>> List.cons(10, List.nil)
4714  cons(10, nil)
4715  """
4716  return CreateDatatypes([self])[0]
4717 
4718 class ScopedConstructor:
4719  """Auxiliary object used to create Z3 datatypes."""
4720  def __init__(self, c, ctx):
4721  self.c = c
4722  self.ctx = ctx
4723  def __del__(self):
4724  if self.ctx.ref() is not None:
4725  Z3_del_constructor(self.ctx.ref(), self.c)
4726 
4727 class ScopedConstructorList:
4728  """Auxiliary object used to create Z3 datatypes."""
4729  def __init__(self, c, ctx):
4730  self.c = c
4731  self.ctx = ctx
4732  def __del__(self):
4733  if self.ctx.ref() is not None:
4734  Z3_del_constructor_list(self.ctx.ref(), self.c)
4735 
4736 def CreateDatatypes(*ds):
4737  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4738 
4739  In the following example we define a Tree-List using two mutually recursive datatypes.
4740 
4741  >>> TreeList = Datatype('TreeList')
4742  >>> Tree = Datatype('Tree')
4743  >>> # Tree has two constructors: leaf and node
4744  >>> Tree.declare('leaf', ('val', IntSort()))
4745  >>> # a node contains a list of trees
4746  >>> Tree.declare('node', ('children', TreeList))
4747  >>> TreeList.declare('nil')
4748  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4749  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4750  >>> Tree.val(Tree.leaf(10))
4751  val(leaf(10))
4752  >>> simplify(Tree.val(Tree.leaf(10)))
4753  10
4754  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4755  >>> n1
4756  node(cons(leaf(10), cons(leaf(20), nil)))
4757  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4758  >>> simplify(n2 == n1)
4759  False
4760  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4761  True
4762  """
4763  ds = _get_args(ds)
4764  if __debug__:
4765  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4766  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4767  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4768  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4769  ctx = ds[0].ctx
4770  num = len(ds)
4771  names = (Symbol * num)()
4772  out = (Sort * num)()
4773  clists = (ConstructorList * num)()
4774  to_delete = []
4775  for i in range(num):
4776  d = ds[i]
4777  names[i] = to_symbol(d.name, ctx)
4778  num_cs = len(d.constructors)
4779  cs = (Constructor * num_cs)()
4780  for j in range(num_cs):
4781  c = d.constructors[j]
4782  cname = to_symbol(c[0], ctx)
4783  rname = to_symbol(c[1], ctx)
4784  fs = c[2]
4785  num_fs = len(fs)
4786  fnames = (Symbol * num_fs)()
4787  sorts = (Sort * num_fs)()
4788  refs = (ctypes.c_uint * num_fs)()
4789  for k in range(num_fs):
4790  fname = fs[k][0]
4791  ftype = fs[k][1]
4792  fnames[k] = to_symbol(fname, ctx)
4793  if isinstance(ftype, Datatype):
4794  if __debug__:
4795  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4796  sorts[k] = None
4797  refs[k] = ds.index(ftype)
4798  else:
4799  if __debug__:
4800  _z3_assert(is_sort(ftype), "Z3 sort expected")
4801  sorts[k] = ftype.ast
4802  refs[k] = 0
4803  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4804  to_delete.append(ScopedConstructor(cs[j], ctx))
4805  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4806  to_delete.append(ScopedConstructorList(clists[i], ctx))
4807  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4808  result = []
4809  ## Create a field for every constructor, recognizer and accessor
4810  for i in range(num):
4811  dref = DatatypeSortRef(out[i], ctx)
4812  num_cs = dref.num_constructors()
4813  for j in range(num_cs):
4814  cref = dref.constructor(j)
4815  cref_name = cref.name()
4816  cref_arity = cref.arity()
4817  if cref.arity() == 0:
4818  cref = cref()
4819  setattr(dref, cref_name, cref)
4820  rref = dref.recognizer(j)
4821  setattr(dref, "is_" + cref_name, rref)
4822  for k in range(cref_arity):
4823  aref = dref.accessor(j, k)
4824  setattr(dref, aref.name(), aref)
4825  result.append(dref)
4826  return tuple(result)
4827 
4828 class DatatypeSortRef(SortRef):
4829  """Datatype sorts."""
4830  def num_constructors(self):
4831  """Return the number of constructors in the given Z3 datatype.
4832 
4833  >>> List = Datatype('List')
4834  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4835  >>> List.declare('nil')
4836  >>> List = List.create()
4837  >>> # List is now a Z3 declaration
4838  >>> List.num_constructors()
4839  2
4840  """
4841  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4842 
4843  def constructor(self, idx):
4844  """Return a constructor of the datatype `self`.
4845 
4846  >>> List = Datatype('List')
4847  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4848  >>> List.declare('nil')
4849  >>> List = List.create()
4850  >>> # List is now a Z3 declaration
4851  >>> List.num_constructors()
4852  2
4853  >>> List.constructor(0)
4854  cons
4855  >>> List.constructor(1)
4856  nil
4857  """
4858  if __debug__:
4859  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4860  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4861 
4862  def recognizer(self, idx):
4863  """In Z3, each constructor has an associated recognizer predicate.
4864 
4865  If the constructor is named `name`, then the recognizer `is_name`.
4866 
4867  >>> List = Datatype('List')
4868  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4869  >>> List.declare('nil')
4870  >>> List = List.create()
4871  >>> # List is now a Z3 declaration
4872  >>> List.num_constructors()
4873  2
4874  >>> List.recognizer(0)
4875  is(cons)
4876  >>> List.recognizer(1)
4877  is(nil)
4878  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4879  False
4880  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4881  True
4882  >>> l = Const('l', List)
4883  >>> simplify(List.is_cons(l))
4884  is(cons, l)
4885  """
4886  if __debug__:
4887  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4888  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4889 
4890  def accessor(self, i, j):
4891  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4892 
4893  >>> List = Datatype('List')
4894  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4895  >>> List.declare('nil')
4896  >>> List = List.create()
4897  >>> List.num_constructors()
4898  2
4899  >>> List.constructor(0)
4900  cons
4901  >>> num_accs = List.constructor(0).arity()
4902  >>> num_accs
4903  2
4904  >>> List.accessor(0, 0)
4905  car
4906  >>> List.accessor(0, 1)
4907  cdr
4908  >>> List.constructor(1)
4909  nil
4910  >>> num_accs = List.constructor(1).arity()
4911  >>> num_accs
4912  0
4913  """
4914  if __debug__:
4915  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4916  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4917  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4918 
4919 class DatatypeRef(ExprRef):
4920  """Datatype expressions."""
4921  def sort(self):
4922  """Return the datatype sort of the datatype expression `self`."""
4923  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4924 
4925 def EnumSort(name, values, ctx=None):
4926  """Return a new enumeration sort named `name` containing the given values.
4927 
4928  The result is a pair (sort, list of constants).
4929  Example:
4930  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4931  """
4932  if __debug__:
4933  _z3_assert(isinstance(name, str), "Name must be a string")
4934  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4935  _z3_assert(len(values) > 0, "At least one value expected")
4936  ctx = _get_ctx(ctx)
4937  num = len(values)
4938  _val_names = (Symbol * num)()
4939  for i in range(num):
4940  _val_names[i] = to_symbol(values[i])
4941  _values = (FuncDecl * num)()
4942  _testers = (FuncDecl * num)()
4943  name = to_symbol(name)
4944  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4945  V = []
4946  for i in range(num):
4947  V.append(FuncDeclRef(_values[i], ctx))
4948  V = [a() for a in V]
4949  return S, V
4950 
4951 #########################################
4952 #
4953 # Parameter Sets
4954 #
4955 #########################################
4956 
4957 class ParamsRef:
4958  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4959 
4960  Consider using the function `args2params` to create instances of this object.
4961  """
4962  def __init__(self, ctx=None, params=None):
4963  self.ctx = _get_ctx(ctx)
4964  if params is None:
4965  self.params = Z3_mk_params(self.ctx.ref())
4966  else:
4967  self.params = params
4968  Z3_params_inc_ref(self.ctx.ref(), self.params)
4969 
4970  def __deepcopy__(self, memo={}):
4971  return ParamsRef(self.ctx, self.params)
4972 
4973  def __del__(self):
4974  if self.ctx.ref() is not None:
4975  Z3_params_dec_ref(self.ctx.ref(), self.params)
4976 
4977  def set(self, name, val):
4978  """Set parameter name with value val."""
4979  if __debug__:
4980  _z3_assert(isinstance(name, str), "parameter name must be a string")
4981  name_sym = to_symbol(name, self.ctx)
4982  if isinstance(val, bool):
4983  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4984  elif _is_int(val):
4985  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4986  elif isinstance(val, float):
4987  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4988  elif isinstance(val, str):
4989  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4990  else:
4991  if __debug__:
4992  _z3_assert(False, "invalid parameter value")
4993 
4994  def __repr__(self):
4995  return Z3_params_to_string(self.ctx.ref(), self.params)
4996 
4997  def validate(self, ds):
4998  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
4999  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5000 
5001 def args2params(arguments, keywords, ctx=None):
5002  """Convert python arguments into a Z3_params object.
5003  A ':' is added to the keywords, and '_' is replaced with '-'
5004 
5005  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5006  (params model true relevancy 2 elim_and true)
5007  """
5008  if __debug__:
5009  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5010  prev = None
5011  r = ParamsRef(ctx)
5012  for a in arguments:
5013  if prev is None:
5014  prev = a
5015  else:
5016  r.set(prev, a)
5017  prev = None
5018  for k in keywords:
5019  v = keywords[k]
5020  r.set(k, v)
5021  return r
5022 
5023 class ParamDescrsRef:
5024  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5025  """
5026  def __init__(self, descr, ctx=None):
5027  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5028  self.ctx = _get_ctx(ctx)
5029  self.descr = descr
5030  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5031 
5032  def __deepcopy__(self, memo={}):
5033  return ParamsDescrsRef(self.descr, self.ctx)
5034 
5035  def __del__(self):
5036  if self.ctx.ref() is not None:
5037  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5038 
5039  def size(self):
5040  """Return the size of in the parameter description `self`.
5041  """
5042  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5043 
5044  def __len__(self):
5045  """Return the size of in the parameter description `self`.
5046  """
5047  return self.size()
5048 
5049  def get_name(self, i):
5050  """Return the i-th parameter name in the parameter description `self`.
5051  """
5052  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5053 
5054  def get_kind(self, n):
5055  """Return the kind of the parameter named `n`.
5056  """
5057  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5058 
5059  def get_documentation(self, n):
5060  """Return the documentation string of the parameter named `n`.
5061  """
5062  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5063 
5064  def __getitem__(self, arg):
5065  if _is_int(arg):
5066  return self.get_name(arg)
5067  else:
5068  return self.get_kind(arg)
5069 
5070  def __repr__(self):
5071  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5072 
5073 #########################################
5074 #
5075 # Goals
5076 #
5077 #########################################
5078 
5079 class Goal(Z3PPObject):
5080  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5081 
5082  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5083  A goal has a solution if one of its subgoals has a solution.
5084  A goal is unsatisfiable if all subgoals are unsatisfiable.
5085  """
5086 
5087  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5088  if __debug__:
5089  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
5090  self.ctx = _get_ctx(ctx)
5091  self.goal = goal
5092  if self.goal is None:
5093  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5094  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5095 
5096  def __deepcopy__(self, memo={}):
5097  return Goal(False, False, False, self.ctx, self.goal)
5098 
5099  def __del__(self):
5100  if self.goal is not None and self.ctx.ref() is not None:
5101  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5102 
5103  def depth(self):
5104  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
5105 
5106  >>> x, y = Ints('x y')
5107  >>> g = Goal()
5108  >>> g.add(x == 0, y >= x + 1)
5109  >>> g.depth()
5110  0
5111  >>> r = Then('simplify', 'solve-eqs')(g)
5112  >>> # r has 1 subgoal
5113  >>> len(r)
5114  1
5115  >>> r[0].depth()
5116  2
5117  """
5118  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5119 
5120  def inconsistent(self):
5121  """Return `True` if `self` contains the `False` constraints.
5122 
5123  >>> x, y = Ints('x y')
5124  >>> g = Goal()
5125  >>> g.inconsistent()
5126  False
5127  >>> g.add(x == 0, x == 1)
5128  >>> g
5129  [x == 0, x == 1]
5130  >>> g.inconsistent()
5131  False
5132  >>> g2 = Tactic('propagate-values')(g)[0]
5133  >>> g2.inconsistent()
5134  True
5135  """
5136  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5137 
5138  def prec(self):
5139  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5140 
5141  >>> g = Goal()
5142  >>> g.prec() == Z3_GOAL_PRECISE
5143  True
5144  >>> x, y = Ints('x y')
5145  >>> g.add(x == y + 1)
5146  >>> g.prec() == Z3_GOAL_PRECISE
5147  True
5148  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5149  >>> g2 = t(g)[0]
5150  >>> g2
5151  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5152  >>> g2.prec() == Z3_GOAL_PRECISE
5153  False
5154  >>> g2.prec() == Z3_GOAL_UNDER
5155  True
5156  """
5157  return Z3_goal_precision(self.ctx.ref(), self.goal)
5158 
5159  def precision(self):
5160  """Alias for `prec()`.
5161 
5162  >>> g = Goal()
5163  >>> g.precision() == Z3_GOAL_PRECISE
5164  True
5165  """
5166  return self.prec()
5167 
5168  def size(self):
5169  """Return the number of constraints in the goal `self`.
5170 
5171  >>> g = Goal()
5172  >>> g.size()
5173  0
5174  >>> x, y = Ints('x y')
5175  >>> g.add(x == 0, y > x)
5176  >>> g.size()
5177  2
5178  """
5179  return int(Z3_goal_size(self.ctx.ref(), self.goal))
5180 
5181  def __len__(self):
5182  """Return the number of constraints in the goal `self`.
5183 
5184  >>> g = Goal()
5185  >>> len(g)
5186  0
5187  >>> x, y = Ints('x y')
5188  >>> g.add(x == 0, y > x)
5189  >>> len(g)
5190  2
5191  """
5192  return self.size()
5193 
5194  def get(self, i):
5195  """Return a constraint in the goal `self`.
5196 
5197  >>> g = Goal()
5198  >>> x, y = Ints('x y')
5199  >>> g.add(x == 0, y > x)
5200  >>> g.get(0)
5201  x == 0
5202  >>> g.get(1)
5203  y > x
5204  """
5205  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5206 
5207  def __getitem__(self, arg):
5208  """Return a constraint in the goal `self`.
5209 
5210  >>> g = Goal()
5211  >>> x, y = Ints('x y')
5212  >>> g.add(x == 0, y > x)
5213  >>> g[0]
5214  x == 0
5215  >>> g[1]
5216  y > x
5217  """
5218  if arg >= len(self):
5219  raise IndexError
5220  return self.get(arg)
5221 
5222  def assert_exprs(self, *args):
5223  """Assert constraints into the goal.
5224 
5225  >>> x = Int('x')
5226  >>> g = Goal()
5227  >>> g.assert_exprs(x > 0, x < 2)
5228  >>> g
5229  [x > 0, x < 2]
5230  """
5231  args = _get_args(args)
5232  s = BoolSort(self.ctx)
5233  for arg in args:
5234  arg = s.cast(arg)
5235  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5236 
5237  def append(self, *args):
5238  """Add constraints.
5239 
5240  >>> x = Int('x')
5241  >>> g = Goal()
5242  >>> g.append(x > 0, x < 2)
5243  >>> g
5244  [x > 0, x < 2]
5245  """
5246  self.assert_exprs(*args)
5247 
5248  def insert(self, *args):
5249  """Add constraints.
5250 
5251  >>> x = Int('x')
5252  >>> g = Goal()
5253  >>> g.insert(x > 0, x < 2)
5254  >>> g
5255  [x > 0, x < 2]
5256  """
5257  self.assert_exprs(*args)
5258 
5259  def add(self, *args):
5260  """Add constraints.
5261 
5262  >>> x = Int('x')
5263  >>> g = Goal()
5264  >>> g.add(x > 0, x < 2)
5265  >>> g
5266  [x > 0, x < 2]
5267  """
5268  self.assert_exprs(*args)
5269 
5270  def convert_model(self, model):
5271  """Retrieve model from a satisfiable goal
5272  >>> a, b = Ints('a b')
5273  >>> g = Goal()
5274  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5275  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5276  >>> r = t(g)
5277  >>> r[0]
5278  [Or(b == 0, b == 1), Not(0 <= b)]
5279  >>> r[1]
5280  [Or(b == 0, b == 1), Not(1 <= b)]
5281  >>> # Remark: the subgoal r[0] is unsatisfiable
5282  >>> # Creating a solver for solving the second subgoal
5283  >>> s = Solver()
5284  >>> s.add(r[1])
5285  >>> s.check()
5286  sat
5287  >>> s.model()
5288  [b = 0]
5289  >>> # Model s.model() does not assign a value to `a`
5290  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5291  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5292  >>> r[1].convert_model(s.model())
5293  [b = 0, a = 1]
5294  """
5295  if __debug__:
5296  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5297  return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5298 
5299  def __repr__(self):
5300  return obj_to_string(self)
5301 
5302  def sexpr(self):
5303  """Return a textual representation of the s-expression representing the goal."""
5304  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5305 
5306  def dimacs(self):
5307  """Return a textual representation of the goal in DIMACS format."""
5308  return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
5309 
5310  def translate(self, target):
5311  """Copy goal `self` to context `target`.
5312 
5313  >>> x = Int('x')
5314  >>> g = Goal()
5315  >>> g.add(x > 10)
5316  >>> g
5317  [x > 10]
5318  >>> c2 = Context()
5319  >>> g2 = g.translate(c2)
5320  >>> g2
5321  [x > 10]
5322  >>> g.ctx == main_ctx()
5323  True
5324  >>> g2.ctx == c2
5325  True
5326  >>> g2.ctx == main_ctx()
5327  False
5328  """
5329  if __debug__:
5330  _z3_assert(isinstance(target, Context), "target must be a context")
5331  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5332 
5333  def __copy__(self):
5334  return self.translate(self.ctx)
5335 
5336  def __deepcopy__(self):
5337  return self.translate(self.ctx)
5338 
5339  def simplify(self, *arguments, **keywords):
5340  """Return a new simplified goal.
5341 
5342  This method is essentially invoking the simplify tactic.
5343 
5344  >>> g = Goal()
5345  >>> x = Int('x')
5346  >>> g.add(x + 1 >= 2)
5347  >>> g
5348  [x + 1 >= 2]
5349  >>> g2 = g.simplify()
5350  >>> g2
5351  [x >= 1]
5352  >>> # g was not modified
5353  >>> g
5354  [x + 1 >= 2]
5355  """
5356  t = Tactic('simplify')
5357  return t.apply(self, *arguments, **keywords)[0]
5358 
5359  def as_expr(self):
5360  """Return goal `self` as a single Z3 expression.
5361 
5362  >>> x = Int('x')
5363  >>> g = Goal()
5364  >>> g.as_expr()
5365  True
5366  >>> g.add(x > 1)
5367  >>> g.as_expr()
5368  x > 1
5369  >>> g.add(x < 10)
5370  >>> g.as_expr()
5371  And(x > 1, x < 10)
5372  """
5373  sz = len(self)
5374  if sz == 0:
5375  return BoolVal(True, self.ctx)
5376  elif sz == 1:
5377  return self.get(0)
5378  else:
5379  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5380 
5381 #########################################
5382 #
5383 # AST Vector
5384 #
5385 #########################################
5386 class AstVector(Z3PPObject):
5387  """A collection (vector) of ASTs."""
5388 
5389  def __init__(self, v=None, ctx=None):
5390  self.vector = None
5391  if v is None:
5392  self.ctx = _get_ctx(ctx)
5393  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5394  else:
5395  self.vector = v
5396  assert ctx is not None
5397  self.ctx = ctx
5398  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5399 
5400  def __deepcopy__(self, memo={}):
5401  return AstVector(self.vector, self.ctx)
5402 
5403  def __del__(self):
5404  if self.vector is not None and self.ctx.ref() is not None:
5405  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5406 
5407  def __len__(self):
5408  """Return the size of the vector `self`.
5409 
5410  >>> A = AstVector()
5411  >>> len(A)
5412  0
5413  >>> A.push(Int('x'))
5414  >>> A.push(Int('x'))
5415  >>> len(A)
5416  2
5417  """
5418  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5419 
5420  def __getitem__(self, i):
5421  """Return the AST at position `i`.
5422 
5423  >>> A = AstVector()
5424  >>> A.push(Int('x') + 1)
5425  >>> A.push(Int('y'))
5426  >>> A[0]
5427  x + 1
5428  >>> A[1]
5429  y
5430  """
5431 
5432  if isinstance(i, int):
5433  if i < 0:
5434  i += self.__len__()
5435 
5436  if i >= self.__len__():
5437  raise IndexError
5438  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5439 
5440  elif isinstance(i, slice):
5441  return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5442 
5443 
5444  def __setitem__(self, i, v):
5445  """Update AST at position `i`.
5446 
5447  >>> A = AstVector()
5448  >>> A.push(Int('x') + 1)
5449  >>> A.push(Int('y'))
5450  >>> A[0]
5451  x + 1
5452  >>> A[0] = Int('x')
5453  >>> A[0]
5454  x
5455  """
5456  if i >= self.__len__():
5457  raise IndexError
5458  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5459 
5460  def push(self, v):
5461  """Add `v` in the end of the vector.
5462 
5463  >>> A = AstVector()
5464  >>> len(A)
5465  0
5466  >>> A.push(Int('x'))
5467  >>> len(A)
5468  1
5469  """
5470  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5471 
5472  def resize(self, sz):
5473  """Resize the vector to `sz` elements.
5474 
5475  >>> A = AstVector()
5476  >>> A.resize(10)
5477  >>> len(A)
5478  10
5479  >>> for i in range(10): A[i] = Int('x')
5480  >>> A[5]
5481  x
5482  """
5483  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5484 
5485  def __contains__(self, item):
5486  """Return `True` if the vector contains `item`.
5487 
5488  >>> x = Int('x')
5489  >>> A = AstVector()
5490  >>> x in A
5491  False
5492  >>> A.push(x)
5493  >>> x in A
5494  True
5495  >>> (x+1) in A
5496  False
5497  >>> A.push(x+1)
5498  >>> (x+1) in A
5499  True
5500  >>> A
5501  [x, x + 1]
5502  """
5503  for elem in self:
5504  if elem.eq(item):
5505  return True
5506  return False
5507 
5508  def translate(self, other_ctx):
5509  """Copy vector `self` to context `other_ctx`.
5510 
5511  >>> x = Int('x')
5512  >>> A = AstVector()
5513  >>> A.push(x)
5514  >>> c2 = Context()
5515  >>> B = A.translate(c2)
5516  >>> B
5517  [x]
5518  """
5519  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5520 
5521  def __copy__(self):
5522  return self.translate(self.ctx)
5523 
5524  def __deepcopy__(self):
5525  return self.translate(self.ctx)
5526 
5527  def __repr__(self):
5528  return obj_to_string(self)
5529 
5530  def sexpr(self):
5531  """Return a textual representation of the s-expression representing the vector."""
5532  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5533 
5534 #########################################
5535 #
5536 # AST Map
5537 #
5538 #########################################
5539 class AstMap:
5540  """A mapping from ASTs to ASTs."""
5541 
5542  def __init__(self, m=None, ctx=None):
5543  self.map = None
5544  if m is None:
5545  self.ctx = _get_ctx(ctx)
5546  self.map = Z3_mk_ast_map(self.ctx.ref())
5547  else:
5548  self.map = m
5549  assert ctx is not None
5550  self.ctx = ctx
5551  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5552 
5553  def __deepcopy__(self, memo={}):
5554  return AstMap(self.map, self.ctx)
5555 
5556  def __del__(self):
5557  if self.map is not None and self.ctx.ref() is not None:
5558  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5559 
5560  def __len__(self):
5561  """Return the size of the map.
5562 
5563  >>> M = AstMap()
5564  >>> len(M)
5565  0
5566  >>> x = Int('x')
5567  >>> M[x] = IntVal(1)
5568  >>> len(M)
5569  1
5570  """
5571  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5572 
5573  def __contains__(self, key):
5574  """Return `True` if the map contains key `key`.
5575 
5576  >>> M = AstMap()
5577  >>> x = Int('x')
5578  >>> M[x] = x + 1
5579  >>> x in M
5580  True
5581  >>> x+1 in M
5582  False
5583  """
5584  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5585 
5586  def __getitem__(self, key):
5587  """Retrieve the value associated with key `key`.
5588 
5589  >>> M = AstMap()
5590  >>> x = Int('x')
5591  >>> M[x] = x + 1
5592  >>> M[x]
5593  x + 1
5594  """
5595  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5596 
5597  def __setitem__(self, k, v):
5598  """Add/Update key `k` with value `v`.
5599 
5600  >>> M = AstMap()
5601  >>> x = Int('x')
5602  >>> M[x] = x + 1
5603  >>> len(M)
5604  1
5605  >>> M[x]
5606  x + 1
5607  >>> M[x] = IntVal(1)
5608  >>> M[x]
5609  1
5610  """
5611  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5612 
5613  def __repr__(self):
5614  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5615 
5616  def erase(self, k):
5617  """Remove the entry associated with key `k`.
5618 
5619  >>> M = AstMap()
5620  >>> x = Int('x')
5621  >>> M[x] = x + 1
5622  >>> len(M)
5623  1
5624  >>> M.erase(x)
5625  >>> len(M)
5626  0
5627  """
5628  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5629 
5630  def reset(self):
5631  """Remove all entries from the map.
5632 
5633  >>> M = AstMap()
5634  >>> x = Int('x')
5635  >>> M[x] = x + 1
5636  >>> M[x+x] = IntVal(1)
5637  >>> len(M)
5638  2
5639  >>> M.reset()
5640  >>> len(M)
5641  0
5642  """
5643  Z3_ast_map_reset(self.ctx.ref(), self.map)
5644 
5645  def keys(self):
5646  """Return an AstVector containing all keys in the map.
5647 
5648  >>> M = AstMap()
5649  >>> x = Int('x')
5650  >>> M[x] = x + 1
5651  >>> M[x+x] = IntVal(1)
5652  >>> M.keys()
5653  [x, x + x]
5654  """
5655  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5656 
5657 #########################################
5658 #
5659 # Model
5660 #
5661 #########################################
5662 
5663 class FuncEntry:
5664  """Store the value of the interpretation of a function in a particular point."""
5665 
5666  def __init__(self, entry, ctx):
5667  self.entry = entry
5668  self.ctx = ctx
5669  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5670 
5671  def __deepcopy__(self, memo={}):
5672  return FuncEntry(self.entry, self.ctx)
5673 
5674  def __del__(self):
5675  if self.ctx.ref() is not None:
5676  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5677 
5678  def num_args(self):
5679  """Return the number of arguments in the given entry.
5680 
5681  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5682  >>> s = Solver()
5683  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5684  >>> s.check()
5685  sat
5686  >>> m = s.model()
5687  >>> f_i = m[f]
5688  >>> f_i.num_entries()
5689  1
5690  >>> e = f_i.entry(0)
5691  >>> e.num_args()
5692  2
5693  """
5694  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5695 
5696  def arg_value(self, idx):
5697  """Return the value of argument `idx`.
5698 
5699  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5700  >>> s = Solver()
5701  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5702  >>> s.check()
5703  sat
5704  >>> m = s.model()
5705  >>> f_i = m[f]
5706  >>> f_i.num_entries()
5707  1
5708  >>> e = f_i.entry(0)
5709  >>> e
5710  [1, 2, 20]
5711  >>> e.num_args()
5712  2
5713  >>> e.arg_value(0)
5714  1
5715  >>> e.arg_value(1)
5716  2
5717  >>> try:
5718  ... e.arg_value(2)
5719  ... except IndexError:
5720  ... print("index error")
5721  index error
5722  """
5723  if idx >= self.num_args():
5724  raise IndexError
5725  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5726 
5727  def value(self):
5728  """Return the value of the function at point `self`.
5729 
5730  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5731  >>> s = Solver()
5732  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5733  >>> s.check()
5734  sat
5735  >>> m = s.model()
5736  >>> f_i = m[f]
5737  >>> f_i.num_entries()
5738  1
5739  >>> e = f_i.entry(0)
5740  >>> e
5741  [1, 2, 20]
5742  >>> e.num_args()
5743  2
5744  >>> e.value()
5745  20
5746  """
5747  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5748 
5749  def as_list(self):
5750  """Return entry `self` as a Python list.
5751  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5752  >>> s = Solver()
5753  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5754  >>> s.check()
5755  sat
5756  >>> m = s.model()
5757  >>> f_i = m[f]
5758  >>> f_i.num_entries()
5759  1
5760  >>> e = f_i.entry(0)
5761  >>> e.as_list()
5762  [1, 2, 20]
5763  """
5764  args = [ self.arg_value(i) for i in range(self.num_args())]
5765  args.append(self.value())
5766  return args
5767 
5768  def __repr__(self):
5769  return repr(self.as_list())
5770 
5771 class FuncInterp(Z3PPObject):
5772  """Stores the interpretation of a function in a Z3 model."""
5773 
5774  def __init__(self, f, ctx):
5775  self.f = f
5776  self.ctx = ctx
5777  if self.f is not None:
5778  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5779 
5780  def __deepcopy__(self, memo={}):
5781  return FuncInterp(self.f, self.ctx)
5782 
5783  def __del__(self):
5784  if self.f is not None and self.ctx.ref() is not None:
5785  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5786 
5787  def else_value(self):
5788  """
5789  Return the `else` value for a function interpretation.
5790  Return None if Z3 did not specify the `else` value for
5791  this object.
5792 
5793  >>> f = Function('f', IntSort(), IntSort())
5794  >>> s = Solver()
5795  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5796  >>> s.check()
5797  sat
5798  >>> m = s.model()
5799  >>> m[f]
5800  [2 -> 0, else -> 1]
5801  >>> m[f].else_value()
5802  1
5803  """
5804  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5805  if r:
5806  return _to_expr_ref(r, self.ctx)
5807  else:
5808  return None
5809 
5810  def num_entries(self):
5811  """Return the number of entries/points in the function interpretation `self`.
5812 
5813  >>> f = Function('f', IntSort(), IntSort())
5814  >>> s = Solver()
5815  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5816  >>> s.check()
5817  sat
5818  >>> m = s.model()
5819  >>> m[f]
5820  [2 -> 0, else -> 1]
5821  >>> m[f].num_entries()
5822  1
5823  """
5824  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5825 
5826  def arity(self):
5827  """Return the number of arguments for each entry in the function interpretation `self`.
5828 
5829  >>> f = Function('f', IntSort(), IntSort())
5830  >>> s = Solver()
5831  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5832  >>> s.check()
5833  sat
5834  >>> m = s.model()
5835  >>> m[f].arity()
5836  1
5837  """
5838  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5839 
5840  def entry(self, idx):
5841  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5842 
5843  >>> f = Function('f', IntSort(), IntSort())
5844  >>> s = Solver()
5845  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5846  >>> s.check()
5847  sat
5848  >>> m = s.model()
5849  >>> m[f]
5850  [2 -> 0, else -> 1]
5851  >>> m[f].num_entries()
5852  1
5853  >>> m[f].entry(0)
5854  [2, 0]
5855  """
5856  if idx >= self.num_entries():
5857  raise IndexError
5858  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5859 
5860  def translate(self, other_ctx):
5861  """Copy model 'self' to context 'other_ctx'.
5862  """
5863  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5864 
5865  def __copy__(self):
5866  return self.translate(self.ctx)
5867 
5868  def __deepcopy__(self):
5869  return self.translate(self.ctx)
5870 
5871  def as_list(self):
5872  """Return the function interpretation as a Python list.
5873  >>> f = Function('f', IntSort(), IntSort())
5874  >>> s = Solver()
5875  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5876  >>> s.check()
5877  sat
5878  >>> m = s.model()
5879  >>> m[f]
5880  [2 -> 0, else -> 1]
5881  >>> m[f].as_list()
5882  [[2, 0], 1]
5883  """
5884  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5885  r.append(self.else_value())
5886  return r
5887 
5888  def __repr__(self):
5889  return obj_to_string(self)
5890 
5891 class ModelRef(Z3PPObject):
5892  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5893 
5894  def __init__(self, m, ctx):
5895  assert ctx is not None
5896  self.model = m
5897  self.ctx = ctx
5898  Z3_model_inc_ref(self.ctx.ref(), self.model)
5899 
5900  def __del__(self):
5901  if self.ctx.ref() is not None:
5902  Z3_model_dec_ref(self.ctx.ref(), self.model)
5903 
5904  def __repr__(self):
5905  return obj_to_string(self)
5906 
5907  def sexpr(self):
5908  """Return a textual representation of the s-expression representing the model."""
5909  return Z3_model_to_string(self.ctx.ref(), self.model)
5910 
5911  def eval(self, t, model_completion=False):
5912  """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`.
5913 
5914  >>> x = Int('x')
5915  >>> s = Solver()
5916  >>> s.add(x > 0, x < 2)
5917  >>> s.check()
5918  sat
5919  >>> m = s.model()
5920  >>> m.eval(x + 1)
5921  2
5922  >>> m.eval(x == 1)
5923  True
5924  >>> y = Int('y')
5925  >>> m.eval(y + x)
5926  1 + y
5927  >>> m.eval(y)
5928  y
5929  >>> m.eval(y, model_completion=True)
5930  0
5931  >>> # Now, m contains an interpretation for y
5932  >>> m.eval(y + x)
5933  1
5934  """
5935  r = (Ast * 1)()
5936  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5937  return _to_expr_ref(r[0], self.ctx)
5938  raise Z3Exception("failed to evaluate expression in the model")
5939 
5940  def evaluate(self, t, model_completion=False):
5941  """Alias for `eval`.
5942 
5943  >>> x = Int('x')
5944  >>> s = Solver()
5945  >>> s.add(x > 0, x < 2)
5946  >>> s.check()
5947  sat
5948  >>> m = s.model()
5949  >>> m.evaluate(x + 1)
5950  2
5951  >>> m.evaluate(x == 1)
5952  True
5953  >>> y = Int('y')
5954  >>> m.evaluate(y + x)
5955  1 + y
5956  >>> m.evaluate(y)
5957  y
5958  >>> m.evaluate(y, model_completion=True)
5959  0
5960  >>> # Now, m contains an interpretation for y
5961  >>> m.evaluate(y + x)
5962  1
5963  """
5964  return self.eval(t, model_completion)
5965 
5966  def __len__(self):
5967  """Return the number of constant and function declarations in the model `self`.
5968 
5969  >>> f = Function('f', IntSort(), IntSort())
5970  >>> x = Int('x')
5971  >>> s = Solver()
5972  >>> s.add(x > 0, f(x) != x)
5973  >>> s.check()
5974  sat
5975  >>> m = s.model()
5976  >>> len(m)
5977  2
5978  """
5979  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5980 
5981  def get_interp(self, decl):
5982  """Return the interpretation for a given declaration or constant.
5983 
5984  >>> f = Function('f', IntSort(), IntSort())
5985  >>> x = Int('x')
5986  >>> s = Solver()
5987  >>> s.add(x > 0, x < 2, f(x) == 0)
5988  >>> s.check()
5989  sat
5990  >>> m = s.model()
5991  >>> m[x]
5992  1
5993  >>> m[f]
5994  [else -> 0]
5995  """
5996  if __debug__:
5997  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
5998  if is_const(decl):
5999  decl = decl.decl()
6000  try:
6001  if decl.arity() == 0:
6002  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6003  if _r.value is None:
6004  return None
6005  r = _to_expr_ref(_r, self.ctx)
6006  if is_as_array(r):
6007  return self.get_interp(get_as_array_func(r))
6008  else:
6009  return r
6010  else:
6011  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6012  except Z3Exception:
6013  return None
6014 
6015  def num_sorts(self):
6016  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6017 
6018  >>> A = DeclareSort('A')
6019  >>> a, b = Consts('a b', A)
6020  >>> s = Solver()
6021  >>> s.add(a != b)
6022  >>> s.check()
6023  sat
6024  >>> m = s.model()
6025  >>> m.num_sorts()
6026  1
6027  """
6028  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6029 
6030  def get_sort(self, idx):
6031  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6032 
6033  >>> A = DeclareSort('A')
6034  >>> B = DeclareSort('B')
6035  >>> a1, a2 = Consts('a1 a2', A)
6036  >>> b1, b2 = Consts('b1 b2', B)
6037  >>> s = Solver()
6038  >>> s.add(a1 != a2, b1 != b2)
6039  >>> s.check()
6040  sat
6041  >>> m = s.model()
6042  >>> m.num_sorts()
6043  2
6044  >>> m.get_sort(0)
6045  A
6046  >>> m.get_sort(1)
6047  B
6048  """
6049  if idx >= self.num_sorts():
6050  raise IndexError
6051  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6052 
6053  def sorts(self):
6054  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6055 
6056  >>> A = DeclareSort('A')
6057  >>> B = DeclareSort('B')
6058  >>> a1, a2 = Consts('a1 a2', A)
6059  >>> b1, b2 = Consts('b1 b2', B)
6060  >>> s = Solver()
6061  >>> s.add(a1 != a2, b1 != b2)
6062  >>> s.check()
6063  sat
6064  >>> m = s.model()
6065  >>> m.sorts()
6066  [A, B]
6067  """
6068  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
6069 
6070  def get_universe(self, s):
6071  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6072 
6073  >>> A = DeclareSort('A')
6074  >>> a, b = Consts('a b', A)
6075  >>> s = Solver()
6076  >>> s.add(a != b)
6077  >>> s.check()
6078  sat
6079  >>> m = s.model()
6080  >>> m.get_universe(A)
6081  [A!val!0, A!val!1]
6082  """
6083  if __debug__:
6084  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6085  try:
6086  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6087  except Z3Exception:
6088  return None
6089 
6090  def __getitem__(self, idx):
6091  """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.
6092 
6093  The elements can be retrieved using position or the actual declaration.
6094 
6095  >>> f = Function('f', IntSort(), IntSort())
6096  >>> x = Int('x')
6097  >>> s = Solver()
6098  >>> s.add(x > 0, x < 2, f(x) == 0)
6099  >>> s.check()
6100  sat
6101  >>> m = s.model()
6102  >>> len(m)
6103  2
6104  >>> m[0]
6105  x
6106  >>> m[1]
6107  f
6108  >>> m[x]
6109  1
6110  >>> m[f]
6111  [else -> 0]
6112  >>> for d in m: print("%s -> %s" % (d, m[d]))
6113  x -> 1
6114  f -> [else -> 0]
6115  """
6116  if _is_int(idx):
6117  if idx >= len(self):
6118  raise IndexError
6119  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6120  if (idx < num_consts):
6121  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6122  else:
6123  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6124  if isinstance(idx, FuncDeclRef):
6125  return self.get_interp(idx)
6126  if is_const(idx):
6127  return self.get_interp(idx.decl())
6128  if isinstance(idx, SortRef):
6129  return self.get_universe(idx)
6130  if __debug__:
6131  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6132  return None
6133 
6134  def decls(self):
6135  """Return a list with all symbols that have an interpretation in the model `self`.
6136  >>> f = Function('f', IntSort(), IntSort())
6137  >>> x = Int('x')
6138  >>> s = Solver()
6139  >>> s.add(x > 0, x < 2, f(x) == 0)
6140  >>> s.check()
6141  sat
6142  >>> m = s.model()
6143  >>> m.decls()
6144  [x, f]
6145  """
6146  r = []
6147  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6148  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6149  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6150  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6151  return r
6152 
6153  def translate(self, target):
6154  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6155  """
6156  if __debug__:
6157  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6158  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6159  return Model(model, target)
6160 
6161  def __copy__(self):
6162  return self.translate(self.ctx)
6163 
6164  def __deepcopy__(self):
6165  return self.translate(self.ctx)
6166 
6167 def Model(ctx = None):
6168  ctx = _get_ctx(ctx)
6169  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6170 
6171 def is_as_array(n):
6172  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6173  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6174 
6175 def get_as_array_func(n):
6176  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6177  if __debug__:
6178  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6179  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6180 
6181 #########################################
6182 #
6183 # Statistics
6184 #
6185 #########################################
6186 class Statistics:
6187  """Statistics for `Solver.check()`."""
6188 
6189  def __init__(self, stats, ctx):
6190  self.stats = stats
6191  self.ctx = ctx
6192  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6193 
6194  def __deepcopy__(self, memo={}):
6195  return Statistics(self.stats, self.ctx)
6196 
6197  def __del__(self):
6198  if self.ctx.ref() is not None:
6199  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6200 
6201  def __repr__(self):
6202  if in_html_mode():
6203  out = io.StringIO()
6204  even = True
6205  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6206  for k, v in self:
6207  if even:
6208  out.write(u('<tr style="background-color:#CFCFCF">'))
6209  even = False
6210  else:
6211  out.write(u('<tr>'))
6212  even = True
6213  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
6214  out.write(u('</table>'))
6215  return out.getvalue()
6216  else:
6217  return Z3_stats_to_string(self.ctx.ref(), self.stats)
6218 
6219  def __len__(self):
6220  """Return the number of statistical counters.
6221 
6222  >>> x = Int('x')
6223  >>> s = Then('simplify', 'nlsat').solver()
6224  >>> s.add(x > 0)
6225  >>> s.check()
6226  sat
6227  >>> st = s.statistics()
6228  >>> len(st)
6229  6
6230  """
6231  return int(Z3_stats_size(self.ctx.ref(), self.stats))
6232 
6233  def __getitem__(self, idx):
6234  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6235 
6236  >>> x = Int('x')
6237  >>> s = Then('simplify', 'nlsat').solver()
6238  >>> s.add(x > 0)
6239  >>> s.check()
6240  sat
6241  >>> st = s.statistics()
6242  >>> len(st)
6243  6
6244  >>> st[0]
6245  ('nlsat propagations', 2)
6246  >>> st[1]
6247  ('nlsat stages', 2)
6248  """
6249  if idx >= len(self):
6250  raise IndexError
6251  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6252  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6253  else:
6254  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6255  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6256 
6257  def keys(self):
6258  """Return the list of statistical counters.
6259 
6260  >>> x = Int('x')
6261  >>> s = Then('simplify', 'nlsat').solver()
6262  >>> s.add(x > 0)
6263  >>> s.check()
6264  sat
6265  >>> st = s.statistics()
6266  """
6267  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6268 
6269  def get_key_value(self, key):
6270  """Return the value of a particular statistical counter.
6271 
6272  >>> x = Int('x')
6273  >>> s = Then('simplify', 'nlsat').solver()
6274  >>> s.add(x > 0)
6275  >>> s.check()
6276  sat
6277  >>> st = s.statistics()
6278  >>> st.get_key_value('nlsat propagations')
6279  2
6280  """
6281  for idx in range(len(self)):
6282  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6283  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6284  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6285  else:
6286  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6287  raise Z3Exception("unknown key")
6288 
6289  def __getattr__(self, name):
6290  """Access the value of statistical using attributes.
6291 
6292  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6293  we should use '_' (e.g., 'nlsat_propagations').
6294 
6295  >>> x = Int('x')
6296  >>> s = Then('simplify', 'nlsat').solver()
6297  >>> s.add(x > 0)
6298  >>> s.check()
6299  sat
6300  >>> st = s.statistics()
6301  >>> st.nlsat_propagations
6302  2
6303  >>> st.nlsat_stages
6304  2
6305  """
6306  key = name.replace('_', ' ')
6307  try:
6308  return self.get_key_value(key)
6309  except Z3Exception:
6310  raise AttributeError
6311 
6312 #########################################
6313 #
6314 # Solver
6315 #
6316 #########################################
6317 class CheckSatResult:
6318  """Represents the result of a satisfiability check: sat, unsat, unknown.
6319 
6320  >>> s = Solver()
6321  >>> s.check()
6322  sat
6323  >>> r = s.check()
6324  >>> isinstance(r, CheckSatResult)
6325  True
6326  """
6327 
6328  def __init__(self, r):
6329  self.r = r
6330 
6331  def __deepcopy__(self, memo={}):
6332  return CheckSatResult(self.r)
6333 
6334  def __eq__(self, other):
6335  return isinstance(other, CheckSatResult) and self.r == other.r
6336 
6337  def __ne__(self, other):
6338  return not self.__eq__(other)
6339 
6340  def __repr__(self):
6341  if in_html_mode():
6342  if self.r == Z3_L_TRUE:
6343  return "<b>sat</b>"
6344  elif self.r == Z3_L_FALSE:
6345  return "<b>unsat</b>"
6346  else:
6347  return "<b>unknown</b>"
6348  else:
6349  if self.r == Z3_L_TRUE:
6350  return "sat"
6351  elif self.r == Z3_L_FALSE:
6352  return "unsat"
6353  else:
6354  return "unknown"
6355 
6356 sat = CheckSatResult(Z3_L_TRUE)
6357 unsat = CheckSatResult(Z3_L_FALSE)
6358 unknown = CheckSatResult(Z3_L_UNDEF)
6359 
6360 class Solver(Z3PPObject):
6361  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6362 
6363  def __init__(self, solver=None, ctx=None):
6364  assert solver is None or ctx is not None
6365  self.ctx = _get_ctx(ctx)
6366  self.backtrack_level = 4000000000
6367  self.solver = None
6368  if solver is None:
6369  self.solver = Z3_mk_solver(self.ctx.ref())
6370  else:
6371  self.solver = solver
6372  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6373 
6374  def __del__(self):
6375  if self.solver is not None and self.ctx.ref() is not None:
6376  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6377 
6378  def set(self, *args, **keys):
6379  """Set a configuration option. The method `help()` return a string containing all available options.
6380 
6381  >>> s = Solver()
6382  >>> # The option MBQI can be set using three different approaches.
6383  >>> s.set(mbqi=True)
6384  >>> s.set('MBQI', True)
6385  >>> s.set(':mbqi', True)
6386  """
6387  p = args2params(args, keys, self.ctx)
6388  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6389 
6390  def push(self):
6391  """Create a backtracking point.
6392 
6393  >>> x = Int('x')
6394  >>> s = Solver()
6395  >>> s.add(x > 0)
6396  >>> s
6397  [x > 0]
6398  >>> s.push()
6399  >>> s.add(x < 1)
6400  >>> s
6401  [x > 0, x < 1]
6402  >>> s.check()
6403  unsat
6404  >>> s.pop()
6405  >>> s.check()
6406  sat
6407  >>> s
6408  [x > 0]
6409  """
6410  Z3_solver_push(self.ctx.ref(), self.solver)
6411 
6412  def pop(self, num=1):
6413  """Backtrack \c num backtracking points.
6414 
6415  >>> x = Int('x')
6416  >>> s = Solver()
6417  >>> s.add(x > 0)
6418  >>> s
6419  [x > 0]
6420  >>> s.push()
6421  >>> s.add(x < 1)
6422  >>> s
6423  [x > 0, x < 1]
6424  >>> s.check()
6425  unsat
6426  >>> s.pop()
6427  >>> s.check()
6428  sat
6429  >>> s
6430  [x > 0]
6431  """
6432  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6433 
6434  def num_scopes(self):
6435  """Return the current number of backtracking points.
6436 
6437  >>> s = Solver()
6438  >>> s.num_scopes()
6439  0L
6440  >>> s.push()
6441  >>> s.num_scopes()
6442  1L
6443  >>> s.push()
6444  >>> s.num_scopes()
6445  2L
6446  >>> s.pop()
6447  >>> s.num_scopes()
6448  1L
6449  """
6450  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6451 
6452  def reset(self):
6453  """Remove all asserted constraints and backtracking points created using `push()`.
6454 
6455  >>> x = Int('x')
6456  >>> s = Solver()
6457  >>> s.add(x > 0)
6458  >>> s
6459  [x > 0]
6460  >>> s.reset()
6461  >>> s
6462  []
6463  """
6464  Z3_solver_reset(self.ctx.ref(), self.solver)
6465 
6466  def assert_exprs(self, *args):
6467  """Assert constraints into the solver.
6468 
6469  >>> x = Int('x')
6470  >>> s = Solver()
6471  >>> s.assert_exprs(x > 0, x < 2)
6472  >>> s
6473  [x > 0, x < 2]
6474  """
6475  args = _get_args(args)
6476  s = BoolSort(self.ctx)
6477  for arg in args:
6478  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6479  for f in arg:
6480  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6481  else:
6482  arg = s.cast(arg)
6483  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6484 
6485  def add(self, *args):
6486  """Assert constraints into the solver.
6487 
6488  >>> x = Int('x')
6489  >>> s = Solver()
6490  >>> s.add(x > 0, x < 2)
6491  >>> s
6492  [x > 0, x < 2]
6493  """
6494  self.assert_exprs(*args)
6495 
6496  def __iadd__(self, fml):
6497  self.add(fml)
6498  return self
6499 
6500  def append(self, *args):
6501  """Assert constraints into the solver.
6502 
6503  >>> x = Int('x')
6504  >>> s = Solver()
6505  >>> s.append(x > 0, x < 2)
6506  >>> s
6507  [x > 0, x < 2]
6508  """
6509  self.assert_exprs(*args)
6510 
6511  def insert(self, *args):
6512  """Assert constraints into the solver.
6513 
6514  >>> x = Int('x')
6515  >>> s = Solver()
6516  >>> s.insert(x > 0, x < 2)
6517  >>> s
6518  [x > 0, x < 2]
6519  """
6520  self.assert_exprs(*args)
6521 
6522  def assert_and_track(self, a, p):
6523  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6524 
6525  If `p` is a string, it will be automatically converted into a Boolean constant.
6526 
6527  >>> x = Int('x')
6528  >>> p3 = Bool('p3')
6529  >>> s = Solver()
6530  >>> s.set(unsat_core=True)
6531  >>> s.assert_and_track(x > 0, 'p1')
6532  >>> s.assert_and_track(x != 1, 'p2')
6533  >>> s.assert_and_track(x < 0, p3)
6534  >>> print(s.check())
6535  unsat
6536  >>> c = s.unsat_core()
6537  >>> len(c)
6538  2
6539  >>> Bool('p1') in c
6540  True
6541  >>> Bool('p2') in c
6542  False
6543  >>> p3 in c
6544  True
6545  """
6546  if isinstance(p, str):
6547  p = Bool(p, self.ctx)
6548  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6549  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6550  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6551 
6552  def check(self, *assumptions):
6553  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6554 
6555  >>> x = Int('x')
6556  >>> s = Solver()
6557  >>> s.check()
6558  sat
6559  >>> s.add(x > 0, x < 2)
6560  >>> s.check()
6561  sat
6562  >>> s.model().eval(x)
6563  1
6564  >>> s.add(x < 1)
6565  >>> s.check()
6566  unsat
6567  >>> s.reset()
6568  >>> s.add(2**x == 4)
6569  >>> s.check()
6570  unknown
6571  """
6572  assumptions = _get_args(assumptions)
6573  num = len(assumptions)
6574  _assumptions = (Ast * num)()
6575  for i in range(num):
6576  _assumptions[i] = assumptions[i].as_ast()
6577  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6578  return CheckSatResult(r)
6579 
6580  def model(self):
6581  """Return a model for the last `check()`.
6582 
6583  This function raises an exception if
6584  a model is not available (e.g., last `check()` returned unsat).
6585 
6586  >>> s = Solver()
6587  >>> a = Int('a')
6588  >>> s.add(a + 2 == 0)
6589  >>> s.check()
6590  sat
6591  >>> s.model()
6592  [a = -2]
6593  """
6594  try:
6595  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6596  except Z3Exception:
6597  raise Z3Exception("model is not available")
6598 
6599  def unsat_core(self):
6600  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6601 
6602  These are the assumptions Z3 used in the unsatisfiability proof.
6603  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6604  They may be also used to "retract" assumptions. Note that, assumptions are not really
6605  "soft constraints", but they can be used to implement them.
6606 
6607  >>> p1, p2, p3 = Bools('p1 p2 p3')
6608  >>> x, y = Ints('x y')
6609  >>> s = Solver()
6610  >>> s.add(Implies(p1, x > 0))
6611  >>> s.add(Implies(p2, y > x))
6612  >>> s.add(Implies(p2, y < 1))
6613  >>> s.add(Implies(p3, y > -3))
6614  >>> s.check(p1, p2, p3)
6615  unsat
6616  >>> core = s.unsat_core()
6617  >>> len(core)
6618  2
6619  >>> p1 in core
6620  True
6621  >>> p2 in core
6622  True
6623  >>> p3 in core
6624  False
6625  >>> # "Retracting" p2
6626  >>> s.check(p1, p3)
6627  sat
6628  """
6629  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6630 
6631  def consequences(self, assumptions, variables):
6632  """Determine fixed values for the variables based on the solver state and assumptions.
6633  >>> s = Solver()
6634  >>> a, b, c, d = Bools('a b c d')
6635  >>> s.add(Implies(a,b), Implies(b, c))
6636  >>> s.consequences([a],[b,c,d])
6637  (sat, [Implies(a, b), Implies(a, c)])
6638  >>> s.consequences([Not(c),d],[a,b,c,d])
6639  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6640  """
6641  if isinstance(assumptions, list):
6642  _asms = AstVector(None, self.ctx)
6643  for a in assumptions:
6644  _asms.push(a)
6645  assumptions = _asms
6646  if isinstance(variables, list):
6647  _vars = AstVector(None, self.ctx)
6648  for a in variables:
6649  _vars.push(a)
6650  variables = _vars
6651  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6652  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6653  consequences = AstVector(None, self.ctx)
6654  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6655  sz = len(consequences)
6656  consequences = [ consequences[i] for i in range(sz) ]
6657  return CheckSatResult(r), consequences
6658 
6659  def from_file(self, filename):
6660  """Parse assertions from a file"""
6661  try:
6662  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6663  except Z3Exception as e:
6664  _handle_parse_error(e, self.ctx)
6665 
6666  def from_string(self, s):
6667  """Parse assertions from a string"""
6668  try:
6669  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6670  except Z3Exception as e:
6671  _handle_parse_error(e, self.ctx)
6672 
6673  def cube(self, vars = None):
6674  """Get set of cubes
6675  The method takes an optional set of variables that restrict which
6676  variables may be used as a starting point for cubing.
6677  If vars is not None, then the first case split is based on a variable in
6678  this set.
6679  """
6680  self.cube_vs = AstVector(None, self.ctx)
6681  if vars is not None:
6682  for v in vars:
6683  self.cube_vs.push(v)
6684  while True:
6685  lvl = self.backtrack_level
6686  self.backtrack_level = 4000000000
6687  r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
6688  if (len(r) == 1 and is_false(r[0])):
6689  return
6690  yield r
6691  if (len(r) == 0):
6692  return
6693 
6694  def cube_vars(self):
6695  """Access the set of variables that were touched by the most recently generated cube.
6696  This set of variables can be used as a starting point for additional cubes.
6697  The idea is that variables that appear in clauses that are reduced by the most recent
6698  cube are likely more useful to cube on."""
6699  return self.cube_vs
6700 
6701  def proof(self):
6702  """Return a proof for the last `check()`. Proof construction must be enabled."""
6703  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6704 
6705  def assertions(self):
6706  """Return an AST vector containing all added constraints.
6707 
6708  >>> s = Solver()
6709  >>> s.assertions()
6710  []
6711  >>> a = Int('a')
6712  >>> s.add(a > 0)
6713  >>> s.add(a < 10)
6714  >>> s.assertions()
6715  [a > 0, a < 10]
6716  """
6717  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6718 
6719  def units(self):
6720  """Return an AST vector containing all currently inferred units.
6721  """
6722  return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
6723 
6724  def non_units(self):
6725  """Return an AST vector containing all atomic formulas in solver state that are not units.
6726  """
6727  return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
6728 
6729  def statistics(self):
6730  """Return statistics for the last `check()`.
6731 
6732  >>> s = SimpleSolver()
6733  >>> x = Int('x')
6734  >>> s.add(x > 0)
6735  >>> s.check()
6736  sat
6737  >>> st = s.statistics()
6738  >>> st.get_key_value('final checks')
6739  1
6740  >>> len(st) > 0
6741  True
6742  >>> st[0] != 0
6743  True
6744  """
6745  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6746 
6747  def reason_unknown(self):
6748  """Return a string describing why the last `check()` returned `unknown`.
6749 
6750  >>> x = Int('x')
6751  >>> s = SimpleSolver()
6752  >>> s.add(2**x == 4)
6753  >>> s.check()
6754  unknown
6755  >>> s.reason_unknown()
6756  '(incomplete (theory arithmetic))'
6757  """
6758  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6759 
6760  def help(self):
6761  """Display a string describing all available options."""
6762  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6763 
6764  def param_descrs(self):
6765  """Return the parameter description set."""
6766  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6767 
6768  def __repr__(self):
6769  """Return a formatted string with all added constraints."""
6770  return obj_to_string(self)
6771 
6772  def translate(self, target):
6773  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6774 
6775  >>> c1 = Context()
6776  >>> c2 = Context()
6777  >>> s1 = Solver(ctx=c1)
6778  >>> s2 = s1.translate(c2)
6779  """
6780  if __debug__:
6781  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6782  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6783  return Solver(solver, target)
6784 
6785  def __copy__(self):
6786  return self.translate(self.ctx)
6787 
6788  def __deepcopy__(self):
6789  return self.translate(self.ctx)
6790 
6791  def sexpr(self):
6792  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6793 
6794  >>> x = Int('x')
6795  >>> s = Solver()
6796  >>> s.add(x > 0)
6797  >>> s.add(x < 2)
6798  >>> r = s.sexpr()
6799  """
6800  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6801 
6802  def to_smt2(self):
6803  """return SMTLIB2 formatted benchmark for solver's assertions"""
6804  es = self.assertions()
6805  sz = len(es)
6806  sz1 = sz
6807  if sz1 > 0:
6808  sz1 -= 1
6809  v = (Ast * sz1)()
6810  for i in range(sz1):
6811  v[i] = es[i].as_ast()
6812  if sz > 0:
6813  e = es[sz1].as_ast()
6814  else:
6815  e = BoolVal(True, self.ctx).as_ast()
6816  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6817 
6818 def SolverFor(logic, ctx=None):
6819  """Create a solver customized for the given logic.
6820 
6821  The parameter `logic` is a string. It should be contains
6822  the name of a SMT-LIB logic.
6823  See http://www.smtlib.org/ for the name of all available logics.
6824 
6825  >>> s = SolverFor("QF_LIA")
6826  >>> x = Int('x')
6827  >>> s.add(x > 0)
6828  >>> s.add(x < 2)
6829  >>> s.check()
6830  sat
6831  >>> s.model()
6832  [x = 1]
6833  """
6834  ctx = _get_ctx(ctx)
6835  logic = to_symbol(logic)
6836  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6837 
6838 def SimpleSolver(ctx=None):
6839  """Return a simple general purpose solver with limited amount of preprocessing.
6840 
6841  >>> s = SimpleSolver()
6842  >>> x = Int('x')
6843  >>> s.add(x > 0)
6844  >>> s.check()
6845  sat
6846  """
6847  ctx = _get_ctx(ctx)
6848  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6849 
6850 
6855 
6857  """Fixedpoint API provides methods for solving with recursive predicates"""
6858 
6859  def __init__(self, fixedpoint=None, ctx=None):
6860  assert fixedpoint is None or ctx is not None
6861  self.ctx = _get_ctx(ctx)
6862  self.fixedpoint = None
6863  if fixedpoint is None:
6864  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6865  else:
6866  self.fixedpoint = fixedpoint
6867  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6868  self.vars = []
6869 
6870  def __deepcopy__(self, memo={}):
6871  return FixedPoint(self.fixedpoint, self.ctx)
6872 
6873  def __del__(self):
6874  if self.fixedpoint is not None and self.ctx.ref() is not None:
6875  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6876 
6877  def set(self, *args, **keys):
6878  """Set a configuration option. The method `help()` return a string containing all available options.
6879  """
6880  p = args2params(args, keys, self.ctx)
6881  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6882 
6883  def help(self):
6884  """Display a string describing all available options."""
6885  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6886 
6887  def param_descrs(self):
6888  """Return the parameter description set."""
6889  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6890 
6891  def assert_exprs(self, *args):
6892  """Assert constraints as background axioms for the fixedpoint solver."""
6893  args = _get_args(args)
6894  s = BoolSort(self.ctx)
6895  for arg in args:
6896  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6897  for f in arg:
6898  f = self.abstract(f)
6899  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6900  else:
6901  arg = s.cast(arg)
6902  arg = self.abstract(arg)
6903  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6904 
6905  def add(self, *args):
6906  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6907  self.assert_exprs(*args)
6908 
6909  def __iadd__(self, fml):
6910  self.add(fml)
6911  return self
6912 
6913  def append(self, *args):
6914  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6915  self.assert_exprs(*args)
6916 
6917  def insert(self, *args):
6918  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6919  self.assert_exprs(*args)
6920 
6921  def add_rule(self, head, body = None, name = None):
6922  """Assert rules defining recursive predicates to the fixedpoint solver.
6923  >>> a = Bool('a')
6924  >>> b = Bool('b')
6925  >>> s = Fixedpoint()
6926  >>> s.register_relation(a.decl())
6927  >>> s.register_relation(b.decl())
6928  >>> s.fact(a)
6929  >>> s.rule(b, a)
6930  >>> s.query(b)
6931  sat
6932  """
6933  if name is None:
6934  name = ""
6935  name = to_symbol(name, self.ctx)
6936  if body is None:
6937  head = self.abstract(head)
6938  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6939  else:
6940  body = _get_args(body)
6941  f = self.abstract(Implies(And(body, self.ctx),head))
6942  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6943 
6944  def rule(self, head, body = None, name = None):
6945  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6946  self.add_rule(head, body, name)
6947 
6948  def fact(self, head, name = None):
6949  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6950  self.add_rule(head, None, name)
6951 
6952  def query(self, *query):
6953  """Query the fixedpoint engine whether formula is derivable.
6954  You can also pass an tuple or list of recursive predicates.
6955  """
6956  query = _get_args(query)
6957  sz = len(query)
6958  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6959  _decls = (FuncDecl * sz)()
6960  i = 0
6961  for q in query:
6962  _decls[i] = q.ast
6963  i = i + 1
6964  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6965  else:
6966  if sz == 1:
6967  query = query[0]
6968  else:
6969  query = And(query, self.ctx)
6970  query = self.abstract(query, False)
6971  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6972  return CheckSatResult(r)
6973 
6974  def query_from_lvl (self, lvl, *query):
6975  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
6976  """
6977  query = _get_args(query)
6978  sz = len(query)
6979  if sz >= 1 and isinstance(query[0], FuncDecl):
6980  _z3_assert (False, "unsupported")
6981  else:
6982  if sz == 1:
6983  query = query[0]
6984  else:
6985  query = And(query)
6986  query = self.abstract(query, False)
6987  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
6988  return CheckSatResult(r)
6989 
6990  def push(self):
6991  """create a backtracking point for added rules, facts and assertions"""
6992  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6993 
6994  def pop(self):
6995  """restore to previously created backtracking point"""
6996  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
6997 
6998  def update_rule(self, head, body, name):
6999  """update rule"""
7000  if name is None:
7001  name = ""
7002  name = to_symbol(name, self.ctx)
7003  body = _get_args(body)
7004  f = self.abstract(Implies(And(body, self.ctx),head))
7005  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7006 
7007  def get_answer(self):
7008  """Retrieve answer from last query call."""
7009  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7010  return _to_expr_ref(r, self.ctx)
7011 
7013  """Retrieve a ground cex from last query call."""
7014  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7015  return _to_expr_ref(r, self.ctx)
7016 
7018  """retrieve rules along the counterexample trace"""
7019  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7020 
7022  """retrieve rule names along the counterexample trace"""
7023  # this is a hack as I don't know how to return a list of symbols from C++;
7024  # obtain names as a single string separated by semicolons
7025  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7026  # split into individual names
7027  return names.split (';')
7028 
7029  def get_num_levels(self, predicate):
7030  """Retrieve number of levels used for predicate in PDR engine"""
7031  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7032 
7033  def get_cover_delta(self, level, predicate):
7034  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
7035  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7036  return _to_expr_ref(r, self.ctx)
7037 
7038  def add_cover(self, level, predicate, property):
7039  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
7040  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7041 
7042  def register_relation(self, *relations):
7043  """Register relation as recursive"""
7044  relations = _get_args(relations)
7045  for f in relations:
7046  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7047 
7048  def set_predicate_representation(self, f, *representations):
7049  """Control how relation is represented"""
7050  representations = _get_args(representations)
7051  representations = [to_symbol(s) for s in representations]
7052  sz = len(representations)
7053  args = (Symbol * sz)()
7054  for i in range(sz):
7055  args[i] = representations[i]
7056  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7057 
7058  def parse_string(self, s):
7059  """Parse rules and queries from a string"""
7060  try:
7061  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7062  except Z3Exception as e:
7063  _handle_parse_error(e, self.ctx)
7064 
7065  def parse_file(self, f):
7066  """Parse rules and queries from a file"""
7067  try:
7068  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7069  except Z3Exception as e:
7070  _handle_parse_error(e, self.ctx)
7071 
7072  def get_rules(self):
7073  """retrieve rules that have been added to fixedpoint context"""
7074  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7075 
7076  def get_assertions(self):
7077  """retrieve assertions that have been added to fixedpoint context"""
7078  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7079 
7080  def __repr__(self):
7081  """Return a formatted string with all added rules and constraints."""
7082  return self.sexpr()
7083 
7084  def sexpr(self):
7085  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7086  """
7087  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7088 
7089  def to_string(self, queries):
7090  """Return a formatted string (in Lisp-like format) with all added constraints.
7091  We say the string is in s-expression format.
7092  Include also queries.
7093  """
7094  args, len = _to_ast_array(queries)
7095  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7096 
7097  def statistics(self):
7098  """Return statistics for the last `query()`.
7099  """
7100  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7101 
7102  def reason_unknown(self):
7103  """Return a string describing why the last `query()` returned `unknown`.
7104  """
7105  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7106 
7107  def declare_var(self, *vars):
7108  """Add variable or several variables.
7109  The added variable or variables will be bound in the rules
7110  and queries
7111  """
7112  vars = _get_args(vars)
7113  for v in vars:
7114  self.vars += [v]
7115 
7116  def abstract(self, fml, is_forall=True):
7117  if self.vars == []:
7118  return fml
7119  if is_forall:
7120  return ForAll(self.vars, fml)
7121  else:
7122  return Exists(self.vars, fml)
7123 
7124 
7125 
7130 
7132  """Finite domain sort."""
7133 
7134  def size(self):
7135  """Return the size of the finite domain sort"""
7136  r = (ctypes.c_ulonglong * 1)()
7137  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7138  return r[0]
7139  else:
7140  raise Z3Exception("Failed to retrieve finite domain sort size")
7141 
7142 def FiniteDomainSort(name, sz, ctx=None):
7143  """Create a named finite domain sort of a given size sz"""
7144  if not isinstance(name, Symbol):
7145  name = to_symbol(name)
7146  ctx = _get_ctx(ctx)
7147  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7148 
7150  """Return True if `s` is a Z3 finite-domain sort.
7151 
7152  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7153  True
7154  >>> is_finite_domain_sort(IntSort())
7155  False
7156  """
7157  return isinstance(s, FiniteDomainSortRef)
7158 
7159 
7161  """Finite-domain expressions."""
7162 
7163  def sort(self):
7164  """Return the sort of the finite-domain expression `self`."""
7165  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7166 
7167  def as_string(self):
7168  """Return a Z3 floating point expression as a Python string."""
7169  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7170 
7172  """Return `True` if `a` is a Z3 finite-domain expression.
7173 
7174  >>> s = FiniteDomainSort('S', 100)
7175  >>> b = Const('b', s)
7176  >>> is_finite_domain(b)
7177  True
7178  >>> is_finite_domain(Int('x'))
7179  False
7180  """
7181  return isinstance(a, FiniteDomainRef)
7182 
7183 
7185  """Integer values."""
7186 
7187  def as_long(self):
7188  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7189 
7190  >>> s = FiniteDomainSort('S', 100)
7191  >>> v = FiniteDomainVal(3, s)
7192  >>> v
7193  3
7194  >>> v.as_long() + 1
7195  4
7196  """
7197  return int(self.as_string())
7198 
7199  def as_string(self):
7200  """Return a Z3 finite-domain numeral as a Python string.
7201 
7202  >>> s = FiniteDomainSort('S', 100)
7203  >>> v = FiniteDomainVal(42, s)
7204  >>> v.as_string()
7205  '42'
7206  """
7207  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
7208 
7209 
7210 def FiniteDomainVal(val, sort, ctx=None):
7211  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7212 
7213  >>> s = FiniteDomainSort('S', 256)
7214  >>> FiniteDomainVal(255, s)
7215  255
7216  >>> FiniteDomainVal('100', s)
7217  100
7218  """
7219  if __debug__:
7220  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
7221  ctx = sort.ctx
7222  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7223 
7225  """Return `True` if `a` is a Z3 finite-domain value.
7226 
7227  >>> s = FiniteDomainSort('S', 100)
7228  >>> b = Const('b', s)
7229  >>> is_finite_domain_value(b)
7230  False
7231  >>> b = FiniteDomainVal(10, s)
7232  >>> b
7233  10
7234  >>> is_finite_domain_value(b)
7235  True
7236  """
7237  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7238 
7239 
7240 
7245 
7247  def __init__(self, opt, value, is_max):
7248  self._opt = opt
7249  self._value = value
7250  self._is_max = is_max
7251 
7252  def lower(self):
7253  opt = self._opt
7254  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7255 
7256  def upper(self):
7257  opt = self._opt
7258  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7259 
7260  def lower_values(self):
7261  opt = self._opt
7262  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7263 
7264  def upper_values(self):
7265  opt = self._opt
7266  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7267 
7268  def value(self):
7269  if self._is_max:
7270  return self.upper()
7271  else:
7272  return self.lower()
7273 
7274  def __str__(self):
7275  return "%s:%s" % (self._value, self._is_max)
7276 
7277 
7279  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7280 
7281  def __init__(self, ctx=None):
7282  self.ctx = _get_ctx(ctx)
7283  self.optimize = Z3_mk_optimize(self.ctx.ref())
7284  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7285 
7286  def __deepcopy__(self, memo={}):
7287  return Optimize(self.optimize, self.ctx)
7288 
7289  def __del__(self):
7290  if self.optimize is not None and self.ctx.ref() is not None:
7291  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7292 
7293  def set(self, *args, **keys):
7294  """Set a configuration option. The method `help()` return a string containing all available options.
7295  """
7296  p = args2params(args, keys, self.ctx)
7297  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7298 
7299  def help(self):
7300  """Display a string describing all available options."""
7301  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7302 
7303  def param_descrs(self):
7304  """Return the parameter description set."""
7305  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7306 
7307  def assert_exprs(self, *args):
7308  """Assert constraints as background axioms for the optimize solver."""
7309  args = _get_args(args)
7310  s = BoolSort(self.ctx)
7311  for arg in args:
7312  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7313  for f in arg:
7314  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7315  else:
7316  arg = s.cast(arg)
7317  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7318 
7319  def add(self, *args):
7320  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7321  self.assert_exprs(*args)
7322 
7323  def __iadd__(self, fml):
7324  self.add(fml)
7325  return self
7326 
7327  def add_soft(self, arg, weight = "1", id = None):
7328  """Add soft constraint with optional weight and optional identifier.
7329  If no weight is supplied, then the penalty for violating the soft constraint
7330  is 1.
7331  Soft constraints are grouped by identifiers. Soft constraints that are
7332  added without identifiers are grouped by default.
7333  """
7334  if _is_int(weight):
7335  weight = "%d" % weight
7336  elif isinstance(weight, float):
7337  weight = "%f" % weight
7338  if not isinstance(weight, str):
7339  raise Z3Exception("weight should be a string or an integer")
7340  if id is None:
7341  id = ""
7342  id = to_symbol(id, self.ctx)
7343  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7344  return OptimizeObjective(self, v, False)
7345 
7346  def maximize(self, arg):
7347  """Add objective function to maximize."""
7348  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7349 
7350  def minimize(self, arg):
7351  """Add objective function to minimize."""
7352  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7353 
7354  def push(self):
7355  """create a backtracking point for added rules, facts and assertions"""
7356  Z3_optimize_push(self.ctx.ref(), self.optimize)
7357 
7358  def pop(self):
7359  """restore to previously created backtracking point"""
7360  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7361 
7362  def check(self, *assumptions):
7363  """Check satisfiability while optimizing objective functions."""
7364  assumptions = _get_args(assumptions)
7365  num = len(assumptions)
7366  _assumptions = (Ast * num)()
7367  for i in range(num):
7368  _assumptions[i] = assumptions[i].as_ast()
7369  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7370 
7371  def reason_unknown(self):
7372  """Return a string that describes why the last `check()` returned `unknown`."""
7373  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7374 
7375  def model(self):
7376  """Return a model for the last check()."""
7377  try:
7378  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7379  except Z3Exception:
7380  raise Z3Exception("model is not available")
7381 
7382  def unsat_core(self):
7383  return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7384 
7385  def lower(self, obj):
7386  if not isinstance(obj, OptimizeObjective):
7387  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7388  return obj.lower()
7389 
7390  def upper(self, obj):
7391  if not isinstance(obj, OptimizeObjective):
7392  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7393  return obj.upper()
7394 
7395  def lower_values(self, obj):
7396  if not isinstance(obj, OptimizeObjective):
7397  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7398  return obj.lower_values()
7399 
7400  def upper_values(self, obj):
7401  if not isinstance(obj, OptimizeObjective):
7402  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7403  return obj.upper_values()
7404 
7405  def from_file(self, filename):
7406  """Parse assertions and objectives from a file"""
7407  try:
7408  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7409  except Z3Exception as e:
7410  _handle_parse_error(e, self.ctx)
7411 
7412  def from_string(self, s):
7413  """Parse assertions and objectives from a string"""
7414  try:
7415  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7416  except Z3Exception as e:
7417  _handle_parse_error(e, self.ctx)
7418 
7419  def assertions(self):
7420  """Return an AST vector containing all added constraints."""
7421  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7422 
7423  def objectives(self):
7424  """returns set of objective functions"""
7425  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7426 
7427  def __repr__(self):
7428  """Return a formatted string with all added rules and constraints."""
7429  return self.sexpr()
7430 
7431  def sexpr(self):
7432  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7433  """
7434  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7435 
7436  def statistics(self):
7437  """Return statistics for the last check`.
7438  """
7439  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7440 
7441 
7442 
7443 
7444 
7450  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7451 
7452  def __init__(self, result, ctx):
7453  self.result = result
7454  self.ctx = ctx
7455  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7456 
7457  def __deepcopy__(self, memo={}):
7458  return ApplyResult(self.result, self.ctx)
7459 
7460  def __del__(self):
7461  if self.ctx.ref() is not None:
7462  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7463 
7464  def __len__(self):
7465  """Return the number of subgoals in `self`.
7466 
7467  >>> a, b = Ints('a b')
7468  >>> g = Goal()
7469  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7470  >>> t = Tactic('split-clause')
7471  >>> r = t(g)
7472  >>> len(r)
7473  2
7474  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7475  >>> len(t(g))
7476  4
7477  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7478  >>> len(t(g))
7479  1
7480  """
7481  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7482 
7483  def __getitem__(self, idx):
7484  """Return one of the subgoals stored in ApplyResult object `self`.
7485 
7486  >>> a, b = Ints('a b')
7487  >>> g = Goal()
7488  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7489  >>> t = Tactic('split-clause')
7490  >>> r = t(g)
7491  >>> r[0]
7492  [a == 0, Or(b == 0, b == 1), a > b]
7493  >>> r[1]
7494  [a == 1, Or(b == 0, b == 1), a > b]
7495  """
7496  if idx >= len(self):
7497  raise IndexError
7498  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7499 
7500  def __repr__(self):
7501  return obj_to_string(self)
7502 
7503  def sexpr(self):
7504  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7505  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7506 
7507 
7508  def as_expr(self):
7509  """Return a Z3 expression consisting of all subgoals.
7510 
7511  >>> x = Int('x')
7512  >>> g = Goal()
7513  >>> g.add(x > 1)
7514  >>> g.add(Or(x == 2, x == 3))
7515  >>> r = Tactic('simplify')(g)
7516  >>> r
7517  [[Not(x <= 1), Or(x == 2, x == 3)]]
7518  >>> r.as_expr()
7519  And(Not(x <= 1), Or(x == 2, x == 3))
7520  >>> r = Tactic('split-clause')(g)
7521  >>> r
7522  [[x > 1, x == 2], [x > 1, x == 3]]
7523  >>> r.as_expr()
7524  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7525  """
7526  sz = len(self)
7527  if sz == 0:
7528  return BoolVal(False, self.ctx)
7529  elif sz == 1:
7530  return self[0].as_expr()
7531  else:
7532  return Or([ self[i].as_expr() for i in range(len(self)) ])
7533 
7534 
7539 class Tactic:
7540  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7541 
7542  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7543  """
7544  def __init__(self, tactic, ctx=None):
7545  self.ctx = _get_ctx(ctx)
7546  self.tactic = None
7547  if isinstance(tactic, TacticObj):
7548  self.tactic = tactic
7549  else:
7550  if __debug__:
7551  _z3_assert(isinstance(tactic, str), "tactic name expected")
7552  try:
7553  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7554  except Z3Exception:
7555  raise Z3Exception("unknown tactic '%s'" % tactic)
7556  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7557 
7558  def __deepcopy__(self, memo={}):
7559  return Tactic(self.tactic, self.ctx)
7560 
7561  def __del__(self):
7562  if self.tactic is not None and self.ctx.ref() is not None:
7563  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7564 
7565  def solver(self):
7566  """Create a solver using the tactic `self`.
7567 
7568  The solver supports the methods `push()` and `pop()`, but it
7569  will always solve each `check()` from scratch.
7570 
7571  >>> t = Then('simplify', 'nlsat')
7572  >>> s = t.solver()
7573  >>> x = Real('x')
7574  >>> s.add(x**2 == 2, x > 0)
7575  >>> s.check()
7576  sat
7577  >>> s.model()
7578  [x = 1.4142135623?]
7579  """
7580  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7581 
7582  def apply(self, goal, *arguments, **keywords):
7583  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7584 
7585  >>> x, y = Ints('x y')
7586  >>> t = Tactic('solve-eqs')
7587  >>> t.apply(And(x == 0, y >= x + 1))
7588  [[y >= 1]]
7589  """
7590  if __debug__:
7591  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7592  goal = _to_goal(goal)
7593  if len(arguments) > 0 or len(keywords) > 0:
7594  p = args2params(arguments, keywords, self.ctx)
7595  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7596  else:
7597  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7598 
7599  def __call__(self, goal, *arguments, **keywords):
7600  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7601 
7602  >>> x, y = Ints('x y')
7603  >>> t = Tactic('solve-eqs')
7604  >>> t(And(x == 0, y >= x + 1))
7605  [[y >= 1]]
7606  """
7607  return self.apply(goal, *arguments, **keywords)
7608 
7609  def help(self):
7610  """Display a string containing a description of the available options for the `self` tactic."""
7611  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7612 
7613  def param_descrs(self):
7614  """Return the parameter description set."""
7615  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7616 
7617 def _to_goal(a):
7618  if isinstance(a, BoolRef):
7619  goal = Goal(ctx = a.ctx)
7620  goal.add(a)
7621  return goal
7622  else:
7623  return a
7624 
7625 def _to_tactic(t, ctx=None):
7626  if isinstance(t, Tactic):
7627  return t
7628  else:
7629  return Tactic(t, ctx)
7630 
7631 def _and_then(t1, t2, ctx=None):
7632  t1 = _to_tactic(t1, ctx)
7633  t2 = _to_tactic(t2, ctx)
7634  if __debug__:
7635  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7636  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7637 
7638 def _or_else(t1, t2, ctx=None):
7639  t1 = _to_tactic(t1, ctx)
7640  t2 = _to_tactic(t2, ctx)
7641  if __debug__:
7642  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7643  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7644 
7645 def AndThen(*ts, **ks):
7646  """Return a tactic that applies the tactics in `*ts` in sequence.
7647 
7648  >>> x, y = Ints('x y')
7649  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7650  >>> t(And(x == 0, y > x + 1))
7651  [[Not(y <= 1)]]
7652  >>> t(And(x == 0, y > x + 1)).as_expr()
7653  Not(y <= 1)
7654  """
7655  if __debug__:
7656  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7657  ctx = ks.get('ctx', None)
7658  num = len(ts)
7659  r = ts[0]
7660  for i in range(num - 1):
7661  r = _and_then(r, ts[i+1], ctx)
7662  return r
7663 
7664 def Then(*ts, **ks):
7665  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7666 
7667  >>> x, y = Ints('x y')
7668  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7669  >>> t(And(x == 0, y > x + 1))
7670  [[Not(y <= 1)]]
7671  >>> t(And(x == 0, y > x + 1)).as_expr()
7672  Not(y <= 1)
7673  """
7674  return AndThen(*ts, **ks)
7675 
7676 def OrElse(*ts, **ks):
7677  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7678 
7679  >>> x = Int('x')
7680  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7681  >>> # Tactic split-clause fails if there is no clause in the given goal.
7682  >>> t(x == 0)
7683  [[x == 0]]
7684  >>> t(Or(x == 0, x == 1))
7685  [[x == 0], [x == 1]]
7686  """
7687  if __debug__:
7688  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7689  ctx = ks.get('ctx', None)
7690  num = len(ts)
7691  r = ts[0]
7692  for i in range(num - 1):
7693  r = _or_else(r, ts[i+1], ctx)
7694  return r
7695 
7696 def ParOr(*ts, **ks):
7697  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7698 
7699  >>> x = Int('x')
7700  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7701  >>> t(x + 1 == 2)
7702  [[x == 1]]
7703  """
7704  if __debug__:
7705  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7706  ctx = _get_ctx(ks.get('ctx', None))
7707  ts = [ _to_tactic(t, ctx) for t in ts ]
7708  sz = len(ts)
7709  _args = (TacticObj * sz)()
7710  for i in range(sz):
7711  _args[i] = ts[i].tactic
7712  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7713 
7714 def ParThen(t1, t2, ctx=None):
7715  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7716 
7717  >>> x, y = Ints('x y')
7718  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7719  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7720  [[x == 1, y == 2], [x == 2, y == 3]]
7721  """
7722  t1 = _to_tactic(t1, ctx)
7723  t2 = _to_tactic(t2, ctx)
7724  if __debug__:
7725  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7726  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7727 
7728 def ParAndThen(t1, t2, ctx=None):
7729  """Alias for ParThen(t1, t2, ctx)."""
7730  return ParThen(t1, t2, ctx)
7731 
7732 def With(t, *args, **keys):
7733  """Return a tactic that applies tactic `t` using the given configuration options.
7734 
7735  >>> x, y = Ints('x y')
7736  >>> t = With(Tactic('simplify'), som=True)
7737  >>> t((x + 1)*(y + 2) == 0)
7738  [[2*x + y + x*y == -2]]
7739  """
7740  ctx = keys.pop('ctx', None)
7741  t = _to_tactic(t, ctx)
7742  p = args2params(args, keys, t.ctx)
7743  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7744 
7745 def WithParams(t, p):
7746  """Return a tactic that applies tactic `t` using the given configuration options.
7747 
7748  >>> x, y = Ints('x y')
7749  >>> p = ParamsRef()
7750  >>> p.set("som", True)
7751  >>> t = WithParams(Tactic('simplify'), p)
7752  >>> t((x + 1)*(y + 2) == 0)
7753  [[2*x + y + x*y == -2]]
7754  """
7755  t = _to_tactic(t, None)
7756  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7757 
7758 def Repeat(t, max=4294967295, ctx=None):
7759  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7760 
7761  >>> x, y = Ints('x y')
7762  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7763  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7764  >>> r = t(c)
7765  >>> for subgoal in r: print(subgoal)
7766  [x == 0, y == 0, x > y]
7767  [x == 0, y == 1, x > y]
7768  [x == 1, y == 0, x > y]
7769  [x == 1, y == 1, x > y]
7770  >>> t = Then(t, Tactic('propagate-values'))
7771  >>> t(c)
7772  [[x == 1, y == 0]]
7773  """
7774  t = _to_tactic(t, ctx)
7775  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7776 
7777 def TryFor(t, ms, ctx=None):
7778  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7779 
7780  If `t` does not terminate in `ms` milliseconds, then it fails.
7781  """
7782  t = _to_tactic(t, ctx)
7783  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7784 
7785 def tactics(ctx=None):
7786  """Return a list of all available tactics in Z3.
7787 
7788  >>> l = tactics()
7789  >>> l.count('simplify') == 1
7790  True
7791  """
7792  ctx = _get_ctx(ctx)
7793  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7794 
7795 def tactic_description(name, ctx=None):
7796  """Return a short description for the tactic named `name`.
7797 
7798  >>> d = tactic_description('simplify')
7799  """
7800  ctx = _get_ctx(ctx)
7801  return Z3_tactic_get_descr(ctx.ref(), name)
7802 
7804  """Display a (tabular) description of all available tactics in Z3."""
7805  if in_html_mode():
7806  even = True
7807  print('<table border="1" cellpadding="2" cellspacing="0">')
7808  for t in tactics():
7809  if even:
7810  print('<tr style="background-color:#CFCFCF">')
7811  even = False
7812  else:
7813  print('<tr>')
7814  even = True
7815  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7816  print('</table>')
7817  else:
7818  for t in tactics():
7819  print('%s : %s' % (t, tactic_description(t)))
7820 
7821 class Probe:
7822  """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."""
7823  def __init__(self, probe, ctx=None):
7824  self.ctx = _get_ctx(ctx)
7825  self.probe = None
7826  if isinstance(probe, ProbeObj):
7827  self.probe = probe
7828  elif isinstance(probe, float):
7829  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7830  elif _is_int(probe):
7831  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7832  elif isinstance(probe, bool):
7833  if probe:
7834  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7835  else:
7836  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7837  else:
7838  if __debug__:
7839  _z3_assert(isinstance(probe, str), "probe name expected")
7840  try:
7841  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7842  except Z3Exception:
7843  raise Z3Exception("unknown probe '%s'" % probe)
7844  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7845 
7846  def __deepcopy__(self, memo={}):
7847  return Probe(self.probe, self.ctx)
7848 
7849  def __del__(self):
7850  if self.probe is not None and self.ctx.ref() is not None:
7851  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7852 
7853  def __lt__(self, other):
7854  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7855 
7856  >>> p = Probe('size') < 10
7857  >>> x = Int('x')
7858  >>> g = Goal()
7859  >>> g.add(x > 0)
7860  >>> g.add(x < 10)
7861  >>> p(g)
7862  1.0
7863  """
7864  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7865 
7866  def __gt__(self, other):
7867  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7868 
7869  >>> p = Probe('size') > 10
7870  >>> x = Int('x')
7871  >>> g = Goal()
7872  >>> g.add(x > 0)
7873  >>> g.add(x < 10)
7874  >>> p(g)
7875  0.0
7876  """
7877  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7878 
7879  def __le__(self, other):
7880  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7881 
7882  >>> p = Probe('size') <= 2
7883  >>> x = Int('x')
7884  >>> g = Goal()
7885  >>> g.add(x > 0)
7886  >>> g.add(x < 10)
7887  >>> p(g)
7888  1.0
7889  """
7890  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7891 
7892  def __ge__(self, other):
7893  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7894 
7895  >>> p = Probe('size') >= 2
7896  >>> x = Int('x')
7897  >>> g = Goal()
7898  >>> g.add(x > 0)
7899  >>> g.add(x < 10)
7900  >>> p(g)
7901  1.0
7902  """
7903  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7904 
7905  def __eq__(self, other):
7906  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7907 
7908  >>> p = Probe('size') == 2
7909  >>> x = Int('x')
7910  >>> g = Goal()
7911  >>> g.add(x > 0)
7912  >>> g.add(x < 10)
7913  >>> p(g)
7914  1.0
7915  """
7916  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7917 
7918  def __ne__(self, other):
7919  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7920 
7921  >>> p = Probe('size') != 2
7922  >>> x = Int('x')
7923  >>> g = Goal()
7924  >>> g.add(x > 0)
7925  >>> g.add(x < 10)
7926  >>> p(g)
7927  0.0
7928  """
7929  p = self.__eq__(other)
7930  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
7931 
7932  def __call__(self, goal):
7933  """Evaluate the probe `self` in the given goal.
7934 
7935  >>> p = Probe('size')
7936  >>> x = Int('x')
7937  >>> g = Goal()
7938  >>> g.add(x > 0)
7939  >>> g.add(x < 10)
7940  >>> p(g)
7941  2.0
7942  >>> g.add(x < 20)
7943  >>> p(g)
7944  3.0
7945  >>> p = Probe('num-consts')
7946  >>> p(g)
7947  1.0
7948  >>> p = Probe('is-propositional')
7949  >>> p(g)
7950  0.0
7951  >>> p = Probe('is-qflia')
7952  >>> p(g)
7953  1.0
7954  """
7955  if __debug__:
7956  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
7957  goal = _to_goal(goal)
7958  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
7959 
7960 def is_probe(p):
7961  """Return `True` if `p` is a Z3 probe.
7962 
7963  >>> is_probe(Int('x'))
7964  False
7965  >>> is_probe(Probe('memory'))
7966  True
7967  """
7968  return isinstance(p, Probe)
7969 
7970 def _to_probe(p, ctx=None):
7971  if is_probe(p):
7972  return p
7973  else:
7974  return Probe(p, ctx)
7975 
7976 def probes(ctx=None):
7977  """Return a list of all available probes in Z3.
7978 
7979  >>> l = probes()
7980  >>> l.count('memory') == 1
7981  True
7982  """
7983  ctx = _get_ctx(ctx)
7984  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
7985 
7986 def probe_description(name, ctx=None):
7987  """Return a short description for the probe named `name`.
7988 
7989  >>> d = probe_description('memory')
7990  """
7991  ctx = _get_ctx(ctx)
7992  return Z3_probe_get_descr(ctx.ref(), name)
7993 
7995  """Display a (tabular) description of all available probes in Z3."""
7996  if in_html_mode():
7997  even = True
7998  print('<table border="1" cellpadding="2" cellspacing="0">')
7999  for p in probes():
8000  if even:
8001  print('<tr style="background-color:#CFCFCF">')
8002  even = False
8003  else:
8004  print('<tr>')
8005  even = True
8006  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
8007  print('</table>')
8008  else:
8009  for p in probes():
8010  print('%s : %s' % (p, probe_description(p)))
8011 
8012 def _probe_nary(f, args, ctx):
8013  if __debug__:
8014  _z3_assert(len(args) > 0, "At least one argument expected")
8015  num = len(args)
8016  r = _to_probe(args[0], ctx)
8017  for i in range(num - 1):
8018  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
8019  return r
8020 
8021 def _probe_and(args, ctx):
8022  return _probe_nary(Z3_probe_and, args, ctx)
8023 
8024 def _probe_or(args, ctx):
8025  return _probe_nary(Z3_probe_or, args, ctx)
8026 
8027 def FailIf(p, ctx=None):
8028  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8029 
8030  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
8031 
8032  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8033  >>> x, y = Ints('x y')
8034  >>> g = Goal()
8035  >>> g.add(x > 0)
8036  >>> g.add(y > 0)
8037  >>> t(g)
8038  [[x > 0, y > 0]]
8039  >>> g.add(x == y + 1)
8040  >>> t(g)
8041  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8042  """
8043  p = _to_probe(p, ctx)
8044  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8045 
8046 def When(p, t, ctx=None):
8047  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8048 
8049  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8050  >>> x, y = Ints('x y')
8051  >>> g = Goal()
8052  >>> g.add(x > 0)
8053  >>> g.add(y > 0)
8054  >>> t(g)
8055  [[x > 0, y > 0]]
8056  >>> g.add(x == y + 1)
8057  >>> t(g)
8058  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8059  """
8060  p = _to_probe(p, ctx)
8061  t = _to_tactic(t, ctx)
8062  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8063 
8064 def Cond(p, t1, t2, ctx=None):
8065  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8066 
8067  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8068  """
8069  p = _to_probe(p, ctx)
8070  t1 = _to_tactic(t1, ctx)
8071  t2 = _to_tactic(t2, ctx)
8072  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8073 
8074 
8079 
8080 def simplify(a, *arguments, **keywords):
8081  """Simplify the expression `a` using the given options.
8082 
8083  This function has many options. Use `help_simplify` to obtain the complete list.
8084 
8085  >>> x = Int('x')
8086  >>> y = Int('y')
8087  >>> simplify(x + 1 + y + x + 1)
8088  2 + 2*x + y
8089  >>> simplify((x + 1)*(y + 1), som=True)
8090  1 + x + y + x*y
8091  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8092  And(Not(x == y), Not(x == 1), Not(y == 1))
8093  >>> simplify(And(x == 0, y == 1), elim_and=True)
8094  Not(Or(Not(x == 0), Not(y == 1)))
8095  """
8096  if __debug__:
8097  _z3_assert(is_expr(a), "Z3 expression expected")
8098  if len(arguments) > 0 or len(keywords) > 0:
8099  p = args2params(arguments, keywords, a.ctx)
8100  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8101  else:
8102  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8103 
8105  """Return a string describing all options available for Z3 `simplify` procedure."""
8106  print(Z3_simplify_get_help(main_ctx().ref()))
8107 
8109  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8111 
8112 def substitute(t, *m):
8113  """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.
8114 
8115  >>> x = Int('x')
8116  >>> y = Int('y')
8117  >>> substitute(x + 1, (x, y + 1))
8118  y + 1 + 1
8119  >>> f = Function('f', IntSort(), IntSort())
8120  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8121  1 + 1
8122  """
8123  if isinstance(m, tuple):
8124  m1 = _get_args(m)
8125  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8126  m = m1
8127  if __debug__:
8128  _z3_assert(is_expr(t), "Z3 expression expected")
8129  _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.")
8130  num = len(m)
8131  _from = (Ast * num)()
8132  _to = (Ast * num)()
8133  for i in range(num):
8134  _from[i] = m[i][0].as_ast()
8135  _to[i] = m[i][1].as_ast()
8136  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8137 
8138 def substitute_vars(t, *m):
8139  """Substitute the free variables in t with the expression in m.
8140 
8141  >>> v0 = Var(0, IntSort())
8142  >>> v1 = Var(1, IntSort())
8143  >>> x = Int('x')
8144  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8145  >>> # replace v0 with x+1 and v1 with x
8146  >>> substitute_vars(f(v0, v1), x + 1, x)
8147  f(x + 1, x)
8148  """
8149  if __debug__:
8150  _z3_assert(is_expr(t), "Z3 expression expected")
8151  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8152  num = len(m)
8153  _to = (Ast * num)()
8154  for i in range(num):
8155  _to[i] = m[i].as_ast()
8156  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8157 
8158 def Sum(*args):
8159  """Create the sum of the Z3 expressions.
8160 
8161  >>> a, b, c = Ints('a b c')
8162  >>> Sum(a, b, c)
8163  a + b + c
8164  >>> Sum([a, b, c])
8165  a + b + c
8166  >>> A = IntVector('a', 5)
8167  >>> Sum(A)
8168  a__0 + a__1 + a__2 + a__3 + a__4
8169  """
8170  args = _get_args(args)
8171  if len(args) == 0:
8172  return 0
8173  ctx = _ctx_from_ast_arg_list(args)
8174  if ctx is None:
8175  return _reduce(lambda a, b: a + b, args, 0)
8176  args = _coerce_expr_list(args, ctx)
8177  if is_bv(args[0]):
8178  return _reduce(lambda a, b: a + b, args, 0)
8179  else:
8180  _args, sz = _to_ast_array(args)
8181  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8182 
8183 
8184 def Product(*args):
8185  """Create the product of the Z3 expressions.
8186 
8187  >>> a, b, c = Ints('a b c')
8188  >>> Product(a, b, c)
8189  a*b*c
8190  >>> Product([a, b, c])
8191  a*b*c
8192  >>> A = IntVector('a', 5)
8193  >>> Product(A)
8194  a__0*a__1*a__2*a__3*a__4
8195  """
8196  args = _get_args(args)
8197  if len(args) == 0:
8198  return 1
8199  ctx = _ctx_from_ast_arg_list(args)
8200  if ctx is None:
8201  return _reduce(lambda a, b: a * b, args, 1)
8202  args = _coerce_expr_list(args, ctx)
8203  if is_bv(args[0]):
8204  return _reduce(lambda a, b: a * b, args, 1)
8205  else:
8206  _args, sz = _to_ast_array(args)
8207  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8208 
8209 def AtMost(*args):
8210  """Create an at-most Pseudo-Boolean k constraint.
8211 
8212  >>> a, b, c = Bools('a b c')
8213  >>> f = AtMost(a, b, c, 2)
8214  """
8215  args = _get_args(args)
8216  if __debug__:
8217  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8218  ctx = _ctx_from_ast_arg_list(args)
8219  if __debug__:
8220  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8221  args1 = _coerce_expr_list(args[:-1], ctx)
8222  k = args[-1]
8223  _args, sz = _to_ast_array(args1)
8224  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8225 
8226 def AtLeast(*args):
8227  """Create an at-most Pseudo-Boolean k constraint.
8228 
8229  >>> a, b, c = Bools('a b c')
8230  >>> f = AtLeast(a, b, c, 2)
8231  """
8232  args = _get_args(args)
8233  if __debug__:
8234  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8235  ctx = _ctx_from_ast_arg_list(args)
8236  if __debug__:
8237  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8238  args1 = _coerce_expr_list(args[:-1], ctx)
8239  k = args[-1]
8240  _args, sz = _to_ast_array(args1)
8241  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8242 
8243 
8244 def _pb_args_coeffs(args, default_ctx = None):
8245  args = _get_args_ast_list(args)
8246  if len(args) == 0:
8247  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8248  args, coeffs = zip(*args)
8249  if __debug__:
8250  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8251  ctx = _ctx_from_ast_arg_list(args)
8252  if __debug__:
8253  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8254  args = _coerce_expr_list(args, ctx)
8255  _args, sz = _to_ast_array(args)
8256  _coeffs = (ctypes.c_int * len(coeffs))()
8257  for i in range(len(coeffs)):
8258  _z3_check_cint_overflow(coeffs[i], "coefficient")
8259  _coeffs[i] = coeffs[i]
8260  return ctx, sz, _args, _coeffs
8261 
8262 def PbLe(args, k):
8263  """Create a Pseudo-Boolean inequality k constraint.
8264 
8265  >>> a, b, c = Bools('a b c')
8266  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8267  """
8268  _z3_check_cint_overflow(k, "k")
8269  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8270  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8271 
8272 def PbGe(args, k):
8273  """Create a Pseudo-Boolean inequality k constraint.
8274 
8275  >>> a, b, c = Bools('a b c')
8276  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8277  """
8278  _z3_check_cint_overflow(k, "k")
8279  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8280  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8281 
8282 def PbEq(args, k, ctx = None):
8283  """Create a Pseudo-Boolean inequality k constraint.
8284 
8285  >>> a, b, c = Bools('a b c')
8286  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8287  """
8288  _z3_check_cint_overflow(k, "k")
8289  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8290  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8291 
8292 
8293 def solve(*args, **keywords):
8294  """Solve the constraints `*args`.
8295 
8296  This is a simple function for creating demonstrations. It creates a solver,
8297  configure it using the options in `keywords`, adds the constraints
8298  in `args`, and invokes check.
8299 
8300  >>> a = Int('a')
8301  >>> solve(a > 0, a < 2)
8302  [a = 1]
8303  """
8304  s = Solver()
8305  s.set(**keywords)
8306  s.add(*args)
8307  if keywords.get('show', False):
8308  print(s)
8309  r = s.check()
8310  if r == unsat:
8311  print("no solution")
8312  elif r == unknown:
8313  print("failed to solve")
8314  try:
8315  print(s.model())
8316  except Z3Exception:
8317  return
8318  else:
8319  print(s.model())
8320 
8321 def solve_using(s, *args, **keywords):
8322  """Solve the constraints `*args` using solver `s`.
8323 
8324  This is a simple function for creating demonstrations. It is similar to `solve`,
8325  but it uses the given solver `s`.
8326  It configures solver `s` using the options in `keywords`, adds the constraints
8327  in `args`, and invokes check.
8328  """
8329  if __debug__:
8330  _z3_assert(isinstance(s, Solver), "Solver object expected")
8331  s.set(**keywords)
8332  s.add(*args)
8333  if keywords.get('show', False):
8334  print("Problem:")
8335  print(s)
8336  r = s.check()
8337  if r == unsat:
8338  print("no solution")
8339  elif r == unknown:
8340  print("failed to solve")
8341  try:
8342  print(s.model())
8343  except Z3Exception:
8344  return
8345  else:
8346  if keywords.get('show', False):
8347  print("Solution:")
8348  print(s.model())
8349 
8350 def prove(claim, **keywords):
8351  """Try to prove the given claim.
8352 
8353  This is a simple function for creating demonstrations. It tries to prove
8354  `claim` by showing the negation is unsatisfiable.
8355 
8356  >>> p, q = Bools('p q')
8357  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8358  proved
8359  """
8360  if __debug__:
8361  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8362  s = Solver()
8363  s.set(**keywords)
8364  s.add(Not(claim))
8365  if keywords.get('show', False):
8366  print(s)
8367  r = s.check()
8368  if r == unsat:
8369  print("proved")
8370  elif r == unknown:
8371  print("failed to prove")
8372  print(s.model())
8373  else:
8374  print("counterexample")
8375  print(s.model())
8376 
8377 def _solve_html(*args, **keywords):
8378  """Version of function `solve` used in RiSE4Fun."""
8379  s = Solver()
8380  s.set(**keywords)
8381  s.add(*args)
8382  if keywords.get('show', False):
8383  print("<b>Problem:</b>")
8384  print(s)
8385  r = s.check()
8386  if r == unsat:
8387  print("<b>no solution</b>")
8388  elif r == unknown:
8389  print("<b>failed to solve</b>")
8390  try:
8391  print(s.model())
8392  except Z3Exception:
8393  return
8394  else:
8395  if keywords.get('show', False):
8396  print("<b>Solution:</b>")
8397  print(s.model())
8398 
8399 def _solve_using_html(s, *args, **keywords):
8400  """Version of function `solve_using` used in RiSE4Fun."""
8401  if __debug__:
8402  _z3_assert(isinstance(s, Solver), "Solver object expected")
8403  s.set(**keywords)
8404  s.add(*args)
8405  if keywords.get('show', False):
8406  print("<b>Problem:</b>")
8407  print(s)
8408  r = s.check()
8409  if r == unsat:
8410  print("<b>no solution</b>")
8411  elif r == unknown:
8412  print("<b>failed to solve</b>")
8413  try:
8414  print(s.model())
8415  except Z3Exception:
8416  return
8417  else:
8418  if keywords.get('show', False):
8419  print("<b>Solution:</b>")
8420  print(s.model())
8421 
8422 def _prove_html(claim, **keywords):
8423  """Version of function `prove` used in RiSE4Fun."""
8424  if __debug__:
8425  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8426  s = Solver()
8427  s.set(**keywords)
8428  s.add(Not(claim))
8429  if keywords.get('show', False):
8430  print(s)
8431  r = s.check()
8432  if r == unsat:
8433  print("<b>proved</b>")
8434  elif r == unknown:
8435  print("<b>failed to prove</b>")
8436  print(s.model())
8437  else:
8438  print("<b>counterexample</b>")
8439  print(s.model())
8440 
8441 def _dict2sarray(sorts, ctx):
8442  sz = len(sorts)
8443  _names = (Symbol * sz)()
8444  _sorts = (Sort * sz) ()
8445  i = 0
8446  for k in sorts:
8447  v = sorts[k]
8448  if __debug__:
8449  _z3_assert(isinstance(k, str), "String expected")
8450  _z3_assert(is_sort(v), "Z3 sort expected")
8451  _names[i] = to_symbol(k, ctx)
8452  _sorts[i] = v.ast
8453  i = i + 1
8454  return sz, _names, _sorts
8455 
8456 def _dict2darray(decls, ctx):
8457  sz = len(decls)
8458  _names = (Symbol * sz)()
8459  _decls = (FuncDecl * sz) ()
8460  i = 0
8461  for k in decls:
8462  v = decls[k]
8463  if __debug__:
8464  _z3_assert(isinstance(k, str), "String expected")
8465  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8466  _names[i] = to_symbol(k, ctx)
8467  if is_const(v):
8468  _decls[i] = v.decl().ast
8469  else:
8470  _decls[i] = v.ast
8471  i = i + 1
8472  return sz, _names, _decls
8473 
8474 
8475 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8476  """Parse a string in SMT 2.0 format using the given sorts and decls.
8477 
8478  The arguments sorts and decls are Python dictionaries used to initialize
8479  the symbol table used for the SMT 2.0 parser.
8480 
8481  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8482  [x > 0, x < 10]
8483  >>> x, y = Ints('x y')
8484  >>> f = Function('f', IntSort(), IntSort())
8485  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8486  [x + f(y) > 0]
8487  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8488  [a > 0]
8489  """
8490  ctx = _get_ctx(ctx)
8491  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8492  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8493  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8494 
8495 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8496  """Parse a file in SMT 2.0 format using the given sorts and decls.
8497 
8498  This function is similar to parse_smt2_string().
8499  """
8500  ctx = _get_ctx(ctx)
8501  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8502  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8503  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8504 
8505 
8506 #########################################
8507 #
8508 # Floating-Point Arithmetic
8509 #
8510 #########################################
8511 
8512 
8513 # Global default rounding mode
8514 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8515 _dflt_fpsort_ebits = 11
8516 _dflt_fpsort_sbits = 53
8517 
8518 def get_default_rounding_mode(ctx=None):
8519  """Retrieves the global default rounding mode."""
8520  global _dflt_rounding_mode
8521  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8522  return RTZ(ctx)
8523  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8524  return RTN(ctx)
8525  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8526  return RTP(ctx)
8527  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8528  return RNE(ctx)
8529  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8530  return RNA(ctx)
8531 
8532 def set_default_rounding_mode(rm, ctx=None):
8533  global _dflt_rounding_mode
8534  if is_fprm_value(rm):
8535  _dflt_rounding_mode = rm.decl().kind()
8536  else:
8537  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8538  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8539  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8540  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8541  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8542  "illegal rounding mode")
8543  _dflt_rounding_mode = rm
8544 
8545 def get_default_fp_sort(ctx=None):
8546  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8547 
8548 def set_default_fp_sort(ebits, sbits, ctx=None):
8549  global _dflt_fpsort_ebits
8550  global _dflt_fpsort_sbits
8551  _dflt_fpsort_ebits = ebits
8552  _dflt_fpsort_sbits = sbits
8553 
8554 def _dflt_rm(ctx=None):
8555  return get_default_rounding_mode(ctx)
8556 
8557 def _dflt_fps(ctx=None):
8558  return get_default_fp_sort(ctx)
8559 
8560 def _coerce_fp_expr_list(alist, ctx):
8561  first_fp_sort = None
8562  for a in alist:
8563  if is_fp(a):
8564  if first_fp_sort is None:
8565  first_fp_sort = a.sort()
8566  elif first_fp_sort == a.sort():
8567  pass # OK, same as before
8568  else:
8569  # we saw at least 2 different float sorts; something will
8570  # throw a sort mismatch later, for now assume None.
8571  first_fp_sort = None
8572  break
8573 
8574  r = []
8575  for i in range(len(alist)):
8576  a = alist[i]
8577  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8578  r.append(FPVal(a, None, first_fp_sort, ctx))
8579  else:
8580  r.append(a)
8581  return _coerce_expr_list(r, ctx)
8582 
8583 
8584 ### FP Sorts
8585 
8586 class FPSortRef(SortRef):
8587  """Floating-point sort."""
8588 
8589  def ebits(self):
8590  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8591  >>> b = FPSort(8, 24)
8592  >>> b.ebits()
8593  8
8594  """
8595  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8596 
8597  def sbits(self):
8598  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8599  >>> b = FPSort(8, 24)
8600  >>> b.sbits()
8601  24
8602  """
8603  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8604 
8605  def cast(self, val):
8606  """Try to cast `val` as a floating-point expression.
8607  >>> b = FPSort(8, 24)
8608  >>> b.cast(1.0)
8609  1
8610  >>> b.cast(1.0).sexpr()
8611  '(fp #b0 #x7f #b00000000000000000000000)'
8612  """
8613  if is_expr(val):
8614  if __debug__:
8615  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8616  return val
8617  else:
8618  return FPVal(val, None, self, self.ctx)
8619 
8620 
8621 def Float16(ctx=None):
8622  """Floating-point 16-bit (half) sort."""
8623  ctx = _get_ctx(ctx)
8624  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8625 
8626 def FloatHalf(ctx=None):
8627  """Floating-point 16-bit (half) sort."""
8628  ctx = _get_ctx(ctx)
8629  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8630 
8631 def Float32(ctx=None):
8632  """Floating-point 32-bit (single) sort."""
8633  ctx = _get_ctx(ctx)
8634  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8635 
8636 def FloatSingle(ctx=None):
8637  """Floating-point 32-bit (single) sort."""
8638  ctx = _get_ctx(ctx)
8639  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8640 
8641 def Float64(ctx=None):
8642  """Floating-point 64-bit (double) sort."""
8643  ctx = _get_ctx(ctx)
8644  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8645 
8646 def FloatDouble(ctx=None):
8647  """Floating-point 64-bit (double) sort."""
8648  ctx = _get_ctx(ctx)
8649  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8650 
8651 def Float128(ctx=None):
8652  """Floating-point 128-bit (quadruple) sort."""
8653  ctx = _get_ctx(ctx)
8654  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8655 
8656 def FloatQuadruple(ctx=None):
8657  """Floating-point 128-bit (quadruple) sort."""
8658  ctx = _get_ctx(ctx)
8659  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8660 
8661 class FPRMSortRef(SortRef):
8662  """"Floating-point rounding mode sort."""
8663 
8664 
8665 def is_fp_sort(s):
8666  """Return True if `s` is a Z3 floating-point sort.
8667 
8668  >>> is_fp_sort(FPSort(8, 24))
8669  True
8670  >>> is_fp_sort(IntSort())
8671  False
8672  """
8673  return isinstance(s, FPSortRef)
8674 
8675 def is_fprm_sort(s):
8676  """Return True if `s` is a Z3 floating-point rounding mode sort.
8677 
8678  >>> is_fprm_sort(FPSort(8, 24))
8679  False
8680  >>> is_fprm_sort(RNE().sort())
8681  True
8682  """
8683  return isinstance(s, FPRMSortRef)
8684 
8685 ### FP Expressions
8686 
8687 class FPRef(ExprRef):
8688  """Floating-point expressions."""
8689 
8690  def sort(self):
8691  """Return the sort of the floating-point expression `self`.
8692 
8693  >>> x = FP('1.0', FPSort(8, 24))
8694  >>> x.sort()
8695  FPSort(8, 24)
8696  >>> x.sort() == FPSort(8, 24)
8697  True
8698  """
8699  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8700 
8701  def ebits(self):
8702  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8703  >>> b = FPSort(8, 24)
8704  >>> b.ebits()
8705  8
8706  """
8707  return self.sort().ebits();
8708 
8709  def sbits(self):
8710  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8711  >>> b = FPSort(8, 24)
8712  >>> b.sbits()
8713  24
8714  """
8715  return self.sort().sbits();
8716 
8717  def as_string(self):
8718  """Return a Z3 floating point expression as a Python string."""
8719  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8720 
8721  def __le__(self, other):
8722  return fpLEQ(self, other, self.ctx)
8723 
8724  def __lt__(self, other):
8725  return fpLT(self, other, self.ctx)
8726 
8727  def __ge__(self, other):
8728  return fpGEQ(self, other, self.ctx)
8729 
8730  def __gt__(self, other):
8731  return fpGT(self, other, self.ctx)
8732 
8733  def __add__(self, other):
8734  """Create the Z3 expression `self + other`.
8735 
8736  >>> x = FP('x', FPSort(8, 24))
8737  >>> y = FP('y', FPSort(8, 24))
8738  >>> x + y
8739  x + y
8740  >>> (x + y).sort()
8741  FPSort(8, 24)
8742  """
8743  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8744  return fpAdd(_dflt_rm(), a, b, self.ctx)
8745 
8746  def __radd__(self, other):
8747  """Create the Z3 expression `other + self`.
8748 
8749  >>> x = FP('x', FPSort(8, 24))
8750  >>> 10 + x
8751  1.25*(2**3) + x
8752  """
8753  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8754  return fpAdd(_dflt_rm(), a, b, self.ctx)
8755 
8756  def __sub__(self, other):
8757  """Create the Z3 expression `self - other`.
8758 
8759  >>> x = FP('x', FPSort(8, 24))
8760  >>> y = FP('y', FPSort(8, 24))
8761  >>> x - y
8762  x - y
8763  >>> (x - y).sort()
8764  FPSort(8, 24)
8765  """
8766  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8767  return fpSub(_dflt_rm(), a, b, self.ctx)
8768 
8769  def __rsub__(self, other):
8770  """Create the Z3 expression `other - self`.
8771 
8772  >>> x = FP('x', FPSort(8, 24))
8773  >>> 10 - x
8774  1.25*(2**3) - x
8775  """
8776  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8777  return fpSub(_dflt_rm(), a, b, self.ctx)
8778 
8779  def __mul__(self, other):
8780  """Create the Z3 expression `self * other`.
8781 
8782  >>> x = FP('x', FPSort(8, 24))
8783  >>> y = FP('y', FPSort(8, 24))
8784  >>> x * y
8785  x * y
8786  >>> (x * y).sort()
8787  FPSort(8, 24)
8788  >>> 10 * y
8789  1.25*(2**3) * y
8790  """
8791  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8792  return fpMul(_dflt_rm(), a, b, self.ctx)
8793 
8794  def __rmul__(self, other):
8795  """Create the Z3 expression `other * self`.
8796 
8797  >>> x = FP('x', FPSort(8, 24))
8798  >>> y = FP('y', FPSort(8, 24))
8799  >>> x * y
8800  x * y
8801  >>> x * 10
8802  x * 1.25*(2**3)
8803  """
8804  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8805  return fpMul(_dflt_rm(), a, b, self.ctx)
8806 
8807  def __pos__(self):
8808  """Create the Z3 expression `+self`."""
8809  return self
8810 
8811  def __neg__(self):
8812  """Create the Z3 expression `-self`.
8813 
8814  >>> x = FP('x', Float32())
8815  >>> -x
8816  -x
8817  """
8818  return fpNeg(self)
8819 
8820  def __div__(self, other):
8821  """Create the Z3 expression `self / other`.
8822 
8823  >>> x = FP('x', FPSort(8, 24))
8824  >>> y = FP('y', FPSort(8, 24))
8825  >>> x / y
8826  x / y
8827  >>> (x / y).sort()
8828  FPSort(8, 24)
8829  >>> 10 / y
8830  1.25*(2**3) / y
8831  """
8832  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8833  return fpDiv(_dflt_rm(), a, b, self.ctx)
8834 
8835  def __rdiv__(self, other):
8836  """Create the Z3 expression `other / self`.
8837 
8838  >>> x = FP('x', FPSort(8, 24))
8839  >>> y = FP('y', FPSort(8, 24))
8840  >>> x / y
8841  x / y
8842  >>> x / 10
8843  x / 1.25*(2**3)
8844  """
8845  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8846  return fpDiv(_dflt_rm(), a, b, self.ctx)
8847 
8848  if not sys.version < '3':
8849  def __truediv__(self, other):
8850  """Create the Z3 expression division `self / other`."""
8851  return self.__div__(other)
8852 
8853  def __rtruediv__(self, other):
8854  """Create the Z3 expression division `other / self`."""
8855  return self.__rdiv__(other)
8856 
8857  def __mod__(self, other):
8858  """Create the Z3 expression mod `self % other`."""
8859  return fpRem(self, other)
8860 
8861  def __rmod__(self, other):
8862  """Create the Z3 expression mod `other % self`."""
8863  return fpRem(other, self)
8864 
8865 class FPRMRef(ExprRef):
8866  """Floating-point rounding mode expressions"""
8867 
8868  def as_string(self):
8869  """Return a Z3 floating point expression as a Python string."""
8870  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8871 
8872 
8873 def RoundNearestTiesToEven(ctx=None):
8874  ctx = _get_ctx(ctx)
8875  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8876 
8877 def RNE (ctx=None):
8878  ctx = _get_ctx(ctx)
8879  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8880 
8881 def RoundNearestTiesToAway(ctx=None):
8882  ctx = _get_ctx(ctx)
8883  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8884 
8885 def RNA (ctx=None):
8886  ctx = _get_ctx(ctx)
8887  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8888 
8889 def RoundTowardPositive(ctx=None):
8890  ctx = _get_ctx(ctx)
8891  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8892 
8893 def RTP(ctx=None):
8894  ctx = _get_ctx(ctx)
8895  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8896 
8897 def RoundTowardNegative(ctx=None):
8898  ctx = _get_ctx(ctx)
8899  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8900 
8901 def RTN(ctx=None):
8902  ctx = _get_ctx(ctx)
8903  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8904 
8905 def RoundTowardZero(ctx=None):
8906  ctx = _get_ctx(ctx)
8907  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8908 
8909 def RTZ(ctx=None):
8910  ctx = _get_ctx(ctx)
8911  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8912 
8913 def is_fprm(a):
8914  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8915 
8916  >>> rm = RNE()
8917  >>> is_fprm(rm)
8918  True
8919  >>> rm = 1.0
8920  >>> is_fprm(rm)
8921  False
8922  """
8923  return isinstance(a, FPRMRef)
8924 
8925 def is_fprm_value(a):
8926  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8927  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8928 
8929 ### FP Numerals
8930 
8931 class FPNumRef(FPRef):
8932  """The sign of the numeral.
8933 
8934  >>> x = FPVal(+1.0, FPSort(8, 24))
8935  >>> x.sign()
8936  False
8937  >>> x = FPVal(-1.0, FPSort(8, 24))
8938  >>> x.sign()
8939  True
8940  """
8941  def sign(self):
8942  l = (ctypes.c_int)()
8943  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
8944  raise Z3Exception("error retrieving the sign of a numeral.")
8945  return l.value != 0
8946 
8947  """The sign of a floating-point numeral as a bit-vector expression.
8948 
8949  Remark: NaN's are invalid arguments.
8950  """
8951  def sign_as_bv(self):
8952  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8953 
8954  """The significand of the numeral.
8955 
8956  >>> x = FPVal(2.5, FPSort(8, 24))
8957  >>> x.significand()
8958  1.25
8959  """
8960  def significand(self):
8961  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
8962 
8963  """The significand of the numeral as a long.
8964 
8965  >>> x = FPVal(2.5, FPSort(8, 24))
8966  >>> x.significand_as_long()
8967  1.25
8968  """
8969  def significand_as_long(self):
8970  ptr = (ctypes.c_ulonglong * 1)()
8971  if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
8972  raise Z3Exception("error retrieving the significand of a numeral.")
8973  return ptr[0]
8974 
8975  """The significand of the numeral as a bit-vector expression.
8976 
8977  Remark: NaN are invalid arguments.
8978  """
8979  def significand_as_bv(self):
8980  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8981 
8982  """The exponent of the numeral.
8983 
8984  >>> x = FPVal(2.5, FPSort(8, 24))
8985  >>> x.exponent()
8986  1
8987  """
8988  def exponent(self, biased=True):
8989  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
8990 
8991  """The exponent of the numeral as a long.
8992 
8993  >>> x = FPVal(2.5, FPSort(8, 24))
8994  >>> x.exponent_as_long()
8995  1
8996  """
8997  def exponent_as_long(self, biased=True):
8998  ptr = (ctypes.c_longlong * 1)()
8999  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
9000  raise Z3Exception("error retrieving the exponent of a numeral.")
9001  return ptr[0]
9002 
9003  """The exponent of the numeral as a bit-vector expression.
9004 
9005  Remark: NaNs are invalid arguments.
9006  """
9007  def exponent_as_bv(self, biased=True):
9008  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
9009 
9010  """Indicates whether the numeral is a NaN."""
9011  def isNaN(self):
9012  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
9013 
9014  """Indicates whether the numeral is +oo or -oo."""
9015  def isInf(self):
9016  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
9017 
9018  """Indicates whether the numeral is +zero or -zero."""
9019  def isZero(self):
9020  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
9021 
9022  """Indicates whether the numeral is normal."""
9023  def isNormal(self):
9024  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
9025 
9026  """Indicates whether the numeral is subnormal."""
9027  def isSubnormal(self):
9028  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
9029 
9030  """Indicates whether the numeral is positive."""
9031  def isPositive(self):
9032  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
9033 
9034  """Indicates whether the numeral is negative."""
9035  def isNegative(self):
9036  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
9037 
9038  """
9039  The string representation of the numeral.
9040 
9041  >>> x = FPVal(20, FPSort(8, 24))
9042  >>> x.as_string()
9043  1.25*(2**4)
9044  """
9045  def as_string(self):
9046  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
9047  return ("FPVal(%s, %s)" % (s, self.sort()))
9048 
9049 def is_fp(a):
9050  """Return `True` if `a` is a Z3 floating-point expression.
9051 
9052  >>> b = FP('b', FPSort(8, 24))
9053  >>> is_fp(b)
9054  True
9055  >>> is_fp(b + 1.0)
9056  True
9057  >>> is_fp(Int('x'))
9058  False
9059  """
9060  return isinstance(a, FPRef)
9061 
9062 def is_fp_value(a):
9063  """Return `True` if `a` is a Z3 floating-point numeral value.
9064 
9065  >>> b = FP('b', FPSort(8, 24))
9066  >>> is_fp_value(b)
9067  False
9068  >>> b = FPVal(1.0, FPSort(8, 24))
9069  >>> b
9070  1
9071  >>> is_fp_value(b)
9072  True
9073  """
9074  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9075 
9076 def FPSort(ebits, sbits, ctx=None):
9077  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9078 
9079  >>> Single = FPSort(8, 24)
9080  >>> Double = FPSort(11, 53)
9081  >>> Single
9082  FPSort(8, 24)
9083  >>> x = Const('x', Single)
9084  >>> eq(x, FP('x', FPSort(8, 24)))
9085  True
9086  """
9087  ctx = _get_ctx(ctx)
9088  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9089 
9090 def _to_float_str(val, exp=0):
9091  if isinstance(val, float):
9092  if math.isnan(val):
9093  res = "NaN"
9094  elif val == 0.0:
9095  sone = math.copysign(1.0, val)
9096  if sone < 0.0:
9097  return "-0.0"
9098  else:
9099  return "+0.0"
9100  elif val == float("+inf"):
9101  res = "+oo"
9102  elif val == float("-inf"):
9103  res = "-oo"
9104  else:
9105  v = val.as_integer_ratio()
9106  num = v[0]
9107  den = v[1]
9108  rvs = str(num) + '/' + str(den)
9109  res = rvs + 'p' + _to_int_str(exp)
9110  elif isinstance(val, bool):
9111  if val:
9112  res = "1.0"
9113  else:
9114  res = "0.0"
9115  elif _is_int(val):
9116  res = str(val)
9117  elif isinstance(val, str):
9118  inx = val.find('*(2**')
9119  if inx == -1:
9120  res = val
9121  elif val[-1] == ')':
9122  res = val[0:inx]
9123  exp = str(int(val[inx+5:-1]) + int(exp))
9124  else:
9125  _z3_assert(False, "String does not have floating-point numeral form.")
9126  elif __debug__:
9127  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9128  if exp == 0:
9129  return res
9130  else:
9131  return res + 'p' + exp
9132 
9133 
9134 def fpNaN(s):
9135  """Create a Z3 floating-point NaN term.
9136 
9137  >>> s = FPSort(8, 24)
9138  >>> set_fpa_pretty(True)
9139  >>> fpNaN(s)
9140  NaN
9141  >>> pb = get_fpa_pretty()
9142  >>> set_fpa_pretty(False)
9143  >>> fpNaN(s)
9144  fpNaN(FPSort(8, 24))
9145  >>> set_fpa_pretty(pb)
9146  """
9147  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9148  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9149 
9150 def fpPlusInfinity(s):
9151  """Create a Z3 floating-point +oo term.
9152 
9153  >>> s = FPSort(8, 24)
9154  >>> pb = get_fpa_pretty()
9155  >>> set_fpa_pretty(True)
9156  >>> fpPlusInfinity(s)
9157  +oo
9158  >>> set_fpa_pretty(False)
9159  >>> fpPlusInfinity(s)
9160  fpPlusInfinity(FPSort(8, 24))
9161  >>> set_fpa_pretty(pb)
9162  """
9163  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9164  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9165 
9166 def fpMinusInfinity(s):
9167  """Create a Z3 floating-point -oo term."""
9168  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9169  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9170 
9171 def fpInfinity(s, negative):
9172  """Create a Z3 floating-point +oo or -oo term."""
9173  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9174  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9175  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9176 
9177 def fpPlusZero(s):
9178  """Create a Z3 floating-point +0.0 term."""
9179  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9180  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9181 
9182 def fpMinusZero(s):
9183  """Create a Z3 floating-point -0.0 term."""
9184  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9185  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9186 
9187 def fpZero(s, negative):
9188  """Create a Z3 floating-point +0.0 or -0.0 term."""
9189  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9190  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9191  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9192 
9193 def FPVal(sig, exp=None, fps=None, ctx=None):
9194  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9195 
9196  >>> v = FPVal(20.0, FPSort(8, 24))
9197  >>> v
9198  1.25*(2**4)
9199  >>> print("0x%.8x" % v.exponent_as_long(False))
9200  0x00000004
9201  >>> v = FPVal(2.25, FPSort(8, 24))
9202  >>> v
9203  1.125*(2**1)
9204  >>> v = FPVal(-2.25, FPSort(8, 24))
9205  >>> v
9206  -1.125*(2**1)
9207  >>> FPVal(-0.0, FPSort(8, 24))
9208  -0.0
9209  >>> FPVal(0.0, FPSort(8, 24))
9210  +0.0
9211  >>> FPVal(+0.0, FPSort(8, 24))
9212  +0.0
9213  """
9214  ctx = _get_ctx(ctx)
9215  if is_fp_sort(exp):
9216  fps = exp
9217  exp = None
9218  elif fps is None:
9219  fps = _dflt_fps(ctx)
9220  _z3_assert(is_fp_sort(fps), "sort mismatch")
9221  if exp is None:
9222  exp = 0
9223  val = _to_float_str(sig)
9224  if val == "NaN" or val == "nan":
9225  return fpNaN(fps)
9226  elif val == "-0.0":
9227  return fpMinusZero(fps)
9228  elif val == "0.0" or val == "+0.0":
9229  return fpPlusZero(fps)
9230  elif val == "+oo" or val == "+inf" or val == "+Inf":
9231  return fpPlusInfinity(fps)
9232  elif val == "-oo" or val == "-inf" or val == "-Inf":
9233  return fpMinusInfinity(fps)
9234  else:
9235  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9236 
9237 def FP(name, fpsort, ctx=None):
9238  """Return a floating-point constant named `name`.
9239  `fpsort` is the floating-point sort.
9240  If `ctx=None`, then the global context is used.
9241 
9242  >>> x = FP('x', FPSort(8, 24))
9243  >>> is_fp(x)
9244  True
9245  >>> x.ebits()
9246  8
9247  >>> x.sort()
9248  FPSort(8, 24)
9249  >>> word = FPSort(8, 24)
9250  >>> x2 = FP('x', word)
9251  >>> eq(x, x2)
9252  True
9253  """
9254  if isinstance(fpsort, FPSortRef) and ctx is None:
9255  ctx = fpsort.ctx
9256  else:
9257  ctx = _get_ctx(ctx)
9258  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9259 
9260 def FPs(names, fpsort, ctx=None):
9261  """Return an array of floating-point constants.
9262 
9263  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9264  >>> x.sort()
9265  FPSort(8, 24)
9266  >>> x.sbits()
9267  24
9268  >>> x.ebits()
9269  8
9270  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9271  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9272  """
9273  ctx = _get_ctx(ctx)
9274  if isinstance(names, str):
9275  names = names.split(" ")
9276  return [FP(name, fpsort, ctx) for name in names]
9277 
9278 def fpAbs(a, ctx=None):
9279  """Create a Z3 floating-point absolute value expression.
9280 
9281  >>> s = FPSort(8, 24)
9282  >>> rm = RNE()
9283  >>> x = FPVal(1.0, s)
9284  >>> fpAbs(x)
9285  fpAbs(1)
9286  >>> y = FPVal(-20.0, s)
9287  >>> y
9288  -1.25*(2**4)
9289  >>> fpAbs(y)
9290  fpAbs(-1.25*(2**4))
9291  >>> fpAbs(-1.25*(2**4))
9292  fpAbs(-1.25*(2**4))
9293  >>> fpAbs(x).sort()
9294  FPSort(8, 24)
9295  """
9296  ctx = _get_ctx(ctx)
9297  [a] = _coerce_fp_expr_list([a], ctx)
9298  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9299 
9300 def fpNeg(a, ctx=None):
9301  """Create a Z3 floating-point addition expression.
9302 
9303  >>> s = FPSort(8, 24)
9304  >>> rm = RNE()
9305  >>> x = FP('x', s)
9306  >>> fpNeg(x)
9307  -x
9308  >>> fpNeg(x).sort()
9309  FPSort(8, 24)
9310  """
9311  ctx = _get_ctx(ctx)
9312  [a] = _coerce_fp_expr_list([a], ctx)
9313  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9314 
9315 def _mk_fp_unary(f, rm, a, ctx):
9316  ctx = _get_ctx(ctx)
9317  [a] = _coerce_fp_expr_list([a], ctx)
9318  if __debug__:
9319  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9320  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9321  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9322 
9323 def _mk_fp_unary_norm(f, a, ctx):
9324  ctx = _get_ctx(ctx)
9325  [a] = _coerce_fp_expr_list([a], ctx)
9326  if __debug__:
9327  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9328  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
9329 
9330 def _mk_fp_unary_pred(f, a, ctx):
9331  ctx = _get_ctx(ctx)
9332  [a] = _coerce_fp_expr_list([a], ctx)
9333  if __debug__:
9334  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9335  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9336 
9337 def _mk_fp_bin(f, rm, a, b, ctx):
9338  ctx = _get_ctx(ctx)
9339  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9340  if __debug__:
9341  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9342  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9343  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9344 
9345 def _mk_fp_bin_norm(f, a, b, ctx):
9346  ctx = _get_ctx(ctx)
9347  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9348  if __debug__:
9349  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9350  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9351 
9352 def _mk_fp_bin_pred(f, a, b, ctx):
9353  ctx = _get_ctx(ctx)
9354  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9355  if __debug__:
9356  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9357  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9358 
9359 def _mk_fp_tern(f, rm, a, b, c, ctx):
9360  ctx = _get_ctx(ctx)
9361  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9362  if __debug__:
9363  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9364  _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")
9365  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9366 
9367 def fpAdd(rm, a, b, ctx=None):
9368  """Create a Z3 floating-point addition expression.
9369 
9370  >>> s = FPSort(8, 24)
9371  >>> rm = RNE()
9372  >>> x = FP('x', s)
9373  >>> y = FP('y', s)
9374  >>> fpAdd(rm, x, y)
9375  fpAdd(RNE(), x, y)
9376  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9377  x + y
9378  >>> fpAdd(rm, x, y).sort()
9379  FPSort(8, 24)
9380  """
9381  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9382 
9383 def fpSub(rm, a, b, ctx=None):
9384  """Create a Z3 floating-point subtraction expression.
9385 
9386  >>> s = FPSort(8, 24)
9387  >>> rm = RNE()
9388  >>> x = FP('x', s)
9389  >>> y = FP('y', s)
9390  >>> fpSub(rm, x, y)
9391  fpSub(RNE(), x, y)
9392  >>> fpSub(rm, x, y).sort()
9393  FPSort(8, 24)
9394  """
9395  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9396 
9397 def fpMul(rm, a, b, ctx=None):
9398  """Create a Z3 floating-point multiplication expression.
9399 
9400  >>> s = FPSort(8, 24)
9401  >>> rm = RNE()
9402  >>> x = FP('x', s)
9403  >>> y = FP('y', s)
9404  >>> fpMul(rm, x, y)
9405  fpMul(RNE(), x, y)
9406  >>> fpMul(rm, x, y).sort()
9407  FPSort(8, 24)
9408  """
9409  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9410 
9411 def fpDiv(rm, a, b, ctx=None):
9412  """Create a Z3 floating-point division expression.
9413 
9414  >>> s = FPSort(8, 24)
9415  >>> rm = RNE()
9416  >>> x = FP('x', s)
9417  >>> y = FP('y', s)
9418  >>> fpDiv(rm, x, y)
9419  fpDiv(RNE(), x, y)
9420  >>> fpDiv(rm, x, y).sort()
9421  FPSort(8, 24)
9422  """
9423  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9424 
9425 def fpRem(a, b, ctx=None):
9426  """Create a Z3 floating-point remainder expression.
9427 
9428  >>> s = FPSort(8, 24)
9429  >>> x = FP('x', s)
9430  >>> y = FP('y', s)
9431  >>> fpRem(x, y)
9432  fpRem(x, y)
9433  >>> fpRem(x, y).sort()
9434  FPSort(8, 24)
9435  """
9436  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9437 
9438 def fpMin(a, b, ctx=None):
9439  """Create a Z3 floating-point minimum expression.
9440 
9441  >>> s = FPSort(8, 24)
9442  >>> rm = RNE()
9443  >>> x = FP('x', s)
9444  >>> y = FP('y', s)
9445  >>> fpMin(x, y)
9446  fpMin(x, y)
9447  >>> fpMin(x, y).sort()
9448  FPSort(8, 24)
9449  """
9450  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9451 
9452 def fpMax(a, b, ctx=None):
9453  """Create a Z3 floating-point maximum expression.
9454 
9455  >>> s = FPSort(8, 24)
9456  >>> rm = RNE()
9457  >>> x = FP('x', s)
9458  >>> y = FP('y', s)
9459  >>> fpMax(x, y)
9460  fpMax(x, y)
9461  >>> fpMax(x, y).sort()
9462  FPSort(8, 24)
9463  """
9464  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9465 
9466 def fpFMA(rm, a, b, c, ctx=None):
9467  """Create a Z3 floating-point fused multiply-add expression.
9468  """
9469  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9470 
9471 def fpSqrt(rm, a, ctx=None):
9472  """Create a Z3 floating-point square root expression.
9473  """
9474  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9475 
9476 def fpRoundToIntegral(rm, a, ctx=None):
9477  """Create a Z3 floating-point roundToIntegral expression.
9478  """
9479  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9480 
9481 def fpIsNaN(a, ctx=None):
9482  """Create a Z3 floating-point isNaN expression.
9483 
9484  >>> s = FPSort(8, 24)
9485  >>> x = FP('x', s)
9486  >>> y = FP('y', s)
9487  >>> fpIsNaN(x)
9488  fpIsNaN(x)
9489  """
9490  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
9491 
9492 def fpIsInf(a, ctx=None):
9493  """Create a Z3 floating-point isInfinite expression.
9494 
9495  >>> s = FPSort(8, 24)
9496  >>> x = FP('x', s)
9497  >>> fpIsInf(x)
9498  fpIsInf(x)
9499  """
9500  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
9501 
9502 def fpIsZero(a, ctx=None):
9503  """Create a Z3 floating-point isZero expression.
9504  """
9505  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
9506 
9507 def fpIsNormal(a, ctx=None):
9508  """Create a Z3 floating-point isNormal expression.
9509  """
9510  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
9511 
9512 def fpIsSubnormal(a, ctx=None):
9513  """Create a Z3 floating-point isSubnormal expression.
9514  """
9515  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
9516 
9517 def fpIsNegative(a, ctx=None):
9518  """Create a Z3 floating-point isNegative expression.
9519  """
9520  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9521 
9522 def fpIsPositive(a, ctx=None):
9523  """Create a Z3 floating-point isPositive expression.
9524  """
9525  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9526  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9527 
9528 def _check_fp_args(a, b):
9529  if __debug__:
9530  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9531 
9532 def fpLT(a, b, ctx=None):
9533  """Create the Z3 floating-point expression `other < self`.
9534 
9535  >>> x, y = FPs('x y', FPSort(8, 24))
9536  >>> fpLT(x, y)
9537  x < y
9538  >>> (x < y).sexpr()
9539  '(fp.lt x y)'
9540  """
9541  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9542 
9543 def fpLEQ(a, b, ctx=None):
9544  """Create the Z3 floating-point expression `other <= self`.
9545 
9546  >>> x, y = FPs('x y', FPSort(8, 24))
9547  >>> fpLEQ(x, y)
9548  x <= y
9549  >>> (x <= y).sexpr()
9550  '(fp.leq x y)'
9551  """
9552  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9553 
9554 def fpGT(a, b, ctx=None):
9555  """Create the Z3 floating-point expression `other > self`.
9556 
9557  >>> x, y = FPs('x y', FPSort(8, 24))
9558  >>> fpGT(x, y)
9559  x > y
9560  >>> (x > y).sexpr()
9561  '(fp.gt x y)'
9562  """
9563  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9564 
9565 def fpGEQ(a, b, ctx=None):
9566  """Create the Z3 floating-point expression `other >= self`.
9567 
9568  >>> x, y = FPs('x y', FPSort(8, 24))
9569  >>> fpGEQ(x, y)
9570  x >= y
9571  >>> (x >= y).sexpr()
9572  '(fp.geq x y)'
9573  """
9574  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9575 
9576 def fpEQ(a, b, ctx=None):
9577  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9578 
9579  >>> x, y = FPs('x y', FPSort(8, 24))
9580  >>> fpEQ(x, y)
9581  fpEQ(x, y)
9582  >>> fpEQ(x, y).sexpr()
9583  '(fp.eq x y)'
9584  """
9585  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9586 
9587 def fpNEQ(a, b, ctx=None):
9588  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9589 
9590  >>> x, y = FPs('x y', FPSort(8, 24))
9591  >>> fpNEQ(x, y)
9592  Not(fpEQ(x, y))
9593  >>> (x != y).sexpr()
9594  '(distinct x y)'
9595  """
9596  return Not(fpEQ(a, b, ctx))
9597 
9598 def fpFP(sgn, exp, sig, ctx=None):
9599  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9600 
9601  >>> s = FPSort(8, 24)
9602  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9603  >>> print(x)
9604  fpFP(1, 127, 4194304)
9605  >>> xv = FPVal(-1.5, s)
9606  >>> print(xv)
9607  -1.5
9608  >>> slvr = Solver()
9609  >>> slvr.add(fpEQ(x, xv))
9610  >>> slvr.check()
9611  sat
9612  >>> xv = FPVal(+1.5, s)
9613  >>> print(xv)
9614  1.5
9615  >>> slvr = Solver()
9616  >>> slvr.add(fpEQ(x, xv))
9617  >>> slvr.check()
9618  unsat
9619  """
9620  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9621  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9622  ctx = _get_ctx(ctx)
9623  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9624  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9625 
9626 def fpToFP(a1, a2=None, a3=None, ctx=None):
9627  """Create a Z3 floating-point conversion expression from other term sorts
9628  to floating-point.
9629 
9630  From a bit-vector term in IEEE 754-2008 format:
9631  >>> x = FPVal(1.0, Float32())
9632  >>> x_bv = fpToIEEEBV(x)
9633  >>> simplify(fpToFP(x_bv, Float32()))
9634  1
9635 
9636  From a floating-point term with different precision:
9637  >>> x = FPVal(1.0, Float32())
9638  >>> x_db = fpToFP(RNE(), x, Float64())
9639  >>> x_db.sort()
9640  FPSort(11, 53)
9641 
9642  From a real term:
9643  >>> x_r = RealVal(1.5)
9644  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9645  1.5
9646 
9647  From a signed bit-vector term:
9648  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9649  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9650  -1.25*(2**2)
9651  """
9652  ctx = _get_ctx(ctx)
9653  if is_bv(a1) and is_fp_sort(a2):
9654  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9655  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9656  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9657  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9658  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9659  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9660  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9661  else:
9662  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9663 
9664 def fpBVToFP(v, sort, ctx=None):
9665  """Create a Z3 floating-point conversion expression that represents the
9666  conversion from a bit-vector term to a floating-point term.
9667 
9668  >>> x_bv = BitVecVal(0x3F800000, 32)
9669  >>> x_fp = fpBVToFP(x_bv, Float32())
9670  >>> x_fp
9671  fpToFP(1065353216)
9672  >>> simplify(x_fp)
9673  1
9674  """
9675  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9676  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9677  ctx = _get_ctx(ctx)
9678  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9679 
9680 def fpFPToFP(rm, v, sort, ctx=None):
9681  """Create a Z3 floating-point conversion expression that represents the
9682  conversion from a floating-point term to a floating-point term of different precision.
9683 
9684  >>> x_sgl = FPVal(1.0, Float32())
9685  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9686  >>> x_dbl
9687  fpToFP(RNE(), 1)
9688  >>> simplify(x_dbl)
9689  1
9690  >>> x_dbl.sort()
9691  FPSort(11, 53)
9692  """
9693  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9694  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9695  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9696  ctx = _get_ctx(ctx)
9697  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9698 
9699 def fpRealToFP(rm, v, sort, ctx=None):
9700  """Create a Z3 floating-point conversion expression that represents the
9701  conversion from a real term to a floating-point term.
9702 
9703  >>> x_r = RealVal(1.5)
9704  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9705  >>> x_fp
9706  fpToFP(RNE(), 3/2)
9707  >>> simplify(x_fp)
9708  1.5
9709  """
9710  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9711  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9712  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9713  ctx = _get_ctx(ctx)
9714  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9715 
9716 def fpSignedToFP(rm, v, sort, ctx=None):
9717  """Create a Z3 floating-point conversion expression that represents the
9718  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9719 
9720  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9721  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9722  >>> x_fp
9723  fpToFP(RNE(), 4294967291)
9724  >>> simplify(x_fp)
9725  -1.25*(2**2)
9726  """
9727  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9728  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9729  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9730  ctx = _get_ctx(ctx)
9731  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9732 
9733 def fpUnsignedToFP(rm, v, sort, ctx=None):
9734  """Create a Z3 floating-point conversion expression that represents the
9735  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9736 
9737  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9738  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9739  >>> x_fp
9740  fpToFPUnsigned(RNE(), 4294967291)
9741  >>> simplify(x_fp)
9742  1*(2**32)
9743  """
9744  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9745  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9746  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9747  ctx = _get_ctx(ctx)
9748  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9749 
9750 def fpToFPUnsigned(rm, x, s, ctx=None):
9751  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9752  if __debug__:
9753  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9754  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9755  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9756  ctx = _get_ctx(ctx)
9757  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9758 
9759 def fpToSBV(rm, x, s, ctx=None):
9760  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9761 
9762  >>> x = FP('x', FPSort(8, 24))
9763  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9764  >>> print(is_fp(x))
9765  True
9766  >>> print(is_bv(y))
9767  True
9768  >>> print(is_fp(y))
9769  False
9770  >>> print(is_bv(x))
9771  False
9772  """
9773  if __debug__:
9774  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9775  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9776  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9777  ctx = _get_ctx(ctx)
9778  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9779 
9780 def fpToUBV(rm, x, s, ctx=None):
9781  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9782 
9783  >>> x = FP('x', FPSort(8, 24))
9784  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9785  >>> print(is_fp(x))
9786  True
9787  >>> print(is_bv(y))
9788  True
9789  >>> print(is_fp(y))
9790  False
9791  >>> print(is_bv(x))
9792  False
9793  """
9794  if __debug__:
9795  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9796  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9797  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9798  ctx = _get_ctx(ctx)
9799  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9800 
9801 def fpToReal(x, ctx=None):
9802  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9803 
9804  >>> x = FP('x', FPSort(8, 24))
9805  >>> y = fpToReal(x)
9806  >>> print(is_fp(x))
9807  True
9808  >>> print(is_real(y))
9809  True
9810  >>> print(is_fp(y))
9811  False
9812  >>> print(is_real(x))
9813  False
9814  """
9815  if __debug__:
9816  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9817  ctx = _get_ctx(ctx)
9818  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9819 
9820 def fpToIEEEBV(x, ctx=None):
9821  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9822 
9823  The size of the resulting bit-vector is automatically determined.
9824 
9825  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9826  knows only one NaN and it will always produce the same bit-vector representation of
9827  that NaN.
9828 
9829  >>> x = FP('x', FPSort(8, 24))
9830  >>> y = fpToIEEEBV(x)
9831  >>> print(is_fp(x))
9832  True
9833  >>> print(is_bv(y))
9834  True
9835  >>> print(is_fp(y))
9836  False
9837  >>> print(is_bv(x))
9838  False
9839  """
9840  if __debug__:
9841  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9842  ctx = _get_ctx(ctx)
9843  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9844 
9845 
9846 
9847 #########################################
9848 #
9849 # Strings, Sequences and Regular expressions
9850 #
9851 #########################################
9852 
9853 class SeqSortRef(SortRef):
9854  """Sequence sort."""
9855 
9856  def is_string(self):
9857  """Determine if sort is a string
9858  >>> s = StringSort()
9859  >>> s.is_string()
9860  True
9861  >>> s = SeqSort(IntSort())
9862  >>> s.is_string()
9863  False
9864  """
9865  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9866 
9867 
9868 def StringSort(ctx=None):
9869  """Create a string sort
9870  >>> s = StringSort()
9871  >>> print(s)
9872  String
9873  """
9874  ctx = _get_ctx(ctx)
9875  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9876 
9877 
9878 def SeqSort(s):
9879  """Create a sequence sort over elements provided in the argument
9880  >>> s = SeqSort(IntSort())
9881  >>> s == Unit(IntVal(1)).sort()
9882  True
9883  """
9884  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9885 
9886 class SeqRef(ExprRef):
9887  """Sequence expression."""
9888 
9889  def sort(self):
9890  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9891 
9892  def __add__(self, other):
9893  return Concat(self, other)
9894 
9895  def __radd__(self, other):
9896  return Concat(other, self)
9897 
9898  def __getitem__(self, i):
9899  if _is_int(i):
9900  i = IntVal(i, self.ctx)
9901  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9902 
9903  def is_string(self):
9904  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9905 
9906  def is_string_value(self):
9907  return Z3_is_string(self.ctx_ref(), self.as_ast())
9908 
9909  def as_string(self):
9910  """Return a string representation of sequence expression."""
9911  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9912 
9913 
9914 def _coerce_seq(s, ctx=None):
9915  if isinstance(s, str):
9916  ctx = _get_ctx(ctx)
9917  s = StringVal(s, ctx)
9918  if not is_expr(s):
9919  raise Z3Exception("Non-expression passed as a sequence")
9920  if not is_seq(s):
9921  raise Z3Exception("Non-sequence passed as a sequence")
9922  return s
9923 
9924 def _get_ctx2(a, b, ctx=None):
9925  if is_expr(a):
9926  return a.ctx
9927  if is_expr(b):
9928  return b.ctx
9929  if ctx is None:
9930  ctx = main_ctx()
9931  return ctx
9932 
9933 def is_seq(a):
9934  """Return `True` if `a` is a Z3 sequence expression.
9935  >>> print (is_seq(Unit(IntVal(0))))
9936  True
9937  >>> print (is_seq(StringVal("abc")))
9938  True
9939  """
9940  return isinstance(a, SeqRef)
9941 
9942 def is_string(a):
9943  """Return `True` if `a` is a Z3 string expression.
9944  >>> print (is_string(StringVal("ab")))
9945  True
9946  """
9947  return isinstance(a, SeqRef) and a.is_string()
9948 
9949 def is_string_value(a):
9950  """return 'True' if 'a' is a Z3 string constant expression.
9951  >>> print (is_string_value(StringVal("a")))
9952  True
9953  >>> print (is_string_value(StringVal("a") + StringVal("b")))
9954  False
9955  """
9956  return isinstance(a, SeqRef) and a.is_string_value()
9957 
9958 
9959 def StringVal(s, ctx=None):
9960  """create a string expression"""
9961  ctx = _get_ctx(ctx)
9962  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
9963 
9964 def String(name, ctx=None):
9965  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
9966 
9967  >>> x = String('x')
9968  """
9969  ctx = _get_ctx(ctx)
9970  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
9971 
9972 def SubString(s, offset, length):
9973  """Extract substring or subsequence starting at offset"""
9974  return Extract(s, offset, length)
9975 
9976 def SubSeq(s, offset, length):
9977  """Extract substring or subsequence starting at offset"""
9978  return Extract(s, offset, length)
9979 
9980 def Strings(names, ctx=None):
9981  """Return a tuple of String constants. """
9982  ctx = _get_ctx(ctx)
9983  if isinstance(names, str):
9984  names = names.split(" ")
9985  return [String(name, ctx) for name in names]
9986 
9987 def Empty(s):
9988  """Create the empty sequence of the given sort
9989  >>> e = Empty(StringSort())
9990  >>> print(e)
9991  ""
9992  >>> e2 = StringVal("")
9993  >>> print(e.eq(e2))
9994  True
9995  >>> e3 = Empty(SeqSort(IntSort()))
9996  >>> print(e3)
9997  seq.empty
9998  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
9999  >>> print(e4)
10000  re.empty
10001  """
10002  if isinstance(s, SeqSortRef):
10003  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10004  if isinstance(s, ReSortRef):
10005  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10006  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10007 
10008 def Full(s):
10009  """Create the regular expression that accepts the universal language
10010  >>> e = Full(ReSort(SeqSort(IntSort())))
10011  >>> print(e)
10012  re.all
10013  >>> e1 = Full(ReSort(StringSort()))
10014  >>> print(e1)
10015  re.all
10016  """
10017  if isinstance(s, ReSortRef):
10018  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10019  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10020 
10021 
10022 def Unit(a):
10023  """Create a singleton sequence"""
10024  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10025 
10026 def PrefixOf(a, b):
10027  """Check if 'a' is a prefix of 'b'
10028  >>> s1 = PrefixOf("ab", "abc")
10029  >>> simplify(s1)
10030  True
10031  >>> s2 = PrefixOf("bc", "abc")
10032  >>> simplify(s2)
10033  False
10034  """
10035  ctx = _get_ctx2(a, b)
10036  a = _coerce_seq(a, ctx)
10037  b = _coerce_seq(b, ctx)
10038  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10039 
10040 def SuffixOf(a, b):
10041  """Check if 'a' is a suffix of 'b'
10042  >>> s1 = SuffixOf("ab", "abc")
10043  >>> simplify(s1)
10044  False
10045  >>> s2 = SuffixOf("bc", "abc")
10046  >>> simplify(s2)
10047  True
10048  """
10049  ctx = _get_ctx2(a, b)
10050  a = _coerce_seq(a, ctx)
10051  b = _coerce_seq(b, ctx)
10052  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10053 
10054 def Contains(a, b):
10055  """Check if 'a' contains 'b'
10056  >>> s1 = Contains("abc", "ab")
10057  >>> simplify(s1)
10058  True
10059  >>> s2 = Contains("abc", "bc")
10060  >>> simplify(s2)
10061  True
10062  >>> x, y, z = Strings('x y z')
10063  >>> s3 = Contains(Concat(x,y,z), y)
10064  >>> simplify(s3)
10065  True
10066  """
10067  ctx = _get_ctx2(a, b)
10068  a = _coerce_seq(a, ctx)
10069  b = _coerce_seq(b, ctx)
10070  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10071 
10072 
10073 def Replace(s, src, dst):
10074  """Replace the first occurrence of 'src' by 'dst' in 's'
10075  >>> r = Replace("aaa", "a", "b")
10076  >>> simplify(r)
10077  "baa"
10078  """
10079  ctx = _get_ctx2(dst, s)
10080  if ctx is None and is_expr(src):
10081  ctx = src.ctx
10082  src = _coerce_seq(src, ctx)
10083  dst = _coerce_seq(dst, ctx)
10084  s = _coerce_seq(s, ctx)
10085  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10086 
10087 def IndexOf(s, substr):
10088  return IndexOf(s, substr, IntVal(0))
10089 
10090 def IndexOf(s, substr, offset):
10091  """Retrieve the index of substring within a string starting at a specified offset.
10092  >>> simplify(IndexOf("abcabc", "bc", 0))
10093  1
10094  >>> simplify(IndexOf("abcabc", "bc", 2))
10095  4
10096  """
10097  ctx = None
10098  if is_expr(offset):
10099  ctx = offset.ctx
10100  ctx = _get_ctx2(s, substr, ctx)
10101  s = _coerce_seq(s, ctx)
10102  substr = _coerce_seq(substr, ctx)
10103  if _is_int(offset):
10104  offset = IntVal(offset, ctx)
10105  return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10106 
10107 def Length(s):
10108  """Obtain the length of a sequence 's'
10109  >>> l = Length(StringVal("abc"))
10110  >>> simplify(l)
10111  3
10112  """
10113  s = _coerce_seq(s)
10114  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10115 
10116 def StrToInt(s):
10117  """Convert string expression to integer
10118  >>> a = StrToInt("1")
10119  >>> simplify(1 == a)
10120  True
10121  >>> b = StrToInt("2")
10122  >>> simplify(1 == b)
10123  False
10124  >>> c = StrToInt(IntToStr(2))
10125  >>> simplify(1 == c)
10126  False
10127  """
10128  s = _coerce_seq(s)
10129  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10130 
10131 
10132 def IntToStr(s):
10133  """Convert integer expression to string"""
10134  if not is_expr(s):
10135  s = _py2expr(s)
10136  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10137 
10138 
10139 def Re(s, ctx=None):
10140  """The regular expression that accepts sequence 's'
10141  >>> s1 = Re("ab")
10142  >>> s2 = Re(StringVal("ab"))
10143  >>> s3 = Re(Unit(BoolVal(True)))
10144  """
10145  s = _coerce_seq(s, ctx)
10146  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10147 
10148 
10149 
10150 
10151 ## Regular expressions
10152 
10153 class ReSortRef(SortRef):
10154  """Regular expression sort."""
10155 
10156 
10157 def ReSort(s):
10158  if is_ast(s):
10159  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10160  if s is None or isinstance(s, Context):
10161  ctx = _get_ctx(s)
10162  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10163  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10164 
10165 
10166 class ReRef(ExprRef):
10167  """Regular expressions."""
10168 
10169  def __add__(self, other):
10170  return Union(self, other)
10171 
10172 
10173 def is_re(s):
10174  return isinstance(s, ReRef)
10175 
10176 
10177 def InRe(s, re):
10178  """Create regular expression membership test
10179  >>> re = Union(Re("a"),Re("b"))
10180  >>> print (simplify(InRe("a", re)))
10181  True
10182  >>> print (simplify(InRe("b", re)))
10183  True
10184  >>> print (simplify(InRe("c", re)))
10185  False
10186  """
10187  s = _coerce_seq(s, re.ctx)
10188  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10189 
10190 def Union(*args):
10191  """Create union of regular expressions.
10192  >>> re = Union(Re("a"), Re("b"), Re("c"))
10193  >>> print (simplify(InRe("d", re)))
10194  False
10195  """
10196  args = _get_args(args)
10197  sz = len(args)
10198  if __debug__:
10199  _z3_assert(sz > 0, "At least one argument expected.")
10200  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10201  if sz == 1:
10202  return args[0]
10203  ctx = args[0].ctx
10204  v = (Ast * sz)()
10205  for i in range(sz):
10206  v[i] = args[i].as_ast()
10207  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10208 
10209 def Plus(re):
10210  """Create the regular expression accepting one or more repetitions of argument.
10211  >>> re = Plus(Re("a"))
10212  >>> print(simplify(InRe("aa", re)))
10213  True
10214  >>> print(simplify(InRe("ab", re)))
10215  False
10216  >>> print(simplify(InRe("", re)))
10217  False
10218  """
10219  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10220 
10221 def Option(re):
10222  """Create the regular expression that optionally accepts the argument.
10223  >>> re = Option(Re("a"))
10224  >>> print(simplify(InRe("a", re)))
10225  True
10226  >>> print(simplify(InRe("", re)))
10227  True
10228  >>> print(simplify(InRe("aa", re)))
10229  False
10230  """
10231  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10232 
10233 def Complement(re):
10234  """Create the complement regular expression."""
10235  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10236 
10237 def Star(re):
10238  """Create the regular expression accepting zero or more repetitions of argument.
10239  >>> re = Star(Re("a"))
10240  >>> print(simplify(InRe("aa", re)))
10241  True
10242  >>> print(simplify(InRe("ab", re)))
10243  False
10244  >>> print(simplify(InRe("", re)))
10245  True
10246  """
10247  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10248 
10249 def Loop(re, lo, hi=0):
10250  """Create the regular expression accepting between a lower and upper bound repetitions
10251  >>> re = Loop(Re("a"), 1, 3)
10252  >>> print(simplify(InRe("aa", re)))
10253  True
10254  >>> print(simplify(InRe("aaaa", re)))
10255  False
10256  >>> print(simplify(InRe("", re)))
10257  False
10258  """
10259  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
def param_descrs(self)
Definition: z3py.py:7303
def value(self)
Definition: z3py.py:7268
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
def lower(self, obj)
Definition: z3py.py:7385
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
def name(self)
Definition: z3py.py:656
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9820
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
def is_lt(a)
Definition: z3py.py:2644
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:8080
def __ge__(self, other)
Definition: z3py.py:7892
Z3_bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:3063
def is_distinct(a)
Definition: z3py.py:1501
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
def __gt__(self, other)
Definition: z3py.py:7866
def Then(ts, ks)
Definition: z3py.py:7664
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def SignExt(n, a)
Definition: z3py.py:4040
def update_rule(self, head, body, name)
Definition: z3py.py:6998
def SeqSort(s)
Definition: z3py.py:9878
Fixedpoint.
Definition: z3py.py:6856
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
def upper(self)
Definition: z3py.py:7256
def OrElse(ts, ks)
Definition: z3py.py:7676
def is_fprm_sort(s)
Definition: z3py.py:8675
def get_version_string()
Definition: z3py.py:69
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
Quantifiers.
Definition: z3py.py:1786
def AtLeast(args)
Definition: z3py.py:8226
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5001
def entry(self, idx)
Definition: z3py.py:5840
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7033
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def upper_values(self, obj)
Definition: z3py.py:7400
def RatVal(a, b, ctx=None)
Definition: z3py.py:2949
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].
def add(self, args)
Definition: z3py.py:7319
def __getitem__(self, idx)
Definition: z3py.py:7483
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Function Declarations.
Definition: z3py.py:640
def SetUnion(args)
Definition: z3py.py:4542
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3050
Booleans.
Definition: z3py.py:1349
def Product(args)
Definition: z3py.py:8184
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def prec(self)
Definition: z3py.py:5138
def IsInt(a)
Definition: z3py.py:3110
def Sum(args)
Definition: z3py.py:8158
def __repr__(self)
Definition: z3py.py:307
def is_arith_sort(s)
Definition: z3py.py:2144
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
Z3_bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def ReSort(s)
Definition: z3py.py:10157
def push(self)
Definition: z3py.py:6990
def Function(name, sig)
Definition: z3py.py:778
def RTZ(ctx=None)
Definition: z3py.py:8909
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
def as_ast(self)
Definition: z3py.py:862
def __iadd__(self, fml)
Definition: z3py.py:7323
def RealSort(ctx=None)
Definition: z3py.py:2889
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3244
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9664
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9260
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9193
def get_rules(self)
Definition: z3py.py:7072
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
def RealVarVector(n, ctx=None)
Definition: z3py.py:1332
def sort(self)
Definition: z3py.py:7163
def AndThen(ts, ks)
Definition: z3py.py:7645
def ZeroExt(n, a)
Definition: z3py.py:4069
def assertions(self)
Definition: z3py.py:7419
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def substitute_vars(t, m)
Definition: z3py.py:8138
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def is_int(self)
Definition: z3py.py:2090
def Var(idx, s)
Definition: z3py.py:1310
def __del__(self)
Definition: z3py.py:7849
def is_bool(self)
Definition: z3py.py:1379
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def probes(ctx=None)
Definition: z3py.py:7976
def ArraySort(sig)
Definition: z3py.py:4334
def to_symbol(s, ctx=None)
Definition: z3py.py:105
def help(self)
Definition: z3py.py:6760
def reset_params()
Definition: z3py.py:256
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def declare(self, name, args)
Definition: z3py.py:4679
def is_string_value(a)
Definition: z3py.py:9949
def as_ast(self)
Definition: z3py.py:338
def assert_exprs(self, args)
Definition: z3py.py:7307
def LShR(a, b)
Definition: z3py.py:3979
def is_default(a)
Definition: z3py.py:4309
def set_option(args, kws)
Definition: z3py.py:261
Z3_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs. The result is the new AST. The arrays from and to must have size num_exprs. For every i smaller than num_exprs, we must have that sort of from[i] must be equal to sort of to[i].
Bit-Vectors.
Definition: z3py.py:3156
def Consts(names, sort)
Definition: z3py.py:1291
def use_pp(self)
Definition: z3py.py:287
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
def IntVal(val, ctx=None)
Definition: z3py.py:2920
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
def __nonzero__(self)
Definition: z3py.py:316
def is_and(a)
Definition: z3py.py:1448
def ref(self)
Definition: z3py.py:192
def push(self)
Definition: z3py.py:6390
def fpGT(a, b, ctx=None)
Definition: z3py.py:9554
def sort(self)
Definition: z3py.py:1385
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8475
def ULT(a, b)
Definition: z3py.py:3868
def fpIsInf(a, ctx=None)
Definition: z3py.py:9492
Arithmetic.
Definition: z3py.py:2073
FP Expressions.
Definition: z3py.py:8687
def __init__(self, ctx=None)
Definition: z3py.py:7281
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
def minimize(self, arg)
Definition: z3py.py:7350
def help(self)
Definition: z3py.py:7299
def sort(self)
Definition: z3py.py:2162
Z3_bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
def is_to_real(a)
Definition: z3py.py:2688
def as_ast(self)
Definition: z3py.py:496
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9626
def assert_exprs(self, args)
Definition: z3py.py:6891
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
def Float64(ctx=None)
Definition: z3py.py:8641
def param_descrs(self)
Definition: z3py.py:6887
def is_select(a)
Definition: z3py.py:4492
def is_real(self)
Definition: z3py.py:2186
Z3_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
def is_int(self)
Definition: z3py.py:2172
ASTs base class.
Definition: z3py.py:285
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
def __ne__(self, other)
Definition: z3py.py:912
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9733
def is_gt(a)
Definition: z3py.py:2666
def lower_values(self, obj)
Definition: z3py.py:7395
def pop(self)
Definition: z3py.py:7358
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
def sexpr(self)
Definition: z3py.py:7503
def set_param(args, kws)
Definition: z3py.py:233
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def __eq__(self, other)
Definition: z3py.py:891
def domain(self, i)
Definition: z3py.py:676
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
def as_string(self)
Definition: z3py.py:7167
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2027
def is_implies(a)
Definition: z3py.py:1470
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
def Loop(re, lo, hi=0)
Definition: z3py.py:10249
def AtMost(args)
Definition: z3py.py:8209
def __deepcopy__(self, memo={})
Definition: z3py.py:7457
def register_relation(self, relations)
Definition: z3py.py:7042
def IndexOf(s, substr)
Definition: z3py.py:10087
def is_app(a)
Definition: z3py.py:1116
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9780
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
def __len__(self)
Definition: z3py.py:7464
def StringSort(ctx=None)
Definition: z3py.py:9868
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
def And(args)
Definition: z3py.py:1655
def open_log(fname)
Definition: z3py.py:97
def __deepcopy__(self, memo={})
Definition: z3py.py:7558
def EmptySet(s)
Definition: z3py.py:4526
def solver(self)
Definition: z3py.py:7565
def PrefixOf(a, b)
Definition: z3py.py:10026
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9565
def PbEq(args, k, ctx=None)
Definition: z3py.py:8282
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def rule(self, head, body=None, name=None)
Definition: z3py.py:6944
def range(self)
Definition: z3py.py:4231
def __repr__(self)
Definition: z3py.py:7500
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
def fpRem(a, b, ctx=None)
Definition: z3py.py:9425
def Cbrt(a, ctx=None)
Definition: z3py.py:3138
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def SetDifference(a, b)
Definition: z3py.py:4595
def disable_trace(msg)
Definition: z3py.py:66
def RotateRight(a, b)
Definition: z3py.py:4025
def sort(self)
Definition: z3py.py:3201
def is_ge(a)
Definition: z3py.py:2655
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
def is_K(a)
Definition: z3py.py:4282
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:880
def tactics(ctx=None)
Definition: z3py.py:7785
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
def is_const(a)
Definition: z3py.py:1141
def Star(re)
Definition: z3py.py:10237
def InRe(s, re)
Definition: z3py.py:10177
def is_finite_domain_sort(s)
Definition: z3py.py:7149
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
def push(self)
Definition: z3py.py:7354
def z3_error_handler(c, e)
Definition: z3py.py:152
def RotateLeft(a, b)
Definition: z3py.py:4010
def Const(name, sort)
Definition: z3py.py:1280
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1573
def substitute(t, m)
Definition: z3py.py:8112
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
def Array(name, dom, rng)
Definition: z3py.py:4366
def main_ctx()
Definition: z3py.py:207
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def If(a, b, c, ctx=None)
Definition: z3py.py:1227
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3720
def get_id(self)
Definition: z3py.py:650
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
def is_array(a)
Definition: z3py.py:4257
def is_pattern(a)
Definition: z3py.py:1734
Statistics.
Definition: z3py.py:6186
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8064
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
def is_fp_value(a)
Definition: z3py.py:9062
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
def help_simplify()
Definition: z3py.py:8104
def fpMax(a, b, ctx=None)
Definition: z3py.py:9452
def IsSubset(a, b)
Definition: z3py.py:4615
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
def upper(self, obj)
Definition: z3py.py:7390
def get_rule_names_along_trace(self)
Definition: z3py.py:7021
def Int(name, ctx=None)
Definition: z3py.py:2976
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6859
def __repr__(self)
Definition: z3py.py:7427
def __repr__(self)
Definition: z3py.py:7080
Arrays.
Definition: z3py.py:4189
def simplify_param_descrs()
Definition: z3py.py:8108
def is_map(a)
Definition: z3py.py:4294
def is_or(a)
Definition: z3py.py:1459
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9750
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9397
Patterns.
Definition: z3py.py:1724
def fpAbs(a, ctx=None)
Definition: z3py.py:9278
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9576
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3736
def SetIntersect(args)
Definition: z3py.py:4554
def is_int_value(a)
Definition: z3py.py:2505
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
def __hash__(self)
Definition: z3py.py:575
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def Default(a)
Definition: z3py.py:4400
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7142
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
def CreateDatatypes(ds)
Definition: z3py.py:4736
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def FreshConst(sort, prefix='c')
Definition: z3py.py:1305
def URem(a, b)
Definition: z3py.py:3939
def PbGe(args, k)
Definition: z3py.py:8272
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def Union(args)
Definition: z3py.py:10190
def SuffixOf(a, b)
Definition: z3py.py:10040
def __eq__(self, other)
Definition: z3py.py:310
def __mul__(self, other)
Definition: z3py.py:1391
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9716
def is_mod(a)
Definition: z3py.py:2622
def fact(self, head, name=None)
Definition: z3py.py:6948
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
def convert_model(self, model)
Definition: z3py.py:5270
def UGE(a, b)
Definition: z3py.py:3885
def Replace(s, src, dst)
Definition: z3py.py:10073
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs...
def Real(name, ctx=None)
Definition: z3py.py:3024
def __init__(self, args, kws)
Definition: z3py.py:168
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective.
def lower_values(self)
Definition: z3py.py:7260
def cast(self, val)
Definition: z3py.py:526
def Length(s)
Definition: z3py.py:10107
def decl(self)
Definition: z3py.py:933
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7728
def Bools(names, ctx=None)
Definition: z3py.py:1558
def is_eq(a)
Definition: z3py.py:1492
def __del__(self)
Definition: z3py.py:187
def Float32(ctx=None)
Definition: z3py.py:8631
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9481
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def statistics(self)
Definition: z3py.py:7436
def depth(self)
Definition: z3py.py:5103
def __str__(self)
Definition: z3py.py:7274
def sort(self)
Definition: z3py.py:868
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def is_real(a)
Definition: z3py.py:2481
def RealVal(val, ctx=None)
Definition: z3py.py:2931
def PbLe(args, k)
Definition: z3py.py:8262
def get_id(self)
Definition: z3py.py:865
def Extract(high, low, a)
Definition: z3py.py:3824
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def RealVar(idx, ctx=None)
Definition: z3py.py:1322
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2010
def solve_using(s, args, keywords)
Definition: z3py.py:8321
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def set_predicate_representation(self, f, representations)
Definition: z3py.py:7048
def maximize(self, arg)
Definition: z3py.py:7346
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
def eq(a, b)
Definition: z3py.py:416
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
def RecFunction(name, sig)
Definition: z3py.py:803
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def help(self)
Definition: z3py.py:7609
def __bool__(self)
Definition: z3py.py:319
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7327
def sexpr(self)
Definition: z3py.py:7431
def is_le(a)
Definition: z3py.py:2633
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def __deepcopy__(self, memo={})
Definition: z3py.py:301
def is_not(a)
Definition: z3py.py:1481
def get_map_func(a)
Definition: z3py.py:4317
def Implies(a, b, ctx=None)
Definition: z3py.py:1600
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7544
def __deepcopy__(self, memo={})
Definition: z3py.py:7286
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def apply(self, goal, arguments, keywords)
Definition: z3py.py:7582
def solve(args, keywords)
Definition: z3py.py:8293
def is_arith(a)
Definition: z3py.py:2443
def __del__(self)
Definition: z3py.py:7561
def is_sort(s)
Definition: z3py.py:579
def objectives(self)
Definition: z3py.py:7423
def Or(args)
Definition: z3py.py:1688
def __init__(self, opt, value, is_max)
Definition: z3py.py:7247
def num_sorts(self)
Definition: z3py.py:6015
def add(self, args)
Definition: z3py.py:6905
def hash(self)
Definition: z3py.py:386
def SetSort(s)
Sets.
Definition: z3py.py:4522
def is_int(a)
Definition: z3py.py:2463
def check(self, assumptions)
Definition: z3py.py:6552
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
def fpPlusInfinity(s)
Definition: z3py.py:9150
def insert(self, args)
Definition: z3py.py:6917
def is_quantifier(a)
Definition: z3py.py:1963
def as_string(self)
Definition: z3py.py:7199
def is_string(a)
Definition: z3py.py:9942
def StringVal(s, ctx=None)
Definition: z3py.py:9959
def Plus(re)
Definition: z3py.py:10209
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:10116
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:7599
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7210
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0...
def params(self)
Definition: z3py.py:930
def num_args(self)
Definition: z3py.py:948
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9076
def __del__(self)
Definition: z3py.py:7460
def prove(claim, keywords)
Definition: z3py.py:8350
def DeclareSort(name, ctx=None)
Definition: z3py.py:616
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def Ints(names, ctx=None)
Definition: z3py.py:2988
def parse_file(self, f)
Definition: z3py.py:7065
def pop(self)
Definition: z3py.py:6994
def is_true(a)
Definition: z3py.py:1418
def Int2BV(a, num_bits)
Definition: z3py.py:3698
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def Contains(a, b)
Definition: z3py.py:10054
def is_finite_domain_value(a)
Definition: z3py.py:7224
def is_real(self)
Definition: z3py.py:2076
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a string of a numeric constant term.
def FreshBool(prefix='b', ctx=None)
Definition: z3py.py:1587
def Bool(name, ctx=None)
Definition: z3py.py:1547
def probe_description(name, ctx=None)
Definition: z3py.py:7986
def get_rules_along_trace(self)
Definition: z3py.py:7017
def __deepcopy__(self, memo={})
Definition: z3py.py:6870
def __del__(self)
Definition: z3py.py:7289
def Lambda(vs, body)
Definition: z3py.py:2047
def tactic_description(name, ctx=None)
Definition: z3py.py:7795
def param_descrs(self)
Definition: z3py.py:7613
def RNE(ctx=None)
Definition: z3py.py:8877
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
def is_store(a)
Definition: z3py.py:4504
def get_version()
Definition: z3py.py:77
def from_string(self, s)
Definition: z3py.py:7412
def SetDel(s, e)
Definition: z3py.py:4576
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def SRem(a, b)
Definition: z3py.py:3959
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9237
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:9759
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9411
def eq(self, other)
Definition: z3py.py:350
def FullSet(s)
Definition: z3py.py:4534
def get_id(self)
Definition: z3py.py:499
def ToReal(a)
Definition: z3py.py:3076
def is_bv_value(a)
Definition: z3py.py:3662
def range(self)
Definition: z3py.py:689
def is_idiv(a)
Definition: z3py.py:2611
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3759
def translate(self, target)
Definition: z3py.py:367
def from_file(self, filename)
Definition: z3py.py:7405
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
def __init__(self, probe, ctx=None)
Definition: z3py.py:7823
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate. ...
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def query_from_lvl(self, lvl, query)
Definition: z3py.py:6974
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
def __ne__(self, other)
Definition: z3py.py:564
def __le__(self, other)
Definition: z3py.py:7879
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
def cast(self, val)
Definition: z3py.py:1351
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality. Thus, two ast nodes created by the same context and having the same children and same function symbols have the same identifiers. Ast nodes created in the same context, but having different children or different functions have different identifiers. Variables and quantifiers are also assigned different identifiers according to their structure.
def as_func_decl(self)
Definition: z3py.py:653
def size(self)
Definition: z3py.py:3212
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def to_string(self, queries)
Definition: z3py.py:7089
def assertions(self)
Definition: z3py.py:6705
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def Strings(names, ctx=None)
Definition: z3py.py:9980
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
def get_id(self)
Definition: z3py.py:342
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9383
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9598
def __lt__(self, other)
Definition: z3py.py:7853
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
def create(self)
Definition: z3py.py:4702
def Full(s)
Definition: z3py.py:10008
def is_const_array(a)
Definition: z3py.py:4270
def fpNaN(s)
Definition: z3py.py:9134
def cast(self, val)
Definition: z3py.py:2108
def as_long(self)
Definition: z3py.py:7187
def sexpr(self)
Definition: z3py.py:329
def reason_unknown(self)
Definition: z3py.py:7371
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
def kind(self)
Definition: z3py.py:502
def IntSort(ctx=None)
Definition: z3py.py:2873
def Unit(a)
Definition: z3py.py:10022
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def parse_string(self, s)
Definition: z3py.py:7058
def is_rational_value(a)
Definition: z3py.py:2528
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def is_finite_domain(a)
Definition: z3py.py:7171
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
def fpNeg(a, ctx=None)
Definition: z3py.py:9300
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:9543
def get_ground_sat_answer(self)
Definition: z3py.py:7012
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4925
def sexpr(self)
Definition: z3py.py:7084
def __ne__(self, other)
Definition: z3py.py:7918
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
def declare_var(self, vars)
Definition: z3py.py:7107
def arg(self, idx)
Definition: z3py.py:964
def sort(self)
Definition: z3py.py:8690
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
def IntToStr(s)
Definition: z3py.py:10132
def Xor(a, b, ctx=None)
Definition: z3py.py:1615
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def Select(a, i)
Definition: z3py.py:4427
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:6921
def __rmul__(self, other)
Definition: z3py.py:1388
def params(self)
Definition: z3py.py:710
def query(self, query)
Definition: z3py.py:6952
def RecAddDefinition(f, args, body)
Definition: z3py.py:820
def get_var_index(a)
Definition: z3py.py:1183
def Not(a, ctx=None)
Definition: z3py.py:1630
def MultiPattern(args)
Definition: z3py.py:1751
def BoolVal(val, ctx=None)
Definition: z3py.py:1529
def upper_values(self)
Definition: z3py.py:7264
def model(self)
Definition: z3py.py:7375
def is_div(a)
Definition: z3py.py:2595
FP Numerals.
Definition: z3py.py:8931
FP Sorts.
Definition: z3py.py:8586
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def ctx_ref(self)
Definition: z3py.py:346
def help(self)
Definition: z3py.py:6883
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
def Re(s, ctx=None)
Definition: z3py.py:10139
def fpMin(a, b, ctx=None)
Definition: z3py.py:9438
def is_fp_sort(s)
Definition: z3py.py:8665
Expressions.
Definition: z3py.py:852
def SetComplement(s)
Definition: z3py.py:4586
def is_app_of(a, k)
Definition: z3py.py:1215
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def is_probe(p)
Definition: z3py.py:7960
def is_mul(a)
Definition: z3py.py:2573
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:3011
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def subsort(self, other)
Definition: z3py.py:518
def kind(self)
Definition: z3py.py:698
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
def is_bv_sort(s)
Definition: z3py.py:3188
def Update(a, i, v)
Definition: z3py.py:4379
def With(t, args, keys)
Definition: z3py.py:7732
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
def append_log(s)
Definition: z3py.py:101
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
def statistics(self)
Definition: z3py.py:7097
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
def is_add(a)
Definition: z3py.py:2562
def ParOr(ts, ks)
Definition: z3py.py:7696
def K(dom, v)
Definition: z3py.py:4464
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3706
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def __hash__(self)
Definition: z3py.py:908
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3000
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9367
def get_assertions(self)
Definition: z3py.py:7076
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def get_num_levels(self, predicate)
Definition: z3py.py:7029
def UGT(a, b)
Definition: z3py.py:3902
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
def get_answer(self)
Definition: z3py.py:7007
def children(self)
Definition: z3py.py:985
def BV2Int(a, is_signed=False)
Definition: z3py.py:3676
def arity(self)
Definition: z3py.py:5826
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def WithParams(t, p)
Definition: z3py.py:7745
def Store(a, i, v)
Definition: z3py.py:4411
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7777
def numerator(self)
Definition: z3py.py:2743
def __str__(self)
Definition: z3py.py:304
def is_int(self)
Definition: z3py.py:1376
def is_ast(a)
Definition: z3py.py:396
def domain(self)
Definition: z3py.py:4222
def Empty(s)
Definition: z3py.py:9987
def __init__(self, ast, ctx=None)
Definition: z3py.py:292
def UDiv(a, b)
Definition: z3py.py:3919
def is_expr(a)
Definition: z3py.py:1094
def __init__(self, result, ctx)
Definition: z3py.py:7452
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7116
def set(self, args, keys)
Definition: z3py.py:6877
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
def fpToReal(x, ctx=None)
Definition: z3py.py:9801
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
def Map(f, args)
Definition: z3py.py:4442
def __call__(self, args)
Definition: z3py.py:734
def else_value(self)
Definition: z3py.py:5787
def subsort(self, other)
Definition: z3py.py:1373
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
def describe_probes()
Definition: z3py.py:7994
def add_cover(self, level, predicate, property)
Definition: z3py.py:7038
def describe_tactics()
Definition: z3py.py:7803
def is_bool(a)
Definition: z3py.py:1401
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
def Distinct(args)
Definition: z3py.py:1249
def __call__(self, goal)
Definition: z3py.py:7932
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
def unsat_core(self)
Definition: z3py.py:7382
def body(self)
Definition: z3py.py:1897
def as_list(self)
Definition: z3py.py:5871
def arity(self)
Definition: z3py.py:667
def Reals(names, ctx=None)
Definition: z3py.py:3036
def is_bv(a)
Definition: z3py.py:3649
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def SetAdd(s, e)
Definition: z3py.py:4566
def is_var(a)
Definition: z3py.py:1159
def as_expr(self)
Definition: z3py.py:7508
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def __copy__(self)
Definition: z3py.py:383
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9680
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9587
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:7758
def RepeatBitVec(n, a)
Definition: z3py.py:4096
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective. The returned vector ...
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
def SolverFor(logic, ctx=None)
Definition: z3py.py:6818
def get_full_version()
Definition: z3py.py:85
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7714
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
def lower(self)
Definition: z3py.py:7252
def as_ast(self)
Definition: z3py.py:647
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def is_false(a)
Definition: z3py.py:1435
def set(self, args, keys)
Definition: z3py.py:7293
def ULE(a, b)
Definition: z3py.py:3851
def is_is_int(a)
Definition: z3py.py:2677
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
def enable_trace(msg)
Definition: z3py.py:63
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
def name(self)
Definition: z3py.py:541
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9699
def is_fprm(a)
Definition: z3py.py:8913
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def __iadd__(self, fml)
Definition: z3py.py:6909
def Option(re)
Definition: z3py.py:10221
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def check(self, assumptions)
Definition: z3py.py:7362
def as_signed_long(self)
Definition: z3py.py:3624
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def __del__(self)
Definition: z3py.py:6873
def is_func_decl(a)
Definition: z3py.py:766
def interrupt(self)
Definition: z3py.py:196
def is_sub(a)
Definition: z3py.py:2584
def Concat(args)
Definition: z3py.py:3779
def FailIf(p, ctx=None)
Definition: z3py.py:8027
def __hash__(self)
Definition: z3py.py:313
def append(self, args)
Definition: z3py.py:6913
def When(p, t, ctx=None)
Definition: z3py.py:8046
def is_seq(a)
Definition: z3py.py:9933
def is_algebraic_value(a)
Definition: z3py.py:2549
def BoolSort(ctx=None)
Definition: z3py.py:1512
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def get_param(name)
Definition: z3py.py:266
def is_to_int(a)
Definition: z3py.py:2702
def __eq__(self, other)
Definition: z3py.py:7905
def Q(a, b, ctx=None)
Definition: z3py.py:2964
def __deepcopy__(self, memo={})
Definition: z3py.py:7846
def String(name, ctx=None)
Definition: z3py.py:9964
def reason_unknown(self)
Definition: z3py.py:7102
def IsMember(e, s)
Definition: z3py.py:4605
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
def ToInt(a)
Definition: z3py.py:3093
def num_entries(self)
Definition: z3py.py:5810
def __del__(self)
Definition: z3py.py:297
def is_fp(a)
Definition: z3py.py:9049
def __eq__(self, other)
Definition: z3py.py:551
def Sqrt(a, ctx=None)
Definition: z3py.py:3126
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def fpLT(a, b, ctx=None)
Definition: z3py.py:9532
def SimpleSolver(ctx=None)
Definition: z3py.py:6838
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.