Z3
z3py.py
Go to the documentation of this file.
1 
2 
9 
10 """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.
11 
12 Several online tutorials for Z3Py are available at:
13 http://rise4fun.com/Z3Py/tutorial/guide
14 
15 Please send feedback, comments and/or corrections to leonardo@microsoft.com. Your comments are very valuable.
16 
17 Small example:
18 
19 >>> x = Int('x')
20 >>> y = Int('y')
21 >>> s = Solver()
22 >>> s.add(x > 0)
23 >>> s.add(x < 2)
24 >>> s.add(y == x + 1)
25 >>> s.check()
26 sat
27 >>> m = s.model()
28 >>> m[x]
29 1
30 >>> m[y]
31 2
32 
33 Z3 exceptions:
34 
35 >>> try:
36 ... x = BitVec('x', 32)
37 ... y = Bool('y')
38 ... # the expression x + y is type incorrect
39 ... n = x + y
40 ... except Z3Exception as ex:
41 ... print("failed: %s" % ex)
42 failed: sort mismatch
43 """
44 from . import z3core
45 from .z3core import *
46 from .z3types import *
47 from .z3consts import *
48 from .z3printer import *
49 from fractions import Fraction
50 import sys
51 import io
52 import math
53 
54 if sys.version < '3':
55  def _is_int(v):
56  return isinstance(v, (int, long))
57 else:
58  def _is_int(v):
59  return isinstance(v, int)
60 
61 def enable_trace(msg):
62  Z3_enable_trace(msg)
63 
64 def disable_trace(msg):
65  Z3_disable_trace(msg)
66 
68  major = ctypes.c_uint(0)
69  minor = ctypes.c_uint(0)
70  build = ctypes.c_uint(0)
71  rev = ctypes.c_uint(0)
72  Z3_get_version(major, minor, build, rev)
73  return "%s.%s.%s" % (major.value, minor.value, build.value)
74 
76  major = ctypes.c_uint(0)
77  minor = ctypes.c_uint(0)
78  build = ctypes.c_uint(0)
79  rev = ctypes.c_uint(0)
80  Z3_get_version(major, minor, build, rev)
81  return (major.value, minor.value, build.value, rev.value)
82 
84  return Z3_get_full_version()
85 
86 # We use _z3_assert instead of the assert command because we want to
87 # produce nice error messages in Z3Py at rise4fun.com
88 def _z3_assert(cond, msg):
89  if not cond:
90  raise Z3Exception(msg)
91 
92 def open_log(fname):
93  """Log interaction to a file. This function must be invoked immediately after init(). """
94  Z3_open_log(fname)
95 
96 def append_log(s):
97  """Append user-defined string to interaction log. """
98  Z3_append_log(s)
99 
100 def to_symbol(s, ctx=None):
101  """Convert an integer or string into a Z3 symbol."""
102  if _is_int(s):
103  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
104  else:
105  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
106 
107 def _symbol2py(ctx, s):
108  """Convert a Z3 symbol back into a Python object. """
109  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
110  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
111  else:
112  return Z3_get_symbol_string(ctx.ref(), s)
113 
114 _error_handler_fptr = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint)
115 
116 # Hack for having nary functions that can receive one argument that is the
117 # list of arguments.
118 def _get_args(args):
119  try:
120  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
121  return args[0]
122  elif len(args) == 1 and isinstance(args[0], set):
123  return [arg for arg in args[0]]
124  else:
125  return args
126  except: # len is not necessarily defined when args is not a sequence (use reflection?)
127  return args
128 
129 def _Z3python_error_handler_core(c, e):
130  # Do nothing error handler, just avoid exit(0)
131  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
132  return
133 
134 _Z3Python_error_handler = _error_handler_fptr(_Z3python_error_handler_core)
135 
136 def _to_param_value(val):
137  if isinstance(val, bool):
138  if val == True:
139  return "true"
140  else:
141  return "false"
142  else:
143  return str(val)
144 
145 class Context:
146  """A Context manages all other Z3 objects, global configuration options, etc.
147 
148  Z3Py uses a default global context. For most applications this is sufficient.
149  An application may use multiple Z3 contexts. Objects created in one context
150  cannot be used in another one. However, several objects may be "translated" from
151  one context to another. It is not safe to access Z3 objects from multiple threads.
152  The only exception is the method `interrupt()` that can be used to interrupt() a long
153  computation.
154  The initialization method receives global configuration options for the new context.
155  """
156  def __init__(self, *args, **kws):
157  if __debug__:
158  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
159  conf = Z3_mk_config()
160  for key in kws:
161  value = kws[key]
162  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
163  prev = None
164  for a in args:
165  if prev is None:
166  prev = a
167  else:
168  Z3_set_param_value(conf, str(prev), _to_param_value(a))
169  prev = None
170  self.lib = lib()
171  self.ctx = Z3_mk_context_rc(conf)
172  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
173  lib().Z3_set_error_handler.restype = None
174  lib().Z3_set_error_handler.argtypes = [ContextObj, _error_handler_fptr]
175  lib().Z3_set_error_handler(self.ctx, _Z3Python_error_handler)
176  Z3_del_config(conf)
177 
178  def __del__(self):
179  self.lib.Z3_del_context(self.ctx)
180  self.ctx = None
181 
182  def ref(self):
183  """Return a reference to the actual C pointer to the Z3 context."""
184  return self.ctx
185 
186  def interrupt(self):
187  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
188 
189  This method can be invoked from a thread different from the one executing the
190  interruptable procedure.
191  """
192  Z3_interrupt(self.ref())
193 
194 
195 # Global Z3 context
196 _main_ctx = None
197 def main_ctx():
198  """Return a reference to the global Z3 context.
199 
200  >>> x = Real('x')
201  >>> x.ctx == main_ctx()
202  True
203  >>> c = Context()
204  >>> c == main_ctx()
205  False
206  >>> x2 = Real('x', c)
207  >>> x2.ctx == c
208  True
209  >>> eq(x, x2)
210  False
211  """
212  global _main_ctx
213  if _main_ctx is None:
214  _main_ctx = Context()
215  return _main_ctx
216 
217 def _get_ctx(ctx):
218  if ctx is None:
219  return main_ctx()
220  else:
221  return ctx
222 
223 def set_param(*args, **kws):
224  """Set Z3 global (or module) parameters.
225 
226  >>> set_param(precision=10)
227  """
228  if __debug__:
229  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
230  new_kws = {}
231  for k in kws:
232  v = kws[k]
233  if not set_pp_option(k, v):
234  new_kws[k] = v
235  for key in new_kws:
236  value = new_kws[key]
237  Z3_global_param_set(str(key).upper(), _to_param_value(value))
238  prev = None
239  for a in args:
240  if prev is None:
241  prev = a
242  else:
243  Z3_global_param_set(str(prev), _to_param_value(a))
244  prev = None
245 
247  """Reset all global (or module) parameters.
248  """
250 
251 def set_option(*args, **kws):
252  """Alias for 'set_param' for backward compatibility.
253  """
254  return set_param(*args, **kws)
255 
256 def get_param(name):
257  """Return the value of a Z3 global (or module) parameter
258 
259  >>> get_param('nlsat.reorder')
260  'true'
261  """
262  ptr = (ctypes.c_char_p * 1)()
263  if Z3_global_param_get(str(name), ptr):
264  r = z3core._to_pystr(ptr[0])
265  return r
266  raise Z3Exception("failed to retrieve value for '%s'" % name)
267 
268 
273 
274 # Mark objects that use pretty printer
276  """Superclass for all Z3 objects that have support for pretty printing."""
277  def use_pp(self):
278  return True
279 
281  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
282  def __init__(self, ast, ctx=None):
283  self.ast = ast
284  self.ctx = _get_ctx(ctx)
285  Z3_inc_ref(self.ctx.ref(), self.as_ast())
286 
287  def __del__(self):
288  if self.ctx.ref() is not None:
289  Z3_dec_ref(self.ctx.ref(), self.as_ast())
290 
291  def __str__(self):
292  return obj_to_string(self)
293 
294  def __repr__(self):
295  return obj_to_string(self)
296 
297  def __eq__(self, other):
298  return self.eq(other)
299 
300  def __hash__(self):
301  return self.hash()
302 
303  def __nonzero__(self):
304  return self.__bool__()
305 
306  def __bool__(self):
307  if is_true(self):
308  return True
309  elif is_false(self):
310  return False
311  elif is_eq(self) and self.num_args() == 2:
312  return self.arg(0).eq(self.arg(1))
313  else:
314  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
315 
316  def sexpr(self):
317  """Return an string representing the AST node in s-expression notation.
318 
319  >>> x = Int('x')
320  >>> ((x + 1)*x).sexpr()
321  '(* (+ x 1) x)'
322  """
323  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
324 
325  def as_ast(self):
326  """Return a pointer to the corresponding C Z3_ast object."""
327  return self.ast
328 
329  def get_id(self):
330  """Return unique identifier for object. It can be used for hash-tables and maps."""
331  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
332 
333  def ctx_ref(self):
334  """Return a reference to the C context where this AST node is stored."""
335  return self.ctx.ref()
336 
337  def eq(self, other):
338  """Return `True` if `self` and `other` are structurally identical.
339 
340  >>> x = Int('x')
341  >>> n1 = x + 1
342  >>> n2 = 1 + x
343  >>> n1.eq(n2)
344  False
345  >>> n1 = simplify(n1)
346  >>> n2 = simplify(n2)
347  >>> n1.eq(n2)
348  True
349  """
350  if __debug__:
351  _z3_assert(is_ast(other), "Z3 AST expected")
352  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
353 
354  def translate(self, target):
355  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
356 
357  >>> c1 = Context()
358  >>> c2 = Context()
359  >>> x = Int('x', c1)
360  >>> y = Int('y', c2)
361  >>> # Nodes in different contexts can't be mixed.
362  >>> # However, we can translate nodes from one context to another.
363  >>> x.translate(c2) + y
364  x + y
365  """
366  if __debug__:
367  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
368  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
369 
370  def hash(self):
371  """Return a hashcode for the `self`.
372 
373  >>> n1 = simplify(Int('x') + 1)
374  >>> n2 = simplify(2 + Int('x') - 1)
375  >>> n1.hash() == n2.hash()
376  True
377  """
378  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
379 
380 def is_ast(a):
381  """Return `True` if `a` is an AST node.
382 
383  >>> is_ast(10)
384  False
385  >>> is_ast(IntVal(10))
386  True
387  >>> is_ast(Int('x'))
388  True
389  >>> is_ast(BoolSort())
390  True
391  >>> is_ast(Function('f', IntSort(), IntSort()))
392  True
393  >>> is_ast("x")
394  False
395  >>> is_ast(Solver())
396  False
397  """
398  return isinstance(a, AstRef)
399 
400 def eq(a, b):
401  """Return `True` if `a` and `b` are structurally identical AST nodes.
402 
403  >>> x = Int('x')
404  >>> y = Int('y')
405  >>> eq(x, y)
406  False
407  >>> eq(x + 1, x + 1)
408  True
409  >>> eq(x + 1, 1 + x)
410  False
411  >>> eq(simplify(x + 1), simplify(1 + x))
412  True
413  """
414  if __debug__:
415  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
416  return a.eq(b)
417 
418 def _ast_kind(ctx, a):
419  if is_ast(a):
420  a = a.as_ast()
421  return Z3_get_ast_kind(ctx.ref(), a)
422 
423 def _ctx_from_ast_arg_list(args, default_ctx=None):
424  ctx = None
425  for a in args:
426  if is_ast(a) or is_probe(a):
427  if ctx is None:
428  ctx = a.ctx
429  else:
430  if __debug__:
431  _z3_assert(ctx == a.ctx, "Context mismatch")
432  if ctx is None:
433  ctx = default_ctx
434  return ctx
435 
436 def _ctx_from_ast_args(*args):
437  return _ctx_from_ast_arg_list(args)
438 
439 def _to_func_decl_array(args):
440  sz = len(args)
441  _args = (FuncDecl * sz)()
442  for i in range(sz):
443  _args[i] = args[i].as_func_decl()
444  return _args, sz
445 
446 def _to_ast_array(args):
447  sz = len(args)
448  _args = (Ast * sz)()
449  for i in range(sz):
450  _args[i] = args[i].as_ast()
451  return _args, sz
452 
453 def _to_ref_array(ref, args):
454  sz = len(args)
455  _args = (ref * sz)()
456  for i in range(sz):
457  _args[i] = args[i].as_ast()
458  return _args, sz
459 
460 def _to_ast_ref(a, ctx):
461  k = _ast_kind(ctx, a)
462  if k == Z3_SORT_AST:
463  return _to_sort_ref(a, ctx)
464  elif k == Z3_FUNC_DECL_AST:
465  return _to_func_decl_ref(a, ctx)
466  else:
467  return _to_expr_ref(a, ctx)
468 
469 
474 
475 def _sort_kind(ctx, s):
476  return Z3_get_sort_kind(ctx.ref(), s)
477 
479  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
480  def as_ast(self):
481  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
482 
483  def get_id(self):
484  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
485 
486  def kind(self):
487  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
488 
489  >>> b = BoolSort()
490  >>> b.kind() == Z3_BOOL_SORT
491  True
492  >>> b.kind() == Z3_INT_SORT
493  False
494  >>> A = ArraySort(IntSort(), IntSort())
495  >>> A.kind() == Z3_ARRAY_SORT
496  True
497  >>> A.kind() == Z3_INT_SORT
498  False
499  """
500  return _sort_kind(self.ctx, self.ast)
501 
502  def subsort(self, other):
503  """Return `True` if `self` is a subsort of `other`.
504 
505  >>> IntSort().subsort(RealSort())
506  True
507  """
508  return False
509 
510  def cast(self, val):
511  """Try to cast `val` as an element of sort `self`.
512 
513  This method is used in Z3Py to convert Python objects such as integers,
514  floats, longs and strings into Z3 expressions.
515 
516  >>> x = Int('x')
517  >>> RealSort().cast(x)
518  ToReal(x)
519  """
520  if __debug__:
521  _z3_assert(is_expr(val), "Z3 expression expected")
522  _z3_assert(self.eq(val.sort()), "Sort mismatch")
523  return val
524 
525  def name(self):
526  """Return the name (string) of sort `self`.
527 
528  >>> BoolSort().name()
529  'Bool'
530  >>> ArraySort(IntSort(), IntSort()).name()
531  'Array'
532  """
533  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
534 
535  def __eq__(self, other):
536  """Return `True` if `self` and `other` are the same Z3 sort.
537 
538  >>> p = Bool('p')
539  >>> p.sort() == BoolSort()
540  True
541  >>> p.sort() == IntSort()
542  False
543  """
544  if other is None:
545  return False
546  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
547 
548  def __ne__(self, other):
549  """Return `True` if `self` and `other` are not the same Z3 sort.
550 
551  >>> p = Bool('p')
552  >>> p.sort() != BoolSort()
553  False
554  >>> p.sort() != IntSort()
555  True
556  """
557  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
558 
559  def __hash__(self):
560  """ Hash code. """
561  return AstRef.__hash__(self)
562 
563 def is_sort(s):
564  """Return `True` if `s` is a Z3 sort.
565 
566  >>> is_sort(IntSort())
567  True
568  >>> is_sort(Int('x'))
569  False
570  >>> is_expr(Int('x'))
571  True
572  """
573  return isinstance(s, SortRef)
574 
575 def _to_sort_ref(s, ctx):
576  if __debug__:
577  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
578  k = _sort_kind(ctx, s)
579  if k == Z3_BOOL_SORT:
580  return BoolSortRef(s, ctx)
581  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
582  return ArithSortRef(s, ctx)
583  elif k == Z3_BV_SORT:
584  return BitVecSortRef(s, ctx)
585  elif k == Z3_ARRAY_SORT:
586  return ArraySortRef(s, ctx)
587  elif k == Z3_DATATYPE_SORT:
588  return DatatypeSortRef(s, ctx)
589  elif k == Z3_FINITE_DOMAIN_SORT:
590  return FiniteDomainSortRef(s, ctx)
591  elif k == Z3_FLOATING_POINT_SORT:
592  return FPSortRef(s, ctx)
593  elif k == Z3_ROUNDING_MODE_SORT:
594  return FPRMSortRef(s, ctx)
595  return SortRef(s, ctx)
596 
597 def _sort(ctx, a):
598  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
599 
600 def DeclareSort(name, ctx=None):
601  """Create a new uninterpred sort named `name`.
602 
603  If `ctx=None`, then the new sort is declared in the global Z3Py context.
604 
605  >>> A = DeclareSort('A')
606  >>> a = Const('a', A)
607  >>> b = Const('b', A)
608  >>> a.sort() == A
609  True
610  >>> b.sort() == A
611  True
612  >>> a == b
613  a == b
614  """
615  ctx = _get_ctx(ctx)
616  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
617 
618 
623 
625  """Function declaration. Every constant and function have an associated declaration.
626 
627  The declaration assigns a name, a sort (i.e., type), and for function
628  the sort (i.e., type) of each of its arguments. Note that, in Z3,
629  a constant is a function with 0 arguments.
630  """
631  def as_ast(self):
632  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
633 
634  def get_id(self):
635  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
636 
637  def as_func_decl(self):
638  return self.ast
639 
640  def name(self):
641  """Return the name of the function declaration `self`.
642 
643  >>> f = Function('f', IntSort(), IntSort())
644  >>> f.name()
645  'f'
646  >>> isinstance(f.name(), str)
647  True
648  """
649  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
650 
651  def arity(self):
652  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
653 
654  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
655  >>> f.arity()
656  2
657  """
658  return int(Z3_get_arity(self.ctx_ref(), self.ast))
659 
660  def domain(self, i):
661  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
662 
663  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
664  >>> f.domain(0)
665  Int
666  >>> f.domain(1)
667  Real
668  """
669  if __debug__:
670  _z3_assert(i < self.arity(), "Index out of bounds")
671  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
672 
673  def range(self):
674  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
675 
676  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
677  >>> f.range()
678  Bool
679  """
680  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
681 
682  def kind(self):
683  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
684 
685  >>> x = Int('x')
686  >>> d = (x + 1).decl()
687  >>> d.kind() == Z3_OP_ADD
688  True
689  >>> d.kind() == Z3_OP_MUL
690  False
691  """
692  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
693 
694  def __call__(self, *args):
695  """Create a Z3 application expression using the function `self`, and the given arguments.
696 
697  The arguments must be Z3 expressions. This method assumes that
698  the sorts of the elements in `args` match the sorts of the
699  domain. Limited coersion is supported. For example, if
700  args[0] is a Python integer, and the function expects a Z3
701  integer, then the argument is automatically converted into a
702  Z3 integer.
703 
704  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
705  >>> x = Int('x')
706  >>> y = Real('y')
707  >>> f(x, y)
708  f(x, y)
709  >>> f(x, x)
710  f(x, ToReal(x))
711  """
712  args = _get_args(args)
713  num = len(args)
714  if __debug__:
715  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
716  _args = (Ast * num)()
717  saved = []
718  for i in range(num):
719  # self.domain(i).cast(args[i]) may create a new Z3 expression,
720  # then we must save in 'saved' to prevent it from being garbage collected.
721  tmp = self.domain(i).cast(args[i])
722  saved.append(tmp)
723  _args[i] = tmp.as_ast()
724  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
725 
727  """Return `True` if `a` is a Z3 function declaration.
728 
729  >>> f = Function('f', IntSort(), IntSort())
730  >>> is_func_decl(f)
731  True
732  >>> x = Real('x')
733  >>> is_func_decl(x)
734  False
735  """
736  return isinstance(a, FuncDeclRef)
737 
738 def Function(name, *sig):
739  """Create a new Z3 uninterpreted function with the given sorts.
740 
741  >>> f = Function('f', IntSort(), IntSort())
742  >>> f(f(0))
743  f(f(0))
744  """
745  sig = _get_args(sig)
746  if __debug__:
747  _z3_assert(len(sig) > 0, "At least two arguments expected")
748  arity = len(sig) - 1
749  rng = sig[arity]
750  if __debug__:
751  _z3_assert(is_sort(rng), "Z3 sort expected")
752  dom = (Sort * arity)()
753  for i in range(arity):
754  if __debug__:
755  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
756  dom[i] = sig[i].ast
757  ctx = rng.ctx
758  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
759 
760 def _to_func_decl_ref(a, ctx):
761  return FuncDeclRef(a, ctx)
762 
763 
768 
770  """Constraints, formulas and terms are expressions in Z3.
771 
772  Expressions are ASTs. Every expression has a sort.
773  There are three main kinds of expressions:
774  function applications, quantifiers and bounded variables.
775  A constant is a function application with 0 arguments.
776  For quantifier free problems, all expressions are
777  function applications.
778  """
779  def as_ast(self):
780  return self.ast
781 
782  def get_id(self):
783  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
784 
785  def sort(self):
786  """Return the sort of expression `self`.
787 
788  >>> x = Int('x')
789  >>> (x + 1).sort()
790  Int
791  >>> y = Real('y')
792  >>> (x + y).sort()
793  Real
794  """
795  return _sort(self.ctx, self.as_ast())
796 
797  def sort_kind(self):
798  """Shorthand for `self.sort().kind()`.
799 
800  >>> a = Array('a', IntSort(), IntSort())
801  >>> a.sort_kind() == Z3_ARRAY_SORT
802  True
803  >>> a.sort_kind() == Z3_INT_SORT
804  False
805  """
806  return self.sort().kind()
807 
808  def __eq__(self, other):
809  """Return a Z3 expression that represents the constraint `self == other`.
810 
811  If `other` is `None`, then this method simply returns `False`.
812 
813  >>> a = Int('a')
814  >>> b = Int('b')
815  >>> a == b
816  a == b
817  >>> a is None
818  False
819  """
820  if other is None:
821  return False
822  a, b = _coerce_exprs(self, other)
823  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
824 
825  def __hash__(self):
826  """ Hash code. """
827  return AstRef.__hash__(self)
828 
829  def __ne__(self, other):
830  """Return a Z3 expression that represents the constraint `self != other`.
831 
832  If `other` is `None`, then this method simply returns `True`.
833 
834  >>> a = Int('a')
835  >>> b = Int('b')
836  >>> a != b
837  a != b
838  >>> a is not None
839  True
840  """
841  if other is None:
842  return True
843  a, b = _coerce_exprs(self, other)
844  _args, sz = _to_ast_array((a, b))
845  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
846 
847  def decl(self):
848  """Return the Z3 function declaration associated with a Z3 application.
849 
850  >>> f = Function('f', IntSort(), IntSort())
851  >>> a = Int('a')
852  >>> t = f(a)
853  >>> eq(t.decl(), f)
854  True
855  >>> (a + 1).decl()
856  +
857  """
858  if __debug__:
859  _z3_assert(is_app(self), "Z3 application expected")
860  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
861 
862  def num_args(self):
863  """Return the number of arguments of a Z3 application.
864 
865  >>> a = Int('a')
866  >>> b = Int('b')
867  >>> (a + b).num_args()
868  2
869  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
870  >>> t = f(a, b, 0)
871  >>> t.num_args()
872  3
873  """
874  if __debug__:
875  _z3_assert(is_app(self), "Z3 application expected")
876  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
877 
878  def arg(self, idx):
879  """Return argument `idx` of the application `self`.
880 
881  This method assumes that `self` is a function application with at least `idx+1` arguments.
882 
883  >>> a = Int('a')
884  >>> b = Int('b')
885  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
886  >>> t = f(a, b, 0)
887  >>> t.arg(0)
888  a
889  >>> t.arg(1)
890  b
891  >>> t.arg(2)
892  0
893  """
894  if __debug__:
895  _z3_assert(is_app(self), "Z3 application expected")
896  _z3_assert(idx < self.num_args(), "Invalid argument index")
897  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
898 
899  def children(self):
900  """Return a list containing the children of the given expression
901 
902  >>> a = Int('a')
903  >>> b = Int('b')
904  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
905  >>> t = f(a, b, 0)
906  >>> t.children()
907  [a, b, 0]
908  """
909  if is_app(self):
910  return [self.arg(i) for i in range(self.num_args())]
911  else:
912  return []
913 
914 def _to_expr_ref(a, ctx):
915  if isinstance(a, Pattern):
916  return PatternRef(a, ctx)
917  ctx_ref = ctx.ref()
918  k = Z3_get_ast_kind(ctx_ref, a)
919  if k == Z3_QUANTIFIER_AST:
920  return QuantifierRef(a, ctx)
921  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
922  if sk == Z3_BOOL_SORT:
923  return BoolRef(a, ctx)
924  if sk == Z3_INT_SORT:
925  if k == Z3_NUMERAL_AST:
926  return IntNumRef(a, ctx)
927  return ArithRef(a, ctx)
928  if sk == Z3_REAL_SORT:
929  if k == Z3_NUMERAL_AST:
930  return RatNumRef(a, ctx)
931  if _is_algebraic(ctx, a):
932  return AlgebraicNumRef(a, ctx)
933  return ArithRef(a, ctx)
934  if sk == Z3_BV_SORT:
935  if k == Z3_NUMERAL_AST:
936  return BitVecNumRef(a, ctx)
937  else:
938  return BitVecRef(a, ctx)
939  if sk == Z3_ARRAY_SORT:
940  return ArrayRef(a, ctx)
941  if sk == Z3_DATATYPE_SORT:
942  return DatatypeRef(a, ctx)
943  if sk == Z3_FLOATING_POINT_SORT:
944  if k == Z3_APP_AST and _is_numeral(ctx, a):
945  return FPNumRef(a, ctx)
946  else:
947  return FPRef(a, ctx)
948  if sk == Z3_FINITE_DOMAIN_SORT:
949  if k == Z3_NUMERAL_AST:
950  return FiniteDomainNumRef(a, ctx)
951  else:
952  return FiniteDomainRef(a, ctx)
953  if sk == Z3_ROUNDING_MODE_SORT:
954  return FPRMRef(a, ctx)
955  if sk == Z3_SEQ_SORT:
956  return SeqRef(a, ctx)
957  if sk == Z3_RE_SORT:
958  return ReRef(a, ctx)
959  return ExprRef(a, ctx)
960 
961 def _coerce_expr_merge(s, a):
962  if is_expr(a):
963  s1 = a.sort()
964  if s is None:
965  return s1
966  if s1.eq(s):
967  return s
968  elif s.subsort(s1):
969  return s1
970  elif s1.subsort(s):
971  return s
972  else:
973  if __debug__:
974  _z3_assert(s1.ctx == s.ctx, "context mismatch")
975  _z3_assert(False, "sort mismatch")
976  else:
977  return s
978 
979 def _coerce_exprs(a, b, ctx=None):
980  if not is_expr(a) and not is_expr(b):
981  a = _py2expr(a, ctx)
982  b = _py2expr(b, ctx)
983  s = None
984  s = _coerce_expr_merge(s, a)
985  s = _coerce_expr_merge(s, b)
986  a = s.cast(a)
987  b = s.cast(b)
988  return (a, b)
989 
990 def _reduce(f, l, a):
991  r = a
992  for e in l:
993  r = f(r, e)
994  return r
995 
996 def _coerce_expr_list(alist, ctx=None):
997  has_expr = False
998  for a in alist:
999  if is_expr(a):
1000  has_expr = True
1001  break
1002  if not has_expr:
1003  alist = [ _py2expr(a, ctx) for a in alist ]
1004  s = _reduce(_coerce_expr_merge, alist, None)
1005  return [ s.cast(a) for a in alist ]
1006 
1007 def is_expr(a):
1008  """Return `True` if `a` is a Z3 expression.
1009 
1010  >>> a = Int('a')
1011  >>> is_expr(a)
1012  True
1013  >>> is_expr(a + 1)
1014  True
1015  >>> is_expr(IntSort())
1016  False
1017  >>> is_expr(1)
1018  False
1019  >>> is_expr(IntVal(1))
1020  True
1021  >>> x = Int('x')
1022  >>> is_expr(ForAll(x, x >= 0))
1023  True
1024  >>> is_expr(FPVal(1.0))
1025  True
1026  """
1027  return isinstance(a, ExprRef)
1028 
1029 def is_app(a):
1030  """Return `True` if `a` is a Z3 function application.
1031 
1032  Note that, constants are function applications with 0 arguments.
1033 
1034  >>> a = Int('a')
1035  >>> is_app(a)
1036  True
1037  >>> is_app(a + 1)
1038  True
1039  >>> is_app(IntSort())
1040  False
1041  >>> is_app(1)
1042  False
1043  >>> is_app(IntVal(1))
1044  True
1045  >>> x = Int('x')
1046  >>> is_app(ForAll(x, x >= 0))
1047  False
1048  """
1049  if not isinstance(a, ExprRef):
1050  return False
1051  k = _ast_kind(a.ctx, a)
1052  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1053 
1054 def is_const(a):
1055  """Return `True` if `a` is Z3 constant/variable expression.
1056 
1057  >>> a = Int('a')
1058  >>> is_const(a)
1059  True
1060  >>> is_const(a + 1)
1061  False
1062  >>> is_const(1)
1063  False
1064  >>> is_const(IntVal(1))
1065  True
1066  >>> x = Int('x')
1067  >>> is_const(ForAll(x, x >= 0))
1068  False
1069  """
1070  return is_app(a) and a.num_args() == 0
1071 
1072 def is_var(a):
1073  """Return `True` if `a` is variable.
1074 
1075  Z3 uses de-Bruijn indices for representing bound variables in
1076  quantifiers.
1077 
1078  >>> x = Int('x')
1079  >>> is_var(x)
1080  False
1081  >>> is_const(x)
1082  True
1083  >>> f = Function('f', IntSort(), IntSort())
1084  >>> # Z3 replaces x with bound variables when ForAll is executed.
1085  >>> q = ForAll(x, f(x) == x)
1086  >>> b = q.body()
1087  >>> b
1088  f(Var(0)) == Var(0)
1089  >>> b.arg(1)
1090  Var(0)
1091  >>> is_var(b.arg(1))
1092  True
1093  """
1094  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1095 
1097  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1098 
1099  >>> x = Int('x')
1100  >>> y = Int('y')
1101  >>> is_var(x)
1102  False
1103  >>> is_const(x)
1104  True
1105  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1106  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1107  >>> q = ForAll([x, y], f(x, y) == x + y)
1108  >>> q.body()
1109  f(Var(1), Var(0)) == Var(1) + Var(0)
1110  >>> b = q.body()
1111  >>> b.arg(0)
1112  f(Var(1), Var(0))
1113  >>> v1 = b.arg(0).arg(0)
1114  >>> v2 = b.arg(0).arg(1)
1115  >>> v1
1116  Var(1)
1117  >>> v2
1118  Var(0)
1119  >>> get_var_index(v1)
1120  1
1121  >>> get_var_index(v2)
1122  0
1123  """
1124  if __debug__:
1125  _z3_assert(is_var(a), "Z3 bound variable expected")
1126  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1127 
1128 def is_app_of(a, k):
1129  """Return `True` if `a` is an application of the given kind `k`.
1130 
1131  >>> x = Int('x')
1132  >>> n = x + 1
1133  >>> is_app_of(n, Z3_OP_ADD)
1134  True
1135  >>> is_app_of(n, Z3_OP_MUL)
1136  False
1137  """
1138  return is_app(a) and a.decl().kind() == k
1139 
1140 def If(a, b, c, ctx=None):
1141  """Create a Z3 if-then-else expression.
1142 
1143  >>> x = Int('x')
1144  >>> y = Int('y')
1145  >>> max = If(x > y, x, y)
1146  >>> max
1147  If(x > y, x, y)
1148  >>> simplify(max)
1149  If(x <= y, y, x)
1150  """
1151  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1152  return Cond(a, b, c, ctx)
1153  else:
1154  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1155  s = BoolSort(ctx)
1156  a = s.cast(a)
1157  b, c = _coerce_exprs(b, c, ctx)
1158  if __debug__:
1159  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1160  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1161 
1162 def Distinct(*args):
1163  """Create a Z3 distinct expression.
1164 
1165  >>> x = Int('x')
1166  >>> y = Int('y')
1167  >>> Distinct(x, y)
1168  x != y
1169  >>> z = Int('z')
1170  >>> Distinct(x, y, z)
1171  Distinct(x, y, z)
1172  >>> simplify(Distinct(x, y, z))
1173  Distinct(x, y, z)
1174  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1175  And(Not(x == y), Not(x == z), Not(y == z))
1176  """
1177  args = _get_args(args)
1178  ctx = _ctx_from_ast_arg_list(args)
1179  if __debug__:
1180  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1181  args = _coerce_expr_list(args, ctx)
1182  _args, sz = _to_ast_array(args)
1183  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1184 
1185 def _mk_bin(f, a, b):
1186  args = (Ast * 2)()
1187  if __debug__:
1188  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1189  args[0] = a.as_ast()
1190  args[1] = b.as_ast()
1191  return f(a.ctx.ref(), 2, args)
1192 
1193 def Const(name, sort):
1194  """Create a constant of the given sort.
1195 
1196  >>> Const('x', IntSort())
1197  x
1198  """
1199  if __debug__:
1200  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1201  ctx = sort.ctx
1202  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1203 
1204 def Consts(names, sort):
1205  """Create a several constants of the given sort.
1206 
1207  `names` is a string containing the names of all constants to be created.
1208  Blank spaces separate the names of different constants.
1209 
1210  >>> x, y, z = Consts('x y z', IntSort())
1211  >>> x + y + z
1212  x + y + z
1213  """
1214  if isinstance(names, str):
1215  names = names.split(" ")
1216  return [Const(name, sort) for name in names]
1217 
1218 def Var(idx, s):
1219  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1220 
1221  >>> Var(0, IntSort())
1222  Var(0)
1223  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1224  False
1225  """
1226  if __debug__:
1227  _z3_assert(is_sort(s), "Z3 sort expected")
1228  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1229 
1230 def RealVar(idx, ctx=None):
1231  """
1232  Create a real free variable. Free variables are used to create quantified formulas.
1233  They are also used to create polynomials.
1234 
1235  >>> RealVar(0)
1236  Var(0)
1237  """
1238  return Var(idx, RealSort(ctx))
1239 
1240 def RealVarVector(n, ctx=None):
1241  """
1242  Create a list of Real free variables.
1243  The variables have ids: 0, 1, ..., n-1
1244 
1245  >>> x0, x1, x2, x3 = RealVarVector(4)
1246  >>> x2
1247  Var(2)
1248  """
1249  return [ RealVar(i, ctx) for i in range(n) ]
1250 
1251 
1256 
1258  """Boolean sort."""
1259  def cast(self, val):
1260  """Try to cast `val` as a Boolean.
1261 
1262  >>> x = BoolSort().cast(True)
1263  >>> x
1264  True
1265  >>> is_expr(x)
1266  True
1267  >>> is_expr(True)
1268  False
1269  >>> x.sort()
1270  Bool
1271  """
1272  if isinstance(val, bool):
1273  return BoolVal(val, self.ctx)
1274  if __debug__:
1275  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected")
1276  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1277  return val
1278 
1279  def subsort(self, other):
1280  return isinstance(other, ArithSortRef)
1281 
1282  def is_int(self):
1283  return True
1284 
1285  def is_bool(self):
1286  return True
1287 
1288 
1290  """All Boolean expressions are instances of this class."""
1291  def sort(self):
1292  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1293 
1294  def __rmul__(self, other):
1295  return self * other
1296 
1297  def __mul__(self, other):
1298  """Create the Z3 expression `self * other`.
1299  """
1300  if other == 1:
1301  return self
1302  if other == 0:
1303  return 0
1304  return If(self, other, 0)
1305 
1306 
1307 def is_bool(a):
1308  """Return `True` if `a` is a Z3 Boolean expression.
1309 
1310  >>> p = Bool('p')
1311  >>> is_bool(p)
1312  True
1313  >>> q = Bool('q')
1314  >>> is_bool(And(p, q))
1315  True
1316  >>> x = Real('x')
1317  >>> is_bool(x)
1318  False
1319  >>> is_bool(x == 0)
1320  True
1321  """
1322  return isinstance(a, BoolRef)
1323 
1324 def is_true(a):
1325  """Return `True` if `a` is the Z3 true expression.
1326 
1327  >>> p = Bool('p')
1328  >>> is_true(p)
1329  False
1330  >>> is_true(simplify(p == p))
1331  True
1332  >>> x = Real('x')
1333  >>> is_true(x == 0)
1334  False
1335  >>> # True is a Python Boolean expression
1336  >>> is_true(True)
1337  False
1338  """
1339  return is_app_of(a, Z3_OP_TRUE)
1340 
1341 def is_false(a):
1342  """Return `True` if `a` is the Z3 false expression.
1343 
1344  >>> p = Bool('p')
1345  >>> is_false(p)
1346  False
1347  >>> is_false(False)
1348  False
1349  >>> is_false(BoolVal(False))
1350  True
1351  """
1352  return is_app_of(a, Z3_OP_FALSE)
1353 
1354 def is_and(a):
1355  """Return `True` if `a` is a Z3 and expression.
1356 
1357  >>> p, q = Bools('p q')
1358  >>> is_and(And(p, q))
1359  True
1360  >>> is_and(Or(p, q))
1361  False
1362  """
1363  return is_app_of(a, Z3_OP_AND)
1364 
1365 def is_or(a):
1366  """Return `True` if `a` is a Z3 or expression.
1367 
1368  >>> p, q = Bools('p q')
1369  >>> is_or(Or(p, q))
1370  True
1371  >>> is_or(And(p, q))
1372  False
1373  """
1374  return is_app_of(a, Z3_OP_OR)
1375 
1376 def is_not(a):
1377  """Return `True` if `a` is a Z3 not expression.
1378 
1379  >>> p = Bool('p')
1380  >>> is_not(p)
1381  False
1382  >>> is_not(Not(p))
1383  True
1384  """
1385  return is_app_of(a, Z3_OP_NOT)
1386 
1387 def is_eq(a):
1388  """Return `True` if `a` is a Z3 equality expression.
1389 
1390  >>> x, y = Ints('x y')
1391  >>> is_eq(x == y)
1392  True
1393  """
1394  return is_app_of(a, Z3_OP_EQ)
1395 
1397  """Return `True` if `a` is a Z3 distinct expression.
1398 
1399  >>> x, y, z = Ints('x y z')
1400  >>> is_distinct(x == y)
1401  False
1402  >>> is_distinct(Distinct(x, y, z))
1403  True
1404  """
1405  return is_app_of(a, Z3_OP_DISTINCT)
1406 
1407 def BoolSort(ctx=None):
1408  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1409 
1410  >>> BoolSort()
1411  Bool
1412  >>> p = Const('p', BoolSort())
1413  >>> is_bool(p)
1414  True
1415  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1416  >>> r(0, 1)
1417  r(0, 1)
1418  >>> is_bool(r(0, 1))
1419  True
1420  """
1421  ctx = _get_ctx(ctx)
1422  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1423 
1424 def BoolVal(val, ctx=None):
1425  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1426 
1427  >>> BoolVal(True)
1428  True
1429  >>> is_true(BoolVal(True))
1430  True
1431  >>> is_true(True)
1432  False
1433  >>> is_false(BoolVal(False))
1434  True
1435  """
1436  ctx = _get_ctx(ctx)
1437  if val == False:
1438  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1439  else:
1440  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1441 
1442 def Bool(name, ctx=None):
1443  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1444 
1445  >>> p = Bool('p')
1446  >>> q = Bool('q')
1447  >>> And(p, q)
1448  And(p, q)
1449  """
1450  ctx = _get_ctx(ctx)
1451  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1452 
1453 def Bools(names, ctx=None):
1454  """Return a tuple of Boolean constants.
1455 
1456  `names` is a single string containing all names separated by blank spaces.
1457  If `ctx=None`, then the global context is used.
1458 
1459  >>> p, q, r = Bools('p q r')
1460  >>> And(p, Or(q, r))
1461  And(p, Or(q, r))
1462  """
1463  ctx = _get_ctx(ctx)
1464  if isinstance(names, str):
1465  names = names.split(" ")
1466  return [Bool(name, ctx) for name in names]
1467 
1468 def BoolVector(prefix, sz, ctx=None):
1469  """Return a list of Boolean constants of size `sz`.
1470 
1471  The constants are named using the given prefix.
1472  If `ctx=None`, then the global context is used.
1473 
1474  >>> P = BoolVector('p', 3)
1475  >>> P
1476  [p__0, p__1, p__2]
1477  >>> And(P)
1478  And(p__0, p__1, p__2)
1479  """
1480  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1481 
1482 def FreshBool(prefix='b', ctx=None):
1483  """Return a fresh Boolean constant in the given context using the given prefix.
1484 
1485  If `ctx=None`, then the global context is used.
1486 
1487  >>> b1 = FreshBool()
1488  >>> b2 = FreshBool()
1489  >>> eq(b1, b2)
1490  False
1491  """
1492  ctx = _get_ctx(ctx)
1493  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1494 
1495 def Implies(a, b, ctx=None):
1496  """Create a Z3 implies expression.
1497 
1498  >>> p, q = Bools('p q')
1499  >>> Implies(p, q)
1500  Implies(p, q)
1501  >>> simplify(Implies(p, q))
1502  Or(Not(p), q)
1503  """
1504  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1505  s = BoolSort(ctx)
1506  a = s.cast(a)
1507  b = s.cast(b)
1508  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1509 
1510 def Xor(a, b, ctx=None):
1511  """Create a Z3 Xor expression.
1512 
1513  >>> p, q = Bools('p q')
1514  >>> Xor(p, q)
1515  Xor(p, q)
1516  >>> simplify(Xor(p, q))
1517  Not(p) == q
1518  """
1519  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1520  s = BoolSort(ctx)
1521  a = s.cast(a)
1522  b = s.cast(b)
1523  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1524 
1525 def Not(a, ctx=None):
1526  """Create a Z3 not expression or probe.
1527 
1528  >>> p = Bool('p')
1529  >>> Not(Not(p))
1530  Not(Not(p))
1531  >>> simplify(Not(Not(p)))
1532  p
1533  """
1534  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1535  if is_probe(a):
1536  # Not is also used to build probes
1537  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1538  else:
1539  s = BoolSort(ctx)
1540  a = s.cast(a)
1541  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1542 
1543 def _has_probe(args):
1544  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1545  for arg in args:
1546  if is_probe(arg):
1547  return True
1548  return False
1549 
1550 def And(*args):
1551  """Create a Z3 and-expression or and-probe.
1552 
1553  >>> p, q, r = Bools('p q r')
1554  >>> And(p, q, r)
1555  And(p, q, r)
1556  >>> P = BoolVector('p', 5)
1557  >>> And(P)
1558  And(p__0, p__1, p__2, p__3, p__4)
1559  """
1560  last_arg = None
1561  if len(args) > 0:
1562  last_arg = args[len(args)-1]
1563  if isinstance(last_arg, Context):
1564  ctx = args[len(args)-1]
1565  args = args[:len(args)-1]
1566  elif len(args) == 1 and isinstance(args[0], AstVector):
1567  ctx = args[0].ctx
1568  args = [a for a in args[0]]
1569  else:
1570  ctx = main_ctx()
1571  args = _get_args(args)
1572  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1573  if __debug__:
1574  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1575  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1576  if _has_probe(args):
1577  return _probe_and(args, ctx)
1578  else:
1579  args = _coerce_expr_list(args, ctx)
1580  _args, sz = _to_ast_array(args)
1581  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1582 
1583 def Or(*args):
1584  """Create a Z3 or-expression or or-probe.
1585 
1586  >>> p, q, r = Bools('p q r')
1587  >>> Or(p, q, r)
1588  Or(p, q, r)
1589  >>> P = BoolVector('p', 5)
1590  >>> Or(P)
1591  Or(p__0, p__1, p__2, p__3, p__4)
1592  """
1593  last_arg = None
1594  if len(args) > 0:
1595  last_arg = args[len(args)-1]
1596  if isinstance(last_arg, Context):
1597  ctx = args[len(args)-1]
1598  args = args[:len(args)-1]
1599  else:
1600  ctx = main_ctx()
1601  args = _get_args(args)
1602  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1603  if __debug__:
1604  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1605  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1606  if _has_probe(args):
1607  return _probe_or(args, ctx)
1608  else:
1609  args = _coerce_expr_list(args, ctx)
1610  _args, sz = _to_ast_array(args)
1611  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1612 
1613 #########################################
1614 #
1615 # Patterns
1616 #
1617 #########################################
1618 
1619 class PatternRef(ExprRef):
1620  """Patterns are hints for quantifier instantiation.
1621 
1622  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1623  """
1624  def as_ast(self):
1625  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1626 
1627  def get_id(self):
1628  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1629 
1630 def is_pattern(a):
1631  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1632 
1633  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1634 
1635  >>> f = Function('f', IntSort(), IntSort())
1636  >>> x = Int('x')
1637  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1638  >>> q
1639  ForAll(x, f(x) == 0)
1640  >>> q.num_patterns()
1641  1
1642  >>> is_pattern(q.pattern(0))
1643  True
1644  >>> q.pattern(0)
1645  f(Var(0))
1646  """
1647  return isinstance(a, PatternRef)
1648 
1649 def MultiPattern(*args):
1650  """Create a Z3 multi-pattern using the given expressions `*args`
1651 
1652  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1653 
1654  >>> f = Function('f', IntSort(), IntSort())
1655  >>> g = Function('g', IntSort(), IntSort())
1656  >>> x = Int('x')
1657  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1658  >>> q
1659  ForAll(x, f(x) != g(x))
1660  >>> q.num_patterns()
1661  1
1662  >>> is_pattern(q.pattern(0))
1663  True
1664  >>> q.pattern(0)
1665  MultiPattern(f(Var(0)), g(Var(0)))
1666  """
1667  if __debug__:
1668  _z3_assert(len(args) > 0, "At least one argument expected")
1669  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1670  ctx = args[0].ctx
1671  args, sz = _to_ast_array(args)
1672  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1673 
1674 def _to_pattern(arg):
1675  if is_pattern(arg):
1676  return arg
1677  else:
1678  return MultiPattern(arg)
1679 
1680 #########################################
1681 #
1682 # Quantifiers
1683 #
1684 #########################################
1685 
1686 class QuantifierRef(BoolRef):
1687  """Universally and Existentially quantified formulas."""
1688 
1689  def as_ast(self):
1690  return self.ast
1691 
1692  def get_id(self):
1693  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1694 
1695  def sort(self):
1696  """Return the Boolean sort."""
1697  return BoolSort(self.ctx)
1698 
1699  def is_forall(self):
1700  """Return `True` if `self` is a universal quantifier.
1701 
1702  >>> f = Function('f', IntSort(), IntSort())
1703  >>> x = Int('x')
1704  >>> q = ForAll(x, f(x) == 0)
1705  >>> q.is_forall()
1706  True
1707  >>> q = Exists(x, f(x) != 0)
1708  >>> q.is_forall()
1709  False
1710  """
1711  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1712 
1713  def weight(self):
1714  """Return the weight annotation of `self`.
1715 
1716  >>> f = Function('f', IntSort(), IntSort())
1717  >>> x = Int('x')
1718  >>> q = ForAll(x, f(x) == 0)
1719  >>> q.weight()
1720  1
1721  >>> q = ForAll(x, f(x) == 0, weight=10)
1722  >>> q.weight()
1723  10
1724  """
1725  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1726 
1727  def num_patterns(self):
1728  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1729 
1730  >>> f = Function('f', IntSort(), IntSort())
1731  >>> g = Function('g', IntSort(), IntSort())
1732  >>> x = Int('x')
1733  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1734  >>> q.num_patterns()
1735  2
1736  """
1737  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1738 
1739  def pattern(self, idx):
1740  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1741 
1742  >>> f = Function('f', IntSort(), IntSort())
1743  >>> g = Function('g', IntSort(), IntSort())
1744  >>> x = Int('x')
1745  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1746  >>> q.num_patterns()
1747  2
1748  >>> q.pattern(0)
1749  f(Var(0))
1750  >>> q.pattern(1)
1751  g(Var(0))
1752  """
1753  if __debug__:
1754  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1755  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1756 
1757  def num_no_patterns(self):
1758  """Return the number of no-patterns."""
1759  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1760 
1761  def no_pattern(self, idx):
1762  """Return a no-pattern."""
1763  if __debug__:
1764  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1765  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1766 
1767  def body(self):
1768  """Return the expression being quantified.
1769 
1770  >>> f = Function('f', IntSort(), IntSort())
1771  >>> x = Int('x')
1772  >>> q = ForAll(x, f(x) == 0)
1773  >>> q.body()
1774  f(Var(0)) == 0
1775  """
1776  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1777 
1778  def num_vars(self):
1779  """Return the number of variables bounded by this quantifier.
1780 
1781  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1782  >>> x = Int('x')
1783  >>> y = Int('y')
1784  >>> q = ForAll([x, y], f(x, y) >= x)
1785  >>> q.num_vars()
1786  2
1787  """
1788  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1789 
1790  def var_name(self, idx):
1791  """Return a string representing a name used when displaying the quantifier.
1792 
1793  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1794  >>> x = Int('x')
1795  >>> y = Int('y')
1796  >>> q = ForAll([x, y], f(x, y) >= x)
1797  >>> q.var_name(0)
1798  'x'
1799  >>> q.var_name(1)
1800  'y'
1801  """
1802  if __debug__:
1803  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1804  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1805 
1806  def var_sort(self, idx):
1807  """Return the sort of a bound variable.
1808 
1809  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1810  >>> x = Int('x')
1811  >>> y = Real('y')
1812  >>> q = ForAll([x, y], f(x, y) >= x)
1813  >>> q.var_sort(0)
1814  Int
1815  >>> q.var_sort(1)
1816  Real
1817  """
1818  if __debug__:
1819  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1820  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1821 
1822  def children(self):
1823  """Return a list containing a single element self.body()
1824 
1825  >>> f = Function('f', IntSort(), IntSort())
1826  >>> x = Int('x')
1827  >>> q = ForAll(x, f(x) == 0)
1828  >>> q.children()
1829  [f(Var(0)) == 0]
1830  """
1831  return [ self.body() ]
1832 
1833 def is_quantifier(a):
1834  """Return `True` if `a` is a Z3 quantifier.
1835 
1836  >>> f = Function('f', IntSort(), IntSort())
1837  >>> x = Int('x')
1838  >>> q = ForAll(x, f(x) == 0)
1839  >>> is_quantifier(q)
1840  True
1841  >>> is_quantifier(f(x))
1842  False
1843  """
1844  return isinstance(a, QuantifierRef)
1845 
1846 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1847  if __debug__:
1848  _z3_assert(is_bool(body), "Z3 expression expected")
1849  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1850  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1851  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1852  ctx = body.ctx
1853  if is_app(vs):
1854  vs = [vs]
1855  num_vars = len(vs)
1856  if num_vars == 0:
1857  return body
1858  _vs = (Ast * num_vars)()
1859  for i in range(num_vars):
1860  ## TODO: Check if is constant
1861  _vs[i] = vs[i].as_ast()
1862  patterns = [ _to_pattern(p) for p in patterns ]
1863  num_pats = len(patterns)
1864  _pats = (Pattern * num_pats)()
1865  for i in range(num_pats):
1866  _pats[i] = patterns[i].ast
1867  _no_pats, num_no_pats = _to_ast_array(no_patterns)
1868  qid = to_symbol(qid, ctx)
1869  skid = to_symbol(skid, ctx)
1870  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
1871  num_vars, _vs,
1872  num_pats, _pats,
1873  num_no_pats, _no_pats,
1874  body.as_ast()), ctx)
1875 
1876 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1877  """Create a Z3 forall formula.
1878 
1879  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1880 
1881  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1882 
1883  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1884  >>> x = Int('x')
1885  >>> y = Int('y')
1886  >>> ForAll([x, y], f(x, y) >= x)
1887  ForAll([x, y], f(x, y) >= x)
1888  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
1889  ForAll([x, y], f(x, y) >= x)
1890  >>> ForAll([x, y], f(x, y) >= x, weight=10)
1891  ForAll([x, y], f(x, y) >= x)
1892  """
1893  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
1894 
1895 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1896  """Create a Z3 exists formula.
1897 
1898  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1899 
1900  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1901 
1902  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1903  >>> x = Int('x')
1904  >>> y = Int('y')
1905  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
1906  >>> q
1907  Exists([x, y], f(x, y) >= x)
1908  >>> is_quantifier(q)
1909  True
1910  >>> r = Tactic('nnf')(q).as_expr()
1911  >>> is_quantifier(r)
1912  False
1913  """
1914  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
1915 
1916 #########################################
1917 #
1918 # Arithmetic
1919 #
1920 #########################################
1921 
1922 class ArithSortRef(SortRef):
1923  """Real and Integer sorts."""
1924 
1925  def is_real(self):
1926  """Return `True` if `self` is of the sort Real.
1927 
1928  >>> x = Real('x')
1929  >>> x.is_real()
1930  True
1931  >>> (x + 1).is_real()
1932  True
1933  >>> x = Int('x')
1934  >>> x.is_real()
1935  False
1936  """
1937  return self.kind() == Z3_REAL_SORT
1938 
1939  def is_int(self):
1940  """Return `True` if `self` is of the sort Integer.
1941 
1942  >>> x = Int('x')
1943  >>> x.is_int()
1944  True
1945  >>> (x + 1).is_int()
1946  True
1947  >>> x = Real('x')
1948  >>> x.is_int()
1949  False
1950  """
1951  return self.kind() == Z3_INT_SORT
1952 
1953  def subsort(self, other):
1954  """Return `True` if `self` is a subsort of `other`."""
1955  return self.is_int() and is_arith_sort(other) and other.is_real()
1956 
1957  def cast(self, val):
1958  """Try to cast `val` as an Integer or Real.
1959 
1960  >>> IntSort().cast(10)
1961  10
1962  >>> is_int(IntSort().cast(10))
1963  True
1964  >>> is_int(10)
1965  False
1966  >>> RealSort().cast(10)
1967  10
1968  >>> is_real(RealSort().cast(10))
1969  True
1970  """
1971  if is_expr(val):
1972  if __debug__:
1973  _z3_assert(self.ctx == val.ctx, "Context mismatch")
1974  val_s = val.sort()
1975  if self.eq(val_s):
1976  return val
1977  if val_s.is_int() and self.is_real():
1978  return ToReal(val)
1979  if val_s.is_bool() and self.is_int():
1980  return If(val, 1, 0)
1981  if val_s.is_bool() and self.is_real():
1982  return ToReal(If(val, 1, 0))
1983  if __debug__:
1984  _z3_assert(False, "Z3 Integer/Real expression expected" )
1985  else:
1986  if self.is_int():
1987  return IntVal(val, self.ctx)
1988  if self.is_real():
1989  return RealVal(val, self.ctx)
1990  if __debug__:
1991  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected")
1992 
1993 def is_arith_sort(s):
1994  """Return `True` if s is an arithmetical sort (type).
1995 
1996  >>> is_arith_sort(IntSort())
1997  True
1998  >>> is_arith_sort(RealSort())
1999  True
2000  >>> is_arith_sort(BoolSort())
2001  False
2002  >>> n = Int('x') + 1
2003  >>> is_arith_sort(n.sort())
2004  True
2005  """
2006  return isinstance(s, ArithSortRef)
2007 
2008 class ArithRef(ExprRef):
2009  """Integer and Real expressions."""
2010 
2011  def sort(self):
2012  """Return the sort (type) of the arithmetical expression `self`.
2013 
2014  >>> Int('x').sort()
2015  Int
2016  >>> (Real('x') + 1).sort()
2017  Real
2018  """
2019  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2020 
2021  def is_int(self):
2022  """Return `True` if `self` is an integer expression.
2023 
2024  >>> x = Int('x')
2025  >>> x.is_int()
2026  True
2027  >>> (x + 1).is_int()
2028  True
2029  >>> y = Real('y')
2030  >>> (x + y).is_int()
2031  False
2032  """
2033  return self.sort().is_int()
2034 
2035  def is_real(self):
2036  """Return `True` if `self` is an real expression.
2037 
2038  >>> x = Real('x')
2039  >>> x.is_real()
2040  True
2041  >>> (x + 1).is_real()
2042  True
2043  """
2044  return self.sort().is_real()
2045 
2046  def __add__(self, other):
2047  """Create the Z3 expression `self + other`.
2048 
2049  >>> x = Int('x')
2050  >>> y = Int('y')
2051  >>> x + y
2052  x + y
2053  >>> (x + y).sort()
2054  Int
2055  """
2056  a, b = _coerce_exprs(self, other)
2057  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2058 
2059  def __radd__(self, other):
2060  """Create the Z3 expression `other + self`.
2061 
2062  >>> x = Int('x')
2063  >>> 10 + x
2064  10 + x
2065  """
2066  a, b = _coerce_exprs(self, other)
2067  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2068 
2069  def __mul__(self, other):
2070  """Create the Z3 expression `self * other`.
2071 
2072  >>> x = Real('x')
2073  >>> y = Real('y')
2074  >>> x * y
2075  x*y
2076  >>> (x * y).sort()
2077  Real
2078  """
2079  a, b = _coerce_exprs(self, other)
2080  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2081 
2082  def __rmul__(self, other):
2083  """Create the Z3 expression `other * self`.
2084 
2085  >>> x = Real('x')
2086  >>> 10 * x
2087  10*x
2088  """
2089  a, b = _coerce_exprs(self, other)
2090  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2091 
2092  def __sub__(self, other):
2093  """Create the Z3 expression `self - other`.
2094 
2095  >>> x = Int('x')
2096  >>> y = Int('y')
2097  >>> x - y
2098  x - y
2099  >>> (x - y).sort()
2100  Int
2101  """
2102  a, b = _coerce_exprs(self, other)
2103  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2104 
2105  def __rsub__(self, other):
2106  """Create the Z3 expression `other - self`.
2107 
2108  >>> x = Int('x')
2109  >>> 10 - x
2110  10 - x
2111  """
2112  a, b = _coerce_exprs(self, other)
2113  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2114 
2115  def __pow__(self, other):
2116  """Create the Z3 expression `self**other` (** is the power operator).
2117 
2118  >>> x = Real('x')
2119  >>> x**3
2120  x**3
2121  >>> (x**3).sort()
2122  Real
2123  >>> simplify(IntVal(2)**8)
2124  256
2125  """
2126  a, b = _coerce_exprs(self, other)
2127  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2128 
2129  def __rpow__(self, other):
2130  """Create the Z3 expression `other**self` (** is the power operator).
2131 
2132  >>> x = Real('x')
2133  >>> 2**x
2134  2**x
2135  >>> (2**x).sort()
2136  Real
2137  >>> simplify(2**IntVal(8))
2138  256
2139  """
2140  a, b = _coerce_exprs(self, other)
2141  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2142 
2143  def __div__(self, other):
2144  """Create the Z3 expression `other/self`.
2145 
2146  >>> x = Int('x')
2147  >>> y = Int('y')
2148  >>> x/y
2149  x/y
2150  >>> (x/y).sort()
2151  Int
2152  >>> (x/y).sexpr()
2153  '(div x y)'
2154  >>> x = Real('x')
2155  >>> y = Real('y')
2156  >>> x/y
2157  x/y
2158  >>> (x/y).sort()
2159  Real
2160  >>> (x/y).sexpr()
2161  '(/ x y)'
2162  """
2163  a, b = _coerce_exprs(self, other)
2164  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2165 
2166  def __truediv__(self, other):
2167  """Create the Z3 expression `other/self`."""
2168  return self.__div__(other)
2169 
2170  def __rdiv__(self, other):
2171  """Create the Z3 expression `other/self`.
2172 
2173  >>> x = Int('x')
2174  >>> 10/x
2175  10/x
2176  >>> (10/x).sexpr()
2177  '(div 10 x)'
2178  >>> x = Real('x')
2179  >>> 10/x
2180  10/x
2181  >>> (10/x).sexpr()
2182  '(/ 10.0 x)'
2183  """
2184  a, b = _coerce_exprs(self, other)
2185  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2186 
2187  def __rtruediv__(self, other):
2188  """Create the Z3 expression `other/self`."""
2189  return self.__rdiv__(other)
2190 
2191  def __mod__(self, other):
2192  """Create the Z3 expression `other%self`.
2193 
2194  >>> x = Int('x')
2195  >>> y = Int('y')
2196  >>> x % y
2197  x%y
2198  >>> simplify(IntVal(10) % IntVal(3))
2199  1
2200  """
2201  a, b = _coerce_exprs(self, other)
2202  if __debug__:
2203  _z3_assert(a.is_int(), "Z3 integer expression expected")
2204  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2205 
2206  def __rmod__(self, other):
2207  """Create the Z3 expression `other%self`.
2208 
2209  >>> x = Int('x')
2210  >>> 10 % x
2211  10%x
2212  """
2213  a, b = _coerce_exprs(self, other)
2214  if __debug__:
2215  _z3_assert(a.is_int(), "Z3 integer expression expected")
2216  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2217 
2218  def __neg__(self):
2219  """Return an expression representing `-self`.
2220 
2221  >>> x = Int('x')
2222  >>> -x
2223  -x
2224  >>> simplify(-(-x))
2225  x
2226  """
2227  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2228 
2229  def __pos__(self):
2230  """Return `self`.
2231 
2232  >>> x = Int('x')
2233  >>> +x
2234  x
2235  """
2236  return self
2237 
2238  def __le__(self, other):
2239  """Create the Z3 expression `other <= self`.
2240 
2241  >>> x, y = Ints('x y')
2242  >>> x <= y
2243  x <= y
2244  >>> y = Real('y')
2245  >>> x <= y
2246  ToReal(x) <= y
2247  """
2248  a, b = _coerce_exprs(self, other)
2249  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2250 
2251  def __lt__(self, other):
2252  """Create the Z3 expression `other < self`.
2253 
2254  >>> x, y = Ints('x y')
2255  >>> x < y
2256  x < y
2257  >>> y = Real('y')
2258  >>> x < y
2259  ToReal(x) < y
2260  """
2261  a, b = _coerce_exprs(self, other)
2262  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2263 
2264  def __gt__(self, other):
2265  """Create the Z3 expression `other > self`.
2266 
2267  >>> x, y = Ints('x y')
2268  >>> x > y
2269  x > y
2270  >>> y = Real('y')
2271  >>> x > y
2272  ToReal(x) > y
2273  """
2274  a, b = _coerce_exprs(self, other)
2275  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2276 
2277  def __ge__(self, other):
2278  """Create the Z3 expression `other >= self`.
2279 
2280  >>> x, y = Ints('x y')
2281  >>> x >= y
2282  x >= y
2283  >>> y = Real('y')
2284  >>> x >= y
2285  ToReal(x) >= y
2286  """
2287  a, b = _coerce_exprs(self, other)
2288  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2289 
2290 def is_arith(a):
2291  """Return `True` if `a` is an arithmetical expression.
2292 
2293  >>> x = Int('x')
2294  >>> is_arith(x)
2295  True
2296  >>> is_arith(x + 1)
2297  True
2298  >>> is_arith(1)
2299  False
2300  >>> is_arith(IntVal(1))
2301  True
2302  >>> y = Real('y')
2303  >>> is_arith(y)
2304  True
2305  >>> is_arith(y + 1)
2306  True
2307  """
2308  return isinstance(a, ArithRef)
2309 
2310 def is_int(a):
2311  """Return `True` if `a` is an integer expression.
2312 
2313  >>> x = Int('x')
2314  >>> is_int(x + 1)
2315  True
2316  >>> is_int(1)
2317  False
2318  >>> is_int(IntVal(1))
2319  True
2320  >>> y = Real('y')
2321  >>> is_int(y)
2322  False
2323  >>> is_int(y + 1)
2324  False
2325  """
2326  return is_arith(a) and a.is_int()
2327 
2328 def is_real(a):
2329  """Return `True` if `a` is a real expression.
2330 
2331  >>> x = Int('x')
2332  >>> is_real(x + 1)
2333  False
2334  >>> y = Real('y')
2335  >>> is_real(y)
2336  True
2337  >>> is_real(y + 1)
2338  True
2339  >>> is_real(1)
2340  False
2341  >>> is_real(RealVal(1))
2342  True
2343  """
2344  return is_arith(a) and a.is_real()
2345 
2346 def _is_numeral(ctx, a):
2347  return Z3_is_numeral_ast(ctx.ref(), a)
2348 
2349 def _is_algebraic(ctx, a):
2350  return Z3_is_algebraic_number(ctx.ref(), a)
2351 
2352 def is_int_value(a):
2353  """Return `True` if `a` is an integer value of sort Int.
2354 
2355  >>> is_int_value(IntVal(1))
2356  True
2357  >>> is_int_value(1)
2358  False
2359  >>> is_int_value(Int('x'))
2360  False
2361  >>> n = Int('x') + 1
2362  >>> n
2363  x + 1
2364  >>> n.arg(1)
2365  1
2366  >>> is_int_value(n.arg(1))
2367  True
2368  >>> is_int_value(RealVal("1/3"))
2369  False
2370  >>> is_int_value(RealVal(1))
2371  False
2372  """
2373  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2374 
2375 def is_rational_value(a):
2376  """Return `True` if `a` is rational value of sort Real.
2377 
2378  >>> is_rational_value(RealVal(1))
2379  True
2380  >>> is_rational_value(RealVal("3/5"))
2381  True
2382  >>> is_rational_value(IntVal(1))
2383  False
2384  >>> is_rational_value(1)
2385  False
2386  >>> n = Real('x') + 1
2387  >>> n.arg(1)
2388  1
2389  >>> is_rational_value(n.arg(1))
2390  True
2391  >>> is_rational_value(Real('x'))
2392  False
2393  """
2394  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2395 
2396 def is_algebraic_value(a):
2397  """Return `True` if `a` is an algerbraic value of sort Real.
2398 
2399  >>> is_algebraic_value(RealVal("3/5"))
2400  False
2401  >>> n = simplify(Sqrt(2))
2402  >>> n
2403  1.4142135623?
2404  >>> is_algebraic_value(n)
2405  True
2406  """
2407  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2408 
2409 def is_add(a):
2410  """Return `True` if `a` is an expression of the form b + c.
2411 
2412  >>> x, y = Ints('x y')
2413  >>> is_add(x + y)
2414  True
2415  >>> is_add(x - y)
2416  False
2417  """
2418  return is_app_of(a, Z3_OP_ADD)
2419 
2420 def is_mul(a):
2421  """Return `True` if `a` is an expression of the form b * c.
2422 
2423  >>> x, y = Ints('x y')
2424  >>> is_mul(x * y)
2425  True
2426  >>> is_mul(x - y)
2427  False
2428  """
2429  return is_app_of(a, Z3_OP_MUL)
2430 
2431 def is_sub(a):
2432  """Return `True` if `a` is an expression of the form b - c.
2433 
2434  >>> x, y = Ints('x y')
2435  >>> is_sub(x - y)
2436  True
2437  >>> is_sub(x + y)
2438  False
2439  """
2440  return is_app_of(a, Z3_OP_SUB)
2441 
2442 def is_div(a):
2443  """Return `True` if `a` is an expression of the form b / c.
2444 
2445  >>> x, y = Reals('x y')
2446  >>> is_div(x / y)
2447  True
2448  >>> is_div(x + y)
2449  False
2450  >>> x, y = Ints('x y')
2451  >>> is_div(x / y)
2452  False
2453  >>> is_idiv(x / y)
2454  True
2455  """
2456  return is_app_of(a, Z3_OP_DIV)
2457 
2458 def is_idiv(a):
2459  """Return `True` if `a` is an expression of the form b div c.
2460 
2461  >>> x, y = Ints('x y')
2462  >>> is_idiv(x / y)
2463  True
2464  >>> is_idiv(x + y)
2465  False
2466  """
2467  return is_app_of(a, Z3_OP_IDIV)
2468 
2469 def is_mod(a):
2470  """Return `True` if `a` is an expression of the form b % c.
2471 
2472  >>> x, y = Ints('x y')
2473  >>> is_mod(x % y)
2474  True
2475  >>> is_mod(x + y)
2476  False
2477  """
2478  return is_app_of(a, Z3_OP_MOD)
2479 
2480 def is_le(a):
2481  """Return `True` if `a` is an expression of the form b <= c.
2482 
2483  >>> x, y = Ints('x y')
2484  >>> is_le(x <= y)
2485  True
2486  >>> is_le(x < y)
2487  False
2488  """
2489  return is_app_of(a, Z3_OP_LE)
2490 
2491 def is_lt(a):
2492  """Return `True` if `a` is an expression of the form b < c.
2493 
2494  >>> x, y = Ints('x y')
2495  >>> is_lt(x < y)
2496  True
2497  >>> is_lt(x == y)
2498  False
2499  """
2500  return is_app_of(a, Z3_OP_LT)
2501 
2502 def is_ge(a):
2503  """Return `True` if `a` is an expression of the form b >= c.
2504 
2505  >>> x, y = Ints('x y')
2506  >>> is_ge(x >= y)
2507  True
2508  >>> is_ge(x == y)
2509  False
2510  """
2511  return is_app_of(a, Z3_OP_GE)
2512 
2513 def is_gt(a):
2514  """Return `True` if `a` is an expression of the form b > c.
2515 
2516  >>> x, y = Ints('x y')
2517  >>> is_gt(x > y)
2518  True
2519  >>> is_gt(x == y)
2520  False
2521  """
2522  return is_app_of(a, Z3_OP_GT)
2523 
2524 def is_is_int(a):
2525  """Return `True` if `a` is an expression of the form IsInt(b).
2526 
2527  >>> x = Real('x')
2528  >>> is_is_int(IsInt(x))
2529  True
2530  >>> is_is_int(x)
2531  False
2532  """
2533  return is_app_of(a, Z3_OP_IS_INT)
2534 
2535 def is_to_real(a):
2536  """Return `True` if `a` is an expression of the form ToReal(b).
2537 
2538  >>> x = Int('x')
2539  >>> n = ToReal(x)
2540  >>> n
2541  ToReal(x)
2542  >>> is_to_real(n)
2543  True
2544  >>> is_to_real(x)
2545  False
2546  """
2547  return is_app_of(a, Z3_OP_TO_REAL)
2548 
2549 def is_to_int(a):
2550  """Return `True` if `a` is an expression of the form ToInt(b).
2551 
2552  >>> x = Real('x')
2553  >>> n = ToInt(x)
2554  >>> n
2555  ToInt(x)
2556  >>> is_to_int(n)
2557  True
2558  >>> is_to_int(x)
2559  False
2560  """
2561  return is_app_of(a, Z3_OP_TO_INT)
2562 
2563 class IntNumRef(ArithRef):
2564  """Integer values."""
2565 
2566  def as_long(self):
2567  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2568 
2569  >>> v = IntVal(1)
2570  >>> v + 1
2571  1 + 1
2572  >>> v.as_long() + 1
2573  2
2574  """
2575  if __debug__:
2576  _z3_assert(self.is_int(), "Integer value expected")
2577  return int(self.as_string())
2578 
2579  def as_string(self):
2580  """Return a Z3 integer numeral as a Python string.
2581  >>> v = IntVal(100)
2582  >>> v.as_string()
2583  '100'
2584  """
2585  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2586 
2587 class RatNumRef(ArithRef):
2588  """Rational values."""
2589 
2590  def numerator(self):
2591  """ Return the numerator of a Z3 rational numeral.
2592 
2593  >>> is_rational_value(RealVal("3/5"))
2594  True
2595  >>> n = RealVal("3/5")
2596  >>> n.numerator()
2597  3
2598  >>> is_rational_value(Q(3,5))
2599  True
2600  >>> Q(3,5).numerator()
2601  3
2602  """
2603  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2604 
2605  def denominator(self):
2606  """ Return the denominator of a Z3 rational numeral.
2607 
2608  >>> is_rational_value(Q(3,5))
2609  True
2610  >>> n = Q(3,5)
2611  >>> n.denominator()
2612  5
2613  """
2614  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2615 
2616  def numerator_as_long(self):
2617  """ Return the numerator as a Python long.
2618 
2619  >>> v = RealVal(10000000000)
2620  >>> v
2621  10000000000
2622  >>> v + 1
2623  10000000000 + 1
2624  >>> v.numerator_as_long() + 1 == 10000000001
2625  True
2626  """
2627  return self.numerator().as_long()
2628 
2629  def denominator_as_long(self):
2630  """ Return the denominator as a Python long.
2631 
2632  >>> v = RealVal("1/3")
2633  >>> v
2634  1/3
2635  >>> v.denominator_as_long()
2636  3
2637  """
2638  return self.denominator().as_long()
2639 
2640  def as_decimal(self, prec):
2641  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2642 
2643  >>> v = RealVal("1/5")
2644  >>> v.as_decimal(3)
2645  '0.2'
2646  >>> v = RealVal("1/3")
2647  >>> v.as_decimal(3)
2648  '0.333?'
2649  """
2650  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2651 
2652  def as_string(self):
2653  """Return a Z3 rational numeral as a Python string.
2654 
2655  >>> v = Q(3,6)
2656  >>> v.as_string()
2657  '1/2'
2658  """
2659  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2660 
2661  def as_fraction(self):
2662  """Return a Z3 rational as a Python Fraction object.
2663 
2664  >>> v = RealVal("1/5")
2665  >>> v.as_fraction()
2666  Fraction(1, 5)
2667  """
2668  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2669 
2670 class AlgebraicNumRef(ArithRef):
2671  """Algebraic irrational values."""
2672 
2673  def approx(self, precision=10):
2674  """Return a Z3 rational number that approximates the algebraic number `self`.
2675  The result `r` is such that |r - self| <= 1/10^precision
2676 
2677  >>> x = simplify(Sqrt(2))
2678  >>> x.approx(20)
2679  6838717160008073720548335/4835703278458516698824704
2680  >>> x.approx(5)
2681  2965821/2097152
2682  """
2683  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2684  def as_decimal(self, prec):
2685  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2686 
2687  >>> x = simplify(Sqrt(2))
2688  >>> x.as_decimal(10)
2689  '1.4142135623?'
2690  >>> x.as_decimal(20)
2691  '1.41421356237309504880?'
2692  """
2693  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2694 
2695 def _py2expr(a, ctx=None):
2696  if isinstance(a, bool):
2697  return BoolVal(a, ctx)
2698  if _is_int(a):
2699  return IntVal(a, ctx)
2700  if isinstance(a, float):
2701  return RealVal(a, ctx)
2702  if __debug__:
2703  _z3_assert(False, "Python bool, int, long or float expected")
2704 
2705 def IntSort(ctx=None):
2706  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2707 
2708  >>> IntSort()
2709  Int
2710  >>> x = Const('x', IntSort())
2711  >>> is_int(x)
2712  True
2713  >>> x.sort() == IntSort()
2714  True
2715  >>> x.sort() == BoolSort()
2716  False
2717  """
2718  ctx = _get_ctx(ctx)
2719  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2720 
2721 def RealSort(ctx=None):
2722  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2723 
2724  >>> RealSort()
2725  Real
2726  >>> x = Const('x', RealSort())
2727  >>> is_real(x)
2728  True
2729  >>> is_int(x)
2730  False
2731  >>> x.sort() == RealSort()
2732  True
2733  """
2734  ctx = _get_ctx(ctx)
2735  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2736 
2737 def _to_int_str(val):
2738  if isinstance(val, float):
2739  return str(int(val))
2740  elif isinstance(val, bool):
2741  if val:
2742  return "1"
2743  else:
2744  return "0"
2745  elif _is_int(val):
2746  return str(val)
2747  elif isinstance(val, str):
2748  return val
2749  if __debug__:
2750  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2751 
2752 def IntVal(val, ctx=None):
2753  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2754 
2755  >>> IntVal(1)
2756  1
2757  >>> IntVal("100")
2758  100
2759  """
2760  ctx = _get_ctx(ctx)
2761  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2762 
2763 def RealVal(val, ctx=None):
2764  """Return a Z3 real value.
2765 
2766  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2767  If `ctx=None`, then the global context is used.
2768 
2769  >>> RealVal(1)
2770  1
2771  >>> RealVal(1).sort()
2772  Real
2773  >>> RealVal("3/5")
2774  3/5
2775  >>> RealVal("1.5")
2776  3/2
2777  """
2778  ctx = _get_ctx(ctx)
2779  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2780 
2781 def RatVal(a, b, ctx=None):
2782  """Return a Z3 rational a/b.
2783 
2784  If `ctx=None`, then the global context is used.
2785 
2786  >>> RatVal(3,5)
2787  3/5
2788  >>> RatVal(3,5).sort()
2789  Real
2790  """
2791  if __debug__:
2792  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2793  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2794  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2795 
2796 def Q(a, b, ctx=None):
2797  """Return a Z3 rational a/b.
2798 
2799  If `ctx=None`, then the global context is used.
2800 
2801  >>> Q(3,5)
2802  3/5
2803  >>> Q(3,5).sort()
2804  Real
2805  """
2806  return simplify(RatVal(a, b))
2807 
2808 def Int(name, ctx=None):
2809  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2810 
2811  >>> x = Int('x')
2812  >>> is_int(x)
2813  True
2814  >>> is_int(x + 1)
2815  True
2816  """
2817  ctx = _get_ctx(ctx)
2818  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2819 
2820 def Ints(names, ctx=None):
2821  """Return a tuple of Integer constants.
2822 
2823  >>> x, y, z = Ints('x y z')
2824  >>> Sum(x, y, z)
2825  x + y + z
2826  """
2827  ctx = _get_ctx(ctx)
2828  if isinstance(names, str):
2829  names = names.split(" ")
2830  return [Int(name, ctx) for name in names]
2831 
2832 def IntVector(prefix, sz, ctx=None):
2833  """Return a list of integer constants of size `sz`.
2834 
2835  >>> X = IntVector('x', 3)
2836  >>> X
2837  [x__0, x__1, x__2]
2838  >>> Sum(X)
2839  x__0 + x__1 + x__2
2840  """
2841  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
2842 
2843 def FreshInt(prefix='x', ctx=None):
2844  """Return a fresh integer constant in the given context using the given prefix.
2845 
2846  >>> x = FreshInt()
2847  >>> y = FreshInt()
2848  >>> eq(x, y)
2849  False
2850  >>> x.sort()
2851  Int
2852  """
2853  ctx = _get_ctx(ctx)
2854  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
2855 
2856 def Real(name, ctx=None):
2857  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
2858 
2859  >>> x = Real('x')
2860  >>> is_real(x)
2861  True
2862  >>> is_real(x + 1)
2863  True
2864  """
2865  ctx = _get_ctx(ctx)
2866  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
2867 
2868 def Reals(names, ctx=None):
2869  """Return a tuple of real constants.
2870 
2871  >>> x, y, z = Reals('x y z')
2872  >>> Sum(x, y, z)
2873  x + y + z
2874  >>> Sum(x, y, z).sort()
2875  Real
2876  """
2877  ctx = _get_ctx(ctx)
2878  if isinstance(names, str):
2879  names = names.split(" ")
2880  return [Real(name, ctx) for name in names]
2881 
2882 def RealVector(prefix, sz, ctx=None):
2883  """Return a list of real constants of size `sz`.
2884 
2885  >>> X = RealVector('x', 3)
2886  >>> X
2887  [x__0, x__1, x__2]
2888  >>> Sum(X)
2889  x__0 + x__1 + x__2
2890  >>> Sum(X).sort()
2891  Real
2892  """
2893  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
2894 
2895 def FreshReal(prefix='b', ctx=None):
2896  """Return a fresh real constant in the given context using the given prefix.
2897 
2898  >>> x = FreshReal()
2899  >>> y = FreshReal()
2900  >>> eq(x, y)
2901  False
2902  >>> x.sort()
2903  Real
2904  """
2905  ctx = _get_ctx(ctx)
2906  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
2907 
2908 def ToReal(a):
2909  """ Return the Z3 expression ToReal(a).
2910 
2911  >>> x = Int('x')
2912  >>> x.sort()
2913  Int
2914  >>> n = ToReal(x)
2915  >>> n
2916  ToReal(x)
2917  >>> n.sort()
2918  Real
2919  """
2920  if __debug__:
2921  _z3_assert(a.is_int(), "Z3 integer expression expected.")
2922  ctx = a.ctx
2923  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
2924 
2925 def ToInt(a):
2926  """ Return the Z3 expression ToInt(a).
2927 
2928  >>> x = Real('x')
2929  >>> x.sort()
2930  Real
2931  >>> n = ToInt(x)
2932  >>> n
2933  ToInt(x)
2934  >>> n.sort()
2935  Int
2936  """
2937  if __debug__:
2938  _z3_assert(a.is_real(), "Z3 real expression expected.")
2939  ctx = a.ctx
2940  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
2941 
2942 def IsInt(a):
2943  """ Return the Z3 predicate IsInt(a).
2944 
2945  >>> x = Real('x')
2946  >>> IsInt(x + "1/2")
2947  IsInt(x + 1/2)
2948  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
2949  [x = 1/2]
2950  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
2951  no solution
2952  """
2953  if __debug__:
2954  _z3_assert(a.is_real(), "Z3 real expression expected.")
2955  ctx = a.ctx
2956  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
2957 
2958 def Sqrt(a, ctx=None):
2959  """ Return a Z3 expression which represents the square root of a.
2960 
2961  >>> x = Real('x')
2962  >>> Sqrt(x)
2963  x**(1/2)
2964  """
2965  if not is_expr(a):
2966  ctx = _get_ctx(ctx)
2967  a = RealVal(a, ctx)
2968  return a ** "1/2"
2969 
2970 def Cbrt(a, ctx=None):
2971  """ Return a Z3 expression which represents the cubic root of a.
2972 
2973  >>> x = Real('x')
2974  >>> Cbrt(x)
2975  x**(1/3)
2976  """
2977  if not is_expr(a):
2978  ctx = _get_ctx(ctx)
2979  a = RealVal(a, ctx)
2980  return a ** "1/3"
2981 
2982 #########################################
2983 #
2984 # Bit-Vectors
2985 #
2986 #########################################
2987 
2988 class BitVecSortRef(SortRef):
2989  """Bit-vector sort."""
2990 
2991  def size(self):
2992  """Return the size (number of bits) of the bit-vector sort `self`.
2993 
2994  >>> b = BitVecSort(32)
2995  >>> b.size()
2996  32
2997  """
2998  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
2999 
3000  def subsort(self, other):
3001  return is_bv_sort(other) and self.size() < other.size()
3002 
3003  def cast(self, val):
3004  """Try to cast `val` as a Bit-Vector.
3005 
3006  >>> b = BitVecSort(32)
3007  >>> b.cast(10)
3008  10
3009  >>> b.cast(10).sexpr()
3010  '#x0000000a'
3011  """
3012  if is_expr(val):
3013  if __debug__:
3014  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3015  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3016  return val
3017  else:
3018  return BitVecVal(val, self)
3019 
3020 def is_bv_sort(s):
3021  """Return True if `s` is a Z3 bit-vector sort.
3022 
3023  >>> is_bv_sort(BitVecSort(32))
3024  True
3025  >>> is_bv_sort(IntSort())
3026  False
3027  """
3028  return isinstance(s, BitVecSortRef)
3029 
3030 class BitVecRef(ExprRef):
3031  """Bit-vector expressions."""
3032 
3033  def sort(self):
3034  """Return the sort of the bit-vector expression `self`.
3035 
3036  >>> x = BitVec('x', 32)
3037  >>> x.sort()
3038  BitVec(32)
3039  >>> x.sort() == BitVecSort(32)
3040  True
3041  """
3042  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3043 
3044  def size(self):
3045  """Return the number of bits of the bit-vector expression `self`.
3046 
3047  >>> x = BitVec('x', 32)
3048  >>> (x + 1).size()
3049  32
3050  >>> Concat(x, x).size()
3051  64
3052  """
3053  return self.sort().size()
3054 
3055  def __add__(self, other):
3056  """Create the Z3 expression `self + other`.
3057 
3058  >>> x = BitVec('x', 32)
3059  >>> y = BitVec('y', 32)
3060  >>> x + y
3061  x + y
3062  >>> (x + y).sort()
3063  BitVec(32)
3064  """
3065  a, b = _coerce_exprs(self, other)
3066  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3067 
3068  def __radd__(self, other):
3069  """Create the Z3 expression `other + self`.
3070 
3071  >>> x = BitVec('x', 32)
3072  >>> 10 + x
3073  10 + x
3074  """
3075  a, b = _coerce_exprs(self, other)
3076  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3077 
3078  def __mul__(self, other):
3079  """Create the Z3 expression `self * other`.
3080 
3081  >>> x = BitVec('x', 32)
3082  >>> y = BitVec('y', 32)
3083  >>> x * y
3084  x*y
3085  >>> (x * y).sort()
3086  BitVec(32)
3087  """
3088  a, b = _coerce_exprs(self, other)
3089  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3090 
3091  def __rmul__(self, other):
3092  """Create the Z3 expression `other * self`.
3093 
3094  >>> x = BitVec('x', 32)
3095  >>> 10 * x
3096  10*x
3097  """
3098  a, b = _coerce_exprs(self, other)
3099  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3100 
3101  def __sub__(self, other):
3102  """Create the Z3 expression `self - other`.
3103 
3104  >>> x = BitVec('x', 32)
3105  >>> y = BitVec('y', 32)
3106  >>> x - y
3107  x - y
3108  >>> (x - y).sort()
3109  BitVec(32)
3110  """
3111  a, b = _coerce_exprs(self, other)
3112  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3113 
3114  def __rsub__(self, other):
3115  """Create the Z3 expression `other - self`.
3116 
3117  >>> x = BitVec('x', 32)
3118  >>> 10 - x
3119  10 - x
3120  """
3121  a, b = _coerce_exprs(self, other)
3122  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3123 
3124  def __or__(self, other):
3125  """Create the Z3 expression bitwise-or `self | other`.
3126 
3127  >>> x = BitVec('x', 32)
3128  >>> y = BitVec('y', 32)
3129  >>> x | y
3130  x | y
3131  >>> (x | y).sort()
3132  BitVec(32)
3133  """
3134  a, b = _coerce_exprs(self, other)
3135  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3136 
3137  def __ror__(self, other):
3138  """Create the Z3 expression bitwise-or `other | self`.
3139 
3140  >>> x = BitVec('x', 32)
3141  >>> 10 | x
3142  10 | x
3143  """
3144  a, b = _coerce_exprs(self, other)
3145  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3146 
3147  def __and__(self, other):
3148  """Create the Z3 expression bitwise-and `self & other`.
3149 
3150  >>> x = BitVec('x', 32)
3151  >>> y = BitVec('y', 32)
3152  >>> x & y
3153  x & y
3154  >>> (x & y).sort()
3155  BitVec(32)
3156  """
3157  a, b = _coerce_exprs(self, other)
3158  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3159 
3160  def __rand__(self, other):
3161  """Create the Z3 expression bitwise-or `other & self`.
3162 
3163  >>> x = BitVec('x', 32)
3164  >>> 10 & x
3165  10 & x
3166  """
3167  a, b = _coerce_exprs(self, other)
3168  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3169 
3170  def __xor__(self, other):
3171  """Create the Z3 expression bitwise-xor `self ^ other`.
3172 
3173  >>> x = BitVec('x', 32)
3174  >>> y = BitVec('y', 32)
3175  >>> x ^ y
3176  x ^ y
3177  >>> (x ^ y).sort()
3178  BitVec(32)
3179  """
3180  a, b = _coerce_exprs(self, other)
3181  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3182 
3183  def __rxor__(self, other):
3184  """Create the Z3 expression bitwise-xor `other ^ self`.
3185 
3186  >>> x = BitVec('x', 32)
3187  >>> 10 ^ x
3188  10 ^ x
3189  """
3190  a, b = _coerce_exprs(self, other)
3191  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3192 
3193  def __pos__(self):
3194  """Return `self`.
3195 
3196  >>> x = BitVec('x', 32)
3197  >>> +x
3198  x
3199  """
3200  return self
3201 
3202  def __neg__(self):
3203  """Return an expression representing `-self`.
3204 
3205  >>> x = BitVec('x', 32)
3206  >>> -x
3207  -x
3208  >>> simplify(-(-x))
3209  x
3210  """
3211  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3212 
3213  def __invert__(self):
3214  """Create the Z3 expression bitwise-not `~self`.
3215 
3216  >>> x = BitVec('x', 32)
3217  >>> ~x
3218  ~x
3219  >>> simplify(~(~x))
3220  x
3221  """
3222  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3223 
3224  def __div__(self, other):
3225  """Create the Z3 expression (signed) division `self / other`.
3226 
3227  Use the function UDiv() for unsigned division.
3228 
3229  >>> x = BitVec('x', 32)
3230  >>> y = BitVec('y', 32)
3231  >>> x / y
3232  x/y
3233  >>> (x / y).sort()
3234  BitVec(32)
3235  >>> (x / y).sexpr()
3236  '(bvsdiv x y)'
3237  >>> UDiv(x, y).sexpr()
3238  '(bvudiv x y)'
3239  """
3240  a, b = _coerce_exprs(self, other)
3241  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3242 
3243  def __truediv__(self, other):
3244  """Create the Z3 expression (signed) division `self / other`."""
3245  return self.__div__(other)
3246 
3247  def __rdiv__(self, other):
3248  """Create the Z3 expression (signed) division `other / self`.
3249 
3250  Use the function UDiv() for unsigned division.
3251 
3252  >>> x = BitVec('x', 32)
3253  >>> 10 / x
3254  10/x
3255  >>> (10 / x).sexpr()
3256  '(bvsdiv #x0000000a x)'
3257  >>> UDiv(10, x).sexpr()
3258  '(bvudiv #x0000000a x)'
3259  """
3260  a, b = _coerce_exprs(self, other)
3261  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3262 
3263  def __rtruediv__(self, other):
3264  """Create the Z3 expression (signed) division `other / self`."""
3265  return self.__rdiv__(other)
3266 
3267  def __mod__(self, other):
3268  """Create the Z3 expression (signed) mod `self % other`.
3269 
3270  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
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  >>> (x % y).sexpr()
3279  '(bvsmod x y)'
3280  >>> URem(x, y).sexpr()
3281  '(bvurem x y)'
3282  >>> SRem(x, y).sexpr()
3283  '(bvsrem x y)'
3284  """
3285  a, b = _coerce_exprs(self, other)
3286  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3287 
3288  def __rmod__(self, other):
3289  """Create the Z3 expression (signed) mod `other % self`.
3290 
3291  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3292 
3293  >>> x = BitVec('x', 32)
3294  >>> 10 % x
3295  10%x
3296  >>> (10 % x).sexpr()
3297  '(bvsmod #x0000000a x)'
3298  >>> URem(10, x).sexpr()
3299  '(bvurem #x0000000a x)'
3300  >>> SRem(10, x).sexpr()
3301  '(bvsrem #x0000000a x)'
3302  """
3303  a, b = _coerce_exprs(self, other)
3304  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3305 
3306  def __le__(self, other):
3307  """Create the Z3 expression (signed) `other <= self`.
3308 
3309  Use the function ULE() for unsigned less than or equal to.
3310 
3311  >>> x, y = BitVecs('x y', 32)
3312  >>> x <= y
3313  x <= y
3314  >>> (x <= y).sexpr()
3315  '(bvsle x y)'
3316  >>> ULE(x, y).sexpr()
3317  '(bvule x y)'
3318  """
3319  a, b = _coerce_exprs(self, other)
3320  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3321 
3322  def __lt__(self, other):
3323  """Create the Z3 expression (signed) `other < self`.
3324 
3325  Use the function ULT() for unsigned less than.
3326 
3327  >>> x, y = BitVecs('x y', 32)
3328  >>> x < y
3329  x < y
3330  >>> (x < y).sexpr()
3331  '(bvslt x y)'
3332  >>> ULT(x, y).sexpr()
3333  '(bvult x y)'
3334  """
3335  a, b = _coerce_exprs(self, other)
3336  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3337 
3338  def __gt__(self, other):
3339  """Create the Z3 expression (signed) `other > self`.
3340 
3341  Use the function UGT() for unsigned greater than.
3342 
3343  >>> x, y = BitVecs('x y', 32)
3344  >>> x > y
3345  x > y
3346  >>> (x > y).sexpr()
3347  '(bvsgt x y)'
3348  >>> UGT(x, y).sexpr()
3349  '(bvugt x y)'
3350  """
3351  a, b = _coerce_exprs(self, other)
3352  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3353 
3354  def __ge__(self, other):
3355  """Create the Z3 expression (signed) `other >= self`.
3356 
3357  Use the function UGE() for unsigned greater than or equal to.
3358 
3359  >>> x, y = BitVecs('x y', 32)
3360  >>> x >= y
3361  x >= y
3362  >>> (x >= y).sexpr()
3363  '(bvsge x y)'
3364  >>> UGE(x, y).sexpr()
3365  '(bvuge x y)'
3366  """
3367  a, b = _coerce_exprs(self, other)
3368  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3369 
3370  def __rshift__(self, other):
3371  """Create the Z3 expression (arithmetical) right shift `self >> other`
3372 
3373  Use the function LShR() for the right logical shift
3374 
3375  >>> x, y = BitVecs('x y', 32)
3376  >>> x >> y
3377  x >> y
3378  >>> (x >> y).sexpr()
3379  '(bvashr x y)'
3380  >>> LShR(x, y).sexpr()
3381  '(bvlshr x y)'
3382  >>> BitVecVal(4, 3)
3383  4
3384  >>> BitVecVal(4, 3).as_signed_long()
3385  -4
3386  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3387  -2
3388  >>> simplify(BitVecVal(4, 3) >> 1)
3389  6
3390  >>> simplify(LShR(BitVecVal(4, 3), 1))
3391  2
3392  >>> simplify(BitVecVal(2, 3) >> 1)
3393  1
3394  >>> simplify(LShR(BitVecVal(2, 3), 1))
3395  1
3396  """
3397  a, b = _coerce_exprs(self, other)
3398  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3399 
3400  def __lshift__(self, other):
3401  """Create the Z3 expression left shift `self << other`
3402 
3403  >>> x, y = BitVecs('x y', 32)
3404  >>> x << y
3405  x << y
3406  >>> (x << y).sexpr()
3407  '(bvshl x y)'
3408  >>> simplify(BitVecVal(2, 3) << 1)
3409  4
3410  """
3411  a, b = _coerce_exprs(self, other)
3412  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3413 
3414  def __rrshift__(self, other):
3415  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3416 
3417  Use the function LShR() for the right logical shift
3418 
3419  >>> x = BitVec('x', 32)
3420  >>> 10 >> x
3421  10 >> x
3422  >>> (10 >> x).sexpr()
3423  '(bvashr #x0000000a x)'
3424  """
3425  a, b = _coerce_exprs(self, other)
3426  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3427 
3428  def __rlshift__(self, other):
3429  """Create the Z3 expression left shift `other << self`.
3430 
3431  Use the function LShR() for the right logical shift
3432 
3433  >>> x = BitVec('x', 32)
3434  >>> 10 << x
3435  10 << x
3436  >>> (10 << x).sexpr()
3437  '(bvshl #x0000000a x)'
3438  """
3439  a, b = _coerce_exprs(self, other)
3440  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3441 
3442 class BitVecNumRef(BitVecRef):
3443  """Bit-vector values."""
3444 
3445  def as_long(self):
3446  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3447 
3448  >>> v = BitVecVal(0xbadc0de, 32)
3449  >>> v
3450  195936478
3451  >>> print("0x%.8x" % v.as_long())
3452  0x0badc0de
3453  """
3454  return int(self.as_string())
3455 
3456  def as_signed_long(self):
3457  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3458 
3459  >>> BitVecVal(4, 3).as_signed_long()
3460  -4
3461  >>> BitVecVal(7, 3).as_signed_long()
3462  -1
3463  >>> BitVecVal(3, 3).as_signed_long()
3464  3
3465  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3466  -1
3467  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3468  -1
3469  """
3470  sz = self.size()
3471  val = self.as_long()
3472  if val >= 2**(sz - 1):
3473  val = val - 2**sz
3474  if val < -2**(sz - 1):
3475  val = val + 2**sz
3476  return int(val)
3477 
3478  def as_string(self):
3479  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3480 
3481 def is_bv(a):
3482  """Return `True` if `a` is a Z3 bit-vector expression.
3483 
3484  >>> b = BitVec('b', 32)
3485  >>> is_bv(b)
3486  True
3487  >>> is_bv(b + 10)
3488  True
3489  >>> is_bv(Int('x'))
3490  False
3491  """
3492  return isinstance(a, BitVecRef)
3493 
3494 def is_bv_value(a):
3495  """Return `True` if `a` is a Z3 bit-vector numeral value.
3496 
3497  >>> b = BitVec('b', 32)
3498  >>> is_bv_value(b)
3499  False
3500  >>> b = BitVecVal(10, 32)
3501  >>> b
3502  10
3503  >>> is_bv_value(b)
3504  True
3505  """
3506  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3507 
3508 def BV2Int(a, is_signed=False):
3509  """Return the Z3 expression BV2Int(a).
3510 
3511  >>> b = BitVec('b', 3)
3512  >>> BV2Int(b).sort()
3513  Int
3514  >>> x = Int('x')
3515  >>> x > BV2Int(b)
3516  x > BV2Int(b)
3517  >>> x > BV2Int(b, is_signed=False)
3518  x > BV2Int(b)
3519  >>> x > BV2Int(b, is_signed=True)
3520  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3521  >>> solve(x > BV2Int(b), b == 1, x < 3)
3522  [b = 1, x = 2]
3523  """
3524  if __debug__:
3525  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3526  ctx = a.ctx
3527  ## investigate problem with bv2int
3528  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3529 
3530 def BitVecSort(sz, ctx=None):
3531  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3532 
3533  >>> Byte = BitVecSort(8)
3534  >>> Word = BitVecSort(16)
3535  >>> Byte
3536  BitVec(8)
3537  >>> x = Const('x', Byte)
3538  >>> eq(x, BitVec('x', 8))
3539  True
3540  """
3541  ctx = _get_ctx(ctx)
3542  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3543 
3544 def BitVecVal(val, bv, ctx=None):
3545  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3546 
3547  >>> v = BitVecVal(10, 32)
3548  >>> v
3549  10
3550  >>> print("0x%.8x" % v.as_long())
3551  0x0000000a
3552  """
3553  if is_bv_sort(bv):
3554  ctx = bv.ctx
3555  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3556  else:
3557  ctx = _get_ctx(ctx)
3558  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3559 
3560 def BitVec(name, bv, ctx=None):
3561  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3562  If `ctx=None`, then the global context is used.
3563 
3564  >>> x = BitVec('x', 16)
3565  >>> is_bv(x)
3566  True
3567  >>> x.size()
3568  16
3569  >>> x.sort()
3570  BitVec(16)
3571  >>> word = BitVecSort(16)
3572  >>> x2 = BitVec('x', word)
3573  >>> eq(x, x2)
3574  True
3575  """
3576  if isinstance(bv, BitVecSortRef):
3577  ctx = bv.ctx
3578  else:
3579  ctx = _get_ctx(ctx)
3580  bv = BitVecSort(bv, ctx)
3581  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3582 
3583 def BitVecs(names, bv, ctx=None):
3584  """Return a tuple of bit-vector constants of size bv.
3585 
3586  >>> x, y, z = BitVecs('x y z', 16)
3587  >>> x.size()
3588  16
3589  >>> x.sort()
3590  BitVec(16)
3591  >>> Sum(x, y, z)
3592  0 + x + y + z
3593  >>> Product(x, y, z)
3594  1*x*y*z
3595  >>> simplify(Product(x, y, z))
3596  x*y*z
3597  """
3598  ctx = _get_ctx(ctx)
3599  if isinstance(names, str):
3600  names = names.split(" ")
3601  return [BitVec(name, bv, ctx) for name in names]
3602 
3603 def Concat(*args):
3604  """Create a Z3 bit-vector concatenation expression.
3605 
3606  >>> v = BitVecVal(1, 4)
3607  >>> Concat(v, v+1, v)
3608  Concat(Concat(1, 1 + 1), 1)
3609  >>> simplify(Concat(v, v+1, v))
3610  289
3611  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3612  121
3613  """
3614  args = _get_args(args)
3615  sz = len(args)
3616  if __debug__:
3617  _z3_assert(sz >= 2, "At least two arguments expected.")
3618 
3619  ctx = None
3620  for a in args:
3621  if is_expr(a):
3622  ctx = a.ctx
3623  break
3624  if is_seq(args[0]) or isinstance(args[0], str):
3625  args = [_coerce_seq(s, ctx) for s in args]
3626  if __debug__:
3627  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3628  v = (Ast * sz)()
3629  for i in range(sz):
3630  v[i] = args[i].as_ast()
3631  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3632 
3633  if is_re(args[0]):
3634  if __debug__:
3635  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3636  v = (Ast * sz)()
3637  for i in range(sz):
3638  v[i] = args[i].as_ast()
3639  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3640 
3641  if __debug__:
3642  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3643  r = args[0]
3644  for i in range(sz - 1):
3645  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3646  return r
3647 
3648 def Extract(high, low, a):
3649  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3650 
3651  >>> x = BitVec('x', 8)
3652  >>> Extract(6, 2, x)
3653  Extract(6, 2, x)
3654  >>> Extract(6, 2, x).sort()
3655  BitVec(5)
3656  >>> simplify(Extract(StringVal("abcd"),2,1))
3657  "c"
3658  """
3659  if isinstance(high, str):
3660  high = StringVal(high)
3661  if is_seq(high):
3662  s = high
3663  offset = _py2expr(low, high.ctx)
3664  length = _py2expr(a, high.ctx)
3665 
3666  if __debug__:
3667  _z3_assert(is_int(offset) and is_int(length), "Second and third arguments must be integers")
3668  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3669  if __debug__:
3670  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3671  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3672  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3673  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3674 
3675 def _check_bv_args(a, b):
3676  if __debug__:
3677  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3678 
3679 def ULE(a, b):
3680  """Create the Z3 expression (unsigned) `other <= self`.
3681 
3682  Use the operator <= for signed less than or equal to.
3683 
3684  >>> x, y = BitVecs('x y', 32)
3685  >>> ULE(x, y)
3686  ULE(x, y)
3687  >>> (x <= y).sexpr()
3688  '(bvsle x y)'
3689  >>> ULE(x, y).sexpr()
3690  '(bvule x y)'
3691  """
3692  _check_bv_args(a, b)
3693  a, b = _coerce_exprs(a, b)
3694  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3695 
3696 def ULT(a, b):
3697  """Create the Z3 expression (unsigned) `other < self`.
3698 
3699  Use the operator < for signed less than.
3700 
3701  >>> x, y = BitVecs('x y', 32)
3702  >>> ULT(x, y)
3703  ULT(x, y)
3704  >>> (x < y).sexpr()
3705  '(bvslt x y)'
3706  >>> ULT(x, y).sexpr()
3707  '(bvult x y)'
3708  """
3709  _check_bv_args(a, b)
3710  a, b = _coerce_exprs(a, b)
3711  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3712 
3713 def UGE(a, b):
3714  """Create the Z3 expression (unsigned) `other >= self`.
3715 
3716  Use the operator >= for signed greater than or equal to.
3717 
3718  >>> x, y = BitVecs('x y', 32)
3719  >>> UGE(x, y)
3720  UGE(x, y)
3721  >>> (x >= y).sexpr()
3722  '(bvsge x y)'
3723  >>> UGE(x, y).sexpr()
3724  '(bvuge x y)'
3725  """
3726  _check_bv_args(a, b)
3727  a, b = _coerce_exprs(a, b)
3728  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3729 
3730 def UGT(a, b):
3731  """Create the Z3 expression (unsigned) `other > self`.
3732 
3733  Use the operator > for signed greater than.
3734 
3735  >>> x, y = BitVecs('x y', 32)
3736  >>> UGT(x, y)
3737  UGT(x, y)
3738  >>> (x > y).sexpr()
3739  '(bvsgt x y)'
3740  >>> UGT(x, y).sexpr()
3741  '(bvugt x y)'
3742  """
3743  _check_bv_args(a, b)
3744  a, b = _coerce_exprs(a, b)
3745  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3746 
3747 def UDiv(a, b):
3748  """Create the Z3 expression (unsigned) division `self / other`.
3749 
3750  Use the operator / for signed division.
3751 
3752  >>> x = BitVec('x', 32)
3753  >>> y = BitVec('y', 32)
3754  >>> UDiv(x, y)
3755  UDiv(x, y)
3756  >>> UDiv(x, y).sort()
3757  BitVec(32)
3758  >>> (x / y).sexpr()
3759  '(bvsdiv x y)'
3760  >>> UDiv(x, y).sexpr()
3761  '(bvudiv x y)'
3762  """
3763  _check_bv_args(a, b)
3764  a, b = _coerce_exprs(a, b)
3765  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3766 
3767 def URem(a, b):
3768  """Create the Z3 expression (unsigned) remainder `self % other`.
3769 
3770  Use the operator % for signed modulus, and SRem() for signed remainder.
3771 
3772  >>> x = BitVec('x', 32)
3773  >>> y = BitVec('y', 32)
3774  >>> URem(x, y)
3775  URem(x, y)
3776  >>> URem(x, y).sort()
3777  BitVec(32)
3778  >>> (x % y).sexpr()
3779  '(bvsmod x y)'
3780  >>> URem(x, y).sexpr()
3781  '(bvurem x y)'
3782  """
3783  _check_bv_args(a, b)
3784  a, b = _coerce_exprs(a, b)
3785  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3786 
3787 def SRem(a, b):
3788  """Create the Z3 expression signed remainder.
3789 
3790  Use the operator % for signed modulus, and URem() for unsigned remainder.
3791 
3792  >>> x = BitVec('x', 32)
3793  >>> y = BitVec('y', 32)
3794  >>> SRem(x, y)
3795  SRem(x, y)
3796  >>> SRem(x, y).sort()
3797  BitVec(32)
3798  >>> (x % y).sexpr()
3799  '(bvsmod x y)'
3800  >>> SRem(x, y).sexpr()
3801  '(bvsrem x y)'
3802  """
3803  _check_bv_args(a, b)
3804  a, b = _coerce_exprs(a, b)
3805  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3806 
3807 def LShR(a, b):
3808  """Create the Z3 expression logical right shift.
3809 
3810  Use the operator >> for the arithmetical right shift.
3811 
3812  >>> x, y = BitVecs('x y', 32)
3813  >>> LShR(x, y)
3814  LShR(x, y)
3815  >>> (x >> y).sexpr()
3816  '(bvashr x y)'
3817  >>> LShR(x, y).sexpr()
3818  '(bvlshr x y)'
3819  >>> BitVecVal(4, 3)
3820  4
3821  >>> BitVecVal(4, 3).as_signed_long()
3822  -4
3823  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3824  -2
3825  >>> simplify(BitVecVal(4, 3) >> 1)
3826  6
3827  >>> simplify(LShR(BitVecVal(4, 3), 1))
3828  2
3829  >>> simplify(BitVecVal(2, 3) >> 1)
3830  1
3831  >>> simplify(LShR(BitVecVal(2, 3), 1))
3832  1
3833  """
3834  _check_bv_args(a, b)
3835  a, b = _coerce_exprs(a, b)
3836  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3837 
3838 def RotateLeft(a, b):
3839  """Return an expression representing `a` rotated to the left `b` times.
3840 
3841  >>> a, b = BitVecs('a b', 16)
3842  >>> RotateLeft(a, b)
3843  RotateLeft(a, b)
3844  >>> simplify(RotateLeft(a, 0))
3845  a
3846  >>> simplify(RotateLeft(a, 16))
3847  a
3848  """
3849  _check_bv_args(a, b)
3850  a, b = _coerce_exprs(a, b)
3851  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3852 
3853 def RotateRight(a, b):
3854  """Return an expression representing `a` rotated to the right `b` times.
3855 
3856  >>> a, b = BitVecs('a b', 16)
3857  >>> RotateRight(a, b)
3858  RotateRight(a, b)
3859  >>> simplify(RotateRight(a, 0))
3860  a
3861  >>> simplify(RotateRight(a, 16))
3862  a
3863  """
3864  _check_bv_args(a, b)
3865  a, b = _coerce_exprs(a, b)
3866  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3867 
3868 def SignExt(n, a):
3869  """Return a bit-vector expression with `n` extra sign-bits.
3870 
3871  >>> x = BitVec('x', 16)
3872  >>> n = SignExt(8, x)
3873  >>> n.size()
3874  24
3875  >>> n
3876  SignExt(8, x)
3877  >>> n.sort()
3878  BitVec(24)
3879  >>> v0 = BitVecVal(2, 2)
3880  >>> v0
3881  2
3882  >>> v0.size()
3883  2
3884  >>> v = simplify(SignExt(6, v0))
3885  >>> v
3886  254
3887  >>> v.size()
3888  8
3889  >>> print("%.x" % v.as_long())
3890  fe
3891  """
3892  if __debug__:
3893  _z3_assert(_is_int(n), "First argument must be an integer")
3894  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3895  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3896 
3897 def ZeroExt(n, a):
3898  """Return a bit-vector expression with `n` extra zero-bits.
3899 
3900  >>> x = BitVec('x', 16)
3901  >>> n = ZeroExt(8, x)
3902  >>> n.size()
3903  24
3904  >>> n
3905  ZeroExt(8, x)
3906  >>> n.sort()
3907  BitVec(24)
3908  >>> v0 = BitVecVal(2, 2)
3909  >>> v0
3910  2
3911  >>> v0.size()
3912  2
3913  >>> v = simplify(ZeroExt(6, v0))
3914  >>> v
3915  2
3916  >>> v.size()
3917  8
3918  """
3919  if __debug__:
3920  _z3_assert(_is_int(n), "First argument must be an integer")
3921  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3922  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3923 
3924 def RepeatBitVec(n, a):
3925  """Return an expression representing `n` copies of `a`.
3926 
3927  >>> x = BitVec('x', 8)
3928  >>> n = RepeatBitVec(4, x)
3929  >>> n
3930  RepeatBitVec(4, x)
3931  >>> n.size()
3932  32
3933  >>> v0 = BitVecVal(10, 4)
3934  >>> print("%.x" % v0.as_long())
3935  a
3936  >>> v = simplify(RepeatBitVec(4, v0))
3937  >>> v.size()
3938  16
3939  >>> print("%.x" % v.as_long())
3940  aaaa
3941  """
3942  if __debug__:
3943  _z3_assert(_is_int(n), "First argument must be an integer")
3944  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3945  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
3946 
3947 def BVRedAnd(a):
3948  """Return the reduction-and expression of `a`."""
3949  if __debug__:
3950  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3951  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
3952 
3953 def BVRedOr(a):
3954  """Return the reduction-or expression of `a`."""
3955  if __debug__:
3956  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3957  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
3958 
3959 #########################################
3960 #
3961 # Arrays
3962 #
3963 #########################################
3964 
3965 class ArraySortRef(SortRef):
3966  """Array sorts."""
3967 
3968  def domain(self):
3969  """Return the domain of the array sort `self`.
3970 
3971  >>> A = ArraySort(IntSort(), BoolSort())
3972  >>> A.domain()
3973  Int
3974  """
3975  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
3976 
3977  def range(self):
3978  """Return the range of the array sort `self`.
3979 
3980  >>> A = ArraySort(IntSort(), BoolSort())
3981  >>> A.range()
3982  Bool
3983  """
3984  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
3985 
3986 class ArrayRef(ExprRef):
3987  """Array expressions. """
3988 
3989  def sort(self):
3990  """Return the array sort of the array expression `self`.
3991 
3992  >>> a = Array('a', IntSort(), BoolSort())
3993  >>> a.sort()
3994  Array(Int, Bool)
3995  """
3996  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3997 
3998  def domain(self):
3999  """Shorthand for `self.sort().domain()`.
4000 
4001  >>> a = Array('a', IntSort(), BoolSort())
4002  >>> a.domain()
4003  Int
4004  """
4005  return self.sort().domain()
4006 
4007  def range(self):
4008  """Shorthand for `self.sort().range()`.
4009 
4010  >>> a = Array('a', IntSort(), BoolSort())
4011  >>> a.range()
4012  Bool
4013  """
4014  return self.sort().range()
4015 
4016  def __getitem__(self, arg):
4017  """Return the Z3 expression `self[arg]`.
4018 
4019  >>> a = Array('a', IntSort(), BoolSort())
4020  >>> i = Int('i')
4021  >>> a[i]
4022  a[i]
4023  >>> a[i].sexpr()
4024  '(select a i)'
4025  """
4026  arg = self.domain().cast(arg)
4027  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4028 
4029  def default(self):
4030  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4031 
4032 
4033 def is_array(a):
4034  """Return `True` if `a` is a Z3 array expression.
4035 
4036  >>> a = Array('a', IntSort(), IntSort())
4037  >>> is_array(a)
4038  True
4039  >>> is_array(Store(a, 0, 1))
4040  True
4041  >>> is_array(a[0])
4042  False
4043  """
4044  return isinstance(a, ArrayRef)
4045 
4046 def is_const_array(a):
4047  """Return `True` if `a` is a Z3 constant array.
4048 
4049  >>> a = K(IntSort(), 10)
4050  >>> is_const_array(a)
4051  True
4052  >>> a = Array('a', IntSort(), IntSort())
4053  >>> is_const_array(a)
4054  False
4055  """
4056  return is_app_of(a, Z3_OP_CONST_ARRAY)
4057 
4058 def is_K(a):
4059  """Return `True` if `a` is a Z3 constant array.
4060 
4061  >>> a = K(IntSort(), 10)
4062  >>> is_K(a)
4063  True
4064  >>> a = Array('a', IntSort(), IntSort())
4065  >>> is_K(a)
4066  False
4067  """
4068  return is_app_of(a, Z3_OP_CONST_ARRAY)
4069 
4070 def is_map(a):
4071  """Return `True` if `a` is a Z3 map array expression.
4072 
4073  >>> f = Function('f', IntSort(), IntSort())
4074  >>> b = Array('b', IntSort(), IntSort())
4075  >>> a = Map(f, b)
4076  >>> a
4077  Map(f, b)
4078  >>> is_map(a)
4079  True
4080  >>> is_map(b)
4081  False
4082  """
4083  return is_app_of(a, Z3_OP_ARRAY_MAP)
4084 
4085 def is_default(a):
4086  """Return `True` if `a` is a Z3 default array expression.
4087  >>> d = Default(K(IntSort(), 10))
4088  >>> is_default(d)
4089  True
4090  """
4091  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4092 
4093 def get_map_func(a):
4094  """Return the function declaration associated with a Z3 map array expression.
4095 
4096  >>> f = Function('f', IntSort(), IntSort())
4097  >>> b = Array('b', IntSort(), IntSort())
4098  >>> a = Map(f, b)
4099  >>> eq(f, get_map_func(a))
4100  True
4101  >>> get_map_func(a)
4102  f
4103  >>> get_map_func(a)(0)
4104  f(0)
4105  """
4106  if __debug__:
4107  _z3_assert(is_map(a), "Z3 array map expression expected.")
4108  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4109 
4110 def ArraySort(d, r):
4111  """Return the Z3 array sort with the given domain and range sorts.
4112 
4113  >>> A = ArraySort(IntSort(), BoolSort())
4114  >>> A
4115  Array(Int, Bool)
4116  >>> A.domain()
4117  Int
4118  >>> A.range()
4119  Bool
4120  >>> AA = ArraySort(IntSort(), A)
4121  >>> AA
4122  Array(Int, Array(Int, Bool))
4123  """
4124  if __debug__:
4125  _z3_assert(is_sort(d), "Z3 sort expected")
4126  _z3_assert(is_sort(r), "Z3 sort expected")
4127  _z3_assert(d.ctx == r.ctx, "Context mismatch")
4128  ctx = d.ctx
4129  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4130 
4131 def Array(name, dom, rng):
4132  """Return an array constant named `name` with the given domain and range sorts.
4133 
4134  >>> a = Array('a', IntSort(), IntSort())
4135  >>> a.sort()
4136  Array(Int, Int)
4137  >>> a[0]
4138  a[0]
4139  """
4140  s = ArraySort(dom, rng)
4141  ctx = s.ctx
4142  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4143 
4144 def Update(a, i, v):
4145  """Return a Z3 store array expression.
4146 
4147  >>> a = Array('a', IntSort(), IntSort())
4148  >>> i, v = Ints('i v')
4149  >>> s = Update(a, i, v)
4150  >>> s.sort()
4151  Array(Int, Int)
4152  >>> prove(s[i] == v)
4153  proved
4154  >>> j = Int('j')
4155  >>> prove(Implies(i != j, s[j] == a[j]))
4156  proved
4157  """
4158  if __debug__:
4159  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4160  i = a.domain().cast(i)
4161  v = a.range().cast(v)
4162  ctx = a.ctx
4163  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4164 
4165 def Default(a):
4166  """ Return a default value for array expression.
4167  >>> b = K(IntSort(), 1)
4168  >>> prove(Default(b) == 1)
4169  proved
4170  """
4171  if __debug__:
4172  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4173  return a.default()
4174 
4175 
4176 def Store(a, i, v):
4177  """Return a Z3 store array expression.
4178 
4179  >>> a = Array('a', IntSort(), IntSort())
4180  >>> i, v = Ints('i v')
4181  >>> s = Store(a, i, v)
4182  >>> s.sort()
4183  Array(Int, Int)
4184  >>> prove(s[i] == v)
4185  proved
4186  >>> j = Int('j')
4187  >>> prove(Implies(i != j, s[j] == a[j]))
4188  proved
4189  """
4190  return Update(a, i, v)
4191 
4192 def Select(a, i):
4193  """Return a Z3 select array expression.
4194 
4195  >>> a = Array('a', IntSort(), IntSort())
4196  >>> i = Int('i')
4197  >>> Select(a, i)
4198  a[i]
4199  >>> eq(Select(a, i), a[i])
4200  True
4201  """
4202  if __debug__:
4203  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4204  return a[i]
4205 
4206 
4207 def Map(f, *args):
4208  """Return a Z3 map array expression.
4209 
4210  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4211  >>> a1 = Array('a1', IntSort(), IntSort())
4212  >>> a2 = Array('a2', IntSort(), IntSort())
4213  >>> b = Map(f, a1, a2)
4214  >>> b
4215  Map(f, a1, a2)
4216  >>> prove(b[0] == f(a1[0], a2[0]))
4217  proved
4218  """
4219  args = _get_args(args)
4220  if __debug__:
4221  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4222  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4223  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4224  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4225  _args, sz = _to_ast_array(args)
4226  ctx = f.ctx
4227  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4228 
4229 def K(dom, v):
4230  """Return a Z3 constant array expression.
4231 
4232  >>> a = K(IntSort(), 10)
4233  >>> a
4234  K(Int, 10)
4235  >>> a.sort()
4236  Array(Int, Int)
4237  >>> i = Int('i')
4238  >>> a[i]
4239  K(Int, 10)[i]
4240  >>> simplify(a[i])
4241  10
4242  """
4243  if __debug__:
4244  _z3_assert(is_sort(dom), "Z3 sort expected")
4245  ctx = dom.ctx
4246  if not is_expr(v):
4247  v = _py2expr(v, ctx)
4248  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4249 
4250 def Ext(a, b):
4251  """Return extensionality index for arrays.
4252  """
4253  if __debug__:
4254  _z3_assert(is_array(a) and is_array(b))
4255  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
4256 
4257 def is_select(a):
4258  """Return `True` if `a` is a Z3 array select application.
4259 
4260  >>> a = Array('a', IntSort(), IntSort())
4261  >>> is_select(a)
4262  False
4263  >>> i = Int('i')
4264  >>> is_select(a[i])
4265  True
4266  """
4267  return is_app_of(a, Z3_OP_SELECT)
4268 
4269 def is_store(a):
4270  """Return `True` if `a` is a Z3 array store application.
4271 
4272  >>> a = Array('a', IntSort(), IntSort())
4273  >>> is_store(a)
4274  False
4275  >>> is_store(Store(a, 0, 1))
4276  True
4277  """
4278  return is_app_of(a, Z3_OP_STORE)
4279 
4280 #########################################
4281 #
4282 # Datatypes
4283 #
4284 #########################################
4285 
4286 def _valid_accessor(acc):
4287  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4288  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4289 
4290 class Datatype:
4291  """Helper class for declaring Z3 datatypes.
4292 
4293  >>> List = Datatype('List')
4294  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4295  >>> List.declare('nil')
4296  >>> List = List.create()
4297  >>> # List is now a Z3 declaration
4298  >>> List.nil
4299  nil
4300  >>> List.cons(10, List.nil)
4301  cons(10, nil)
4302  >>> List.cons(10, List.nil).sort()
4303  List
4304  >>> cons = List.cons
4305  >>> nil = List.nil
4306  >>> car = List.car
4307  >>> cdr = List.cdr
4308  >>> n = cons(1, cons(0, nil))
4309  >>> n
4310  cons(1, cons(0, nil))
4311  >>> simplify(cdr(n))
4312  cons(0, nil)
4313  >>> simplify(car(n))
4314  1
4315  """
4316  def __init__(self, name, ctx=None):
4317  self.ctx = _get_ctx(ctx)
4318  self.name = name
4319  self.constructors = []
4320 
4321  def declare_core(self, name, rec_name, *args):
4322  if __debug__:
4323  _z3_assert(isinstance(name, str), "String expected")
4324  _z3_assert(isinstance(rec_name, str), "String expected")
4325  _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)")
4326  self.constructors.append((name, rec_name, args))
4327 
4328  def declare(self, name, *args):
4329  """Declare constructor named `name` with the given accessors `args`.
4330  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.
4331 
4332  In the followin example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4333  declares the constructor named `cons` that builds a new List using an integer and a List.
4334  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4335  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4336  the actual datatype in Z3.
4337 
4338  >>> List = Datatype('List')
4339  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4340  >>> List.declare('nil')
4341  >>> List = List.create()
4342  """
4343  if __debug__:
4344  _z3_assert(isinstance(name, str), "String expected")
4345  _z3_assert(name != "", "Constructor name cannot be empty")
4346  return self.declare_core(name, "is_" + name, *args)
4347 
4348  def __repr__(self):
4349  return "Datatype(%s, %s)" % (self.name, self.constructors)
4350 
4351  def create(self):
4352  """Create a Z3 datatype based on the constructors declared using the mehtod `declare()`.
4353 
4354  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4355 
4356  >>> List = Datatype('List')
4357  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4358  >>> List.declare('nil')
4359  >>> List = List.create()
4360  >>> List.nil
4361  nil
4362  >>> List.cons(10, List.nil)
4363  cons(10, nil)
4364  """
4365  return CreateDatatypes([self])[0]
4366 
4367 class ScopedConstructor:
4368  """Auxiliary object used to create Z3 datatypes."""
4369  def __init__(self, c, ctx):
4370  self.c = c
4371  self.ctx = ctx
4372  def __del__(self):
4373  if self.ctx.ref() is not None:
4374  Z3_del_constructor(self.ctx.ref(), self.c)
4375 
4376 class ScopedConstructorList:
4377  """Auxiliary object used to create Z3 datatypes."""
4378  def __init__(self, c, ctx):
4379  self.c = c
4380  self.ctx = ctx
4381  def __del__(self):
4382  if self.ctx.ref() is not None:
4383  Z3_del_constructor_list(self.ctx.ref(), self.c)
4384 
4385 def CreateDatatypes(*ds):
4386  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4387 
4388  In the following example we define a Tree-List using two mutually recursive datatypes.
4389 
4390  >>> TreeList = Datatype('TreeList')
4391  >>> Tree = Datatype('Tree')
4392  >>> # Tree has two constructors: leaf and node
4393  >>> Tree.declare('leaf', ('val', IntSort()))
4394  >>> # a node contains a list of trees
4395  >>> Tree.declare('node', ('children', TreeList))
4396  >>> TreeList.declare('nil')
4397  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4398  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4399  >>> Tree.val(Tree.leaf(10))
4400  val(leaf(10))
4401  >>> simplify(Tree.val(Tree.leaf(10)))
4402  10
4403  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4404  >>> n1
4405  node(cons(leaf(10), cons(leaf(20), nil)))
4406  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4407  >>> simplify(n2 == n1)
4408  False
4409  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4410  True
4411  """
4412  ds = _get_args(ds)
4413  if __debug__:
4414  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4415  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4416  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4417  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4418  ctx = ds[0].ctx
4419  num = len(ds)
4420  names = (Symbol * num)()
4421  out = (Sort * num)()
4422  clists = (ConstructorList * num)()
4423  to_delete = []
4424  for i in range(num):
4425  d = ds[i]
4426  names[i] = to_symbol(d.name, ctx)
4427  num_cs = len(d.constructors)
4428  cs = (Constructor * num_cs)()
4429  for j in range(num_cs):
4430  c = d.constructors[j]
4431  cname = to_symbol(c[0], ctx)
4432  rname = to_symbol(c[1], ctx)
4433  fs = c[2]
4434  num_fs = len(fs)
4435  fnames = (Symbol * num_fs)()
4436  sorts = (Sort * num_fs)()
4437  refs = (ctypes.c_uint * num_fs)()
4438  for k in range(num_fs):
4439  fname = fs[k][0]
4440  ftype = fs[k][1]
4441  fnames[k] = to_symbol(fname, ctx)
4442  if isinstance(ftype, Datatype):
4443  if __debug__:
4444  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4445  sorts[k] = None
4446  refs[k] = ds.index(ftype)
4447  else:
4448  if __debug__:
4449  _z3_assert(is_sort(ftype), "Z3 sort expected")
4450  sorts[k] = ftype.ast
4451  refs[k] = 0
4452  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4453  to_delete.append(ScopedConstructor(cs[j], ctx))
4454  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4455  to_delete.append(ScopedConstructorList(clists[i], ctx))
4456  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4457  result = []
4458  ## Create a field for every constructor, recognizer and accessor
4459  for i in range(num):
4460  dref = DatatypeSortRef(out[i], ctx)
4461  num_cs = dref.num_constructors()
4462  for j in range(num_cs):
4463  cref = dref.constructor(j)
4464  cref_name = cref.name()
4465  cref_arity = cref.arity()
4466  if cref.arity() == 0:
4467  cref = cref()
4468  setattr(dref, cref_name, cref)
4469  rref = dref.recognizer(j)
4470  setattr(dref, rref.name(), rref)
4471  for k in range(cref_arity):
4472  aref = dref.accessor(j, k)
4473  setattr(dref, aref.name(), aref)
4474  result.append(dref)
4475  return tuple(result)
4476 
4477 class DatatypeSortRef(SortRef):
4478  """Datatype sorts."""
4479  def num_constructors(self):
4480  """Return the number of constructors in the given Z3 datatype.
4481 
4482  >>> List = Datatype('List')
4483  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4484  >>> List.declare('nil')
4485  >>> List = List.create()
4486  >>> # List is now a Z3 declaration
4487  >>> List.num_constructors()
4488  2
4489  """
4490  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4491 
4492  def constructor(self, idx):
4493  """Return a constructor of the datatype `self`.
4494 
4495  >>> List = Datatype('List')
4496  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4497  >>> List.declare('nil')
4498  >>> List = List.create()
4499  >>> # List is now a Z3 declaration
4500  >>> List.num_constructors()
4501  2
4502  >>> List.constructor(0)
4503  cons
4504  >>> List.constructor(1)
4505  nil
4506  """
4507  if __debug__:
4508  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4509  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4510 
4511  def recognizer(self, idx):
4512  """In Z3, each constructor has an associated recognizer predicate.
4513 
4514  If the constructor is named `name`, then the recognizer `is_name`.
4515 
4516  >>> List = Datatype('List')
4517  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4518  >>> List.declare('nil')
4519  >>> List = List.create()
4520  >>> # List is now a Z3 declaration
4521  >>> List.num_constructors()
4522  2
4523  >>> List.recognizer(0)
4524  is_cons
4525  >>> List.recognizer(1)
4526  is_nil
4527  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4528  False
4529  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4530  True
4531  >>> l = Const('l', List)
4532  >>> simplify(List.is_cons(l))
4533  is_cons(l)
4534  """
4535  if __debug__:
4536  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4537  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4538 
4539  def accessor(self, i, j):
4540  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4541 
4542  >>> List = Datatype('List')
4543  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4544  >>> List.declare('nil')
4545  >>> List = List.create()
4546  >>> List.num_constructors()
4547  2
4548  >>> List.constructor(0)
4549  cons
4550  >>> num_accs = List.constructor(0).arity()
4551  >>> num_accs
4552  2
4553  >>> List.accessor(0, 0)
4554  car
4555  >>> List.accessor(0, 1)
4556  cdr
4557  >>> List.constructor(1)
4558  nil
4559  >>> num_accs = List.constructor(1).arity()
4560  >>> num_accs
4561  0
4562  """
4563  if __debug__:
4564  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4565  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4566  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4567 
4568 class DatatypeRef(ExprRef):
4569  """Datatype expressions."""
4570  def sort(self):
4571  """Return the datatype sort of the datatype expression `self`."""
4572  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4573 
4574 def EnumSort(name, values, ctx=None):
4575  """Return a new enumeration sort named `name` containing the given values.
4576 
4577  The result is a pair (sort, list of constants).
4578  Example:
4579  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4580  """
4581  if __debug__:
4582  _z3_assert(isinstance(name, str), "Name must be a string")
4583  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4584  _z3_assert(len(values) > 0, "At least one value expected")
4585  ctx = _get_ctx(ctx)
4586  num = len(values)
4587  _val_names = (Symbol * num)()
4588  for i in range(num):
4589  _val_names[i] = to_symbol(values[i])
4590  _values = (FuncDecl * num)()
4591  _testers = (FuncDecl * num)()
4592  name = to_symbol(name)
4593  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4594  V = []
4595  for i in range(num):
4596  V.append(FuncDeclRef(_values[i], ctx))
4597  V = [a() for a in V]
4598  return S, V
4599 
4600 #########################################
4601 #
4602 # Parameter Sets
4603 #
4604 #########################################
4605 
4606 class ParamsRef:
4607  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4608 
4609  Consider using the function `args2params` to create instances of this object.
4610  """
4611  def __init__(self, ctx=None):
4612  self.ctx = _get_ctx(ctx)
4613  self.params = Z3_mk_params(self.ctx.ref())
4614  Z3_params_inc_ref(self.ctx.ref(), self.params)
4615 
4616  def __del__(self):
4617  if self.ctx.ref() is not None:
4618  Z3_params_dec_ref(self.ctx.ref(), self.params)
4619 
4620  def set(self, name, val):
4621  """Set parameter name with value val."""
4622  if __debug__:
4623  _z3_assert(isinstance(name, str), "parameter name must be a string")
4624  name_sym = to_symbol(name, self.ctx)
4625  if isinstance(val, bool):
4626  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4627  elif _is_int(val):
4628  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4629  elif isinstance(val, float):
4630  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4631  elif isinstance(val, str):
4632  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4633  else:
4634  if __debug__:
4635  _z3_assert(False, "invalid parameter value")
4636 
4637  def __repr__(self):
4638  return Z3_params_to_string(self.ctx.ref(), self.params)
4639 
4640  def validate(self, ds):
4641  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
4642  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
4643 
4644 def args2params(arguments, keywords, ctx=None):
4645  """Convert python arguments into a Z3_params object.
4646  A ':' is added to the keywords, and '_' is replaced with '-'
4647 
4648  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
4649  (params model true relevancy 2 elim_and true)
4650  """
4651  if __debug__:
4652  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
4653  prev = None
4654  r = ParamsRef(ctx)
4655  for a in arguments:
4656  if prev is None:
4657  prev = a
4658  else:
4659  r.set(prev, a)
4660  prev = None
4661  for k in keywords:
4662  v = keywords[k]
4663  r.set(k, v)
4664  return r
4665 
4666 class ParamDescrsRef:
4667  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
4668  """
4669  def __init__(self, descr, ctx=None):
4670  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
4671  self.ctx = _get_ctx(ctx)
4672  self.descr = descr
4673  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
4674 
4675  def __del__(self):
4676  if self.ctx.ref() is not None:
4677  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
4678 
4679  def size(self):
4680  """Return the size of in the parameter description `self`.
4681  """
4682  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
4683 
4684  def __len__(self):
4685  """Return the size of in the parameter description `self`.
4686  """
4687  return self.size()
4688 
4689  def get_name(self, i):
4690  """Return the i-th parameter name in the parameter description `self`.
4691  """
4692  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
4693 
4694  def get_kind(self, n):
4695  """Return the kind of the parameter named `n`.
4696  """
4697  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4698 
4699  def get_documentation(self, n):
4700  """Return the documentation string of the parameter named `n`.
4701  """
4702  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4703 
4704  def __getitem__(self, arg):
4705  if _is_int(arg):
4706  return self.get_name(arg)
4707  else:
4708  return self.get_kind(arg)
4709 
4710  def __repr__(self):
4711  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
4712 
4713 #########################################
4714 #
4715 # Goals
4716 #
4717 #########################################
4718 
4719 class Goal(Z3PPObject):
4720  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
4721 
4722  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
4723  A goal has a solution if one of its subgoals has a solution.
4724  A goal is unsatisfiable if all subgoals are unsatisfiable.
4725  """
4726 
4727  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
4728  if __debug__:
4729  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
4730  self.ctx = _get_ctx(ctx)
4731  self.goal = goal
4732  if self.goal is None:
4733  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
4734  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
4735 
4736  def __del__(self):
4737  if self.goal is not None and self.ctx.ref() is not None:
4738  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
4739 
4740  def depth(self):
4741  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
4742 
4743  >>> x, y = Ints('x y')
4744  >>> g = Goal()
4745  >>> g.add(x == 0, y >= x + 1)
4746  >>> g.depth()
4747  0
4748  >>> r = Then('simplify', 'solve-eqs')(g)
4749  >>> # r has 1 subgoal
4750  >>> len(r)
4751  1
4752  >>> r[0].depth()
4753  2
4754  """
4755  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
4756 
4757  def inconsistent(self):
4758  """Return `True` if `self` contains the `False` constraints.
4759 
4760  >>> x, y = Ints('x y')
4761  >>> g = Goal()
4762  >>> g.inconsistent()
4763  False
4764  >>> g.add(x == 0, x == 1)
4765  >>> g
4766  [x == 0, x == 1]
4767  >>> g.inconsistent()
4768  False
4769  >>> g2 = Tactic('propagate-values')(g)[0]
4770  >>> g2.inconsistent()
4771  True
4772  """
4773  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
4774 
4775  def prec(self):
4776  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
4777 
4778  >>> g = Goal()
4779  >>> g.prec() == Z3_GOAL_PRECISE
4780  True
4781  >>> x, y = Ints('x y')
4782  >>> g.add(x == y + 1)
4783  >>> g.prec() == Z3_GOAL_PRECISE
4784  True
4785  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
4786  >>> g2 = t(g)[0]
4787  >>> g2
4788  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
4789  >>> g2.prec() == Z3_GOAL_PRECISE
4790  False
4791  >>> g2.prec() == Z3_GOAL_UNDER
4792  True
4793  """
4794  return Z3_goal_precision(self.ctx.ref(), self.goal)
4795 
4796  def precision(self):
4797  """Alias for `prec()`.
4798 
4799  >>> g = Goal()
4800  >>> g.precision() == Z3_GOAL_PRECISE
4801  True
4802  """
4803  return self.prec()
4804 
4805  def size(self):
4806  """Return the number of constraints in the goal `self`.
4807 
4808  >>> g = Goal()
4809  >>> g.size()
4810  0
4811  >>> x, y = Ints('x y')
4812  >>> g.add(x == 0, y > x)
4813  >>> g.size()
4814  2
4815  """
4816  return int(Z3_goal_size(self.ctx.ref(), self.goal))
4817 
4818  def __len__(self):
4819  """Return the number of constraints in the goal `self`.
4820 
4821  >>> g = Goal()
4822  >>> len(g)
4823  0
4824  >>> x, y = Ints('x y')
4825  >>> g.add(x == 0, y > x)
4826  >>> len(g)
4827  2
4828  """
4829  return self.size()
4830 
4831  def get(self, i):
4832  """Return a constraint in the goal `self`.
4833 
4834  >>> g = Goal()
4835  >>> x, y = Ints('x y')
4836  >>> g.add(x == 0, y > x)
4837  >>> g.get(0)
4838  x == 0
4839  >>> g.get(1)
4840  y > x
4841  """
4842  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
4843 
4844  def __getitem__(self, arg):
4845  """Return a constraint in the goal `self`.
4846 
4847  >>> g = Goal()
4848  >>> x, y = Ints('x y')
4849  >>> g.add(x == 0, y > x)
4850  >>> g[0]
4851  x == 0
4852  >>> g[1]
4853  y > x
4854  """
4855  if arg >= len(self):
4856  raise IndexError
4857  return self.get(arg)
4858 
4859  def assert_exprs(self, *args):
4860  """Assert constraints into the goal.
4861 
4862  >>> x = Int('x')
4863  >>> g = Goal()
4864  >>> g.assert_exprs(x > 0, x < 2)
4865  >>> g
4866  [x > 0, x < 2]
4867  """
4868  args = _get_args(args)
4869  s = BoolSort(self.ctx)
4870  for arg in args:
4871  arg = s.cast(arg)
4872  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
4873 
4874  def append(self, *args):
4875  """Add constraints.
4876 
4877  >>> x = Int('x')
4878  >>> g = Goal()
4879  >>> g.append(x > 0, x < 2)
4880  >>> g
4881  [x > 0, x < 2]
4882  """
4883  self.assert_exprs(*args)
4884 
4885  def insert(self, *args):
4886  """Add constraints.
4887 
4888  >>> x = Int('x')
4889  >>> g = Goal()
4890  >>> g.insert(x > 0, x < 2)
4891  >>> g
4892  [x > 0, x < 2]
4893  """
4894  self.assert_exprs(*args)
4895 
4896  def add(self, *args):
4897  """Add constraints.
4898 
4899  >>> x = Int('x')
4900  >>> g = Goal()
4901  >>> g.add(x > 0, x < 2)
4902  >>> g
4903  [x > 0, x < 2]
4904  """
4905  self.assert_exprs(*args)
4906 
4907  def __repr__(self):
4908  return obj_to_string(self)
4909 
4910  def sexpr(self):
4911  """Return a textual representation of the s-expression representing the goal."""
4912  return Z3_goal_to_string(self.ctx.ref(), self.goal)
4913 
4914  def translate(self, target):
4915  """Copy goal `self` to context `target`.
4916 
4917  >>> x = Int('x')
4918  >>> g = Goal()
4919  >>> g.add(x > 10)
4920  >>> g
4921  [x > 10]
4922  >>> c2 = Context()
4923  >>> g2 = g.translate(c2)
4924  >>> g2
4925  [x > 10]
4926  >>> g.ctx == main_ctx()
4927  True
4928  >>> g2.ctx == c2
4929  True
4930  >>> g2.ctx == main_ctx()
4931  False
4932  """
4933  if __debug__:
4934  _z3_assert(isinstance(target, Context), "target must be a context")
4935  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
4936 
4937  def simplify(self, *arguments, **keywords):
4938  """Return a new simplified goal.
4939 
4940  This method is essentially invoking the simplify tactic.
4941 
4942  >>> g = Goal()
4943  >>> x = Int('x')
4944  >>> g.add(x + 1 >= 2)
4945  >>> g
4946  [x + 1 >= 2]
4947  >>> g2 = g.simplify()
4948  >>> g2
4949  [x >= 1]
4950  >>> # g was not modified
4951  >>> g
4952  [x + 1 >= 2]
4953  """
4954  t = Tactic('simplify')
4955  return t.apply(self, *arguments, **keywords)[0]
4956 
4957  def as_expr(self):
4958  """Return goal `self` as a single Z3 expression.
4959 
4960  >>> x = Int('x')
4961  >>> g = Goal()
4962  >>> g.as_expr()
4963  True
4964  >>> g.add(x > 1)
4965  >>> g.as_expr()
4966  x > 1
4967  >>> g.add(x < 10)
4968  >>> g.as_expr()
4969  And(x > 1, x < 10)
4970  """
4971  sz = len(self)
4972  if sz == 0:
4973  return BoolVal(True, self.ctx)
4974  elif sz == 1:
4975  return self.get(0)
4976  else:
4977  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
4978 
4979 #########################################
4980 #
4981 # AST Vector
4982 #
4983 #########################################
4984 class AstVector(Z3PPObject):
4985  """A collection (vector) of ASTs."""
4986 
4987  def __init__(self, v=None, ctx=None):
4988  self.vector = None
4989  if v is None:
4990  self.ctx = _get_ctx(ctx)
4991  self.vector = Z3_mk_ast_vector(self.ctx.ref())
4992  else:
4993  self.vector = v
4994  assert ctx is not None
4995  self.ctx = ctx
4996  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
4997 
4998  def __del__(self):
4999  if self.vector is not None and self.ctx.ref() is not None:
5000  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5001 
5002  def __len__(self):
5003  """Return the size of the vector `self`.
5004 
5005  >>> A = AstVector()
5006  >>> len(A)
5007  0
5008  >>> A.push(Int('x'))
5009  >>> A.push(Int('x'))
5010  >>> len(A)
5011  2
5012  """
5013  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5014 
5015  def __getitem__(self, i):
5016  """Return the AST at position `i`.
5017 
5018  >>> A = AstVector()
5019  >>> A.push(Int('x') + 1)
5020  >>> A.push(Int('y'))
5021  >>> A[0]
5022  x + 1
5023  >>> A[1]
5024  y
5025  """
5026  if i >= self.__len__():
5027  raise IndexError
5028  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5029 
5030  def __setitem__(self, i, v):
5031  """Update AST at position `i`.
5032 
5033  >>> A = AstVector()
5034  >>> A.push(Int('x') + 1)
5035  >>> A.push(Int('y'))
5036  >>> A[0]
5037  x + 1
5038  >>> A[0] = Int('x')
5039  >>> A[0]
5040  x
5041  """
5042  if i >= self.__len__():
5043  raise IndexError
5044  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5045 
5046  def push(self, v):
5047  """Add `v` in the end of the vector.
5048 
5049  >>> A = AstVector()
5050  >>> len(A)
5051  0
5052  >>> A.push(Int('x'))
5053  >>> len(A)
5054  1
5055  """
5056  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5057 
5058  def resize(self, sz):
5059  """Resize the vector to `sz` elements.
5060 
5061  >>> A = AstVector()
5062  >>> A.resize(10)
5063  >>> len(A)
5064  10
5065  >>> for i in range(10): A[i] = Int('x')
5066  >>> A[5]
5067  x
5068  """
5069  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5070 
5071  def __contains__(self, item):
5072  """Return `True` if the vector contains `item`.
5073 
5074  >>> x = Int('x')
5075  >>> A = AstVector()
5076  >>> x in A
5077  False
5078  >>> A.push(x)
5079  >>> x in A
5080  True
5081  >>> (x+1) in A
5082  False
5083  >>> A.push(x+1)
5084  >>> (x+1) in A
5085  True
5086  >>> A
5087  [x, x + 1]
5088  """
5089  for elem in self:
5090  if elem.eq(item):
5091  return True
5092  return False
5093 
5094  def translate(self, other_ctx):
5095  """Copy vector `self` to context `other_ctx`.
5096 
5097  >>> x = Int('x')
5098  >>> A = AstVector()
5099  >>> A.push(x)
5100  >>> c2 = Context()
5101  >>> B = A.translate(c2)
5102  >>> B
5103  [x]
5104  """
5105  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5106 
5107  def __repr__(self):
5108  return obj_to_string(self)
5109 
5110  def sexpr(self):
5111  """Return a textual representation of the s-expression representing the vector."""
5112  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5113 
5114 #########################################
5115 #
5116 # AST Map
5117 #
5118 #########################################
5119 class AstMap:
5120  """A mapping from ASTs to ASTs."""
5121 
5122  def __init__(self, m=None, ctx=None):
5123  self.map = None
5124  if m is None:
5125  self.ctx = _get_ctx(ctx)
5126  self.map = Z3_mk_ast_map(self.ctx.ref())
5127  else:
5128  self.map = m
5129  assert ctx is not None
5130  self.ctx = ctx
5131  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5132 
5133  def __del__(self):
5134  if self.map is not None and self.ctx.ref() is not None:
5135  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5136 
5137  def __len__(self):
5138  """Return the size of the map.
5139 
5140  >>> M = AstMap()
5141  >>> len(M)
5142  0
5143  >>> x = Int('x')
5144  >>> M[x] = IntVal(1)
5145  >>> len(M)
5146  1
5147  """
5148  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5149 
5150  def __contains__(self, key):
5151  """Return `True` if the map contains key `key`.
5152 
5153  >>> M = AstMap()
5154  >>> x = Int('x')
5155  >>> M[x] = x + 1
5156  >>> x in M
5157  True
5158  >>> x+1 in M
5159  False
5160  """
5161  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5162 
5163  def __getitem__(self, key):
5164  """Retrieve the value associated with key `key`.
5165 
5166  >>> M = AstMap()
5167  >>> x = Int('x')
5168  >>> M[x] = x + 1
5169  >>> M[x]
5170  x + 1
5171  """
5172  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5173 
5174  def __setitem__(self, k, v):
5175  """Add/Update key `k` with value `v`.
5176 
5177  >>> M = AstMap()
5178  >>> x = Int('x')
5179  >>> M[x] = x + 1
5180  >>> len(M)
5181  1
5182  >>> M[x]
5183  x + 1
5184  >>> M[x] = IntVal(1)
5185  >>> M[x]
5186  1
5187  """
5188  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5189 
5190  def __repr__(self):
5191  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5192 
5193  def erase(self, k):
5194  """Remove the entry associated with key `k`.
5195 
5196  >>> M = AstMap()
5197  >>> x = Int('x')
5198  >>> M[x] = x + 1
5199  >>> len(M)
5200  1
5201  >>> M.erase(x)
5202  >>> len(M)
5203  0
5204  """
5205  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5206 
5207  def reset(self):
5208  """Remove all entries from the map.
5209 
5210  >>> M = AstMap()
5211  >>> x = Int('x')
5212  >>> M[x] = x + 1
5213  >>> M[x+x] = IntVal(1)
5214  >>> len(M)
5215  2
5216  >>> M.reset()
5217  >>> len(M)
5218  0
5219  """
5220  Z3_ast_map_reset(self.ctx.ref(), self.map)
5221 
5222  def keys(self):
5223  """Return an AstVector containing all keys in the map.
5224 
5225  >>> M = AstMap()
5226  >>> x = Int('x')
5227  >>> M[x] = x + 1
5228  >>> M[x+x] = IntVal(1)
5229  >>> M.keys()
5230  [x, x + x]
5231  """
5232  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5233 
5234 #########################################
5235 #
5236 # Model
5237 #
5238 #########################################
5239 
5240 class FuncEntry:
5241  """Store the value of the interpretation of a function in a particular point."""
5242 
5243  def __init__(self, entry, ctx):
5244  self.entry = entry
5245  self.ctx = ctx
5246  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5247 
5248  def __del__(self):
5249  if self.ctx.ref() is not None:
5250  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5251 
5252  def num_args(self):
5253  """Return the number of arguments in the given entry.
5254 
5255  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5256  >>> s = Solver()
5257  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5258  >>> s.check()
5259  sat
5260  >>> m = s.model()
5261  >>> f_i = m[f]
5262  >>> f_i.num_entries()
5263  3
5264  >>> e = f_i.entry(0)
5265  >>> e.num_args()
5266  2
5267  """
5268  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5269 
5270  def arg_value(self, idx):
5271  """Return the value of argument `idx`.
5272 
5273  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5274  >>> s = Solver()
5275  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5276  >>> s.check()
5277  sat
5278  >>> m = s.model()
5279  >>> f_i = m[f]
5280  >>> f_i.num_entries()
5281  3
5282  >>> e = f_i.entry(0)
5283  >>> e
5284  [0, 1, 10]
5285  >>> e.num_args()
5286  2
5287  >>> e.arg_value(0)
5288  0
5289  >>> e.arg_value(1)
5290  1
5291  >>> try:
5292  ... e.arg_value(2)
5293  ... except IndexError:
5294  ... print("index error")
5295  index error
5296  """
5297  if idx >= self.num_args():
5298  raise IndexError
5299  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5300 
5301  def value(self):
5302  """Return the value of the function at point `self`.
5303 
5304  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5305  >>> s = Solver()
5306  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5307  >>> s.check()
5308  sat
5309  >>> m = s.model()
5310  >>> f_i = m[f]
5311  >>> f_i.num_entries()
5312  3
5313  >>> e = f_i.entry(0)
5314  >>> e
5315  [0, 1, 10]
5316  >>> e.num_args()
5317  2
5318  >>> e.value()
5319  10
5320  """
5321  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5322 
5323  def as_list(self):
5324  """Return entry `self` as a Python list.
5325  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5326  >>> s = Solver()
5327  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5328  >>> s.check()
5329  sat
5330  >>> m = s.model()
5331  >>> f_i = m[f]
5332  >>> f_i.num_entries()
5333  3
5334  >>> e = f_i.entry(0)
5335  >>> e.as_list()
5336  [0, 1, 10]
5337  """
5338  args = [ self.arg_value(i) for i in range(self.num_args())]
5339  args.append(self.value())
5340  return args
5341 
5342  def __repr__(self):
5343  return repr(self.as_list())
5344 
5345 class FuncInterp(Z3PPObject):
5346  """Stores the interpretation of a function in a Z3 model."""
5347 
5348  def __init__(self, f, ctx):
5349  self.f = f
5350  self.ctx = ctx
5351  if self.f is not None:
5352  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5353 
5354  def __del__(self):
5355  if self.f is not None and self.ctx.ref() is not None:
5356  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5357 
5358  def else_value(self):
5359  """
5360  Return the `else` value for a function interpretation.
5361  Return None if Z3 did not specify the `else` value for
5362  this object.
5363 
5364  >>> f = Function('f', IntSort(), IntSort())
5365  >>> s = Solver()
5366  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5367  >>> s.check()
5368  sat
5369  >>> m = s.model()
5370  >>> m[f]
5371  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5372  >>> m[f].else_value()
5373  1
5374  """
5375  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5376  if r:
5377  return _to_expr_ref(r, self.ctx)
5378  else:
5379  return None
5380 
5381  def num_entries(self):
5382  """Return the number of entries/points in the function interpretation `self`.
5383 
5384  >>> f = Function('f', IntSort(), IntSort())
5385  >>> s = Solver()
5386  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5387  >>> s.check()
5388  sat
5389  >>> m = s.model()
5390  >>> m[f]
5391  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5392  >>> m[f].num_entries()
5393  3
5394  """
5395  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5396 
5397  def arity(self):
5398  """Return the number of arguments for each entry in the function interpretation `self`.
5399 
5400  >>> f = Function('f', IntSort(), IntSort())
5401  >>> s = Solver()
5402  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5403  >>> s.check()
5404  sat
5405  >>> m = s.model()
5406  >>> m[f].arity()
5407  1
5408  """
5409  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5410 
5411  def entry(self, idx):
5412  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5413 
5414  >>> f = Function('f', IntSort(), IntSort())
5415  >>> s = Solver()
5416  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5417  >>> s.check()
5418  sat
5419  >>> m = s.model()
5420  >>> m[f]
5421  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5422  >>> m[f].num_entries()
5423  3
5424  >>> m[f].entry(0)
5425  [0, 1]
5426  >>> m[f].entry(1)
5427  [1, 1]
5428  >>> m[f].entry(2)
5429  [2, 0]
5430  """
5431  if idx >= self.num_entries():
5432  raise IndexError
5433  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5434 
5435  def as_list(self):
5436  """Return the function interpretation as a Python list.
5437  >>> f = Function('f', IntSort(), IntSort())
5438  >>> s = Solver()
5439  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5440  >>> s.check()
5441  sat
5442  >>> m = s.model()
5443  >>> m[f]
5444  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5445  >>> m[f].as_list()
5446  [[0, 1], [1, 1], [2, 0], 1]
5447  """
5448  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5449  r.append(self.else_value())
5450  return r
5451 
5452  def __repr__(self):
5453  return obj_to_string(self)
5454 
5455 class ModelRef(Z3PPObject):
5456  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5457 
5458  def __init__(self, m, ctx):
5459  assert ctx is not None
5460  self.model = m
5461  self.ctx = ctx
5462  Z3_model_inc_ref(self.ctx.ref(), self.model)
5463 
5464  def __del__(self):
5465  if self.ctx.ref() is not None:
5466  Z3_model_dec_ref(self.ctx.ref(), self.model)
5467 
5468  def __repr__(self):
5469  return obj_to_string(self)
5470 
5471  def sexpr(self):
5472  """Return a textual representation of the s-expression representing the model."""
5473  return Z3_model_to_string(self.ctx.ref(), self.model)
5474 
5475  def eval(self, t, model_completion=False):
5476  """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`.
5477 
5478  >>> x = Int('x')
5479  >>> s = Solver()
5480  >>> s.add(x > 0, x < 2)
5481  >>> s.check()
5482  sat
5483  >>> m = s.model()
5484  >>> m.eval(x + 1)
5485  2
5486  >>> m.eval(x == 1)
5487  True
5488  >>> y = Int('y')
5489  >>> m.eval(y + x)
5490  1 + y
5491  >>> m.eval(y)
5492  y
5493  >>> m.eval(y, model_completion=True)
5494  0
5495  >>> # Now, m contains an interpretation for y
5496  >>> m.eval(y + x)
5497  1
5498  """
5499  r = (Ast * 1)()
5500  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5501  return _to_expr_ref(r[0], self.ctx)
5502  raise Z3Exception("failed to evaluate expression in the model")
5503 
5504  def evaluate(self, t, model_completion=False):
5505  """Alias for `eval`.
5506 
5507  >>> x = Int('x')
5508  >>> s = Solver()
5509  >>> s.add(x > 0, x < 2)
5510  >>> s.check()
5511  sat
5512  >>> m = s.model()
5513  >>> m.evaluate(x + 1)
5514  2
5515  >>> m.evaluate(x == 1)
5516  True
5517  >>> y = Int('y')
5518  >>> m.evaluate(y + x)
5519  1 + y
5520  >>> m.evaluate(y)
5521  y
5522  >>> m.evaluate(y, model_completion=True)
5523  0
5524  >>> # Now, m contains an interpretation for y
5525  >>> m.evaluate(y + x)
5526  1
5527  """
5528  return self.eval(t, model_completion)
5529 
5530  def __len__(self):
5531  """Return the number of constant and function declarations in the model `self`.
5532 
5533  >>> f = Function('f', IntSort(), IntSort())
5534  >>> x = Int('x')
5535  >>> s = Solver()
5536  >>> s.add(x > 0, f(x) != x)
5537  >>> s.check()
5538  sat
5539  >>> m = s.model()
5540  >>> len(m)
5541  2
5542  """
5543  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5544 
5545  def get_interp(self, decl):
5546  """Return the interpretation for a given declaration or constant.
5547 
5548  >>> f = Function('f', IntSort(), IntSort())
5549  >>> x = Int('x')
5550  >>> s = Solver()
5551  >>> s.add(x > 0, x < 2, f(x) == 0)
5552  >>> s.check()
5553  sat
5554  >>> m = s.model()
5555  >>> m[x]
5556  1
5557  >>> m[f]
5558  [1 -> 0, else -> 0]
5559  """
5560  if __debug__:
5561  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
5562  if is_const(decl):
5563  decl = decl.decl()
5564  try:
5565  if decl.arity() == 0:
5566  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
5567  if _r.value is None:
5568  return None
5569  r = _to_expr_ref(_r, self.ctx)
5570  if is_as_array(r):
5571  return self.get_interp(get_as_array_func(r))
5572  else:
5573  return r
5574  else:
5575  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
5576  except Z3Exception:
5577  return None
5578 
5579  def num_sorts(self):
5580  """Return the number of unintepreted sorts that contain an interpretation in the model `self`.
5581 
5582  >>> A = DeclareSort('A')
5583  >>> a, b = Consts('a b', A)
5584  >>> s = Solver()
5585  >>> s.add(a != b)
5586  >>> s.check()
5587  sat
5588  >>> m = s.model()
5589  >>> m.num_sorts()
5590  1
5591  """
5592  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
5593 
5594  def get_sort(self, idx):
5595  """Return the unintepreted sort at position `idx` < self.num_sorts().
5596 
5597  >>> A = DeclareSort('A')
5598  >>> B = DeclareSort('B')
5599  >>> a1, a2 = Consts('a1 a2', A)
5600  >>> b1, b2 = Consts('b1 b2', B)
5601  >>> s = Solver()
5602  >>> s.add(a1 != a2, b1 != b2)
5603  >>> s.check()
5604  sat
5605  >>> m = s.model()
5606  >>> m.num_sorts()
5607  2
5608  >>> m.get_sort(0)
5609  A
5610  >>> m.get_sort(1)
5611  B
5612  """
5613  if idx >= self.num_sorts():
5614  raise IndexError
5615  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
5616 
5617  def sorts(self):
5618  """Return all uninterpreted sorts that have an interpretation in the model `self`.
5619 
5620  >>> A = DeclareSort('A')
5621  >>> B = DeclareSort('B')
5622  >>> a1, a2 = Consts('a1 a2', A)
5623  >>> b1, b2 = Consts('b1 b2', B)
5624  >>> s = Solver()
5625  >>> s.add(a1 != a2, b1 != b2)
5626  >>> s.check()
5627  sat
5628  >>> m = s.model()
5629  >>> m.sorts()
5630  [A, B]
5631  """
5632  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
5633 
5634  def get_universe(self, s):
5635  """Return the intepretation for the uninterpreted sort `s` in the model `self`.
5636 
5637  >>> A = DeclareSort('A')
5638  >>> a, b = Consts('a b', A)
5639  >>> s = Solver()
5640  >>> s.add(a != b)
5641  >>> s.check()
5642  sat
5643  >>> m = s.model()
5644  >>> m.get_universe(A)
5645  [A!val!0, A!val!1]
5646  """
5647  if __debug__:
5648  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
5649  try:
5650  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
5651  except Z3Exception:
5652  return None
5653 
5654  def __getitem__(self, idx):
5655  """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 interpreation is returned.
5656 
5657  The elements can be retrieved using position or the actual declaration.
5658 
5659  >>> f = Function('f', IntSort(), IntSort())
5660  >>> x = Int('x')
5661  >>> s = Solver()
5662  >>> s.add(x > 0, x < 2, f(x) == 0)
5663  >>> s.check()
5664  sat
5665  >>> m = s.model()
5666  >>> len(m)
5667  2
5668  >>> m[0]
5669  x
5670  >>> m[1]
5671  f
5672  >>> m[x]
5673  1
5674  >>> m[f]
5675  [1 -> 0, else -> 0]
5676  >>> for d in m: print("%s -> %s" % (d, m[d]))
5677  x -> 1
5678  f -> [1 -> 0, else -> 0]
5679  """
5680  if _is_int(idx):
5681  if idx >= len(self):
5682  raise IndexError
5683  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
5684  if (idx < num_consts):
5685  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
5686  else:
5687  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
5688  if isinstance(idx, FuncDeclRef):
5689  return self.get_interp(idx)
5690  if is_const(idx):
5691  return self.get_interp(idx.decl())
5692  if isinstance(idx, SortRef):
5693  return self.get_universe(idx)
5694  if __debug__:
5695  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
5696  return None
5697 
5698  def decls(self):
5699  """Return a list with all symbols that have an interpreation in the model `self`.
5700  >>> f = Function('f', IntSort(), IntSort())
5701  >>> x = Int('x')
5702  >>> s = Solver()
5703  >>> s.add(x > 0, x < 2, f(x) == 0)
5704  >>> s.check()
5705  sat
5706  >>> m = s.model()
5707  >>> m.decls()
5708  [x, f]
5709  """
5710  r = []
5711  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
5712  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
5713  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
5714  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
5715  return r
5716 
5717 def is_as_array(n):
5718  """Return true if n is a Z3 expression of the form (_ as-array f)."""
5719  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
5720 
5721 def get_as_array_func(n):
5722  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
5723  if __debug__:
5724  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
5725  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
5726 
5727 #########################################
5728 #
5729 # Statistics
5730 #
5731 #########################################
5732 class Statistics:
5733  """Statistics for `Solver.check()`."""
5734 
5735  def __init__(self, stats, ctx):
5736  self.stats = stats
5737  self.ctx = ctx
5738  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
5739 
5740  def __del__(self):
5741  if self.ctx.ref() is not None:
5742  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
5743 
5744  def __repr__(self):
5745  if in_html_mode():
5746  out = io.StringIO()
5747  even = True
5748  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
5749  for k, v in self:
5750  if even:
5751  out.write(u('<tr style="background-color:#CFCFCF">'))
5752  even = False
5753  else:
5754  out.write(u('<tr>'))
5755  even = True
5756  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
5757  out.write(u('</table>'))
5758  return out.getvalue()
5759  else:
5760  return Z3_stats_to_string(self.ctx.ref(), self.stats)
5761 
5762  def __len__(self):
5763  """Return the number of statistical counters.
5764 
5765  >>> x = Int('x')
5766  >>> s = Then('simplify', 'nlsat').solver()
5767  >>> s.add(x > 0)
5768  >>> s.check()
5769  sat
5770  >>> st = s.statistics()
5771  >>> len(st)
5772  6
5773  """
5774  return int(Z3_stats_size(self.ctx.ref(), self.stats))
5775 
5776  def __getitem__(self, idx):
5777  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
5778 
5779  >>> x = Int('x')
5780  >>> s = Then('simplify', 'nlsat').solver()
5781  >>> s.add(x > 0)
5782  >>> s.check()
5783  sat
5784  >>> st = s.statistics()
5785  >>> len(st)
5786  6
5787  >>> st[0]
5788  ('nlsat propagations', 2)
5789  >>> st[1]
5790  ('nlsat stages', 2)
5791  """
5792  if idx >= len(self):
5793  raise IndexError
5794  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5795  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5796  else:
5797  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5798  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
5799 
5800  def keys(self):
5801  """Return the list of statistical counters.
5802 
5803  >>> x = Int('x')
5804  >>> s = Then('simplify', 'nlsat').solver()
5805  >>> s.add(x > 0)
5806  >>> s.check()
5807  sat
5808  >>> st = s.statistics()
5809  """
5810  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
5811 
5812  def get_key_value(self, key):
5813  """Return the value of a particular statistical counter.
5814 
5815  >>> x = Int('x')
5816  >>> s = Then('simplify', 'nlsat').solver()
5817  >>> s.add(x > 0)
5818  >>> s.check()
5819  sat
5820  >>> st = s.statistics()
5821  >>> st.get_key_value('nlsat propagations')
5822  2
5823  """
5824  for idx in range(len(self)):
5825  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
5826  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5827  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5828  else:
5829  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5830  raise Z3Exception("unknown key")
5831 
5832  def __getattr__(self, name):
5833  """Access the value of statistical using attributes.
5834 
5835  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
5836  we should use '_' (e.g., 'nlsat_propagations').
5837 
5838  >>> x = Int('x')
5839  >>> s = Then('simplify', 'nlsat').solver()
5840  >>> s.add(x > 0)
5841  >>> s.check()
5842  sat
5843  >>> st = s.statistics()
5844  >>> st.nlsat_propagations
5845  2
5846  >>> st.nlsat_stages
5847  2
5848  """
5849  key = name.replace('_', ' ')
5850  try:
5851  return self.get_key_value(key)
5852  except Z3Exception:
5853  raise AttributeError
5854 
5855 #########################################
5856 #
5857 # Solver
5858 #
5859 #########################################
5860 class CheckSatResult:
5861  """Represents the result of a satisfiability check: sat, unsat, unknown.
5862 
5863  >>> s = Solver()
5864  >>> s.check()
5865  sat
5866  >>> r = s.check()
5867  >>> isinstance(r, CheckSatResult)
5868  True
5869  """
5870 
5871  def __init__(self, r):
5872  self.r = r
5873 
5874  def __eq__(self, other):
5875  return isinstance(other, CheckSatResult) and self.r == other.r
5876 
5877  def __ne__(self, other):
5878  return not self.__eq__(other)
5879 
5880  def __repr__(self):
5881  if in_html_mode():
5882  if self.r == Z3_L_TRUE:
5883  return "<b>sat</b>"
5884  elif self.r == Z3_L_FALSE:
5885  return "<b>unsat</b>"
5886  else:
5887  return "<b>unknown</b>"
5888  else:
5889  if self.r == Z3_L_TRUE:
5890  return "sat"
5891  elif self.r == Z3_L_FALSE:
5892  return "unsat"
5893  else:
5894  return "unknown"
5895 
5896 sat = CheckSatResult(Z3_L_TRUE)
5897 unsat = CheckSatResult(Z3_L_FALSE)
5898 unknown = CheckSatResult(Z3_L_UNDEF)
5899 
5900 class Solver(Z3PPObject):
5901  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
5902 
5903  def __init__(self, solver=None, ctx=None):
5904  assert solver is None or ctx is not None
5905  self.ctx = _get_ctx(ctx)
5906  self.solver = None
5907  if solver is None:
5908  self.solver = Z3_mk_solver(self.ctx.ref())
5909  else:
5910  self.solver = solver
5911  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
5912 
5913  def __del__(self):
5914  if self.solver is not None and self.ctx.ref() is not None:
5915  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
5916 
5917  def set(self, *args, **keys):
5918  """Set a configuration option. The method `help()` return a string containing all available options.
5919 
5920  >>> s = Solver()
5921  >>> # The option MBQI can be set using three different approaches.
5922  >>> s.set(mbqi=True)
5923  >>> s.set('MBQI', True)
5924  >>> s.set(':mbqi', True)
5925  """
5926  p = args2params(args, keys, self.ctx)
5927  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
5928 
5929  def push(self):
5930  """Create a backtracking point.
5931 
5932  >>> x = Int('x')
5933  >>> s = Solver()
5934  >>> s.add(x > 0)
5935  >>> s
5936  [x > 0]
5937  >>> s.push()
5938  >>> s.add(x < 1)
5939  >>> s
5940  [x > 0, x < 1]
5941  >>> s.check()
5942  unsat
5943  >>> s.pop()
5944  >>> s.check()
5945  sat
5946  >>> s
5947  [x > 0]
5948  """
5949  Z3_solver_push(self.ctx.ref(), self.solver)
5950 
5951  def pop(self, num=1):
5952  """Backtrack \c num backtracking points.
5953 
5954  >>> x = Int('x')
5955  >>> s = Solver()
5956  >>> s.add(x > 0)
5957  >>> s
5958  [x > 0]
5959  >>> s.push()
5960  >>> s.add(x < 1)
5961  >>> s
5962  [x > 0, x < 1]
5963  >>> s.check()
5964  unsat
5965  >>> s.pop()
5966  >>> s.check()
5967  sat
5968  >>> s
5969  [x > 0]
5970  """
5971  Z3_solver_pop(self.ctx.ref(), self.solver, num)
5972 
5973  def reset(self):
5974  """Remove all asserted constraints and backtracking points created using `push()`.
5975 
5976  >>> x = Int('x')
5977  >>> s = Solver()
5978  >>> s.add(x > 0)
5979  >>> s
5980  [x > 0]
5981  >>> s.reset()
5982  >>> s
5983  []
5984  """
5985  Z3_solver_reset(self.ctx.ref(), self.solver)
5986 
5987  def assert_exprs(self, *args):
5988  """Assert constraints into the solver.
5989 
5990  >>> x = Int('x')
5991  >>> s = Solver()
5992  >>> s.assert_exprs(x > 0, x < 2)
5993  >>> s
5994  [x > 0, x < 2]
5995  """
5996  args = _get_args(args)
5997  s = BoolSort(self.ctx)
5998  for arg in args:
5999  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6000  for f in arg:
6001  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6002  else:
6003  arg = s.cast(arg)
6004  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6005 
6006  def add(self, *args):
6007  """Assert constraints into the solver.
6008 
6009  >>> x = Int('x')
6010  >>> s = Solver()
6011  >>> s.add(x > 0, x < 2)
6012  >>> s
6013  [x > 0, x < 2]
6014  """
6015  self.assert_exprs(*args)
6016 
6017  def __iadd__(self, fml):
6018  self.add(fml)
6019  return self
6020 
6021  def append(self, *args):
6022  """Assert constraints into the solver.
6023 
6024  >>> x = Int('x')
6025  >>> s = Solver()
6026  >>> s.append(x > 0, x < 2)
6027  >>> s
6028  [x > 0, x < 2]
6029  """
6030  self.assert_exprs(*args)
6031 
6032  def insert(self, *args):
6033  """Assert constraints into the solver.
6034 
6035  >>> x = Int('x')
6036  >>> s = Solver()
6037  >>> s.insert(x > 0, x < 2)
6038  >>> s
6039  [x > 0, x < 2]
6040  """
6041  self.assert_exprs(*args)
6042 
6043  def assert_and_track(self, a, p):
6044  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6045 
6046  If `p` is a string, it will be automatically converted into a Boolean constant.
6047 
6048  >>> x = Int('x')
6049  >>> p3 = Bool('p3')
6050  >>> s = Solver()
6051  >>> s.set(unsat_core=True)
6052  >>> s.assert_and_track(x > 0, 'p1')
6053  >>> s.assert_and_track(x != 1, 'p2')
6054  >>> s.assert_and_track(x < 0, p3)
6055  >>> print(s.check())
6056  unsat
6057  >>> c = s.unsat_core()
6058  >>> len(c)
6059  2
6060  >>> Bool('p1') in c
6061  True
6062  >>> Bool('p2') in c
6063  False
6064  >>> p3 in c
6065  True
6066  """
6067  if isinstance(p, str):
6068  p = Bool(p, self.ctx)
6069  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6070  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6071  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6072 
6073  def check(self, *assumptions):
6074  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6075 
6076  >>> x = Int('x')
6077  >>> s = Solver()
6078  >>> s.check()
6079  sat
6080  >>> s.add(x > 0, x < 2)
6081  >>> s.check()
6082  sat
6083  >>> s.model()
6084  [x = 1]
6085  >>> s.add(x < 1)
6086  >>> s.check()
6087  unsat
6088  >>> s.reset()
6089  >>> s.add(2**x == 4)
6090  >>> s.check()
6091  unknown
6092  """
6093  assumptions = _get_args(assumptions)
6094  num = len(assumptions)
6095  _assumptions = (Ast * num)()
6096  for i in range(num):
6097  _assumptions[i] = assumptions[i].as_ast()
6098  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6099  return CheckSatResult(r)
6100 
6101  def model(self):
6102  """Return a model for the last `check()`.
6103 
6104  This function raises an exception if
6105  a model is not available (e.g., last `check()` returned unsat).
6106 
6107  >>> s = Solver()
6108  >>> a = Int('a')
6109  >>> s.add(a + 2 == 0)
6110  >>> s.check()
6111  sat
6112  >>> s.model()
6113  [a = -2]
6114  """
6115  try:
6116  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6117  except Z3Exception:
6118  raise Z3Exception("model is not available")
6119 
6120  def unsat_core(self):
6121  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6122 
6123  These are the assumptions Z3 used in the unsatisfiability proof.
6124  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6125  They may be also used to "retract" assumptions. Note that, assumptions are not really
6126  "soft constraints", but they can be used to implement them.
6127 
6128  >>> p1, p2, p3 = Bools('p1 p2 p3')
6129  >>> x, y = Ints('x y')
6130  >>> s = Solver()
6131  >>> s.add(Implies(p1, x > 0))
6132  >>> s.add(Implies(p2, y > x))
6133  >>> s.add(Implies(p2, y < 1))
6134  >>> s.add(Implies(p3, y > -3))
6135  >>> s.check(p1, p2, p3)
6136  unsat
6137  >>> core = s.unsat_core()
6138  >>> len(core)
6139  2
6140  >>> p1 in core
6141  True
6142  >>> p2 in core
6143  True
6144  >>> p3 in core
6145  False
6146  >>> # "Retracting" p2
6147  >>> s.check(p1, p3)
6148  sat
6149  """
6150  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6151 
6152  def consequences(self, assumptions, variables):
6153  """Determine fixed values for the variables based on the solver state and assumptions.
6154  >>> s = Solver()
6155  >>> a, b, c, d = Bools('a b c d')
6156  >>> s.add(Implies(a,b), Implies(b, c))
6157  >>> s.consequences([a],[b,c,d])
6158  (sat, [Implies(a, b), Implies(a, c)])
6159  >>> s.consequences([Not(c),d],[a,b,c,d])
6160  (sat, [Implies(Not(c), Not(c)), Implies(d, d), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6161  """
6162  if isinstance(assumptions, list):
6163  _asms = AstVector(None, self.ctx)
6164  for a in assumptions:
6165  _asms.push(a)
6166  assumptions = _asms
6167  if isinstance(variables, list):
6168  _vars = AstVector(None, self.ctx)
6169  for a in variables:
6170  _vars.push(a)
6171  variables = _vars
6172  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6173  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6174  consequences = AstVector(None, self.ctx)
6175  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6176  sz = len(consequences)
6177  consequences = [ consequences[i] for i in range(sz) ]
6178  return CheckSatResult(r), consequences
6179 
6180  def proof(self):
6181  """Return a proof for the last `check()`. Proof construction must be enabled."""
6182  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6183 
6184  def assertions(self):
6185  """Return an AST vector containing all added constraints.
6186 
6187  >>> s = Solver()
6188  >>> s.assertions()
6189  []
6190  >>> a = Int('a')
6191  >>> s.add(a > 0)
6192  >>> s.add(a < 10)
6193  >>> s.assertions()
6194  [a > 0, a < 10]
6195  """
6196  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6197 
6198  def statistics(self):
6199  """Return statistics for the last `check()`.
6200 
6201  >>> s = SimpleSolver()
6202  >>> x = Int('x')
6203  >>> s.add(x > 0)
6204  >>> s.check()
6205  sat
6206  >>> st = s.statistics()
6207  >>> st.get_key_value('final checks')
6208  1
6209  >>> len(st) > 0
6210  True
6211  >>> st[0] != 0
6212  True
6213  """
6214  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6215 
6216  def reason_unknown(self):
6217  """Return a string describing why the last `check()` returned `unknown`.
6218 
6219  >>> x = Int('x')
6220  >>> s = SimpleSolver()
6221  >>> s.add(2**x == 4)
6222  >>> s.check()
6223  unknown
6224  >>> s.reason_unknown()
6225  '(incomplete (theory arithmetic))'
6226  """
6227  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6228 
6229  def help(self):
6230  """Display a string describing all available options."""
6231  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6232 
6233  def param_descrs(self):
6234  """Return the parameter description set."""
6235  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6236 
6237  def __repr__(self):
6238  """Return a formatted string with all added constraints."""
6239  return obj_to_string(self)
6240 
6241  def translate(self, target):
6242  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6243 
6244  >>> c1 = Context()
6245  >>> c2 = Context()
6246  >>> s1 = Solver(ctx=c1)
6247  >>> s2 = s1.translate(c2)
6248  """
6249  if __debug__:
6250  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6251  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6252  return Solver(solver, target)
6253 
6254  def sexpr(self):
6255  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6256 
6257  >>> x = Int('x')
6258  >>> s = Solver()
6259  >>> s.add(x > 0)
6260  >>> s.add(x < 2)
6261  >>> r = s.sexpr()
6262  """
6263  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6264 
6265  def to_smt2(self):
6266  """return SMTLIB2 formatted benchmark for solver's assertions"""
6267  es = self.assertions()
6268  sz = len(es)
6269  sz1 = sz
6270  if sz1 > 0:
6271  sz1 -= 1
6272  v = (Ast * sz1)()
6273  for i in range(sz1):
6274  v[i] = es[i].as_ast()
6275  if sz > 0:
6276  e = es[sz1].as_ast()
6277  else:
6278  e = BoolVal(True, self.ctx).as_ast()
6279  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6280 
6281 def SolverFor(logic, ctx=None):
6282  """Create a solver customized for the given logic.
6283 
6284  The parameter `logic` is a string. It should be contains
6285  the name of a SMT-LIB logic.
6286  See http://www.smtlib.org/ for the name of all available logics.
6287 
6288  >>> s = SolverFor("QF_LIA")
6289  >>> x = Int('x')
6290  >>> s.add(x > 0)
6291  >>> s.add(x < 2)
6292  >>> s.check()
6293  sat
6294  >>> s.model()
6295  [x = 1]
6296  """
6297  ctx = _get_ctx(ctx)
6298  logic = to_symbol(logic)
6299  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6300 
6301 def SimpleSolver(ctx=None):
6302  """Return a simple general purpose solver with limited amount of preprocessing.
6303 
6304  >>> s = SimpleSolver()
6305  >>> x = Int('x')
6306  >>> s.add(x > 0)
6307  >>> s.check()
6308  sat
6309  """
6310  ctx = _get_ctx(ctx)
6311  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6312 
6313 
6318 
6320  """Fixedpoint API provides methods for solving with recursive predicates"""
6321 
6322  def __init__(self, fixedpoint=None, ctx=None):
6323  assert fixedpoint is None or ctx is not None
6324  self.ctx = _get_ctx(ctx)
6325  self.fixedpoint = None
6326  if fixedpoint is None:
6327  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6328  else:
6329  self.fixedpoint = fixedpoint
6330  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6331  self.vars = []
6332 
6333  def __del__(self):
6334  if self.fixedpoint is not None and self.ctx.ref() is not None:
6335  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6336 
6337  def set(self, *args, **keys):
6338  """Set a configuration option. The method `help()` return a string containing all available options.
6339  """
6340  p = args2params(args, keys, self.ctx)
6341  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6342 
6343  def help(self):
6344  """Display a string describing all available options."""
6345  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6346 
6347  def param_descrs(self):
6348  """Return the parameter description set."""
6349  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6350 
6351  def assert_exprs(self, *args):
6352  """Assert constraints as background axioms for the fixedpoint solver."""
6353  args = _get_args(args)
6354  s = BoolSort(self.ctx)
6355  for arg in args:
6356  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6357  for f in arg:
6358  f = self.abstract(f)
6359  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6360  else:
6361  arg = s.cast(arg)
6362  arg = self.abstract(arg)
6363  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6364 
6365  def add(self, *args):
6366  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6367  self.assert_exprs(*args)
6368 
6369  def __iadd__(self, fml):
6370  self.add(fml)
6371  return self
6372 
6373  def append(self, *args):
6374  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6375  self.assert_exprs(*args)
6376 
6377  def insert(self, *args):
6378  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6379  self.assert_exprs(*args)
6380 
6381  def add_rule(self, head, body = None, name = None):
6382  """Assert rules defining recursive predicates to the fixedpoint solver.
6383  >>> a = Bool('a')
6384  >>> b = Bool('b')
6385  >>> s = Fixedpoint()
6386  >>> s.register_relation(a.decl())
6387  >>> s.register_relation(b.decl())
6388  >>> s.fact(a)
6389  >>> s.rule(b, a)
6390  >>> s.query(b)
6391  sat
6392  """
6393  if name is None:
6394  name = ""
6395  name = to_symbol(name, self.ctx)
6396  if body is None:
6397  head = self.abstract(head)
6398  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6399  else:
6400  body = _get_args(body)
6401  f = self.abstract(Implies(And(body, self.ctx),head))
6402  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6403 
6404  def rule(self, head, body = None, name = None):
6405  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6406  self.add_rule(head, body, name)
6407 
6408  def fact(self, head, name = None):
6409  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6410  self.add_rule(head, None, name)
6411 
6412  def query(self, *query):
6413  """Query the fixedpoint engine whether formula is derivable.
6414  You can also pass an tuple or list of recursive predicates.
6415  """
6416  query = _get_args(query)
6417  sz = len(query)
6418  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6419  _decls = (FuncDecl * sz)()
6420  i = 0
6421  for q in query:
6422  _decls[i] = q.ast
6423  i = i + 1
6424  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6425  else:
6426  if sz == 1:
6427  query = query[0]
6428  else:
6429  query = And(query, self.ctx)
6430  query = self.abstract(query, False)
6431  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6432  return CheckSatResult(r)
6433 
6434  def push(self):
6435  """create a backtracking point for added rules, facts and assertions"""
6436  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6437 
6438  def pop(self):
6439  """restore to previously created backtracking point"""
6440  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
6441 
6442  def update_rule(self, head, body, name):
6443  """update rule"""
6444  if name is None:
6445  name = ""
6446  name = to_symbol(name, self.ctx)
6447  body = _get_args(body)
6448  f = self.abstract(Implies(And(body, self.ctx),head))
6449  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6450 
6451  def get_answer(self):
6452  """Retrieve answer from last query call."""
6453  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
6454  return _to_expr_ref(r, self.ctx)
6455 
6456  def get_num_levels(self, predicate):
6457  """Retrieve number of levels used for predicate in PDR engine"""
6458  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
6459 
6460  def get_cover_delta(self, level, predicate):
6461  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
6462  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
6463  return _to_expr_ref(r, self.ctx)
6464 
6465  def add_cover(self, level, predicate, property):
6466  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
6467  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
6468 
6469  def register_relation(self, *relations):
6470  """Register relation as recursive"""
6471  relations = _get_args(relations)
6472  for f in relations:
6473  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
6474 
6475  def set_predicate_representation(self, f, *representations):
6476  """Control how relation is represented"""
6477  representations = _get_args(representations)
6478  representations = [to_symbol(s) for s in representations]
6479  sz = len(representations)
6480  args = (Symbol * sz)()
6481  for i in range(sz):
6482  args[i] = representations[i]
6483  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
6484 
6485  def parse_string(self, s):
6486  """Parse rules and queries from a string"""
6487  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
6488 
6489  def parse_file(self, f):
6490  """Parse rules and queries from a file"""
6491  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
6492 
6493  def get_rules(self):
6494  """retrieve rules that have been added to fixedpoint context"""
6495  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
6496 
6497  def get_assertions(self):
6498  """retrieve assertions that have been added to fixedpoint context"""
6499  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
6500 
6501  def __repr__(self):
6502  """Return a formatted string with all added rules and constraints."""
6503  return self.sexpr()
6504 
6505  def sexpr(self):
6506  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6507  """
6508  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
6509 
6510  def to_string(self, queries):
6511  """Return a formatted string (in Lisp-like format) with all added constraints.
6512  We say the string is in s-expression format.
6513  Include also queries.
6514  """
6515  args, len = _to_ast_array(queries)
6516  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
6517 
6518  def statistics(self):
6519  """Return statistics for the last `query()`.
6520  """
6521  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
6522 
6523  def reason_unknown(self):
6524  """Return a string describing why the last `query()` returned `unknown`.
6525  """
6526  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
6527 
6528  def declare_var(self, *vars):
6529  """Add variable or several variables.
6530  The added variable or variables will be bound in the rules
6531  and queries
6532  """
6533  vars = _get_args(vars)
6534  for v in vars:
6535  self.vars += [v]
6536 
6537  def abstract(self, fml, is_forall=True):
6538  if self.vars == []:
6539  return fml
6540  if is_forall:
6541  return ForAll(self.vars, fml)
6542  else:
6543  return Exists(self.vars, fml)
6544 
6545 
6546 
6551 
6553  """Finite domain sort."""
6554 
6555  def size(self):
6556  """Return the size of the finite domain sort"""
6557  r = (ctype.c_ulonglong * 1)()
6558  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast(), r):
6559  return r[0]
6560  else:
6561  raise Z3Exception("Failed to retrieve finite domain sort size")
6562 
6563 def FiniteDomainSort(name, sz, ctx=None):
6564  """Create a named finite domain sort of a given size sz"""
6565  if not isinstance(name, Symbol):
6566  name = to_symbol(name)
6567  ctx = _get_ctx(ctx)
6568  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
6569 
6571  """Return True if `s` is a Z3 finite-domain sort.
6572 
6573  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
6574  True
6575  >>> is_finite_domain_sort(IntSort())
6576  False
6577  """
6578  return isinstance(s, FiniteDomainSortRef)
6579 
6580 
6582  """Finite-domain expressions."""
6583 
6584  def sort(self):
6585  """Return the sort of the finite-domain expression `self`."""
6586  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
6587 
6588  def as_string(self):
6589  """Return a Z3 floating point expression as a Python string."""
6590  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
6591 
6593  """Return `True` if `a` is a Z3 finite-domain expression.
6594 
6595  >>> s = FiniteDomainSort('S', 100)
6596  >>> b = Const('b', s)
6597  >>> is_finite_domain(b)
6598  True
6599  >>> is_finite_domain(Int('x'))
6600  False
6601  """
6602  return isinstance(a, FiniteDomainRef)
6603 
6604 
6606  """Integer values."""
6607 
6608  def as_long(self):
6609  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
6610 
6611  >>> s = FiniteDomainSort('S', 100)
6612  >>> v = FiniteDomainVal(3, s)
6613  >>> v
6614  3
6615  >>> v.as_long() + 1
6616  4
6617  """
6618  return int(self.as_string())
6619 
6620  def as_string(self):
6621  """Return a Z3 finite-domain numeral as a Python string.
6622 
6623  >>> s = FiniteDomainSort('S', 100)
6624  >>> v = FiniteDomainVal(42, s)
6625  >>> v.as_string()
6626  '42'
6627  """
6628  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
6629 
6630 
6631 def FiniteDomainVal(val, sort, ctx=None):
6632  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
6633 
6634  >>> s = FiniteDomainSort('S', 256)
6635  >>> FiniteDomainVal(255, s)
6636  255
6637  >>> FiniteDomainVal('100', s)
6638  100
6639  """
6640  if __debug__:
6641  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
6642  ctx = sort.ctx
6643  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
6644 
6646  """Return `True` if `a` is a Z3 finite-domain value.
6647 
6648  >>> s = FiniteDomainSort('S', 100)
6649  >>> b = Const('b', s)
6650  >>> is_finite_domain_value(b)
6651  False
6652  >>> b = FiniteDomainVal(10, s)
6653  >>> b
6654  10
6655  >>> is_finite_domain_value(b)
6656  True
6657  """
6658  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
6659 
6660 
6661 
6666 
6668  def __init__(self, opt, value, is_max):
6669  self._opt = opt
6670  self._value = value
6671  self._is_max = is_max
6672 
6673  def lower(self):
6674  opt = self._opt
6675  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6676 
6677  def upper(self):
6678  opt = self._opt
6679  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6680 
6681  def value(self):
6682  if self._is_max:
6683  return self.upper()
6684  else:
6685  return self.lower()
6686 
6688  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
6689 
6690  def __init__(self, ctx=None):
6691  self.ctx = _get_ctx(ctx)
6692  self.optimize = Z3_mk_optimize(self.ctx.ref())
6693  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
6694 
6695  def __del__(self):
6696  if self.optimize is not None and self.ctx.ref() is not None:
6697  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
6698 
6699  def set(self, *args, **keys):
6700  """Set a configuration option. The method `help()` return a string containing all available options.
6701  """
6702  p = args2params(args, keys, self.ctx)
6703  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
6704 
6705  def help(self):
6706  """Display a string describing all available options."""
6707  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
6708 
6709  def param_descrs(self):
6710  """Return the parameter description set."""
6711  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
6712 
6713  def assert_exprs(self, *args):
6714  """Assert constraints as background axioms for the optimize solver."""
6715  args = _get_args(args)
6716  for arg in args:
6717  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6718  for f in arg:
6719  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
6720  else:
6721  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
6722 
6723  def add(self, *args):
6724  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
6725  self.assert_exprs(*args)
6726 
6727  def __iadd__(self, fml):
6728  self.add(fml)
6729  return self
6730 
6731  def add_soft(self, arg, weight = "1", id = None):
6732  """Add soft constraint with optional weight and optional identifier.
6733  If no weight is supplied, then the penalty for violating the soft constraint
6734  is 1.
6735  Soft constraints are grouped by identifiers. Soft constraints that are
6736  added without identifiers are grouped by default.
6737  """
6738  if _is_int(weight):
6739  weight = "%d" % weight
6740  elif isinstance(weight, float):
6741  weight = "%f" % weight
6742  if not isinstance(weight, str):
6743  raise Z3Exception("weight should be a string or an integer")
6744  if id is None:
6745  id = ""
6746  id = to_symbol(id, self.ctx)
6747  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
6748  return OptimizeObjective(self, v, False)
6749 
6750  def maximize(self, arg):
6751  """Add objective function to maximize."""
6752  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
6753 
6754  def minimize(self, arg):
6755  """Add objective function to minimize."""
6756  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
6757 
6758  def push(self):
6759  """create a backtracking point for added rules, facts and assertions"""
6760  Z3_optimize_push(self.ctx.ref(), self.optimize)
6761 
6762  def pop(self):
6763  """restore to previously created backtracking point"""
6764  Z3_optimize_pop(self.ctx.ref(), self.optimize)
6765 
6766  def check(self):
6767  """Check satisfiability while optimizing objective functions."""
6768  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize))
6769 
6770  def reason_unknown(self):
6771  """Return a string that describes why the last `check()` returned `unknown`."""
6772  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
6773 
6774  def model(self):
6775  """Return a model for the last check()."""
6776  try:
6777  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
6778  except Z3Exception:
6779  raise Z3Exception("model is not available")
6780 
6781  def lower(self, obj):
6782  if not isinstance(obj, OptimizeObjective):
6783  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
6784  return obj.lower()
6785 
6786  def upper(self, obj):
6787  if not isinstance(obj, OptimizeObjective):
6788  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
6789  return obj.upper()
6790 
6791  def from_file(self, filename):
6792  """Parse assertions and objectives from a file"""
6793  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
6794 
6795  def from_string(self, s):
6796  """Parse assertions and objectives from a string"""
6797  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
6798 
6799  def assertions(self):
6800  """Return an AST vector containing all added constraints."""
6801  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
6802 
6803  def objectives(self):
6804  """returns set of objective functions"""
6805  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
6806 
6807  def __repr__(self):
6808  """Return a formatted string with all added rules and constraints."""
6809  return self.sexpr()
6810 
6811  def sexpr(self):
6812  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6813  """
6814  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
6815 
6816  def statistics(self):
6817  """Return statistics for the last check`.
6818  """
6819  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
6820 
6821 
6822 
6823 
6824 
6830  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
6831 
6832  def __init__(self, result, ctx):
6833  self.result = result
6834  self.ctx = ctx
6835  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
6836 
6837  def __del__(self):
6838  if self.ctx.ref() is not None:
6839  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
6840 
6841  def __len__(self):
6842  """Return the number of subgoals in `self`.
6843 
6844  >>> a, b = Ints('a b')
6845  >>> g = Goal()
6846  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6847  >>> t = Tactic('split-clause')
6848  >>> r = t(g)
6849  >>> len(r)
6850  2
6851  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
6852  >>> len(t(g))
6853  4
6854  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
6855  >>> len(t(g))
6856  1
6857  """
6858  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
6859 
6860  def __getitem__(self, idx):
6861  """Return one of the subgoals stored in ApplyResult object `self`.
6862 
6863  >>> a, b = Ints('a b')
6864  >>> g = Goal()
6865  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6866  >>> t = Tactic('split-clause')
6867  >>> r = t(g)
6868  >>> r[0]
6869  [a == 0, Or(b == 0, b == 1), a > b]
6870  >>> r[1]
6871  [a == 1, Or(b == 0, b == 1), a > b]
6872  """
6873  if idx >= len(self):
6874  raise IndexError
6875  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
6876 
6877  def __repr__(self):
6878  return obj_to_string(self)
6879 
6880  def sexpr(self):
6881  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
6882  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
6883 
6884  def convert_model(self, model, idx=0):
6885  """Convert a model for a subgoal into a model for the original goal.
6886 
6887  >>> a, b = Ints('a b')
6888  >>> g = Goal()
6889  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6890  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6891  >>> r = t(g)
6892  >>> r[0]
6893  [Or(b == 0, b == 1), Not(0 <= b)]
6894  >>> r[1]
6895  [Or(b == 0, b == 1), Not(1 <= b)]
6896  >>> # Remark: the subgoal r[0] is unsatisfiable
6897  >>> # Creating a solver for solving the second subgoal
6898  >>> s = Solver()
6899  >>> s.add(r[1])
6900  >>> s.check()
6901  sat
6902  >>> s.model()
6903  [b = 0]
6904  >>> # Model s.model() does not assign a value to `a`
6905  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6906  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6907  >>> r.convert_model(s.model(), 1)
6908  [b = 0, a = 1]
6909  """
6910  if __debug__:
6911  _z3_assert(idx < len(self), "index out of bounds")
6912  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
6913  return ModelRef(Z3_apply_result_convert_model(self.ctx.ref(), self.result, idx, model.model), self.ctx)
6914 
6915  def as_expr(self):
6916  """Return a Z3 expression consisting of all subgoals.
6917 
6918  >>> x = Int('x')
6919  >>> g = Goal()
6920  >>> g.add(x > 1)
6921  >>> g.add(Or(x == 2, x == 3))
6922  >>> r = Tactic('simplify')(g)
6923  >>> r
6924  [[Not(x <= 1), Or(x == 2, x == 3)]]
6925  >>> r.as_expr()
6926  And(Not(x <= 1), Or(x == 2, x == 3))
6927  >>> r = Tactic('split-clause')(g)
6928  >>> r
6929  [[x > 1, x == 2], [x > 1, x == 3]]
6930  >>> r.as_expr()
6931  Or(And(x > 1, x == 2), And(x > 1, x == 3))
6932  """
6933  sz = len(self)
6934  if sz == 0:
6935  return BoolVal(False, self.ctx)
6936  elif sz == 1:
6937  return self[0].as_expr()
6938  else:
6939  return Or([ self[i].as_expr() for i in range(len(self)) ])
6940 
6941 
6946 class Tactic:
6947  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
6948 
6949  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
6950  """
6951  def __init__(self, tactic, ctx=None):
6952  self.ctx = _get_ctx(ctx)
6953  self.tactic = None
6954  if isinstance(tactic, TacticObj):
6955  self.tactic = tactic
6956  else:
6957  if __debug__:
6958  _z3_assert(isinstance(tactic, str), "tactic name expected")
6959  try:
6960  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
6961  except Z3Exception:
6962  raise Z3Exception("unknown tactic '%s'" % tactic)
6963  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
6964 
6965  def __del__(self):
6966  if self.tactic is not None and self.ctx.ref() is not None:
6967  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
6968 
6969  def solver(self):
6970  """Create a solver using the tactic `self`.
6971 
6972  The solver supports the methods `push()` and `pop()`, but it
6973  will always solve each `check()` from scratch.
6974 
6975  >>> t = Then('simplify', 'nlsat')
6976  >>> s = t.solver()
6977  >>> x = Real('x')
6978  >>> s.add(x**2 == 2, x > 0)
6979  >>> s.check()
6980  sat
6981  >>> s.model()
6982  [x = 1.4142135623?]
6983  """
6984  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
6985 
6986  def apply(self, goal, *arguments, **keywords):
6987  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
6988 
6989  >>> x, y = Ints('x y')
6990  >>> t = Tactic('solve-eqs')
6991  >>> t.apply(And(x == 0, y >= x + 1))
6992  [[y >= 1]]
6993  """
6994  if __debug__:
6995  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
6996  goal = _to_goal(goal)
6997  if len(arguments) > 0 or len(keywords) > 0:
6998  p = args2params(arguments, keywords, self.ctx)
6999  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7000  else:
7001  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7002 
7003  def __call__(self, goal, *arguments, **keywords):
7004  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7005 
7006  >>> x, y = Ints('x y')
7007  >>> t = Tactic('solve-eqs')
7008  >>> t(And(x == 0, y >= x + 1))
7009  [[y >= 1]]
7010  """
7011  return self.apply(goal, *arguments, **keywords)
7012 
7013  def help(self):
7014  """Display a string containing a description of the available options for the `self` tactic."""
7015  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7016 
7017  def param_descrs(self):
7018  """Return the parameter description set."""
7019  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7020 
7021 def _to_goal(a):
7022  if isinstance(a, BoolRef):
7023  goal = Goal(ctx = a.ctx)
7024  goal.add(a)
7025  return goal
7026  else:
7027  return a
7028 
7029 def _to_tactic(t, ctx=None):
7030  if isinstance(t, Tactic):
7031  return t
7032  else:
7033  return Tactic(t, ctx)
7034 
7035 def _and_then(t1, t2, ctx=None):
7036  t1 = _to_tactic(t1, ctx)
7037  t2 = _to_tactic(t2, ctx)
7038  if __debug__:
7039  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7040  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7041 
7042 def _or_else(t1, t2, ctx=None):
7043  t1 = _to_tactic(t1, ctx)
7044  t2 = _to_tactic(t2, ctx)
7045  if __debug__:
7046  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7047  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7048 
7049 def AndThen(*ts, **ks):
7050  """Return a tactic that applies the tactics in `*ts` in sequence.
7051 
7052  >>> x, y = Ints('x y')
7053  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7054  >>> t(And(x == 0, y > x + 1))
7055  [[Not(y <= 1)]]
7056  >>> t(And(x == 0, y > x + 1)).as_expr()
7057  Not(y <= 1)
7058  """
7059  if __debug__:
7060  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7061  ctx = ks.get('ctx', None)
7062  num = len(ts)
7063  r = ts[0]
7064  for i in range(num - 1):
7065  r = _and_then(r, ts[i+1], ctx)
7066  return r
7067 
7068 def Then(*ts, **ks):
7069  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7070 
7071  >>> x, y = Ints('x y')
7072  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7073  >>> t(And(x == 0, y > x + 1))
7074  [[Not(y <= 1)]]
7075  >>> t(And(x == 0, y > x + 1)).as_expr()
7076  Not(y <= 1)
7077  """
7078  return AndThen(*ts, **ks)
7079 
7080 def OrElse(*ts, **ks):
7081  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7082 
7083  >>> x = Int('x')
7084  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7085  >>> # Tactic split-clause fails if there is no clause in the given goal.
7086  >>> t(x == 0)
7087  [[x == 0]]
7088  >>> t(Or(x == 0, x == 1))
7089  [[x == 0], [x == 1]]
7090  """
7091  if __debug__:
7092  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7093  ctx = ks.get('ctx', None)
7094  num = len(ts)
7095  r = ts[0]
7096  for i in range(num - 1):
7097  r = _or_else(r, ts[i+1], ctx)
7098  return r
7099 
7100 def ParOr(*ts, **ks):
7101  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7102 
7103  >>> x = Int('x')
7104  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7105  >>> t(x + 1 == 2)
7106  [[x == 1]]
7107  """
7108  if __debug__:
7109  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7110  ctx = _get_ctx(ks.get('ctx', None))
7111  ts = [ _to_tactic(t, ctx) for t in ts ]
7112  sz = len(ts)
7113  _args = (TacticObj * sz)()
7114  for i in range(sz):
7115  _args[i] = ts[i].tactic
7116  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7117 
7118 def ParThen(t1, t2, ctx=None):
7119  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7120 
7121  >>> x, y = Ints('x y')
7122  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7123  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7124  [[x == 1, y == 2], [x == 2, y == 3]]
7125  """
7126  t1 = _to_tactic(t1, ctx)
7127  t2 = _to_tactic(t2, ctx)
7128  if __debug__:
7129  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7130  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7131 
7132 def ParAndThen(t1, t2, ctx=None):
7133  """Alias for ParThen(t1, t2, ctx)."""
7134  return ParThen(t1, t2, ctx)
7135 
7136 def With(t, *args, **keys):
7137  """Return a tactic that applies tactic `t` using the given configuration options.
7138 
7139  >>> x, y = Ints('x y')
7140  >>> t = With(Tactic('simplify'), som=True)
7141  >>> t((x + 1)*(y + 2) == 0)
7142  [[2*x + y + x*y == -2]]
7143  """
7144  ctx = keys.get('ctx', None)
7145  t = _to_tactic(t, ctx)
7146  p = args2params(args, keys, t.ctx)
7147  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7148 
7149 def Repeat(t, max=4294967295, ctx=None):
7150  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7151 
7152  >>> x, y = Ints('x y')
7153  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7154  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7155  >>> r = t(c)
7156  >>> for subgoal in r: print(subgoal)
7157  [x == 0, y == 0, x > y]
7158  [x == 0, y == 1, x > y]
7159  [x == 1, y == 0, x > y]
7160  [x == 1, y == 1, x > y]
7161  >>> t = Then(t, Tactic('propagate-values'))
7162  >>> t(c)
7163  [[x == 1, y == 0]]
7164  """
7165  t = _to_tactic(t, ctx)
7166  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7167 
7168 def TryFor(t, ms, ctx=None):
7169  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7170 
7171  If `t` does not terminate in `ms` milliseconds, then it fails.
7172  """
7173  t = _to_tactic(t, ctx)
7174  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7175 
7176 def tactics(ctx=None):
7177  """Return a list of all available tactics in Z3.
7178 
7179  >>> l = tactics()
7180  >>> l.count('simplify') == 1
7181  True
7182  """
7183  ctx = _get_ctx(ctx)
7184  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7185 
7186 def tactic_description(name, ctx=None):
7187  """Return a short description for the tactic named `name`.
7188 
7189  >>> d = tactic_description('simplify')
7190  """
7191  ctx = _get_ctx(ctx)
7192  return Z3_tactic_get_descr(ctx.ref(), name)
7193 
7195  """Display a (tabular) description of all available tactics in Z3."""
7196  if in_html_mode():
7197  even = True
7198  print('<table border="1" cellpadding="2" cellspacing="0">')
7199  for t in tactics():
7200  if even:
7201  print('<tr style="background-color:#CFCFCF">')
7202  even = False
7203  else:
7204  print('<tr>')
7205  even = True
7206  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7207  print('</table>')
7208  else:
7209  for t in tactics():
7210  print('%s : %s' % (t, tactic_description(t)))
7211 
7212 class Probe:
7213  """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."""
7214  def __init__(self, probe, ctx=None):
7215  self.ctx = _get_ctx(ctx)
7216  self.probe = None
7217  if isinstance(probe, ProbeObj):
7218  self.probe = probe
7219  elif isinstance(probe, float):
7220  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7221  elif _is_int(probe):
7222  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7223  elif isinstance(probe, bool):
7224  if probe:
7225  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7226  else:
7227  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7228  else:
7229  if __debug__:
7230  _z3_assert(isinstance(probe, str), "probe name expected")
7231  try:
7232  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7233  except Z3Exception:
7234  raise Z3Exception("unknown probe '%s'" % probe)
7235  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7236 
7237  def __del__(self):
7238  if self.probe is not None and self.ctx.ref() is not None:
7239  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7240 
7241  def __lt__(self, other):
7242  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7243 
7244  >>> p = Probe('size') < 10
7245  >>> x = Int('x')
7246  >>> g = Goal()
7247  >>> g.add(x > 0)
7248  >>> g.add(x < 10)
7249  >>> p(g)
7250  1.0
7251  """
7252  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7253 
7254  def __gt__(self, other):
7255  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7256 
7257  >>> p = Probe('size') > 10
7258  >>> x = Int('x')
7259  >>> g = Goal()
7260  >>> g.add(x > 0)
7261  >>> g.add(x < 10)
7262  >>> p(g)
7263  0.0
7264  """
7265  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7266 
7267  def __le__(self, other):
7268  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7269 
7270  >>> p = Probe('size') <= 2
7271  >>> x = Int('x')
7272  >>> g = Goal()
7273  >>> g.add(x > 0)
7274  >>> g.add(x < 10)
7275  >>> p(g)
7276  1.0
7277  """
7278  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7279 
7280  def __ge__(self, other):
7281  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7282 
7283  >>> p = Probe('size') >= 2
7284  >>> x = Int('x')
7285  >>> g = Goal()
7286  >>> g.add(x > 0)
7287  >>> g.add(x < 10)
7288  >>> p(g)
7289  1.0
7290  """
7291  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7292 
7293  def __eq__(self, other):
7294  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7295 
7296  >>> p = Probe('size') == 2
7297  >>> x = Int('x')
7298  >>> g = Goal()
7299  >>> g.add(x > 0)
7300  >>> g.add(x < 10)
7301  >>> p(g)
7302  1.0
7303  """
7304  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7305 
7306  def __ne__(self, other):
7307  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7308 
7309  >>> p = Probe('size') != 2
7310  >>> x = Int('x')
7311  >>> g = Goal()
7312  >>> g.add(x > 0)
7313  >>> g.add(x < 10)
7314  >>> p(g)
7315  0.0
7316  """
7317  p = self.__eq__(other)
7318  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
7319 
7320  def __call__(self, goal):
7321  """Evaluate the probe `self` in the given goal.
7322 
7323  >>> p = Probe('size')
7324  >>> x = Int('x')
7325  >>> g = Goal()
7326  >>> g.add(x > 0)
7327  >>> g.add(x < 10)
7328  >>> p(g)
7329  2.0
7330  >>> g.add(x < 20)
7331  >>> p(g)
7332  3.0
7333  >>> p = Probe('num-consts')
7334  >>> p(g)
7335  1.0
7336  >>> p = Probe('is-propositional')
7337  >>> p(g)
7338  0.0
7339  >>> p = Probe('is-qflia')
7340  >>> p(g)
7341  1.0
7342  """
7343  if __debug__:
7344  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
7345  goal = _to_goal(goal)
7346  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
7347 
7348 def is_probe(p):
7349  """Return `True` if `p` is a Z3 probe.
7350 
7351  >>> is_probe(Int('x'))
7352  False
7353  >>> is_probe(Probe('memory'))
7354  True
7355  """
7356  return isinstance(p, Probe)
7357 
7358 def _to_probe(p, ctx=None):
7359  if is_probe(p):
7360  return p
7361  else:
7362  return Probe(p, ctx)
7363 
7364 def probes(ctx=None):
7365  """Return a list of all available probes in Z3.
7366 
7367  >>> l = probes()
7368  >>> l.count('memory') == 1
7369  True
7370  """
7371  ctx = _get_ctx(ctx)
7372  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
7373 
7374 def probe_description(name, ctx=None):
7375  """Return a short description for the probe named `name`.
7376 
7377  >>> d = probe_description('memory')
7378  """
7379  ctx = _get_ctx(ctx)
7380  return Z3_probe_get_descr(ctx.ref(), name)
7381 
7383  """Display a (tabular) description of all available probes in Z3."""
7384  if in_html_mode():
7385  even = True
7386  print('<table border="1" cellpadding="2" cellspacing="0">')
7387  for p in probes():
7388  if even:
7389  print('<tr style="background-color:#CFCFCF">')
7390  even = False
7391  else:
7392  print('<tr>')
7393  even = True
7394  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
7395  print('</table>')
7396  else:
7397  for p in probes():
7398  print('%s : %s' % (p, probe_description(p)))
7399 
7400 def _probe_nary(f, args, ctx):
7401  if __debug__:
7402  _z3_assert(len(args) > 0, "At least one argument expected")
7403  num = len(args)
7404  r = _to_probe(args[0], ctx)
7405  for i in range(num - 1):
7406  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
7407  return r
7408 
7409 def _probe_and(args, ctx):
7410  return _probe_nary(Z3_probe_and, args, ctx)
7411 
7412 def _probe_or(args, ctx):
7413  return _probe_nary(Z3_probe_or, args, ctx)
7414 
7415 def FailIf(p, ctx=None):
7416  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7417 
7418  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
7419 
7420  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
7421  >>> x, y = Ints('x y')
7422  >>> g = Goal()
7423  >>> g.add(x > 0)
7424  >>> g.add(y > 0)
7425  >>> t(g)
7426  [[x > 0, y > 0]]
7427  >>> g.add(x == y + 1)
7428  >>> t(g)
7429  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7430  """
7431  p = _to_probe(p, ctx)
7432  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
7433 
7434 def When(p, t, ctx=None):
7435  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7436 
7437  >>> t = When(Probe('size') > 2, Tactic('simplify'))
7438  >>> x, y = Ints('x y')
7439  >>> g = Goal()
7440  >>> g.add(x > 0)
7441  >>> g.add(y > 0)
7442  >>> t(g)
7443  [[x > 0, y > 0]]
7444  >>> g.add(x == y + 1)
7445  >>> t(g)
7446  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7447  """
7448  p = _to_probe(p, ctx)
7449  t = _to_tactic(t, ctx)
7450  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
7451 
7452 def Cond(p, t1, t2, ctx=None):
7453  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
7454 
7455  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
7456  """
7457  p = _to_probe(p, ctx)
7458  t1 = _to_tactic(t1, ctx)
7459  t2 = _to_tactic(t2, ctx)
7460  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
7461 
7462 
7467 
7468 def simplify(a, *arguments, **keywords):
7469  """Simplify the expression `a` using the given options.
7470 
7471  This function has many options. Use `help_simplify` to obtain the complete list.
7472 
7473  >>> x = Int('x')
7474  >>> y = Int('y')
7475  >>> simplify(x + 1 + y + x + 1)
7476  2 + 2*x + y
7477  >>> simplify((x + 1)*(y + 1), som=True)
7478  1 + x + y + x*y
7479  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
7480  And(Not(x == y), Not(x == 1), Not(y == 1))
7481  >>> simplify(And(x == 0, y == 1), elim_and=True)
7482  Not(Or(Not(x == 0), Not(y == 1)))
7483  """
7484  if __debug__:
7485  _z3_assert(is_expr(a), "Z3 expression expected")
7486  if len(arguments) > 0 or len(keywords) > 0:
7487  p = args2params(arguments, keywords, a.ctx)
7488  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
7489  else:
7490  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
7491 
7493  """Return a string describing all options available for Z3 `simplify` procedure."""
7494  print(Z3_simplify_get_help(main_ctx().ref()))
7495 
7497  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
7499 
7500 def substitute(t, *m):
7501  """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.
7502 
7503  >>> x = Int('x')
7504  >>> y = Int('y')
7505  >>> substitute(x + 1, (x, y + 1))
7506  y + 1 + 1
7507  >>> f = Function('f', IntSort(), IntSort())
7508  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
7509  1 + 1
7510  """
7511  if isinstance(m, tuple):
7512  m1 = _get_args(m)
7513  if isinstance(m1, list):
7514  m = m1
7515  if __debug__:
7516  _z3_assert(is_expr(t), "Z3 expression expected")
7517  _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.")
7518  num = len(m)
7519  _from = (Ast * num)()
7520  _to = (Ast * num)()
7521  for i in range(num):
7522  _from[i] = m[i][0].as_ast()
7523  _to[i] = m[i][1].as_ast()
7524  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
7525 
7526 def substitute_vars(t, *m):
7527  """Substitute the free variables in t with the expression in m.
7528 
7529  >>> v0 = Var(0, IntSort())
7530  >>> v1 = Var(1, IntSort())
7531  >>> x = Int('x')
7532  >>> f = Function('f', IntSort(), IntSort(), IntSort())
7533  >>> # replace v0 with x+1 and v1 with x
7534  >>> substitute_vars(f(v0, v1), x + 1, x)
7535  f(x + 1, x)
7536  """
7537  if __debug__:
7538  _z3_assert(is_expr(t), "Z3 expression expected")
7539  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
7540  num = len(m)
7541  _to = (Ast * num)()
7542  for i in range(num):
7543  _to[i] = m[i].as_ast()
7544  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
7545 
7546 def Sum(*args):
7547  """Create the sum of the Z3 expressions.
7548 
7549  >>> a, b, c = Ints('a b c')
7550  >>> Sum(a, b, c)
7551  a + b + c
7552  >>> Sum([a, b, c])
7553  a + b + c
7554  >>> A = IntVector('a', 5)
7555  >>> Sum(A)
7556  a__0 + a__1 + a__2 + a__3 + a__4
7557  """
7558  args = _get_args(args)
7559  if len(args) == 0:
7560  return 0
7561  ctx = _ctx_from_ast_arg_list(args)
7562  if ctx is None:
7563  return _reduce(lambda a, b: a + b, args, 0)
7564  args = _coerce_expr_list(args, ctx)
7565  if is_bv(args[0]):
7566  return _reduce(lambda a, b: a + b, args, 0)
7567  else:
7568  _args, sz = _to_ast_array(args)
7569  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
7570 
7571 
7572 def Product(*args):
7573  """Create the product of the Z3 expressions.
7574 
7575  >>> a, b, c = Ints('a b c')
7576  >>> Product(a, b, c)
7577  a*b*c
7578  >>> Product([a, b, c])
7579  a*b*c
7580  >>> A = IntVector('a', 5)
7581  >>> Product(A)
7582  a__0*a__1*a__2*a__3*a__4
7583  """
7584  args = _get_args(args)
7585  if len(args) == 0:
7586  return 1
7587  ctx = _ctx_from_ast_arg_list(args)
7588  if ctx is None:
7589  return _reduce(lambda a, b: a * b, args, 1)
7590  args = _coerce_expr_list(args, ctx)
7591  if is_bv(args[0]):
7592  return _reduce(lambda a, b: a * b, args, 1)
7593  else:
7594  _args, sz = _to_ast_array(args)
7595  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
7596 
7597 def AtMost(*args):
7598  """Create an at-most Pseudo-Boolean k constraint.
7599 
7600  >>> a, b, c = Bools('a b c')
7601  >>> f = AtMost(a, b, c, 2)
7602  """
7603  args = _get_args(args)
7604  if __debug__:
7605  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7606  ctx = _ctx_from_ast_arg_list(args)
7607  if __debug__:
7608  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7609  args1 = _coerce_expr_list(args[:-1], ctx)
7610  k = args[-1]
7611  _args, sz = _to_ast_array(args1)
7612  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
7613 
7614 def AtLeast(*args):
7615  """Create an at-most Pseudo-Boolean k constraint.
7616 
7617  >>> a, b, c = Bools('a b c')
7618  >>> f = AtLeast(a, b, c, 2)
7619  """
7620  def mk_not(a):
7621  if is_not(a):
7622  return a.arg(0)
7623  else:
7624  return Not(a)
7625  args = _get_args(args)
7626  if __debug__:
7627  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7628  ctx = _ctx_from_ast_arg_list(args)
7629  if __debug__:
7630  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7631  args1 = _coerce_expr_list(args[:-1], ctx)
7632  args1 = [ mk_not(a) for a in args1 ]
7633  k = len(args1) - args[-1]
7634  _args, sz = _to_ast_array(args1)
7635  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
7636 
7637 def PbLe(args, k):
7638  """Create a Pseudo-Boolean inequality k constraint.
7639 
7640  >>> a, b, c = Bools('a b c')
7641  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
7642  """
7643  args = _get_args(args)
7644  args, coeffs = zip(*args)
7645  if __debug__:
7646  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7647  ctx = _ctx_from_ast_arg_list(args)
7648  if __debug__:
7649  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7650  args = _coerce_expr_list(args, ctx)
7651  _args, sz = _to_ast_array(args)
7652  _coeffs = (ctypes.c_int * len(coeffs))()
7653  for i in range(len(coeffs)):
7654  _coeffs[i] = coeffs[i]
7655  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
7656 
7657 def PbEq(args, k):
7658  """Create a Pseudo-Boolean inequality k constraint.
7659 
7660  >>> a, b, c = Bools('a b c')
7661  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
7662  """
7663  args = _get_args(args)
7664  args, coeffs = zip(*args)
7665  if __debug__:
7666  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7667  ctx = _ctx_from_ast_arg_list(args)
7668  if __debug__:
7669  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7670  args = _coerce_expr_list(args, ctx)
7671  _args, sz = _to_ast_array(args)
7672  _coeffs = (ctypes.c_int * len(coeffs))()
7673  for i in range(len(coeffs)):
7674  _coeffs[i] = coeffs[i]
7675  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
7676 
7677 
7678 def solve(*args, **keywords):
7679  """Solve the constraints `*args`.
7680 
7681  This is a simple function for creating demonstrations. It creates a solver,
7682  configure it using the options in `keywords`, adds the constraints
7683  in `args`, and invokes check.
7684 
7685  >>> a = Int('a')
7686  >>> solve(a > 0, a < 2)
7687  [a = 1]
7688  """
7689  s = Solver()
7690  s.set(**keywords)
7691  s.add(*args)
7692  if keywords.get('show', False):
7693  print(s)
7694  r = s.check()
7695  if r == unsat:
7696  print("no solution")
7697  elif r == unknown:
7698  print("failed to solve")
7699  try:
7700  print(s.model())
7701  except Z3Exception:
7702  return
7703  else:
7704  print(s.model())
7705 
7706 def solve_using(s, *args, **keywords):
7707  """Solve the constraints `*args` using solver `s`.
7708 
7709  This is a simple function for creating demonstrations. It is similar to `solve`,
7710  but it uses the given solver `s`.
7711  It configures solver `s` using the options in `keywords`, adds the constraints
7712  in `args`, and invokes check.
7713  """
7714  if __debug__:
7715  _z3_assert(isinstance(s, Solver), "Solver object expected")
7716  s.set(**keywords)
7717  s.add(*args)
7718  if keywords.get('show', False):
7719  print("Problem:")
7720  print(s)
7721  r = s.check()
7722  if r == unsat:
7723  print("no solution")
7724  elif r == unknown:
7725  print("failed to solve")
7726  try:
7727  print(s.model())
7728  except Z3Exception:
7729  return
7730  else:
7731  if keywords.get('show', False):
7732  print("Solution:")
7733  print(s.model())
7734 
7735 def prove(claim, **keywords):
7736  """Try to prove the given claim.
7737 
7738  This is a simple function for creating demonstrations. It tries to prove
7739  `claim` by showing the negation is unsatisfiable.
7740 
7741  >>> p, q = Bools('p q')
7742  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
7743  proved
7744  """
7745  if __debug__:
7746  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
7747  s = Solver()
7748  s.set(**keywords)
7749  s.add(Not(claim))
7750  if keywords.get('show', False):
7751  print(s)
7752  r = s.check()
7753  if r == unsat:
7754  print("proved")
7755  elif r == unknown:
7756  print("failed to prove")
7757  print(s.model())
7758  else:
7759  print("counterexample")
7760  print(s.model())
7761 
7762 def _solve_html(*args, **keywords):
7763  """Version of funcion `solve` used in RiSE4Fun."""
7764  s = Solver()
7765  s.set(**keywords)
7766  s.add(*args)
7767  if keywords.get('show', False):
7768  print("<b>Problem:</b>")
7769  print(s)
7770  r = s.check()
7771  if r == unsat:
7772  print("<b>no solution</b>")
7773  elif r == unknown:
7774  print("<b>failed to solve</b>")
7775  try:
7776  print(s.model())
7777  except Z3Exception:
7778  return
7779  else:
7780  if keywords.get('show', False):
7781  print("<b>Solution:</b>")
7782  print(s.model())
7783 
7784 def _solve_using_html(s, *args, **keywords):
7785  """Version of funcion `solve_using` used in RiSE4Fun."""
7786  if __debug__:
7787  _z3_assert(isinstance(s, Solver), "Solver object expected")
7788  s.set(**keywords)
7789  s.add(*args)
7790  if keywords.get('show', False):
7791  print("<b>Problem:</b>")
7792  print(s)
7793  r = s.check()
7794  if r == unsat:
7795  print("<b>no solution</b>")
7796  elif r == unknown:
7797  print("<b>failed to solve</b>")
7798  try:
7799  print(s.model())
7800  except Z3Exception:
7801  return
7802  else:
7803  if keywords.get('show', False):
7804  print("<b>Solution:</b>")
7805  print(s.model())
7806 
7807 def _prove_html(claim, **keywords):
7808  """Version of funcion `prove` used in RiSE4Fun."""
7809  if __debug__:
7810  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
7811  s = Solver()
7812  s.set(**keywords)
7813  s.add(Not(claim))
7814  if keywords.get('show', False):
7815  print(s)
7816  r = s.check()
7817  if r == unsat:
7818  print("<b>proved</b>")
7819  elif r == unknown:
7820  print("<b>failed to prove</b>")
7821  print(s.model())
7822  else:
7823  print("<b>counterexample</b>")
7824  print(s.model())
7825 
7826 def _dict2sarray(sorts, ctx):
7827  sz = len(sorts)
7828  _names = (Symbol * sz)()
7829  _sorts = (Sort * sz) ()
7830  i = 0
7831  for k in sorts:
7832  v = sorts[k]
7833  if __debug__:
7834  _z3_assert(isinstance(k, str), "String expected")
7835  _z3_assert(is_sort(v), "Z3 sort expected")
7836  _names[i] = to_symbol(k, ctx)
7837  _sorts[i] = v.ast
7838  i = i + 1
7839  return sz, _names, _sorts
7840 
7841 def _dict2darray(decls, ctx):
7842  sz = len(decls)
7843  _names = (Symbol * sz)()
7844  _decls = (FuncDecl * sz) ()
7845  i = 0
7846  for k in decls:
7847  v = decls[k]
7848  if __debug__:
7849  _z3_assert(isinstance(k, str), "String expected")
7850  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
7851  _names[i] = to_symbol(k, ctx)
7852  if is_const(v):
7853  _decls[i] = v.decl().ast
7854  else:
7855  _decls[i] = v.ast
7856  i = i + 1
7857  return sz, _names, _decls
7858 
7859 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
7860  """Parse a string in SMT 2.0 format using the given sorts and decls.
7861 
7862  The arguments sorts and decls are Python dictionaries used to initialize
7863  the symbol table used for the SMT 2.0 parser.
7864 
7865  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
7866  And(x > 0, x < 10)
7867  >>> x, y = Ints('x y')
7868  >>> f = Function('f', IntSort(), IntSort())
7869  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
7870  x + f(y) > 0
7871  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
7872  a > 0
7873  """
7874  ctx = _get_ctx(ctx)
7875  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
7876  dsz, dnames, ddecls = _dict2darray(decls, ctx)
7877  return _to_expr_ref(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
7878 
7879 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
7880  """Parse a file in SMT 2.0 format using the given sorts and decls.
7881 
7882  This function is similar to parse_smt2_string().
7883  """
7884  ctx = _get_ctx(ctx)
7885  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
7886  dsz, dnames, ddecls = _dict2darray(decls, ctx)
7887  return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
7888 
7889 def Interpolant(a,ctx=None):
7890  """Create an interpolation operator.
7891 
7892  The argument is an interpolation pattern (see tree_interpolant).
7893 
7894  >>> x = Int('x')
7895  >>> print(Interpolant(x>0))
7896  interp(x > 0)
7897  """
7898  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
7899  s = BoolSort(ctx)
7900  a = s.cast(a)
7901  return BoolRef(Z3_mk_interpolant(ctx.ref(), a.as_ast()), ctx)
7902 
7903 def tree_interpolant(pat,p=None,ctx=None):
7904  """Compute interpolant for a tree of formulas.
7905 
7906  The input is an interpolation pattern over a set of formulas C.
7907  The pattern pat is a formula combining the formulas in C using
7908  logical conjunction and the "interp" operator (see Interp). This
7909  interp operator is logically the identity operator. It marks the
7910  sub-formulas of the pattern for which interpolants should be
7911  computed. The interpolant is a map sigma from marked subformulas
7912  to formulas, such that, for each marked subformula phi of pat
7913  (where phi sigma is phi with sigma(psi) substituted for each
7914  subformula psi of phi such that psi in dom(sigma)):
7915 
7916  1) phi sigma implies sigma(phi), and
7917 
7918  2) sigma(phi) is in the common uninterpreted vocabulary between
7919  the formulas of C occurring in phi and those not occurring in
7920  phi
7921 
7922  and moreover pat sigma implies false. In the simplest case
7923  an interpolant for the pattern "(and (interp A) B)" maps A
7924  to an interpolant for A /\ B.
7925 
7926  The return value is a vector of formulas representing sigma. This
7927  vector contains sigma(phi) for each marked subformula of pat, in
7928  pre-order traversal. This means that subformulas of phi occur before phi
7929  in the vector. Also, subformulas that occur multiply in pat will
7930  occur multiply in the result vector.
7931 
7932  If pat is satisfiable, raises an object of class ModelRef
7933  that represents a model of pat.
7934 
7935  If neither a proof of unsatisfiability nor a model is obtained
7936  (for example, because of a timeout, or because models are disabled)
7937  then None is returned.
7938 
7939  If parameters p are supplied, these are used in creating the
7940  solver that determines satisfiability.
7941 
7942  >>> x = Int('x')
7943  >>> y = Int('y')
7944  >>> print(tree_interpolant(And(Interpolant(x < 0), Interpolant(y > 2), x == y)))
7945  [Not(x >= 0), Not(y <= 2)]
7946 
7947  # >>> g = And(Interpolant(x<0),x<2)
7948  # >>> try:
7949  # ... print tree_interpolant(g).sexpr()
7950  # ... except ModelRef as m:
7951  # ... print m.sexpr()
7952  (define-fun x () Int
7953  (- 1))
7954  """
7955  f = pat
7956  ctx = _get_ctx(_ctx_from_ast_arg_list([f], ctx))
7957  ptr = (AstVectorObj * 1)()
7958  mptr = (Model * 1)()
7959  if p is None:
7960  p = ParamsRef(ctx)
7961  res = Z3_compute_interpolant(ctx.ref(),f.as_ast(),p.params,ptr,mptr)
7962  if res == Z3_L_FALSE:
7963  return AstVector(ptr[0],ctx)
7964  if mptr[0]:
7965  raise ModelRef(mptr[0], ctx)
7966  return None
7967 
7968 def binary_interpolant(a,b,p=None,ctx=None):
7969  """Compute an interpolant for a binary conjunction.
7970 
7971  If a & b is unsatisfiable, returns an interpolant for a & b.
7972  This is a formula phi such that
7973 
7974  1) a implies phi
7975  2) b implies not phi
7976  3) All the uninterpreted symbols of phi occur in both a and b.
7977 
7978  If a & b is satisfiable, raises an object of class ModelRef
7979  that represents a model of a &b.
7980 
7981  If neither a proof of unsatisfiability nor a model is obtained
7982  (for example, because of a timeout, or because models are disabled)
7983  then None is returned.
7984 
7985  If parameters p are supplied, these are used in creating the
7986  solver that determines satisfiability.
7987 
7988  x = Int('x')
7989  print(binary_interpolant(x<0,x>2))
7990  Not(x >= 0)
7991  """
7992  f = And(Interpolant(a),b)
7993  ti = tree_interpolant(f,p,ctx)
7994  return ti[0] if ti is not None else None
7995 
7996 def sequence_interpolant(v,p=None,ctx=None):
7997  """Compute interpolant for a sequence of formulas.
7998 
7999  If len(v) == N, and if the conjunction of the formulas in v is
8000  unsatisfiable, the interpolant is a sequence of formulas w
8001  such that len(w) = N-1 and v[0] implies w[0] and for i in 0..N-1:
8002 
8003  1) w[i] & v[i+1] implies w[i+1] (or false if i+1 = N)
8004  2) All uninterpreted symbols in w[i] occur in both v[0]..v[i]
8005  and v[i+1]..v[n]
8006 
8007  Requires len(v) >= 1.
8008 
8009  If a & b is satisfiable, raises an object of class ModelRef
8010  that represents a model of a & b.
8011 
8012  If neither a proof of unsatisfiability nor a model is obtained
8013  (for example, because of a timeout, or because models are disabled)
8014  then None is returned.
8015 
8016  If parameters p are supplied, these are used in creating the
8017  solver that determines satisfiability.
8018 
8019  >>> x = Int('x')
8020  >>> y = Int('y')
8021  >>> print(sequence_interpolant([x < 0, y == x , y > 2]))
8022  [Not(x >= 0), Not(y >= 0)]
8023  """
8024  f = v[0]
8025  for i in range(1,len(v)):
8026  f = And(Interpolant(f),v[i])
8027  return tree_interpolant(f,p,ctx)
8028 
8029 
8030 #########################################
8031 #
8032 # Floating-Point Arithmetic
8033 #
8034 #########################################
8035 
8036 
8037 # Global default rounding mode
8038 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8039 _dflt_fpsort_ebits = 11
8040 _dflt_fpsort_sbits = 53
8041 
8042 def get_default_rounding_mode(ctx=None):
8043  """Retrieves the global default rounding mode."""
8044  global _dflt_rounding_mode
8045  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8046  return RTZ(ctx)
8047  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8048  return RTN(ctx)
8049  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8050  return RTP(ctx)
8051  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8052  return RNE(ctx)
8053  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8054  return RNA(ctx)
8055 
8056 def set_default_rounding_mode(rm, ctx=None):
8057  global _dflt_rounding_mode
8058  if is_fprm_value(rm):
8059  _dflt_rounding_mode = rm.decl().kind()
8060  else:
8061  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8062  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8063  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8064  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8065  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8066  "illegal rounding mode")
8067  _dflt_rounding_mode = rm
8068 
8069 def get_default_fp_sort(ctx=None):
8070  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8071 
8072 def set_default_fp_sort(ebits, sbits, ctx=None):
8073  global _dflt_fpsort_ebits
8074  global _dflt_fpsort_sbits
8075  _dflt_fpsort_ebits = ebits
8076  _dflt_fpsort_sbits = sbits
8077 
8078 def _dflt_rm(ctx=None):
8079  return get_default_rounding_mode(ctx)
8080 
8081 def _dflt_fps(ctx=None):
8082  return get_default_fp_sort(ctx)
8083 
8084 def _coerce_fp_expr_list(alist, ctx):
8085  first_fp_sort = None
8086  for a in alist:
8087  if is_fp(a):
8088  if first_fp_sort is None:
8089  first_fp_sort = a.sort()
8090  elif first_fp_sort == a.sort():
8091  pass # OK, same as before
8092  else:
8093  # we saw at least 2 different float sorts; something will
8094  # throw a sort mismatch later, for now assume None.
8095  first_fp_sort = None
8096  break
8097 
8098  r = []
8099  for i in range(len(alist)):
8100  a = alist[i]
8101  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8102  r.append(FPVal(a, None, first_fp_sort, ctx))
8103  else:
8104  r.append(a)
8105  return _coerce_expr_list(r, ctx)
8106 
8107 
8108 ### FP Sorts
8109 
8110 class FPSortRef(SortRef):
8111  """Floating-point sort."""
8112 
8113  def ebits(self):
8114  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8115  >>> b = FPSort(8, 24)
8116  >>> b.ebits()
8117  8
8118  """
8119  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8120 
8121  def sbits(self):
8122  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8123  >>> b = FPSort(8, 24)
8124  >>> b.sbits()
8125  24
8126  """
8127  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8128 
8129  def cast(self, val):
8130  """Try to cast `val` as a floating-point expression.
8131  >>> b = FPSort(8, 24)
8132  >>> b.cast(1.0)
8133  1
8134  >>> b.cast(1.0).sexpr()
8135  '(fp #b0 #x7f #b00000000000000000000000)'
8136  """
8137  if is_expr(val):
8138  if __debug__:
8139  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8140  return val
8141  else:
8142  return FPVal(val, None, self, self.ctx)
8143 
8144 
8145 def Float16(ctx=None):
8146  """Floating-point 16-bit (half) sort."""
8147  ctx = _get_ctx(ctx)
8148  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8149 
8150 def FloatHalf(ctx=None):
8151  """Floating-point 16-bit (half) sort."""
8152  ctx = _get_ctx(ctx)
8153  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8154 
8155 def Float32(ctx=None):
8156  """Floating-point 32-bit (single) sort."""
8157  ctx = _get_ctx(ctx)
8158  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8159 
8160 def FloatSingle(ctx=None):
8161  """Floating-point 32-bit (single) sort."""
8162  ctx = _get_ctx(ctx)
8163  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8164 
8165 def Float64(ctx=None):
8166  """Floating-point 64-bit (double) sort."""
8167  ctx = _get_ctx(ctx)
8168  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8169 
8170 def FloatDouble(ctx=None):
8171  """Floating-point 64-bit (double) sort."""
8172  ctx = _get_ctx(ctx)
8173  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8174 
8175 def Float128(ctx=None):
8176  """Floating-point 128-bit (quadruple) sort."""
8177  ctx = _get_ctx(ctx)
8178  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8179 
8180 def FloatQuadruple(ctx=None):
8181  """Floating-point 128-bit (quadruple) sort."""
8182  ctx = _get_ctx(ctx)
8183  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8184 
8185 class FPRMSortRef(SortRef):
8186  """"Floating-point rounding mode sort."""
8187 
8188 
8189 def is_fp_sort(s):
8190  """Return True if `s` is a Z3 floating-point sort.
8191 
8192  >>> is_fp_sort(FPSort(8, 24))
8193  True
8194  >>> is_fp_sort(IntSort())
8195  False
8196  """
8197  return isinstance(s, FPSortRef)
8198 
8199 def is_fprm_sort(s):
8200  """Return True if `s` is a Z3 floating-point rounding mode sort.
8201 
8202  >>> is_fprm_sort(FPSort(8, 24))
8203  False
8204  >>> is_fprm_sort(RNE().sort())
8205  True
8206  """
8207  return isinstance(s, FPRMSortRef)
8208 
8209 ### FP Expressions
8210 
8211 class FPRef(ExprRef):
8212  """Floating-point expressions."""
8213 
8214  def sort(self):
8215  """Return the sort of the floating-point expression `self`.
8216 
8217  >>> x = FP('1.0', FPSort(8, 24))
8218  >>> x.sort()
8219  FPSort(8, 24)
8220  >>> x.sort() == FPSort(8, 24)
8221  True
8222  """
8223  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8224 
8225  def ebits(self):
8226  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8227  >>> b = FPSort(8, 24)
8228  >>> b.ebits()
8229  8
8230  """
8231  return self.sort().ebits();
8232 
8233  def sbits(self):
8234  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8235  >>> b = FPSort(8, 24)
8236  >>> b.sbits()
8237  24
8238  """
8239  return self.sort().sbits();
8240 
8241  def as_string(self):
8242  """Return a Z3 floating point expression as a Python string."""
8243  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8244 
8245  def __le__(self, other):
8246  return fpLEQ(self, other, self.ctx)
8247 
8248  def __lt__(self, other):
8249  return fpLT(self, other, self.ctx)
8250 
8251  def __ge__(self, other):
8252  return fpGEQ(self, other, self.ctx)
8253 
8254  def __gt__(self, other):
8255  return fpGT(self, other, self.ctx)
8256 
8257  def __add__(self, other):
8258  """Create the Z3 expression `self + other`.
8259 
8260  >>> x = FP('x', FPSort(8, 24))
8261  >>> y = FP('y', FPSort(8, 24))
8262  >>> x + y
8263  x + y
8264  >>> (x + y).sort()
8265  FPSort(8, 24)
8266  """
8267  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8268  return fpAdd(_dflt_rm(), a, b, self.ctx)
8269 
8270  def __radd__(self, other):
8271  """Create the Z3 expression `other + self`.
8272 
8273  >>> x = FP('x', FPSort(8, 24))
8274  >>> 10 + x
8275  1.25*(2**3) + x
8276  """
8277  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8278  return fpAdd(_dflt_rm(), a, b, self.ctx)
8279 
8280  def __sub__(self, other):
8281  """Create the Z3 expression `self - other`.
8282 
8283  >>> x = FP('x', FPSort(8, 24))
8284  >>> y = FP('y', FPSort(8, 24))
8285  >>> x - y
8286  x - y
8287  >>> (x - y).sort()
8288  FPSort(8, 24)
8289  """
8290  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8291  return fpSub(_dflt_rm(), a, b, self.ctx)
8292 
8293  def __rsub__(self, other):
8294  """Create the Z3 expression `other - self`.
8295 
8296  >>> x = FP('x', FPSort(8, 24))
8297  >>> 10 - x
8298  1.25*(2**3) - x
8299  """
8300  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8301  return fpSub(_dflt_rm(), a, b, self.ctx)
8302 
8303  def __mul__(self, other):
8304  """Create the Z3 expression `self * other`.
8305 
8306  >>> x = FP('x', FPSort(8, 24))
8307  >>> y = FP('y', FPSort(8, 24))
8308  >>> x * y
8309  x * y
8310  >>> (x * y).sort()
8311  FPSort(8, 24)
8312  >>> 10 * y
8313  1.25*(2**3) * y
8314  """
8315  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8316  return fpMul(_dflt_rm(), a, b, self.ctx)
8317 
8318  def __rmul__(self, other):
8319  """Create the Z3 expression `other * self`.
8320 
8321  >>> x = FP('x', FPSort(8, 24))
8322  >>> y = FP('y', FPSort(8, 24))
8323  >>> x * y
8324  x * y
8325  >>> x * 10
8326  x * 1.25*(2**3)
8327  """
8328  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8329  return fpMul(_dflt_rm(), a, b, self.ctx)
8330 
8331  def __pos__(self):
8332  """Create the Z3 expression `+self`."""
8333  return self
8334 
8335  def __neg__(self):
8336  """Create the Z3 expression `-self`.
8337 
8338  >>> x = FP('x', Float32())
8339  >>> -x
8340  -x
8341  """
8342  return fpNeg(self)
8343 
8344  def __div__(self, other):
8345  """Create the Z3 expression `self / other`.
8346 
8347  >>> x = FP('x', FPSort(8, 24))
8348  >>> y = FP('y', FPSort(8, 24))
8349  >>> x / y
8350  x / y
8351  >>> (x / y).sort()
8352  FPSort(8, 24)
8353  >>> 10 / y
8354  1.25*(2**3) / y
8355  """
8356  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8357  return fpDiv(_dflt_rm(), a, b, self.ctx)
8358 
8359  def __rdiv__(self, other):
8360  """Create the Z3 expression `other / self`.
8361 
8362  >>> x = FP('x', FPSort(8, 24))
8363  >>> y = FP('y', FPSort(8, 24))
8364  >>> x / y
8365  x / y
8366  >>> x / 10
8367  x / 1.25*(2**3)
8368  """
8369  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8370  return fpDiv(_dflt_rm(), a, b, self.ctx)
8371 
8372  if not sys.version < '3':
8373  def __truediv__(self, other):
8374  """Create the Z3 expression division `self / other`."""
8375  return self.__div__(other)
8376 
8377  def __rtruediv__(self, other):
8378  """Create the Z3 expression division `other / self`."""
8379  return self.__rdiv__(other)
8380 
8381  def __mod__(self, other):
8382  """Create the Z3 expression mod `self % other`."""
8383  return fpRem(self, other)
8384 
8385  def __rmod__(self, other):
8386  """Create the Z3 expression mod `other % self`."""
8387  return fpRem(other, self)
8388 
8389 class FPRMRef(ExprRef):
8390  """Floating-point rounding mode expressions"""
8391 
8392  def as_string(self):
8393  """Return a Z3 floating point expression as a Python string."""
8394  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8395 
8396 
8397 def RoundNearestTiesToEven(ctx=None):
8398  ctx = _get_ctx(ctx)
8399  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8400 
8401 def RNE (ctx=None):
8402  ctx = _get_ctx(ctx)
8403  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8404 
8405 def RoundNearestTiesToAway(ctx=None):
8406  ctx = _get_ctx(ctx)
8407  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8408 
8409 def RNA (ctx=None):
8410  ctx = _get_ctx(ctx)
8411  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8412 
8413 def RoundTowardPositive(ctx=None):
8414  ctx = _get_ctx(ctx)
8415  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8416 
8417 def RTP(ctx=None):
8418  ctx = _get_ctx(ctx)
8419  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8420 
8421 def RoundTowardNegative(ctx=None):
8422  ctx = _get_ctx(ctx)
8423  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8424 
8425 def RTN(ctx=None):
8426  ctx = _get_ctx(ctx)
8427  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8428 
8429 def RoundTowardZero(ctx=None):
8430  ctx = _get_ctx(ctx)
8431  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8432 
8433 def RTZ(ctx=None):
8434  ctx = _get_ctx(ctx)
8435  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8436 
8437 def is_fprm(a):
8438  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8439 
8440  >>> rm = RNE()
8441  >>> is_fprm(rm)
8442  True
8443  >>> rm = 1.0
8444  >>> is_fprm(rm)
8445  False
8446  """
8447  return isinstance(a, FPRMRef)
8448 
8449 def is_fprm_value(a):
8450  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8451  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8452 
8453 ### FP Numerals
8454 
8455 class FPNumRef(FPRef):
8456  def isNaN(self):
8457  return self.decl().kind() == Z3_OP_FPA_NAN
8458 
8459  def isInf(self):
8460  return self.decl().kind() == Z3_OP_FPA_PLUS_INF or self.decl().kind() == Z3_OP_FPA_MINUS_INF
8461 
8462  def isZero(self):
8463  return self.decl().kind() == Z3_OP_FPA_PLUS_ZERO or self.decl().kind() == Z3_OP_FPA_MINUS_ZERO
8464 
8465  def isNegative(self):
8466  k = self.decl().kind()
8467  return (self.num_args() == 0 and (k == Z3_OP_FPA_MINUS_INF or k == Z3_OP_FPA_MINUS_ZERO)) or (self.sign() == True)
8468 
8469  """
8470  The sign of the numeral.
8471 
8472  >>> x = FPNumRef(+1.0, FPSort(8, 24))
8473  >>> x.sign()
8474  False
8475  >>> x = FPNumRef(-1.0, FPSort(8, 24))
8476  >>> x.sign()
8477  True
8478  """
8479  def sign(self):
8480  l = (ctypes.c_int)()
8481  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
8482  raise Z3Exception("error retrieving the sign of a numeral.")
8483  return l.value != 0
8484 
8485  """
8486  The significand of the numeral.
8487 
8488  >>> x = FPNumRef(2.5, FPSort(8, 24))
8489  >>> x.significand()
8490  1.25
8491  """
8492  def significand(self):
8493  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
8494 
8495  """
8496  The exponent of the numeral.
8497 
8498  >>> x = FPNumRef(2.5, FPSort(8, 24))
8499  >>> x.exponent()
8500  1
8501  """
8502  def exponent(self):
8503  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast())
8504 
8505  """
8506  The exponent of the numeral as a long.
8507 
8508  >>> x = FPNumRef(2.5, FPSort(8, 24))
8509  >>> x.exponent_as_long()
8510  1
8511  """
8512  def exponent_as_long(self):
8513  ptr = (ctypes.c_longlong * 1)()
8514  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr):
8515  raise Z3Exception("error retrieving the exponent of a numeral.")
8516  return ptr[0]
8517 
8518  """
8519  The string representation of the numeral.
8520 
8521  >>> x = FPNumRef(20, FPSort(8, 24))
8522  >>> x.as_string()
8523  1.25*(2**4)
8524  """
8525  def as_string(self):
8526  s = Z3_fpa_get_numeral_string(self.ctx.ref(), self.as_ast())
8527  return ("FPVal(%s, %s)" % (s, self.sort()))
8528 
8529 def is_fp(a):
8530  """Return `True` if `a` is a Z3 floating-point expression.
8531 
8532  >>> b = FP('b', FPSort(8, 24))
8533  >>> is_fp(b)
8534  True
8535  >>> is_fp(b + 1.0)
8536  True
8537  >>> is_fp(Int('x'))
8538  False
8539  """
8540  return isinstance(a, FPRef)
8541 
8542 def is_fp_value(a):
8543  """Return `True` if `a` is a Z3 floating-point numeral value.
8544 
8545  >>> b = FP('b', FPSort(8, 24))
8546  >>> is_fp_value(b)
8547  False
8548  >>> b = FPVal(1.0, FPSort(8, 24))
8549  >>> b
8550  1
8551  >>> is_fp_value(b)
8552  True
8553  """
8554  return is_fp(a) and _is_numeral(a.ctx, a.ast)
8555 
8556 def FPSort(ebits, sbits, ctx=None):
8557  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
8558 
8559  >>> Single = FPSort(8, 24)
8560  >>> Double = FPSort(11, 53)
8561  >>> Single
8562  FPSort(8, 24)
8563  >>> x = Const('x', Single)
8564  >>> eq(x, FP('x', FPSort(8, 24)))
8565  True
8566  """
8567  ctx = _get_ctx(ctx)
8568  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
8569 
8570 def _to_float_str(val, exp=0):
8571  if isinstance(val, float):
8572  if math.isnan(val):
8573  res = "NaN"
8574  elif val == 0.0:
8575  sone = math.copysign(1.0, val)
8576  if sone < 0.0:
8577  return "-0.0"
8578  else:
8579  return "+0.0"
8580  elif val == float("+inf"):
8581  res = "+oo"
8582  elif val == float("-inf"):
8583  res = "-oo"
8584  else:
8585  v = val.as_integer_ratio()
8586  num = v[0]
8587  den = v[1]
8588  rvs = str(num) + '/' + str(den)
8589  res = rvs + 'p' + _to_int_str(exp)
8590  elif isinstance(val, bool):
8591  if val:
8592  res = "1.0"
8593  else:
8594  res = "0.0"
8595  elif _is_int(val):
8596  res = str(val)
8597  elif isinstance(val, str):
8598  inx = val.find('*(2**')
8599  if inx == -1:
8600  res = val
8601  elif val[-1] == ')':
8602  res = val[0:inx]
8603  exp = str(int(val[inx+5:-1]) + int(exp))
8604  else:
8605  _z3_assert(False, "String does not have floating-point numeral form.")
8606  elif __debug__:
8607  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
8608  if exp == 0:
8609  return res
8610  else:
8611  return res + 'p' + exp
8612 
8613 
8614 def fpNaN(s):
8615  """Create a Z3 floating-point NaN term.
8616 
8617  >>> s = FPSort(8, 24)
8618  >>> set_fpa_pretty(True)
8619  >>> fpNaN(s)
8620  NaN
8621  >>> pb = get_fpa_pretty()
8622  >>> set_fpa_pretty(False)
8623  >>> fpNaN(s)
8624  fpNaN(FPSort(8, 24))
8625  >>> set_fpa_pretty(pb)
8626  """
8627  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8628  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
8629 
8630 def fpPlusInfinity(s):
8631  """Create a Z3 floating-point +oo term.
8632 
8633  >>> s = FPSort(8, 24)
8634  >>> pb = get_fpa_pretty()
8635  >>> set_fpa_pretty(True)
8636  >>> fpPlusInfinity(s)
8637  +oo
8638  >>> set_fpa_pretty(False)
8639  >>> fpPlusInfinity(s)
8640  fpPlusInfinity(FPSort(8, 24))
8641  >>> set_fpa_pretty(pb)
8642  """
8643  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8644  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
8645 
8646 def fpMinusInfinity(s):
8647  """Create a Z3 floating-point -oo term."""
8648  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8649  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
8650 
8651 def fpInfinity(s, negative):
8652  """Create a Z3 floating-point +oo or -oo term."""
8653  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8654  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
8655  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
8656 
8657 def fpPlusZero(s):
8658  """Create a Z3 floating-point +0.0 term."""
8659  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8660  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
8661 
8662 def fpMinusZero(s):
8663  """Create a Z3 floating-point -0.0 term."""
8664  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8665  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
8666 
8667 def fpZero(s, negative):
8668  """Create a Z3 floating-point +0.0 or -0.0 term."""
8669  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8670  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
8671  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
8672 
8673 def FPVal(sig, exp=None, fps=None, ctx=None):
8674  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
8675 
8676  >>> v = FPVal(20.0, FPSort(8, 24))
8677  >>> v
8678  1.25*(2**4)
8679  >>> print("0x%.8x" % v.exponent_as_long())
8680  0x00000004
8681  >>> v = FPVal(2.25, FPSort(8, 24))
8682  >>> v
8683  1.125*(2**1)
8684  >>> v = FPVal(-2.25, FPSort(8, 24))
8685  >>> v
8686  -1.125*(2**1)
8687  >>> FPVal(-0.0, FPSort(8, 24))
8688  -0.0
8689  >>> FPVal(0.0, FPSort(8, 24))
8690  +0.0
8691  >>> FPVal(+0.0, FPSort(8, 24))
8692  +0.0
8693  """
8694  ctx = _get_ctx(ctx)
8695  if is_fp_sort(exp):
8696  fps = exp
8697  exp = None
8698  elif fps is None:
8699  fps = _dflt_fps(ctx)
8700  _z3_assert(is_fp_sort(fps), "sort mismatch")
8701  if exp is None:
8702  exp = 0
8703  val = _to_float_str(sig)
8704  if val == "NaN" or val == "nan":
8705  return fpNaN(fps)
8706  elif val == "-0.0":
8707  return fpMinusZero(fps)
8708  elif val == "0.0" or val == "+0.0":
8709  return fpPlusZero(fps)
8710  elif val == "+oo" or val == "+inf" or val == "+Inf":
8711  return fpPlusInfinity(fps)
8712  elif val == "-oo" or val == "-inf" or val == "-Inf":
8713  return fpMinusInfinity(fps)
8714  else:
8715  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
8716 
8717 def FP(name, fpsort, ctx=None):
8718  """Return a floating-point constant named `name`.
8719  `fpsort` is the floating-point sort.
8720  If `ctx=None`, then the global context is used.
8721 
8722  >>> x = FP('x', FPSort(8, 24))
8723  >>> is_fp(x)
8724  True
8725  >>> x.ebits()
8726  8
8727  >>> x.sort()
8728  FPSort(8, 24)
8729  >>> word = FPSort(8, 24)
8730  >>> x2 = FP('x', word)
8731  >>> eq(x, x2)
8732  True
8733  """
8734  if isinstance(fpsort, FPSortRef) and ctx is None:
8735  ctx = fpsort.ctx
8736  else:
8737  ctx = _get_ctx(ctx)
8738  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
8739 
8740 def FPs(names, fpsort, ctx=None):
8741  """Return an array of floating-point constants.
8742 
8743  >>> x, y, z = FPs('x y z', FPSort(8, 24))
8744  >>> x.sort()
8745  FPSort(8, 24)
8746  >>> x.sbits()
8747  24
8748  >>> x.ebits()
8749  8
8750  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
8751  fpMul(RNE(), fpAdd(RNE(), x, y), z)
8752  """
8753  ctx = _get_ctx(ctx)
8754  if isinstance(names, str):
8755  names = names.split(" ")
8756  return [FP(name, fpsort, ctx) for name in names]
8757 
8758 def fpAbs(a, ctx=None):
8759  """Create a Z3 floating-point absolute value expression.
8760 
8761  >>> s = FPSort(8, 24)
8762  >>> rm = RNE()
8763  >>> x = FPVal(1.0, s)
8764  >>> fpAbs(x)
8765  fpAbs(1)
8766  >>> y = FPVal(-20.0, s)
8767  >>> y
8768  -1.25*(2**4)
8769  >>> fpAbs(y)
8770  fpAbs(-1.25*(2**4))
8771  >>> fpAbs(-1.25*(2**4))
8772  fpAbs(-1.25*(2**4))
8773  >>> fpAbs(x).sort()
8774  FPSort(8, 24)
8775  """
8776  ctx = _get_ctx(ctx)
8777  [a] = _coerce_fp_expr_list([a], ctx)
8778  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
8779 
8780 def fpNeg(a, ctx=None):
8781  """Create a Z3 floating-point addition expression.
8782 
8783  >>> s = FPSort(8, 24)
8784  >>> rm = RNE()
8785  >>> x = FP('x', s)
8786  >>> fpNeg(x)
8787  -x
8788  >>> fpNeg(x).sort()
8789  FPSort(8, 24)
8790  """
8791  ctx = _get_ctx(ctx)
8792  [a] = _coerce_fp_expr_list([a], ctx)
8793  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
8794 
8795 def _mk_fp_unary(f, rm, a, ctx):
8796  ctx = _get_ctx(ctx)
8797  [a] = _coerce_fp_expr_list([a], ctx)
8798  if __debug__:
8799  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8800  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
8801  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
8802 
8803 def _mk_fp_unary_norm(f, a, ctx):
8804  ctx = _get_ctx(ctx)
8805  [a] = _coerce_fp_expr_list([a], ctx)
8806  if __debug__:
8807  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
8808  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
8809 
8810 def _mk_fp_unary_pred(f, a, ctx):
8811  ctx = _get_ctx(ctx)
8812  [a] = _coerce_fp_expr_list([a], ctx)
8813  if __debug__:
8814  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8815  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
8816 
8817 def _mk_fp_bin(f, rm, a, b, ctx):
8818  ctx = _get_ctx(ctx)
8819  [a, b] = _coerce_fp_expr_list([a, b], ctx)
8820  if __debug__:
8821  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8822  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8823  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
8824 
8825 def _mk_fp_bin_norm(f, a, b, ctx):
8826  ctx = _get_ctx(ctx)
8827  [a, b] = _coerce_fp_expr_list([a, b], ctx)
8828  if __debug__:
8829  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
8830  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
8831 
8832 def _mk_fp_bin_pred(f, a, b, ctx):
8833  ctx = _get_ctx(ctx)
8834  [a, b] = _coerce_fp_expr_list([a, b], ctx)
8835  if __debug__:
8836  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8837  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
8838 
8839 def _mk_fp_tern(f, rm, a, b, c, ctx):
8840  ctx = _get_ctx(ctx)
8841  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
8842  if __debug__:
8843  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8844  _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")
8845  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
8846 
8847 def fpAdd(rm, a, b, ctx=None):
8848  """Create a Z3 floating-point addition expression.
8849 
8850  >>> s = FPSort(8, 24)
8851  >>> rm = RNE()
8852  >>> x = FP('x', s)
8853  >>> y = FP('y', s)
8854  >>> fpAdd(rm, x, y)
8855  fpAdd(RNE(), x, y)
8856  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
8857  x + y
8858  >>> fpAdd(rm, x, y).sort()
8859  FPSort(8, 24)
8860  """
8861  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
8862 
8863 def fpSub(rm, a, b, ctx=None):
8864  """Create a Z3 floating-point subtraction expression.
8865 
8866  >>> s = FPSort(8, 24)
8867  >>> rm = RNE()
8868  >>> x = FP('x', s)
8869  >>> y = FP('y', s)
8870  >>> fpSub(rm, x, y)
8871  fpSub(RNE(), x, y)
8872  >>> fpSub(rm, x, y).sort()
8873  FPSort(8, 24)
8874  """
8875  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
8876 
8877 def fpMul(rm, a, b, ctx=None):
8878  """Create a Z3 floating-point multiplication expression.
8879 
8880  >>> s = FPSort(8, 24)
8881  >>> rm = RNE()
8882  >>> x = FP('x', s)
8883  >>> y = FP('y', s)
8884  >>> fpMul(rm, x, y)
8885  fpMul(RNE(), x, y)
8886  >>> fpMul(rm, x, y).sort()
8887  FPSort(8, 24)
8888  """
8889  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
8890 
8891 def fpDiv(rm, a, b, ctx=None):
8892  """Create a Z3 floating-point divison expression.
8893 
8894  >>> s = FPSort(8, 24)
8895  >>> rm = RNE()
8896  >>> x = FP('x', s)
8897  >>> y = FP('y', s)
8898  >>> fpDiv(rm, x, y)
8899  fpDiv(RNE(), x, y)
8900  >>> fpDiv(rm, x, y).sort()
8901  FPSort(8, 24)
8902  """
8903  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
8904 
8905 def fpRem(a, b, ctx=None):
8906  """Create a Z3 floating-point remainder expression.
8907 
8908  >>> s = FPSort(8, 24)
8909  >>> x = FP('x', s)
8910  >>> y = FP('y', s)
8911  >>> fpRem(x, y)
8912  fpRem(x, y)
8913  >>> fpRem(x, y).sort()
8914  FPSort(8, 24)
8915  """
8916  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
8917 
8918 def fpMin(a, b, ctx=None):
8919  """Create a Z3 floating-point minimium expression.
8920 
8921  >>> s = FPSort(8, 24)
8922  >>> rm = RNE()
8923  >>> x = FP('x', s)
8924  >>> y = FP('y', s)
8925  >>> fpMin(x, y)
8926  fpMin(x, y)
8927  >>> fpMin(x, y).sort()
8928  FPSort(8, 24)
8929  """
8930  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
8931 
8932 def fpMax(a, b, ctx=None):
8933  """Create a Z3 floating-point maximum expression.
8934 
8935  >>> s = FPSort(8, 24)
8936  >>> rm = RNE()
8937  >>> x = FP('x', s)
8938  >>> y = FP('y', s)
8939  >>> fpMax(x, y)
8940  fpMax(x, y)
8941  >>> fpMax(x, y).sort()
8942  FPSort(8, 24)
8943  """
8944  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
8945 
8946 def fpFMA(rm, a, b, c, ctx=None):
8947  """Create a Z3 floating-point fused multiply-add expression.
8948  """
8949  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
8950 
8951 def fpSqrt(rm, a, ctx=None):
8952  """Create a Z3 floating-point square root expression.
8953  """
8954  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
8955 
8956 def fpRoundToIntegral(rm, a, ctx=None):
8957  """Create a Z3 floating-point roundToIntegral expression.
8958  """
8959  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
8960 
8961 def fpIsNaN(a, ctx=None):
8962  """Create a Z3 floating-point isNaN expression.
8963 
8964  >>> s = FPSort(8, 24)
8965  >>> x = FP('x', s)
8966  >>> y = FP('y', s)
8967  >>> fpIsNaN(x)
8968  fpIsNaN(x)
8969  """
8970  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
8971 
8972 def fpIsInf(a, ctx=None):
8973  """Create a Z3 floating-point isInfinite expression.
8974 
8975  >>> s = FPSort(8, 24)
8976  >>> x = FP('x', s)
8977  >>> fpIsInf(x)
8978  fpIsInf(x)
8979  """
8980  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
8981 
8982 def fpIsZero(a, ctx=None):
8983  """Create a Z3 floating-point isZero expression.
8984  """
8985  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
8986 
8987 def fpIsNormal(a, ctx=None):
8988  """Create a Z3 floating-point isNormal expression.
8989  """
8990  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
8991 
8992 def fpIsSubnormal(a, ctx=None):
8993  """Create a Z3 floating-point isSubnormal expression.
8994  """
8995  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
8996 
8997 def fpIsNegative(a, ctx=None):
8998  """Create a Z3 floating-point isNegative expression.
8999  """
9000  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9001 
9002 def fpIsPositive(a, ctx=None):
9003  """Create a Z3 floating-point isPositive expression.
9004  """
9005  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9006  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9007 
9008 def _check_fp_args(a, b):
9009  if __debug__:
9010  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9011 
9012 def fpLT(a, b, ctx=None):
9013  """Create the Z3 floating-point expression `other < self`.
9014 
9015  >>> x, y = FPs('x y', FPSort(8, 24))
9016  >>> fpLT(x, y)
9017  x < y
9018  >>> (x < y).sexpr()
9019  '(fp.lt x y)'
9020  """
9021  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9022 
9023 def fpLEQ(a, b, ctx=None):
9024  """Create the Z3 floating-point expression `other <= self`.
9025 
9026  >>> x, y = FPs('x y', FPSort(8, 24))
9027  >>> fpLEQ(x, y)
9028  x <= y
9029  >>> (x <= y).sexpr()
9030  '(fp.leq x y)'
9031  """
9032  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9033 
9034 def fpGT(a, b, ctx=None):
9035  """Create the Z3 floating-point expression `other > self`.
9036 
9037  >>> x, y = FPs('x y', FPSort(8, 24))
9038  >>> fpGT(x, y)
9039  x > y
9040  >>> (x > y).sexpr()
9041  '(fp.gt x y)'
9042  """
9043  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9044 
9045 def fpGEQ(a, b, ctx=None):
9046  """Create the Z3 floating-point expression `other >= self`.
9047 
9048  >>> x, y = FPs('x y', FPSort(8, 24))
9049  >>> fpGEQ(x, y)
9050  x >= y
9051  >>> (x >= y).sexpr()
9052  '(fp.geq x y)'
9053  """
9054  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9055 
9056 def fpEQ(a, b, ctx=None):
9057  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9058 
9059  >>> x, y = FPs('x y', FPSort(8, 24))
9060  >>> fpEQ(x, y)
9061  fpEQ(x, y)
9062  >>> fpEQ(x, y).sexpr()
9063  '(fp.eq x y)'
9064  """
9065  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9066 
9067 def fpNEQ(a, b, ctx=None):
9068  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9069 
9070  >>> x, y = FPs('x y', FPSort(8, 24))
9071  >>> fpNEQ(x, y)
9072  Not(fpEQ(x, y))
9073  >>> (x != y).sexpr()
9074  '(distinct x y)'
9075  """
9076  return Not(fpEQ(a, b, ctx))
9077 
9078 def fpFP(sgn, exp, sig, ctx=None):
9079  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9080 
9081  >>> s = FPSort(8, 24)
9082  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9083  >>> print(x)
9084  fpFP(1, 127, 4194304)
9085  >>> xv = FPVal(-1.5, s)
9086  >>> print(xv)
9087  -1.5
9088  >>> slvr = Solver()
9089  >>> slvr.add(fpEQ(x, xv))
9090  >>> slvr.check()
9091  sat
9092  >>> xv = FPVal(+1.5, s)
9093  >>> print(xv)
9094  1.5
9095  >>> slvr = Solver()
9096  >>> slvr.add(fpEQ(x, xv))
9097  >>> slvr.check()
9098  unsat
9099  """
9100  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9101  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9102  ctx = _get_ctx(ctx)
9103  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9104  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9105 
9106 def fpToFP(a1, a2=None, a3=None, ctx=None):
9107  """Create a Z3 floating-point conversion expression from other term sorts
9108  to floating-point.
9109 
9110  From a bit-vector term in IEEE 754-2008 format:
9111  >>> x = FPVal(1.0, Float32())
9112  >>> x_bv = fpToIEEEBV(x)
9113  >>> simplify(fpToFP(x_bv, Float32()))
9114  1
9115 
9116  From a floating-point term with different precision:
9117  >>> x = FPVal(1.0, Float32())
9118  >>> x_db = fpToFP(RNE(), x, Float64())
9119  >>> x_db.sort()
9120  FPSort(11, 53)
9121 
9122  From a real term:
9123  >>> x_r = RealVal(1.5)
9124  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9125  1.5
9126 
9127  From a signed bit-vector term:
9128  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9129  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9130  -1.25*(2**2)
9131  """
9132  ctx = _get_ctx(ctx)
9133  if is_bv(a1) and is_fp_sort(a2):
9134  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9135  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9136  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9137  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9138  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9139  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9140  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9141  else:
9142  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9143 
9144 def fpBVToFP(v, sort, ctx=None):
9145  """Create a Z3 floating-point conversion expression that represents the
9146  conversion from a bit-vector term to a floating-point term.
9147 
9148  >>> x_bv = BitVecVal(0x3F800000, 32)
9149  >>> x_fp = fpBVToFP(x_bv, Float32())
9150  >>> x_fp
9151  fpToFP(1065353216)
9152  >>> simplify(x_fp)
9153  1
9154  """
9155  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9156  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9157  ctx = _get_ctx(ctx)
9158  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9159 
9160 def fpFPToFP(rm, v, sort, ctx=None):
9161  """Create a Z3 floating-point conversion expression that represents the
9162  conversion from a floating-point term to a floating-point term of different precision.
9163 
9164  >>> x_sgl = FPVal(1.0, Float32())
9165  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9166  >>> x_dbl
9167  fpToFP(RNE(), 1)
9168  >>> simplify(x_dbl)
9169  1
9170  >>> x_dbl.sort()
9171  FPSort(11, 53)
9172  """
9173  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9174  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9175  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9176  ctx = _get_ctx(ctx)
9177  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9178 
9179 def fpRealToFP(rm, v, sort, ctx=None):
9180  """Create a Z3 floating-point conversion expression that represents the
9181  conversion from a real term to a floating-point term.
9182 
9183  >>> x_r = RealVal(1.5)
9184  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9185  >>> x_fp
9186  fpToFP(RNE(), 3/2)
9187  >>> simplify(x_fp)
9188  1.5
9189  """
9190  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9191  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9192  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9193  ctx = _get_ctx(ctx)
9194  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9195 
9196 def fpSignedToFP(rm, v, sort, ctx=None):
9197  """Create a Z3 floating-point conversion expression that represents the
9198  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9199 
9200  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9201  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9202  >>> x_fp
9203  fpToFP(RNE(), 4294967291)
9204  >>> simplify(x_fp)
9205  -1.25*(2**2)
9206  """
9207  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9208  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9209  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9210  ctx = _get_ctx(ctx)
9211  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9212 
9213 def fpUnsignedToFP(rm, v, sort, ctx=None):
9214  """Create a Z3 floating-point conversion expression that represents the
9215  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9216 
9217  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9218  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9219  >>> x_fp
9220  fpToFPUnsigned(RNE(), 4294967291)
9221  >>> simplify(x_fp)
9222  1*(2**32)
9223  """
9224  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9225  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9226  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9227  ctx = _get_ctx(ctx)
9228  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9229 
9230 def fpToFPUnsigned(rm, x, s, ctx=None):
9231  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9232  if __debug__:
9233  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9234  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9235  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9236  ctx = _get_ctx(ctx)
9237  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9238 
9239 def fpToSBV(rm, x, s, ctx=None):
9240  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9241 
9242  >>> x = FP('x', FPSort(8, 24))
9243  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9244  >>> print(is_fp(x))
9245  True
9246  >>> print(is_bv(y))
9247  True
9248  >>> print(is_fp(y))
9249  False
9250  >>> print(is_bv(x))
9251  False
9252  """
9253  if __debug__:
9254  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9255  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9256  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9257  ctx = _get_ctx(ctx)
9258  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9259 
9260 def fpToUBV(rm, x, s, ctx=None):
9261  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9262 
9263  >>> x = FP('x', FPSort(8, 24))
9264  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9265  >>> print(is_fp(x))
9266  True
9267  >>> print(is_bv(y))
9268  True
9269  >>> print(is_fp(y))
9270  False
9271  >>> print(is_bv(x))
9272  False
9273  """
9274  if __debug__:
9275  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9276  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9277  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9278  ctx = _get_ctx(ctx)
9279  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9280 
9281 def fpToReal(x, ctx=None):
9282  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9283 
9284  >>> x = FP('x', FPSort(8, 24))
9285  >>> y = fpToReal(x)
9286  >>> print(is_fp(x))
9287  True
9288  >>> print(is_real(y))
9289  True
9290  >>> print(is_fp(y))
9291  False
9292  >>> print(is_real(x))
9293  False
9294  """
9295  if __debug__:
9296  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9297  ctx = _get_ctx(ctx)
9298  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9299 
9300 def fpToIEEEBV(x, ctx=None):
9301  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9302 
9303  The size of the resulting bit-vector is automatically determined.
9304 
9305  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9306  knows only one NaN and it will always produce the same bit-vector represenatation of
9307  that NaN.
9308 
9309  >>> x = FP('x', FPSort(8, 24))
9310  >>> y = fpToIEEEBV(x)
9311  >>> print(is_fp(x))
9312  True
9313  >>> print(is_bv(y))
9314  True
9315  >>> print(is_fp(y))
9316  False
9317  >>> print(is_bv(x))
9318  False
9319  """
9320  if __debug__:
9321  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9322  ctx = _get_ctx(ctx)
9323  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9324 
9325 
9326 
9327 #########################################
9328 #
9329 # Strings, Sequences and Regular expressions
9330 #
9331 #########################################
9332 
9333 class SeqSortRef(SortRef):
9334  """Sequence sort."""
9335 
9336  def is_string(self):
9337  """Determine if sort is a string
9338  >>> s = StringSort()
9339  >>> s.is_string()
9340  True
9341  >>> s = SeqSort(IntSort())
9342  >>> s.is_string()
9343  False
9344  """
9345  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9346 
9347 def StringSort(ctx=None):
9348  """Create a string sort
9349  >>> s = StringSort()
9350  >>> print(s)
9351  String
9352  """
9353  ctx = _get_ctx(ctx)
9354  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9355 
9356 
9357 def SeqSort(s):
9358  """Create a sequence sort over elements provided in the argument
9359  >>> s = SeqSort(IntSort())
9360  >>> s == Unit(IntVal(1)).sort()
9361  True
9362  """
9363  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9364 
9365 class SeqRef(ExprRef):
9366  """Sequence expression."""
9367 
9368  def sort(self):
9369  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9370 
9371  def __add__(self, other):
9372  return Concat(self, other)
9373 
9374  def __radd__(self, other):
9375  return Concat(other, self)
9376 
9377  def __getitem__(self, i):
9378  if _is_int(i):
9379  i = IntVal(i, self.ctx)
9380  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9381 
9382  def is_string(self):
9383  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9384 
9385  def is_string_value(self):
9386  return Z3_is_string(self.ctx_ref(), self.as_ast())
9387 
9388  def as_string(self):
9389  """Return a string representation of sequence expression."""
9390  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9391 
9392 
9393 def _coerce_seq(s, ctx=None):
9394  if isinstance(s, str):
9395  ctx = _get_ctx(ctx)
9396  s = StringVal(s, ctx)
9397  if not is_expr(s):
9398  raise Z3Exception("Non-expression passed as a sequence")
9399  if not is_seq(s):
9400  raise Z3Exception("Non-sequence passed as a sequence")
9401  return s
9402 
9403 def _get_ctx2(a, b, ctx=None):
9404  if is_expr(a):
9405  return a.ctx
9406  if is_expr(b):
9407  return b.ctx
9408  if ctx is None:
9409  ctx = main_ctx()
9410  return ctx
9411 
9412 def is_seq(a):
9413  """Return `True` if `a` is a Z3 sequence expression.
9414  >>> print (is_seq(Unit(IntVal(0))))
9415  True
9416  >>> print (is_seq(StringVal("abc")))
9417  True
9418  """
9419  return isinstance(a, SeqRef)
9420 
9421 def is_string(a):
9422  """Return `True` if `a` is a Z3 string expression.
9423  >>> print (is_string(StringVal("ab")))
9424  True
9425  """
9426  return isinstance(a, SeqRef) and a.is_string()
9427 
9428 def is_string_value(a):
9429  """return 'True' if 'a' is a Z3 string constant expression.
9430  >>> print (is_string_value(StringVal("a")))
9431  True
9432  >>> print (is_string_value(StringVal("a") + StringVal("b")))
9433  False
9434  """
9435  return isinstance(a, SeqRef) and a.is_string_value()
9436 
9437 
9438 def StringVal(s, ctx=None):
9439  """create a string expression"""
9440  ctx = _get_ctx(ctx)
9441  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
9442 
9443 def String(name, ctx=None):
9444  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
9445 
9446  >>> x = String('x')
9447  """
9448  ctx = _get_ctx(ctx)
9449  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
9450 
9451 def Strings(names, ctx=None):
9452  """Return a tuple of String constants. """
9453  ctx = _get_ctx(ctx)
9454  if isinstance(names, str):
9455  names = names.split(" ")
9456  return [String(name, ctx) for name in names]
9457 
9458 def Empty(s):
9459  """Create the empty sequence of the given sort
9460  >>> e = Empty(StringSort())
9461  >>> print(e)
9462  ""
9463  >>> e2 = StringVal("")
9464  >>> print(e.eq(e2))
9465  True
9466  >>> e3 = Empty(SeqSort(IntSort()))
9467  >>> print(e3)
9468  seq.empty
9469  """
9470  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
9471 
9472 def Unit(a):
9473  """Create a singleton sequence"""
9474  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
9475 
9476 def PrefixOf(a, b):
9477  """Check if 'a' is a prefix of 'b'
9478  >>> s1 = PrefixOf("ab", "abc")
9479  >>> simplify(s1)
9480  True
9481  >>> s2 = PrefixOf("bc", "abc")
9482  >>> simplify(s2)
9483  False
9484  """
9485  ctx = _get_ctx2(a, b)
9486  a = _coerce_seq(a, ctx)
9487  b = _coerce_seq(b, ctx)
9488  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9489 
9490 def SuffixOf(a, b):
9491  """Check if 'a' is a suffix of 'b'
9492  >>> s1 = SuffixOf("ab", "abc")
9493  >>> simplify(s1)
9494  False
9495  >>> s2 = SuffixOf("bc", "abc")
9496  >>> simplify(s2)
9497  True
9498  """
9499  ctx = _get_ctx2(a, b)
9500  a = _coerce_seq(a, ctx)
9501  b = _coerce_seq(b, ctx)
9502  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9503 
9504 def Contains(a, b):
9505  """Check if 'a' contains 'b'
9506  >>> s1 = Contains("abc", "ab")
9507  >>> simplify(s1)
9508  True
9509  >>> s2 = Contains("abc", "bc")
9510  >>> simplify(s2)
9511  True
9512  >>> x, y, z = Strings('x y z')
9513  >>> s3 = Contains(Concat(x,y,z), y)
9514  >>> simplify(s3)
9515  True
9516  """
9517  ctx = _get_ctx2(a, b)
9518  a = _coerce_seq(a, ctx)
9519  b = _coerce_seq(b, ctx)
9520  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9521 
9522 
9523 def Replace(s, src, dst):
9524  """Replace the first occurrence of 'src' by 'dst' in 's'
9525  >>> r = Replace("aaa", "a", "b")
9526  >>> simplify(r)
9527  "baa"
9528  """
9529  ctx = _get_ctx2(dst, s)
9530  if ctx is None and is_expr(src):
9531  ctx = src.ctx
9532  src = _coerce_seq(src, ctx)
9533  dst = _coerce_seq(dst, ctx)
9534  s = _coerce_seq(s, ctx)
9535  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
9536 
9537 def IndexOf(s, substr):
9538  return IndexOf(s, substr, IntVal(0))
9539 
9540 def IndexOf(s, substr, offset):
9541  """Retrieve the index of substring within a string starting at a specified offset.
9542  >>> simplify(IndexOf("abcabc", "bc", 0))
9543  1
9544  >>> simplify(IndexOf("abcabc", "bc", 2))
9545  4
9546  """
9547  ctx = None
9548  if is_expr(offset):
9549  ctx = offset.ctx
9550  ctx = _get_ctx2(s, substr, ctx)
9551  s = _coerce_seq(s, ctx)
9552  substr = _coerce_seq(substr, ctx)
9553  if _is_int(offset):
9554  offset = IntVal(offset, ctx)
9555  return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
9556 
9557 def Length(s):
9558  """Obtain the length of a sequence 's'
9559  >>> l = Length(StringVal("abc"))
9560  >>> simplify(l)
9561  3
9562  """
9563  s = _coerce_seq(s)
9564  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
9565 
9566 def Re(s, ctx=None):
9567  """The regular expression that accepts sequence 's'
9568  >>> s1 = Re("ab")
9569  >>> s2 = Re(StringVal("ab"))
9570  >>> s3 = Re(Unit(BoolVal(True)))
9571  """
9572  s = _coerce_seq(s, ctx)
9573  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
9574 
9575 
9576 
9577 
9578 ## Regular expressions
9579 
9580 class ReSortRef(SortRef):
9581  """Regular expression sort."""
9582 
9583 
9584 def ReSort(s):
9585  if is_ast(s):
9586  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.as_ast()), ctx)
9587  if s is None or isinstance(s, Context):
9588  ctx = _get_ctx(s)
9589  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), ctx)
9590  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
9591 
9592 
9593 class ReRef(ExprRef):
9594  """Regular expressions."""
9595 
9596  def __add__(self, other):
9597  return Union(self, other)
9598 
9599 
9600 def is_re(s):
9601  return isinstance(s, ReRef)
9602 
9603 
9604 def InRe(s, re):
9605  """Create regular expression membership test
9606  >>> re = Union(Re("a"),Re("b"))
9607  >>> print (simplify(InRe("a", re)))
9608  True
9609  >>> print (simplify(InRe("b", re)))
9610  True
9611  >>> print (simplify(InRe("c", re)))
9612  False
9613  """
9614  s = _coerce_seq(s, re.ctx)
9615  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
9616 
9617 def Union(*args):
9618  """Create union of regular expressions.
9619  >>> re = Union(Re("a"), Re("b"), Re("c"))
9620  >>> print (simplify(InRe("d", re)))
9621  False
9622  """
9623  args = _get_args(args)
9624  sz = len(args)
9625  if __debug__:
9626  _z3_assert(sz > 0, "At least one argument expected.")
9627  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
9628  if sz == 1:
9629  return args[0]
9630  ctx = args[0].ctx
9631  v = (Ast * sz)()
9632  for i in range(sz):
9633  v[i] = args[i].as_ast()
9634  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
9635 
9636 def Plus(re):
9637  """Create the regular expression accepting one or more repetitions of argument.
9638  >>> re = Plus(Re("a"))
9639  >>> print(simplify(InRe("aa", re)))
9640  True
9641  >>> print(simplify(InRe("ab", re)))
9642  False
9643  >>> print(simplify(InRe("", re)))
9644  False
9645  """
9646  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
9647 
9648 def Option(re):
9649  """Create the regular expression that optionally accepts the argument.
9650  >>> re = Option(Re("a"))
9651  >>> print(simplify(InRe("a", re)))
9652  True
9653  >>> print(simplify(InRe("", re)))
9654  True
9655  >>> print(simplify(InRe("aa", re)))
9656  False
9657  """
9658  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
9659 
9660 def Star(re):
9661  """Create the regular expression accepting zero or more repetitions of argument.
9662  >>> re = Star(Re("a"))
9663  >>> print(simplify(InRe("aa", re)))
9664  True
9665  >>> print(simplify(InRe("ab", re)))
9666  False
9667  >>> print(simplify(InRe("", re)))
9668  True
9669  """
9670  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
def param_descrs(self)
Definition: z3py.py:6709
def value(self)
Definition: z3py.py:6681
def lower(self, obj)
Definition: z3py.py:6781
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:640
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9300
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]).
def is_lt(a)
Definition: z3py.py:2491
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:7468
def __ge__(self, other)
Definition: z3py.py:7280
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.
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:2895
def is_distinct(a)
Definition: z3py.py:1396
def __gt__(self, other)
Definition: z3py.py:7254
def Then(ts, ks)
Definition: z3py.py:7068
def PbEq(args, k)
Definition: z3py.py:7657
def SignExt(n, a)
Definition: z3py.py:3868
def update_rule(self, head, body, name)
Definition: z3py.py:6442
def SeqSort(s)
Definition: z3py.py:9357
Fixedpoint.
Definition: z3py.py:6319
def upper(self)
Definition: z3py.py:6677
def OrElse(ts, ks)
Definition: z3py.py:7080
def is_fprm_sort(s)
Definition: z3py.py:8199
def get_version_string()
Definition: z3py.py:67
Quantifiers.
Definition: z3py.py:1686
def AtLeast(args)
Definition: z3py.py:7614
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:4644
def entry(self, idx)
Definition: z3py.py:5411
def get_cover_delta(self, level, predicate)
Definition: z3py.py:6460
def RatVal(a, b, ctx=None)
Definition: z3py.py:2781
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:6723
def __getitem__(self, idx)
Definition: z3py.py:6860
Function Declarations.
Definition: z3py.py:624
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:2882
Booleans.
Definition: z3py.py:1257
def Product(args)
Definition: z3py.py:7572
def prec(self)
Definition: z3py.py:4775
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
def IsInt(a)
Definition: z3py.py:2942
def Sum(args)
Definition: z3py.py:7546
def __repr__(self)
Definition: z3py.py:294
def is_arith_sort(s)
Definition: z3py.py:1993
def push(self)
Definition: z3py.py:6434
def Function(name, sig)
Definition: z3py.py:738
def RTZ(ctx=None)
Definition: z3py.py:8433
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...
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:779
def __iadd__(self, fml)
Definition: z3py.py:6727
def RealSort(ctx=None)
Definition: z3py.py:2721
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9144
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:8740
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:8673
def get_rules(self)
Definition: z3py.py:6493
def RealVarVector(n, ctx=None)
Definition: z3py.py:1240
def sort(self)
Definition: z3py.py:6584
def AndThen(ts, ks)
Definition: z3py.py:7049
def ZeroExt(n, a)
Definition: z3py.py:3897
def assertions(self)
Definition: z3py.py:6799
def substitute_vars(t, m)
Definition: z3py.py:7526
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:1939
def Var(idx, s)
Definition: z3py.py:1218
def __del__(self)
Definition: z3py.py:7237
def is_bool(self)
Definition: z3py.py:1285
def probes(ctx=None)
Definition: z3py.py:7364
def to_symbol(s, ctx=None)
Definition: z3py.py:100
def help(self)
Definition: z3py.py:6229
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...
def reset_params()
Definition: z3py.py:246
def declare(self, name, args)
Definition: z3py.py:4328
def is_string_value(a)
Definition: z3py.py:9428
def as_ast(self)
Definition: z3py.py:325
def assert_exprs(self, args)
Definition: z3py.py:6713
def LShR(a, b)
Definition: z3py.py:3807
def is_default(a)
Definition: z3py.py:4085
def set_option(args, kws)
Definition: z3py.py:251
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:2988
def Consts(names, sort)
Definition: z3py.py:1204
def use_pp(self)
Definition: z3py.py:277
def IntVal(val, ctx=None)
Definition: z3py.py:2752
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...
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:303
def is_and(a)
Definition: z3py.py:1354
def ref(self)
Definition: z3py.py:182
def push(self)
Definition: z3py.py:5929
def fpGT(a, b, ctx=None)
Definition: z3py.py:9034
def sort(self)
Definition: z3py.py:1291
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:7859
def ULT(a, b)
Definition: z3py.py:3696
def fpIsInf(a, ctx=None)
Definition: z3py.py:8972
Arithmetic.
Definition: z3py.py:1922
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.
FP Expressions.
Definition: z3py.py:8211
def __init__(self, ctx=None)
Definition: z3py.py:6690
def minimize(self, arg)
Definition: z3py.py:6754
def help(self)
Definition: z3py.py:6705
def sort(self)
Definition: z3py.py:2011
def is_to_real(a)
Definition: z3py.py:2535
def as_ast(self)
Definition: z3py.py:480
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9106
def assert_exprs(self, args)
Definition: z3py.py:6351
def Float64(ctx=None)
Definition: z3py.py:8165
def param_descrs(self)
Definition: z3py.py:6347
def is_select(a)
Definition: z3py.py:4257
def is_real(self)
Definition: z3py.py:2035
def is_int(self)
Definition: z3py.py:2021
ASTs base class.
Definition: z3py.py:275
def __ne__(self, other)
Definition: z3py.py:829
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9213
def is_gt(a)
Definition: z3py.py:2513
def pop(self)
Definition: z3py.py:6762
def sexpr(self)
Definition: z3py.py:6880
def set_param(args, kws)
Definition: z3py.py:223
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 __eq__(self, other)
Definition: z3py.py:808
def domain(self, i)
Definition: z3py.py:660
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:6588
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:1895
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.
def AtMost(args)
Definition: z3py.py:7597
def register_relation(self, relations)
Definition: z3py.py:6469
def IndexOf(s, substr)
Definition: z3py.py:9537
def is_app(a)
Definition: z3py.py:1029
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9260
def __len__(self)
Definition: z3py.py:6841
def StringSort(ctx=None)
Definition: z3py.py:9347
def And(args)
Definition: z3py.py:1550
def open_log(fname)
Definition: z3py.py:92
def solver(self)
Definition: z3py.py:6969
def PrefixOf(a, b)
Definition: z3py.py:9476
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9045
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def rule(self, head, body=None, name=None)
Definition: z3py.py:6404
def range(self)
Definition: z3py.py:4007
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 __repr__(self)
Definition: z3py.py:6877
def fpRem(a, b, ctx=None)
Definition: z3py.py:8905
def Cbrt(a, ctx=None)
Definition: z3py.py:2970
def disable_trace(msg)
Definition: z3py.py:64
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def RotateRight(a, b)
Definition: z3py.py:3853
def sort(self)
Definition: z3py.py:3033
def is_ge(a)
Definition: z3py.py:2502
def is_K(a)
Definition: z3py.py:4058
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:797
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 tactics(ctx=None)
Definition: z3py.py:7176
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Brujin bound variable.
def is_const(a)
Definition: z3py.py:1054
def Star(re)
Definition: z3py.py:9660
def InRe(s, re)
Definition: z3py.py:9604
def is_finite_domain_sort(s)
Definition: z3py.py:6570
def push(self)
Definition: z3py.py:6758
def RotateLeft(a, b)
Definition: z3py.py:3838
def Const(name, sort)
Definition: z3py.py:1193
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1468
def substitute(t, m)
Definition: z3py.py:7500
def Array(name, dom, rng)
Definition: z3py.py:4131
def main_ctx()
Definition: z3py.py:197
def If(a, b, c, ctx=None)
Definition: z3py.py:1140
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3544
def get_id(self)
Definition: z3py.py:634
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.
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, unsigned __int64 size)
Create a named finite domain sort.
def is_array(a)
Definition: z3py.py:4033
def is_pattern(a)
Definition: z3py.py:1630
Statistics.
Definition: z3py.py:5732
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:7452
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:8542
def help_simplify()
Definition: z3py.py:7492
def fpMax(a, b, ctx=None)
Definition: z3py.py:8932
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:6786
def Int(name, ctx=None)
Definition: z3py.py:2808
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6322
def __repr__(self)
Definition: z3py.py:6807
def __repr__(self)
Definition: z3py.py:6501
Arrays.
Definition: z3py.py:3965
def simplify_param_descrs()
Definition: z3py.py:7496
def is_map(a)
Definition: z3py.py:4070
def is_or(a)
Definition: z3py.py:1365
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9230
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...
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:8877
Patterns.
Definition: z3py.py:1619
def fpAbs(a, ctx=None)
Definition: z3py.py:8758
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9056
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3560
def is_int_value(a)
Definition: z3py.py:2352
def __hash__(self)
Definition: z3py.py:559
def Default(a)
Definition: z3py.py:4165
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:6563
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
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...
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
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 CreateDatatypes(ds)
Definition: z3py.py:4385
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 URem(a, b)
Definition: z3py.py:3767
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def binary_interpolant(a, b, p=None, ctx=None)
Definition: z3py.py:7968
def Union(args)
Definition: z3py.py:9617
def SuffixOf(a, b)
Definition: z3py.py:9490
def __eq__(self, other)
Definition: z3py.py:297
def __mul__(self, other)
Definition: z3py.py:1297
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9196
def is_mod(a)
Definition: z3py.py:2469
def fact(self, head, name=None)
Definition: z3py.py:6408
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 UGE(a, b)
Definition: z3py.py:3713
def Replace(s, src, dst)
Definition: z3py.py:9523
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:2856
def __init__(self, args, kws)
Definition: z3py.py:156
def cast(self, val)
Definition: z3py.py:510
def Length(s)
Definition: z3py.py:9557
def decl(self)
Definition: z3py.py:847
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7132
def Bools(names, ctx=None)
Definition: z3py.py:1453
def is_eq(a)
Definition: z3py.py:1387
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...
def __del__(self)
Definition: z3py.py:178
def Float32(ctx=None)
Definition: z3py.py:8155
def fpIsNaN(a, ctx=None)
Definition: z3py.py:8961
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 statistics(self)
Definition: z3py.py:6816
def depth(self)
Definition: z3py.py:4740
def sort(self)
Definition: z3py.py:785
def is_real(a)
Definition: z3py.py:2328
def RealVal(val, ctx=None)
Definition: z3py.py:2763
def PbLe(args, k)
Definition: z3py.py:7637
def get_id(self)
Definition: z3py.py:782
def Extract(high, low, a)
Definition: z3py.py:3648
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def RealVar(idx, ctx=None)
Definition: z3py.py:1230
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:1876
def solve_using(s, args, keywords)
Definition: z3py.py:7706
def set_predicate_representation(self, f, representations)
Definition: z3py.py:6475
def maximize(self, arg)
Definition: z3py.py:6750
def eq(a, b)
Definition: z3py.py:400
def help(self)
Definition: z3py.py:7013
def __bool__(self)
Definition: z3py.py:306
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 add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:6731
def sexpr(self)
Definition: z3py.py:6811
def is_le(a)
Definition: z3py.py:2480
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
def is_not(a)
Definition: z3py.py:1376
def get_map_func(a)
Definition: z3py.py:4093
def Implies(a, b, ctx=None)
Definition: z3py.py:1495
def __init__(self, tactic, ctx=None)
Definition: z3py.py:6951
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.
def apply(self, goal, arguments, keywords)
Definition: z3py.py:6986
def solve(args, keywords)
Definition: z3py.py:7678
def is_arith(a)
Definition: z3py.py:2290
def __del__(self)
Definition: z3py.py:6965
def is_sort(s)
Definition: z3py.py:563
def objectives(self)
Definition: z3py.py:6803
def Or(args)
Definition: z3py.py:1583
def __init__(self, opt, value, is_max)
Definition: z3py.py:6668
def num_sorts(self)
Definition: z3py.py:5579
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
def add(self, args)
Definition: z3py.py:6365
def hash(self)
Definition: z3py.py:370
def is_int(a)
Definition: z3py.py:2310
def check(self, assumptions)
Definition: z3py.py:6073
def fpPlusInfinity(s)
Definition: z3py.py:8630
def insert(self, args)
Definition: z3py.py:6377
def is_quantifier(a)
Definition: z3py.py:1833
def as_string(self)
Definition: z3py.py:6620
def is_string(a)
Definition: z3py.py:9421
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 StringVal(s, ctx=None)
Definition: z3py.py:9438
def Plus(re)
Definition: z3py.py:9636
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:7003
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:6631
def num_args(self)
Definition: z3py.py:862
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:8556
def __del__(self)
Definition: z3py.py:6837
def prove(claim, keywords)
Definition: z3py.py:7735
def DeclareSort(name, ctx=None)
Definition: z3py.py:600
def Ints(names, ctx=None)
Definition: z3py.py:2820
def parse_file(self, f)
Definition: z3py.py:6489
def Interpolant(a, ctx=None)
Definition: z3py.py:7889
def pop(self)
Definition: z3py.py:6438
def is_true(a)
Definition: z3py.py:1324
def Contains(a, b)
Definition: z3py.py:9504
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 is_finite_domain_value(a)
Definition: z3py.py:6645
def is_real(self)
Definition: z3py.py:1925
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:1482
def Bool(name, ctx=None)
Definition: z3py.py:1442
def probe_description(name, ctx=None)
Definition: z3py.py:7374
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 __del__(self)
Definition: z3py.py:6695
def tactic_description(name, ctx=None)
Definition: z3py.py:7186
def param_descrs(self)
Definition: z3py.py:7017
def RNE(ctx=None)
Definition: z3py.py:8401
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...
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
def is_store(a)
Definition: z3py.py:4269
def get_version()
Definition: z3py.py:75
def from_string(self, s)
Definition: z3py.py:6795
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new (incremental) solver.
def SRem(a, b)
Definition: z3py.py:3787
def FP(name, fpsort, ctx=None)
Definition: z3py.py:8717
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:9239
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:8891
def eq(self, other)
Definition: z3py.py:337
def get_id(self)
Definition: z3py.py:483
def ToReal(a)
Definition: z3py.py:2908
def is_bv_value(a)
Definition: z3py.py:3494
def range(self)
Definition: z3py.py:673
def is_idiv(a)
Definition: z3py.py:2458
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3583
def translate(self, target)
Definition: z3py.py:354
def from_file(self, filename)
Definition: z3py.py:6791
def __init__(self, probe, ctx=None)
Definition: z3py.py:7214
def __ne__(self, other)
Definition: z3py.py:548
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.
def __le__(self, other)
Definition: z3py.py:7267
def cast(self, val)
Definition: z3py.py:1259
def as_func_decl(self)
Definition: z3py.py:637
def size(self)
Definition: z3py.py:3044
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
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:6510
def assertions(self)
Definition: z3py.py:6184
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.
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 Strings(names, ctx=None)
Definition: z3py.py:9451
def get_id(self)
Definition: z3py.py:329
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:8863
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9078
def __lt__(self, other)
Definition: z3py.py:7241
def ArraySort(d, r)
Definition: z3py.py:4110
def create(self)
Definition: z3py.py:4351
def is_const_array(a)
Definition: z3py.py:4046
def fpNaN(s)
Definition: z3py.py:8614
def cast(self, val)
Definition: z3py.py:1957
def as_long(self)
Definition: z3py.py:6608
def sexpr(self)
Definition: z3py.py:316
def reason_unknown(self)
Definition: z3py.py:6770
def kind(self)
Definition: z3py.py:486
def IntSort(ctx=None)
Definition: z3py.py:2705
def Unit(a)
Definition: z3py.py:9472
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
def parse_string(self, s)
Definition: z3py.py:6485
def is_rational_value(a)
Definition: z3py.py:2375
def is_finite_domain(a)
Definition: z3py.py:6592
def fpNeg(a, ctx=None)
Definition: z3py.py:8780
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:9023
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4574
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 sexpr(self)
Definition: z3py.py:6505
def __ne__(self, other)
Definition: z3py.py:7306
def declare_var(self, vars)
Definition: z3py.py:6528
def arg(self, idx)
Definition: z3py.py:878
def sort(self)
Definition: z3py.py:8214
def Xor(a, b, ctx=None)
Definition: z3py.py:1510
def Select(a, i)
Definition: z3py.py:4192
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:6381
def __rmul__(self, other)
Definition: z3py.py:1294
def query(self, query)
Definition: z3py.py:6412
def get_var_index(a)
Definition: z3py.py:1096
def Not(a, ctx=None)
Definition: z3py.py:1525
def MultiPattern(args)
Definition: z3py.py:1649
def BoolVal(val, ctx=None)
Definition: z3py.py:1424
def model(self)
Definition: z3py.py:6774
def is_div(a)
Definition: z3py.py:2442
FP Numerals.
Definition: z3py.py:8455
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.
FP Sorts.
Definition: z3py.py:8110
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 ctx_ref(self)
Definition: z3py.py:333
def help(self)
Definition: z3py.py:6343
def Re(s, ctx=None)
Definition: z3py.py:9566
def fpMin(a, b, ctx=None)
Definition: z3py.py:8918
def is_fp_sort(s)
Definition: z3py.py:8189
Expressions.
Definition: z3py.py:769
def is_app_of(a, k)
Definition: z3py.py:1128
def is_probe(p)
Definition: z3py.py:7348
def is_mul(a)
Definition: z3py.py:2420
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:2843
def subsort(self, other)
Definition: z3py.py:502
def kind(self)
Definition: z3py.py:682
def is_bv_sort(s)
Definition: z3py.py:3020
def Update(a, i, v)
Definition: z3py.py:4144
def With(t, args, keys)
Definition: z3py.py:7136
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:96
def statistics(self)
Definition: z3py.py:6518
def is_add(a)
Definition: z3py.py:2409
def ParOr(ts, ks)
Definition: z3py.py:7100
def K(dom, v)
Definition: z3py.py:4229
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3530
def __hash__(self)
Definition: z3py.py:825
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:2832
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:8847
def get_assertions(self)
Definition: z3py.py:6497
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...
def get_num_levels(self, predicate)
Definition: z3py.py:6456
def UGT(a, b)
Definition: z3py.py:3730
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.
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.
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 get_answer(self)
Definition: z3py.py:6451
def children(self)
Definition: z3py.py:899
def BV2Int(a, is_signed=False)
Definition: z3py.py:3508
def arity(self)
Definition: z3py.py:5397
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def Store(a, i, v)
Definition: z3py.py:4176
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7168
def numerator(self)
Definition: z3py.py:2590
def __str__(self)
Definition: z3py.py:291
def is_int(self)
Definition: z3py.py:1282
def is_ast(a)
Definition: z3py.py:380
def sequence_interpolant(v, p=None, ctx=None)
Definition: z3py.py:7996
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 domain(self)
Definition: z3py.py:3998
def Empty(s)
Definition: z3py.py:9458
def __init__(self, ast, ctx=None)
Definition: z3py.py:282
def UDiv(a, b)
Definition: z3py.py:3747
def convert_model(self, model, idx=0)
Definition: z3py.py:6884
def is_expr(a)
Definition: z3py.py:1007
def __init__(self, result, ctx)
Definition: z3py.py:6832
def abstract(self, fml, is_forall=True)
Definition: z3py.py:6537
def set(self, args, keys)
Definition: z3py.py:6337
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:9281
def Map(f, args)
Definition: z3py.py:4207
def __call__(self, args)
Definition: z3py.py:694
def else_value(self)
Definition: z3py.py:5358
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 subsort(self, other)
Definition: z3py.py:1279
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:7382
def add_cover(self, level, predicate, property)
Definition: z3py.py:6465
def describe_tactics()
Definition: z3py.py:7194
def is_bool(a)
Definition: z3py.py:1307
def Distinct(args)
Definition: z3py.py:1162
def __call__(self, goal)
Definition: z3py.py:7320
def body(self)
Definition: z3py.py:1767
def as_list(self)
Definition: z3py.py:5435
def check(self)
Definition: z3py.py:6766
def arity(self)
Definition: z3py.py:651
def Reals(names, ctx=None)
Definition: z3py.py:2868
def is_bv(a)
Definition: z3py.py:3481
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
def is_var(a)
Definition: z3py.py:1072
def as_expr(self)
Definition: z3py.py:6915
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...
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 fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9160
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9067
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 Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:7149
def RepeatBitVec(n, a)
Definition: z3py.py:3924
def SolverFor(logic, ctx=None)
Definition: z3py.py:6281
def get_full_version()
Definition: z3py.py:83
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7118
def lower(self)
Definition: z3py.py:6673
def as_ast(self)
Definition: z3py.py:631
def is_false(a)
Definition: z3py.py:1341
def set(self, args, keys)
Definition: z3py.py:6699
def ULE(a, b)
Definition: z3py.py:3679
def is_is_int(a)
Definition: z3py.py:2524
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
def enable_trace(msg)
Definition: z3py.py:61
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_...
def name(self)
Definition: z3py.py:525
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9179
def is_fprm(a)
Definition: z3py.py:8437
def __iadd__(self, fml)
Definition: z3py.py:6369
def Option(re)
Definition: z3py.py:9648
def as_signed_long(self)
Definition: z3py.py:3456
def __del__(self)
Definition: z3py.py:6333
def is_func_decl(a)
Definition: z3py.py:726
def interrupt(self)
Definition: z3py.py:186
def is_sub(a)
Definition: z3py.py:2431
def Concat(args)
Definition: z3py.py:3603
def FailIf(p, ctx=None)
Definition: z3py.py:7415
def __hash__(self)
Definition: z3py.py:300
def append(self, args)
Definition: z3py.py:6373
def When(p, t, ctx=None)
Definition: z3py.py:7434
def is_seq(a)
Definition: z3py.py:9412
def is_algebraic_value(a)
Definition: z3py.py:2396
def BoolSort(ctx=None)
Definition: z3py.py:1407
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.
def get_param(name)
Definition: z3py.py:256
def is_to_int(a)
Definition: z3py.py:2549
def __eq__(self, other)
Definition: z3py.py:7293
def Q(a, b, ctx=None)
Definition: z3py.py:2796
def String(name, ctx=None)
Definition: z3py.py:9443
def reason_unknown(self)
Definition: z3py.py:6523
def ToInt(a)
Definition: z3py.py:2925
Z3_model Z3_API Z3_apply_result_convert_model(Z3_context c, Z3_apply_result r, unsigned i, Z3_model m)
Convert a model for the subgoal Z3_apply_result_get_subgoal(c, r, i) into a model for the original go...
def num_entries(self)
Definition: z3py.py:5381
def tree_interpolant(pat, p=None, ctx=None)
Definition: z3py.py:7903
def __del__(self)
Definition: z3py.py:287
def is_fp(a)
Definition: z3py.py:8529
def __eq__(self, other)
Definition: z3py.py:535
def Sqrt(a, ctx=None)
Definition: z3py.py:2958
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...
def fpLT(a, b, ctx=None)
Definition: z3py.py:9012
def SimpleSolver(ctx=None)
Definition: z3py.py:6301