Z3
z3py.py
Go to the documentation of this file.
1 ############################################
2 # Copyright (c) 2012 Microsoft Corporation
3 #
4 # Z3 Python interface
5 #
6 # Author: Leonardo de Moura (leonardo)
7 ############################################
8 
9 """Z3 is a high performance theorem prover developed at Microsoft Research.
10 
11 Z3 is used in many applications such as: software/hardware verification and testing,
12 constraint solving, analysis of hybrid systems, security, biology (in silico analysis),
13 and geometrical problems.
14 
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for
17 https://github.com/Z3prover/z3.git. Your comments are very valuable.
18 
19 Small example:
20 
21 >>> x = Int('x')
22 >>> y = Int('y')
23 >>> s = Solver()
24 >>> s.add(x > 0)
25 >>> s.add(x < 2)
26 >>> s.add(y == x + 1)
27 >>> s.check()
28 sat
29 >>> m = s.model()
30 >>> m[x]
31 1
32 >>> m[y]
33 2
34 
35 Z3 exceptions:
36 
37 >>> try:
38 ... x = BitVec('x', 32)
39 ... y = Bool('y')
40 ... # the expression x + y is type incorrect
41 ... n = x + y
42 ... except Z3Exception as ex:
43 ... print("failed: %s" % ex)
44 failed: sort mismatch
45 """
46 from . import z3core
47 from .z3core import *
48 from .z3types import *
49 from .z3consts import *
50 from .z3printer import *
51 from fractions import Fraction
52 import sys
53 import io
54 import math
55 import copy
56 if sys.version_info.major >= 3:
57  from typing import Iterable
58 
59 Z3_DEBUG = __debug__
60 
61 
62 def z3_debug():
63  global Z3_DEBUG
64  return Z3_DEBUG
65 
66 
67 if sys.version_info.major < 3:
68  def _is_int(v):
69  return isinstance(v, (int, long))
70 else:
71  def _is_int(v):
72  return isinstance(v, int)
73 
74 
75 def enable_trace(msg):
76  Z3_enable_trace(msg)
77 
78 
79 def disable_trace(msg):
80  Z3_disable_trace(msg)
81 
82 
84  major = ctypes.c_uint(0)
85  minor = ctypes.c_uint(0)
86  build = ctypes.c_uint(0)
87  rev = ctypes.c_uint(0)
88  Z3_get_version(major, minor, build, rev)
89  return "%s.%s.%s" % (major.value, minor.value, build.value)
90 
91 
93  major = ctypes.c_uint(0)
94  minor = ctypes.c_uint(0)
95  build = ctypes.c_uint(0)
96  rev = ctypes.c_uint(0)
97  Z3_get_version(major, minor, build, rev)
98  return (major.value, minor.value, build.value, rev.value)
99 
100 
102  return Z3_get_full_version()
103 
104 
105 def _z3_assert(cond, msg):
106  if not cond:
107  raise Z3Exception(msg)
108 
109 
110 def _z3_check_cint_overflow(n, name):
111  _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
112 
113 
114 def open_log(fname):
115  """Log interaction to a file. This function must be invoked immediately after init(). """
116  Z3_open_log(fname)
117 
118 
119 def append_log(s):
120  """Append user-defined string to interaction log. """
121  Z3_append_log(s)
122 
123 
124 def to_symbol(s, ctx=None):
125  """Convert an integer or string into a Z3 symbol."""
126  if _is_int(s):
127  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
128  else:
129  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
130 
131 
132 def _symbol2py(ctx, s):
133  """Convert a Z3 symbol back into a Python object. """
134  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
135  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
136  else:
137  return Z3_get_symbol_string(ctx.ref(), s)
138 
139 # Hack for having nary functions that can receive one argument that is the
140 # list of arguments.
141 # Use this when function takes a single list of arguments
142 
143 
144 def _get_args(args):
145  try:
146  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
147  return args[0]
148  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
149  return [arg for arg in args[0]]
150  else:
151  return args
152  except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?)
153  return args
154 
155 # Use this when function takes multiple arguments
156 
157 
158 def _get_args_ast_list(args):
159  try:
160  if isinstance(args, (set, AstVector, tuple)):
161  return [arg for arg in args]
162  else:
163  return args
164  except Exception:
165  return args
166 
167 
168 def _to_param_value(val):
169  if isinstance(val, bool):
170  return "true" if val else "false"
171  return str(val)
172 
173 
175  # Do nothing error handler, just avoid exit(0)
176  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
177  return
178 
179 
180 class Context:
181  """A Context manages all other Z3 objects, global configuration options, etc.
182 
183  Z3Py uses a default global context. For most applications this is sufficient.
184  An application may use multiple Z3 contexts. Objects created in one context
185  cannot be used in another one. However, several objects may be "translated" from
186  one context to another. It is not safe to access Z3 objects from multiple threads.
187  The only exception is the method `interrupt()` that can be used to interrupt() a long
188  computation.
189  The initialization method receives global configuration options for the new context.
190  """
191 
192  def __init__(self, *args, **kws):
193  if z3_debug():
194  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
195  conf = Z3_mk_config()
196  for key in kws:
197  value = kws[key]
198  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
199  prev = None
200  for a in args:
201  if prev is None:
202  prev = a
203  else:
204  Z3_set_param_value(conf, str(prev), _to_param_value(a))
205  prev = None
206  self.ctx = Z3_mk_context_rc(conf)
207  self.owner = True
208  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
209  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
210  Z3_del_config(conf)
211 
212  def __del__(self):
213  if Z3_del_context is not None and self.owner:
214  Z3_del_context(self.ctx)
215  self.ctx = None
216  self.eh = None
217 
218  def ref(self):
219  """Return a reference to the actual C pointer to the Z3 context."""
220  return self.ctx
221 
222  def interrupt(self):
223  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
224 
225  This method can be invoked from a thread different from the one executing the
226  interruptible procedure.
227  """
228  Z3_interrupt(self.ref())
229 
230  def param_descrs(self):
231  """Return the global parameter description set."""
232  return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self)
233 
234 
235 # Global Z3 context
236 _main_ctx = None
237 
238 
239 def main_ctx():
240  """Return a reference to the global Z3 context.
241 
242  >>> x = Real('x')
243  >>> x.ctx == main_ctx()
244  True
245  >>> c = Context()
246  >>> c == main_ctx()
247  False
248  >>> x2 = Real('x', c)
249  >>> x2.ctx == c
250  True
251  >>> eq(x, x2)
252  False
253  """
254  global _main_ctx
255  if _main_ctx is None:
256  _main_ctx = Context()
257  return _main_ctx
258 
259 
260 def _get_ctx(ctx):
261  if ctx is None:
262  return main_ctx()
263  else:
264  return ctx
265 
266 
267 def get_ctx(ctx):
268  return _get_ctx(ctx)
269 
270 
271 def set_param(*args, **kws):
272  """Set Z3 global (or module) parameters.
273 
274  >>> set_param(precision=10)
275  """
276  if z3_debug():
277  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
278  new_kws = {}
279  for k in kws:
280  v = kws[k]
281  if not set_pp_option(k, v):
282  new_kws[k] = v
283  for key in new_kws:
284  value = new_kws[key]
285  Z3_global_param_set(str(key).upper(), _to_param_value(value))
286  prev = None
287  for a in args:
288  if prev is None:
289  prev = a
290  else:
291  Z3_global_param_set(str(prev), _to_param_value(a))
292  prev = None
293 
294 
296  """Reset all global (or module) parameters.
297  """
299 
300 
301 def set_option(*args, **kws):
302  """Alias for 'set_param' for backward compatibility.
303  """
304  return set_param(*args, **kws)
305 
306 
307 def get_param(name):
308  """Return the value of a Z3 global (or module) parameter
309 
310  >>> get_param('nlsat.reorder')
311  'true'
312  """
313  ptr = (ctypes.c_char_p * 1)()
314  if Z3_global_param_get(str(name), ptr):
315  r = z3core._to_pystr(ptr[0])
316  return r
317  raise Z3Exception("failed to retrieve value for '%s'" % name)
318 
319 #########################################
320 #
321 # ASTs base class
322 #
323 #########################################
324 
325 # Mark objects that use pretty printer
326 
327 
329  """Superclass for all Z3 objects that have support for pretty printing."""
330 
331  def use_pp(self):
332  return True
333 
334  def _repr_html_(self):
335  in_html = in_html_mode()
336  set_html_mode(True)
337  res = repr(self)
338  set_html_mode(in_html)
339  return res
340 
341 
343  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
344 
345  def __init__(self, ast, ctx=None):
346  self.ast = ast
347  self.ctx = _get_ctx(ctx)
348  Z3_inc_ref(self.ctx.ref(), self.as_ast())
349 
350  def __del__(self):
351  if self.ctx.ref() is not None and self.ast is not None and Z3_dec_ref is not None:
352  Z3_dec_ref(self.ctx.ref(), self.as_ast())
353  self.ast = None
354 
355  def __deepcopy__(self, memo={}):
356  return _to_ast_ref(self.ast, self.ctx)
357 
358  def __str__(self):
359  return obj_to_string(self)
360 
361  def __repr__(self):
362  return obj_to_string(self)
363 
364  def __eq__(self, other):
365  return self.eq(other)
366 
367  def __hash__(self):
368  return self.hash()
369 
370  def __nonzero__(self):
371  return self.__bool__()
372 
373  def __bool__(self):
374  if is_true(self):
375  return True
376  elif is_false(self):
377  return False
378  elif is_eq(self) and self.num_args() == 2:
379  return self.arg(0).eq(self.arg(1))
380  else:
381  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
382 
383  def sexpr(self):
384  """Return a string representing the AST node in s-expression notation.
385 
386  >>> x = Int('x')
387  >>> ((x + 1)*x).sexpr()
388  '(* (+ x 1) x)'
389  """
390  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
391 
392  def as_ast(self):
393  """Return a pointer to the corresponding C Z3_ast object."""
394  return self.ast
395 
396  def get_id(self):
397  """Return unique identifier for object. It can be used for hash-tables and maps."""
398  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
399 
400  def ctx_ref(self):
401  """Return a reference to the C context where this AST node is stored."""
402  return self.ctx.ref()
403 
404  def eq(self, other):
405  """Return `True` if `self` and `other` are structurally identical.
406 
407  >>> x = Int('x')
408  >>> n1 = x + 1
409  >>> n2 = 1 + x
410  >>> n1.eq(n2)
411  False
412  >>> n1 = simplify(n1)
413  >>> n2 = simplify(n2)
414  >>> n1.eq(n2)
415  True
416  """
417  if z3_debug():
418  _z3_assert(is_ast(other), "Z3 AST expected")
419  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
420 
421  def translate(self, target):
422  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
423 
424  >>> c1 = Context()
425  >>> c2 = Context()
426  >>> x = Int('x', c1)
427  >>> y = Int('y', c2)
428  >>> # Nodes in different contexts can't be mixed.
429  >>> # However, we can translate nodes from one context to another.
430  >>> x.translate(c2) + y
431  x + y
432  """
433  if z3_debug():
434  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
435  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
436 
437  def __copy__(self):
438  return self.translate(self.ctx)
439 
440  def hash(self):
441  """Return a hashcode for the `self`.
442 
443  >>> n1 = simplify(Int('x') + 1)
444  >>> n2 = simplify(2 + Int('x') - 1)
445  >>> n1.hash() == n2.hash()
446  True
447  """
448  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
449 
450 
451 def is_ast(a):
452  """Return `True` if `a` is an AST node.
453 
454  >>> is_ast(10)
455  False
456  >>> is_ast(IntVal(10))
457  True
458  >>> is_ast(Int('x'))
459  True
460  >>> is_ast(BoolSort())
461  True
462  >>> is_ast(Function('f', IntSort(), IntSort()))
463  True
464  >>> is_ast("x")
465  False
466  >>> is_ast(Solver())
467  False
468  """
469  return isinstance(a, AstRef)
470 
471 
472 def eq(a, b):
473  """Return `True` if `a` and `b` are structurally identical AST nodes.
474 
475  >>> x = Int('x')
476  >>> y = Int('y')
477  >>> eq(x, y)
478  False
479  >>> eq(x + 1, x + 1)
480  True
481  >>> eq(x + 1, 1 + x)
482  False
483  >>> eq(simplify(x + 1), simplify(1 + x))
484  True
485  """
486  if z3_debug():
487  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
488  return a.eq(b)
489 
490 
491 def _ast_kind(ctx, a):
492  if is_ast(a):
493  a = a.as_ast()
494  return Z3_get_ast_kind(ctx.ref(), a)
495 
496 
497 def _ctx_from_ast_arg_list(args, default_ctx=None):
498  ctx = None
499  for a in args:
500  if is_ast(a) or is_probe(a):
501  if ctx is None:
502  ctx = a.ctx
503  else:
504  if z3_debug():
505  _z3_assert(ctx == a.ctx, "Context mismatch")
506  if ctx is None:
507  ctx = default_ctx
508  return ctx
509 
510 
511 def _ctx_from_ast_args(*args):
512  return _ctx_from_ast_arg_list(args)
513 
514 
515 def _to_func_decl_array(args):
516  sz = len(args)
517  _args = (FuncDecl * sz)()
518  for i in range(sz):
519  _args[i] = args[i].as_func_decl()
520  return _args, sz
521 
522 
523 def _to_ast_array(args):
524  sz = len(args)
525  _args = (Ast * sz)()
526  for i in range(sz):
527  _args[i] = args[i].as_ast()
528  return _args, sz
529 
530 
531 def _to_ref_array(ref, args):
532  sz = len(args)
533  _args = (ref * sz)()
534  for i in range(sz):
535  _args[i] = args[i].as_ast()
536  return _args, sz
537 
538 
539 def _to_ast_ref(a, ctx):
540  k = _ast_kind(ctx, a)
541  if k == Z3_SORT_AST:
542  return _to_sort_ref(a, ctx)
543  elif k == Z3_FUNC_DECL_AST:
544  return _to_func_decl_ref(a, ctx)
545  else:
546  return _to_expr_ref(a, ctx)
547 
548 
549 #########################################
550 #
551 # Sorts
552 #
553 #########################################
554 
555 def _sort_kind(ctx, s):
556  return Z3_get_sort_kind(ctx.ref(), s)
557 
558 
560  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
561 
562  def as_ast(self):
563  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
564 
565  def get_id(self):
566  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
567 
568  def kind(self):
569  """Return the Z3 internal kind of a sort.
570  This method can be used to test if `self` is one of the Z3 builtin sorts.
571 
572  >>> b = BoolSort()
573  >>> b.kind() == Z3_BOOL_SORT
574  True
575  >>> b.kind() == Z3_INT_SORT
576  False
577  >>> A = ArraySort(IntSort(), IntSort())
578  >>> A.kind() == Z3_ARRAY_SORT
579  True
580  >>> A.kind() == Z3_INT_SORT
581  False
582  """
583  return _sort_kind(self.ctx, self.ast)
584 
585  def subsort(self, other):
586  """Return `True` if `self` is a subsort of `other`.
587 
588  >>> IntSort().subsort(RealSort())
589  True
590  """
591  return False
592 
593  def cast(self, val):
594  """Try to cast `val` as an element of sort `self`.
595 
596  This method is used in Z3Py to convert Python objects such as integers,
597  floats, longs and strings into Z3 expressions.
598 
599  >>> x = Int('x')
600  >>> RealSort().cast(x)
601  ToReal(x)
602  """
603  if z3_debug():
604  _z3_assert(is_expr(val), "Z3 expression expected")
605  _z3_assert(self.eq(val.sort()), "Sort mismatch")
606  return val
607 
608  def name(self):
609  """Return the name (string) of sort `self`.
610 
611  >>> BoolSort().name()
612  'Bool'
613  >>> ArraySort(IntSort(), IntSort()).name()
614  'Array'
615  """
616  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
617 
618  def __eq__(self, other):
619  """Return `True` if `self` and `other` are the same Z3 sort.
620 
621  >>> p = Bool('p')
622  >>> p.sort() == BoolSort()
623  True
624  >>> p.sort() == IntSort()
625  False
626  """
627  if other is None:
628  return False
629  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
630 
631  def __ne__(self, other):
632  """Return `True` if `self` and `other` are not the same Z3 sort.
633 
634  >>> p = Bool('p')
635  >>> p.sort() != BoolSort()
636  False
637  >>> p.sort() != IntSort()
638  True
639  """
640  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
641 
642  def __hash__(self):
643  """ Hash code. """
644  return AstRef.__hash__(self)
645 
646 
647 def is_sort(s):
648  """Return `True` if `s` is a Z3 sort.
649 
650  >>> is_sort(IntSort())
651  True
652  >>> is_sort(Int('x'))
653  False
654  >>> is_expr(Int('x'))
655  True
656  """
657  return isinstance(s, SortRef)
658 
659 
660 def _to_sort_ref(s, ctx):
661  if z3_debug():
662  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
663  k = _sort_kind(ctx, s)
664  if k == Z3_BOOL_SORT:
665  return BoolSortRef(s, ctx)
666  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
667  return ArithSortRef(s, ctx)
668  elif k == Z3_BV_SORT:
669  return BitVecSortRef(s, ctx)
670  elif k == Z3_ARRAY_SORT:
671  return ArraySortRef(s, ctx)
672  elif k == Z3_DATATYPE_SORT:
673  return DatatypeSortRef(s, ctx)
674  elif k == Z3_FINITE_DOMAIN_SORT:
675  return FiniteDomainSortRef(s, ctx)
676  elif k == Z3_FLOATING_POINT_SORT:
677  return FPSortRef(s, ctx)
678  elif k == Z3_ROUNDING_MODE_SORT:
679  return FPRMSortRef(s, ctx)
680  elif k == Z3_RE_SORT:
681  return ReSortRef(s, ctx)
682  elif k == Z3_SEQ_SORT:
683  return SeqSortRef(s, ctx)
684  elif k == Z3_CHAR_SORT:
685  return CharSortRef(s, ctx)
686  return SortRef(s, ctx)
687 
688 
689 def _sort(ctx, a):
690  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
691 
692 
693 def DeclareSort(name, ctx=None):
694  """Create a new uninterpreted sort named `name`.
695 
696  If `ctx=None`, then the new sort is declared in the global Z3Py context.
697 
698  >>> A = DeclareSort('A')
699  >>> a = Const('a', A)
700  >>> b = Const('b', A)
701  >>> a.sort() == A
702  True
703  >>> b.sort() == A
704  True
705  >>> a == b
706  a == b
707  """
708  ctx = _get_ctx(ctx)
709  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
710 
711 #########################################
712 #
713 # Function Declarations
714 #
715 #########################################
716 
717 
719  """Function declaration. Every constant and function have an associated declaration.
720 
721  The declaration assigns a name, a sort (i.e., type), and for function
722  the sort (i.e., type) of each of its arguments. Note that, in Z3,
723  a constant is a function with 0 arguments.
724  """
725 
726  def as_ast(self):
727  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
728 
729  def get_id(self):
730  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
731 
732  def as_func_decl(self):
733  return self.ast
734 
735  def name(self):
736  """Return the name of the function declaration `self`.
737 
738  >>> f = Function('f', IntSort(), IntSort())
739  >>> f.name()
740  'f'
741  >>> isinstance(f.name(), str)
742  True
743  """
744  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
745 
746  def arity(self):
747  """Return the number of arguments of a function declaration.
748  If `self` is a constant, then `self.arity()` is 0.
749 
750  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
751  >>> f.arity()
752  2
753  """
754  return int(Z3_get_arity(self.ctx_ref(), self.ast))
755 
756  def domain(self, i):
757  """Return the sort of the argument `i` of a function declaration.
758  This method assumes that `0 <= i < self.arity()`.
759 
760  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
761  >>> f.domain(0)
762  Int
763  >>> f.domain(1)
764  Real
765  """
766  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
767 
768  def range(self):
769  """Return the sort of the range of a function declaration.
770  For constants, this is the sort of the constant.
771 
772  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
773  >>> f.range()
774  Bool
775  """
776  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
777 
778  def kind(self):
779  """Return the internal kind of a function declaration.
780  It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
781 
782  >>> x = Int('x')
783  >>> d = (x + 1).decl()
784  >>> d.kind() == Z3_OP_ADD
785  True
786  >>> d.kind() == Z3_OP_MUL
787  False
788  """
789  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
790 
791  def params(self):
792  ctx = self.ctx
793  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
794  result = [None for i in range(n)]
795  for i in range(n):
796  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
797  if k == Z3_PARAMETER_INT:
798  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
799  elif k == Z3_PARAMETER_DOUBLE:
800  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
801  elif k == Z3_PARAMETER_RATIONAL:
802  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
803  elif k == Z3_PARAMETER_SYMBOL:
804  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
805  elif k == Z3_PARAMETER_SORT:
806  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
807  elif k == Z3_PARAMETER_AST:
808  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
809  elif k == Z3_PARAMETER_FUNC_DECL:
810  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
811  else:
812  assert(False)
813  return result
814 
815  def __call__(self, *args):
816  """Create a Z3 application expression using the function `self`, and the given arguments.
817 
818  The arguments must be Z3 expressions. This method assumes that
819  the sorts of the elements in `args` match the sorts of the
820  domain. Limited coercion is supported. For example, if
821  args[0] is a Python integer, and the function expects a Z3
822  integer, then the argument is automatically converted into a
823  Z3 integer.
824 
825  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
826  >>> x = Int('x')
827  >>> y = Real('y')
828  >>> f(x, y)
829  f(x, y)
830  >>> f(x, x)
831  f(x, ToReal(x))
832  """
833  args = _get_args(args)
834  num = len(args)
835  _args = (Ast * num)()
836  saved = []
837  for i in range(num):
838  # self.domain(i).cast(args[i]) may create a new Z3 expression,
839  # then we must save in 'saved' to prevent it from being garbage collected.
840  tmp = self.domain(i).cast(args[i])
841  saved.append(tmp)
842  _args[i] = tmp.as_ast()
843  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
844 
845 
847  """Return `True` if `a` is a Z3 function declaration.
848 
849  >>> f = Function('f', IntSort(), IntSort())
850  >>> is_func_decl(f)
851  True
852  >>> x = Real('x')
853  >>> is_func_decl(x)
854  False
855  """
856  return isinstance(a, FuncDeclRef)
857 
858 
859 def Function(name, *sig):
860  """Create a new Z3 uninterpreted function with the given sorts.
861 
862  >>> f = Function('f', IntSort(), IntSort())
863  >>> f(f(0))
864  f(f(0))
865  """
866  sig = _get_args(sig)
867  if z3_debug():
868  _z3_assert(len(sig) > 0, "At least two arguments expected")
869  arity = len(sig) - 1
870  rng = sig[arity]
871  if z3_debug():
872  _z3_assert(is_sort(rng), "Z3 sort expected")
873  dom = (Sort * arity)()
874  for i in range(arity):
875  if z3_debug():
876  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
877  dom[i] = sig[i].ast
878  ctx = rng.ctx
879  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
880 
881 
882 def FreshFunction(*sig):
883  """Create a new fresh Z3 uninterpreted function with the given sorts.
884  """
885  sig = _get_args(sig)
886  if z3_debug():
887  _z3_assert(len(sig) > 0, "At least two arguments expected")
888  arity = len(sig) - 1
889  rng = sig[arity]
890  if z3_debug():
891  _z3_assert(is_sort(rng), "Z3 sort expected")
892  dom = (z3.Sort * arity)()
893  for i in range(arity):
894  if z3_debug():
895  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
896  dom[i] = sig[i].ast
897  ctx = rng.ctx
898  return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
899 
900 
901 def _to_func_decl_ref(a, ctx):
902  return FuncDeclRef(a, ctx)
903 
904 
905 def RecFunction(name, *sig):
906  """Create a new Z3 recursive with the given sorts."""
907  sig = _get_args(sig)
908  if z3_debug():
909  _z3_assert(len(sig) > 0, "At least two arguments expected")
910  arity = len(sig) - 1
911  rng = sig[arity]
912  if z3_debug():
913  _z3_assert(is_sort(rng), "Z3 sort expected")
914  dom = (Sort * arity)()
915  for i in range(arity):
916  if z3_debug():
917  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
918  dom[i] = sig[i].ast
919  ctx = rng.ctx
920  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
921 
922 
923 def RecAddDefinition(f, args, body):
924  """Set the body of a recursive function.
925  Recursive definitions can be simplified if they are applied to ground
926  arguments.
927  >>> ctx = Context()
928  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
929  >>> n = Int('n', ctx)
930  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
931  >>> simplify(fac(5))
932  120
933  >>> s = Solver(ctx=ctx)
934  >>> s.add(fac(n) < 3)
935  >>> s.check()
936  sat
937  >>> s.model().eval(fac(5))
938  120
939  """
940  if is_app(args):
941  args = [args]
942  ctx = body.ctx
943  args = _get_args(args)
944  n = len(args)
945  _args = (Ast * n)()
946  for i in range(n):
947  _args[i] = args[i].ast
948  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
949 
950 #########################################
951 #
952 # Expressions
953 #
954 #########################################
955 
956 
958  """Constraints, formulas and terms are expressions in Z3.
959 
960  Expressions are ASTs. Every expression has a sort.
961  There are three main kinds of expressions:
962  function applications, quantifiers and bounded variables.
963  A constant is a function application with 0 arguments.
964  For quantifier free problems, all expressions are
965  function applications.
966  """
967 
968  def as_ast(self):
969  return self.ast
970 
971  def get_id(self):
972  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
973 
974  def sort(self):
975  """Return the sort of expression `self`.
976 
977  >>> x = Int('x')
978  >>> (x + 1).sort()
979  Int
980  >>> y = Real('y')
981  >>> (x + y).sort()
982  Real
983  """
984  return _sort(self.ctx, self.as_ast())
985 
986  def sort_kind(self):
987  """Shorthand for `self.sort().kind()`.
988 
989  >>> a = Array('a', IntSort(), IntSort())
990  >>> a.sort_kind() == Z3_ARRAY_SORT
991  True
992  >>> a.sort_kind() == Z3_INT_SORT
993  False
994  """
995  return self.sort().kind()
996 
997  def __eq__(self, other):
998  """Return a Z3 expression that represents the constraint `self == other`.
999 
1000  If `other` is `None`, then this method simply returns `False`.
1001 
1002  >>> a = Int('a')
1003  >>> b = Int('b')
1004  >>> a == b
1005  a == b
1006  >>> a is None
1007  False
1008  """
1009  if other is None:
1010  return False
1011  a, b = _coerce_exprs(self, other)
1012  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
1013 
1014  def __hash__(self):
1015  """ Hash code. """
1016  return AstRef.__hash__(self)
1017 
1018  def __ne__(self, other):
1019  """Return a Z3 expression that represents the constraint `self != other`.
1020 
1021  If `other` is `None`, then this method simply returns `True`.
1022 
1023  >>> a = Int('a')
1024  >>> b = Int('b')
1025  >>> a != b
1026  a != b
1027  >>> a is not None
1028  True
1029  """
1030  if other is None:
1031  return True
1032  a, b = _coerce_exprs(self, other)
1033  _args, sz = _to_ast_array((a, b))
1034  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
1035 
1036  def params(self):
1037  return self.decl().params()
1038 
1039  def decl(self):
1040  """Return the Z3 function declaration associated with a Z3 application.
1041 
1042  >>> f = Function('f', IntSort(), IntSort())
1043  >>> a = Int('a')
1044  >>> t = f(a)
1045  >>> eq(t.decl(), f)
1046  True
1047  >>> (a + 1).decl()
1048  +
1049  """
1050  if z3_debug():
1051  _z3_assert(is_app(self), "Z3 application expected")
1052  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
1053 
1054  def num_args(self):
1055  """Return the number of arguments of a Z3 application.
1056 
1057  >>> a = Int('a')
1058  >>> b = Int('b')
1059  >>> (a + b).num_args()
1060  2
1061  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1062  >>> t = f(a, b, 0)
1063  >>> t.num_args()
1064  3
1065  """
1066  if z3_debug():
1067  _z3_assert(is_app(self), "Z3 application expected")
1068  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
1069 
1070  def arg(self, idx):
1071  """Return argument `idx` of the application `self`.
1072 
1073  This method assumes that `self` is a function application with at least `idx+1` arguments.
1074 
1075  >>> a = Int('a')
1076  >>> b = Int('b')
1077  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1078  >>> t = f(a, b, 0)
1079  >>> t.arg(0)
1080  a
1081  >>> t.arg(1)
1082  b
1083  >>> t.arg(2)
1084  0
1085  """
1086  if z3_debug():
1087  _z3_assert(is_app(self), "Z3 application expected")
1088  _z3_assert(idx < self.num_args(), "Invalid argument index")
1089  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
1090 
1091  def children(self):
1092  """Return a list containing the children of the given expression
1093 
1094  >>> a = Int('a')
1095  >>> b = Int('b')
1096  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1097  >>> t = f(a, b, 0)
1098  >>> t.children()
1099  [a, b, 0]
1100  """
1101  if is_app(self):
1102  return [self.arg(i) for i in range(self.num_args())]
1103  else:
1104  return []
1105 
1106  def from_string(self, s):
1107  pass
1108 
1109  def serialize(self):
1110  s = Solver()
1111  f = Function('F', self.sort(), BoolSort(self.ctx))
1112  s.add(f(self))
1113  return s.sexpr()
1114 
1115 def deserialize(st):
1116  """inverse function to the serialize method on ExprRef.
1117  It is made available to make it easier for users to serialize expressions back and forth between
1118  strings. Solvers can be serialized using the 'sexpr()' method.
1119  """
1120  s = Solver()
1121  s.from_string(st)
1122  if len(s.assertions()) != 1:
1123  raise Z3Exception("single assertion expected")
1124  fml = s.assertions()[0]
1125  if fml.num_args() != 1:
1126  raise Z3Exception("dummy function 'F' expected")
1127  return fml.arg(0)
1128 
1129 def _to_expr_ref(a, ctx):
1130  if isinstance(a, Pattern):
1131  return PatternRef(a, ctx)
1132  ctx_ref = ctx.ref()
1133  k = Z3_get_ast_kind(ctx_ref, a)
1134  if k == Z3_QUANTIFIER_AST:
1135  return QuantifierRef(a, ctx)
1136  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1137  if sk == Z3_BOOL_SORT:
1138  return BoolRef(a, ctx)
1139  if sk == Z3_INT_SORT:
1140  if k == Z3_NUMERAL_AST:
1141  return IntNumRef(a, ctx)
1142  return ArithRef(a, ctx)
1143  if sk == Z3_REAL_SORT:
1144  if k == Z3_NUMERAL_AST:
1145  return RatNumRef(a, ctx)
1146  if _is_algebraic(ctx, a):
1147  return AlgebraicNumRef(a, ctx)
1148  return ArithRef(a, ctx)
1149  if sk == Z3_BV_SORT:
1150  if k == Z3_NUMERAL_AST:
1151  return BitVecNumRef(a, ctx)
1152  else:
1153  return BitVecRef(a, ctx)
1154  if sk == Z3_ARRAY_SORT:
1155  return ArrayRef(a, ctx)
1156  if sk == Z3_DATATYPE_SORT:
1157  return DatatypeRef(a, ctx)
1158  if sk == Z3_FLOATING_POINT_SORT:
1159  if k == Z3_APP_AST and _is_numeral(ctx, a):
1160  return FPNumRef(a, ctx)
1161  else:
1162  return FPRef(a, ctx)
1163  if sk == Z3_FINITE_DOMAIN_SORT:
1164  if k == Z3_NUMERAL_AST:
1165  return FiniteDomainNumRef(a, ctx)
1166  else:
1167  return FiniteDomainRef(a, ctx)
1168  if sk == Z3_ROUNDING_MODE_SORT:
1169  return FPRMRef(a, ctx)
1170  if sk == Z3_SEQ_SORT:
1171  return SeqRef(a, ctx)
1172  if sk == Z3_CHAR_SORT:
1173  return CharRef(a, ctx)
1174  if sk == Z3_RE_SORT:
1175  return ReRef(a, ctx)
1176  return ExprRef(a, ctx)
1177 
1178 
1179 def _coerce_expr_merge(s, a):
1180  if is_expr(a):
1181  s1 = a.sort()
1182  if s is None:
1183  return s1
1184  if s1.eq(s):
1185  return s
1186  elif s.subsort(s1):
1187  return s1
1188  elif s1.subsort(s):
1189  return s
1190  else:
1191  if z3_debug():
1192  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1193  _z3_assert(False, "sort mismatch")
1194  else:
1195  return s
1196 
1197 
1198 def _coerce_exprs(a, b, ctx=None):
1199  if not is_expr(a) and not is_expr(b):
1200  a = _py2expr(a, ctx)
1201  b = _py2expr(b, ctx)
1202  if isinstance(a, str) and isinstance(b, SeqRef):
1203  a = StringVal(a, b.ctx)
1204  if isinstance(b, str) and isinstance(a, SeqRef):
1205  b = StringVal(b, a.ctx)
1206  if isinstance(a, float) and isinstance(b, ArithRef):
1207  a = RealVal(a, b.ctx)
1208  if isinstance(b, float) and isinstance(a, ArithRef):
1209  b = RealVal(b, a.ctx)
1210 
1211  s = None
1212  s = _coerce_expr_merge(s, a)
1213  s = _coerce_expr_merge(s, b)
1214  a = s.cast(a)
1215  b = s.cast(b)
1216  return (a, b)
1217 
1218 
1219 def _reduce(func, sequence, initial):
1220  result = initial
1221  for element in sequence:
1222  result = func(result, element)
1223  return result
1224 
1225 
1226 def _coerce_expr_list(alist, ctx=None):
1227  has_expr = False
1228  for a in alist:
1229  if is_expr(a):
1230  has_expr = True
1231  break
1232  if not has_expr:
1233  alist = [_py2expr(a, ctx) for a in alist]
1234  s = _reduce(_coerce_expr_merge, alist, None)
1235  return [s.cast(a) for a in alist]
1236 
1237 
1238 def is_expr(a):
1239  """Return `True` if `a` is a Z3 expression.
1240 
1241  >>> a = Int('a')
1242  >>> is_expr(a)
1243  True
1244  >>> is_expr(a + 1)
1245  True
1246  >>> is_expr(IntSort())
1247  False
1248  >>> is_expr(1)
1249  False
1250  >>> is_expr(IntVal(1))
1251  True
1252  >>> x = Int('x')
1253  >>> is_expr(ForAll(x, x >= 0))
1254  True
1255  >>> is_expr(FPVal(1.0))
1256  True
1257  """
1258  return isinstance(a, ExprRef)
1259 
1260 
1261 def is_app(a):
1262  """Return `True` if `a` is a Z3 function application.
1263 
1264  Note that, constants are function applications with 0 arguments.
1265 
1266  >>> a = Int('a')
1267  >>> is_app(a)
1268  True
1269  >>> is_app(a + 1)
1270  True
1271  >>> is_app(IntSort())
1272  False
1273  >>> is_app(1)
1274  False
1275  >>> is_app(IntVal(1))
1276  True
1277  >>> x = Int('x')
1278  >>> is_app(ForAll(x, x >= 0))
1279  False
1280  """
1281  if not isinstance(a, ExprRef):
1282  return False
1283  k = _ast_kind(a.ctx, a)
1284  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1285 
1286 
1287 def is_const(a):
1288  """Return `True` if `a` is Z3 constant/variable expression.
1289 
1290  >>> a = Int('a')
1291  >>> is_const(a)
1292  True
1293  >>> is_const(a + 1)
1294  False
1295  >>> is_const(1)
1296  False
1297  >>> is_const(IntVal(1))
1298  True
1299  >>> x = Int('x')
1300  >>> is_const(ForAll(x, x >= 0))
1301  False
1302  """
1303  return is_app(a) and a.num_args() == 0
1304 
1305 
1306 def is_var(a):
1307  """Return `True` if `a` is variable.
1308 
1309  Z3 uses de-Bruijn indices for representing bound variables in
1310  quantifiers.
1311 
1312  >>> x = Int('x')
1313  >>> is_var(x)
1314  False
1315  >>> is_const(x)
1316  True
1317  >>> f = Function('f', IntSort(), IntSort())
1318  >>> # Z3 replaces x with bound variables when ForAll is executed.
1319  >>> q = ForAll(x, f(x) == x)
1320  >>> b = q.body()
1321  >>> b
1322  f(Var(0)) == Var(0)
1323  >>> b.arg(1)
1324  Var(0)
1325  >>> is_var(b.arg(1))
1326  True
1327  """
1328  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1329 
1330 
1332  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1333 
1334  >>> x = Int('x')
1335  >>> y = Int('y')
1336  >>> is_var(x)
1337  False
1338  >>> is_const(x)
1339  True
1340  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1341  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1342  >>> q = ForAll([x, y], f(x, y) == x + y)
1343  >>> q.body()
1344  f(Var(1), Var(0)) == Var(1) + Var(0)
1345  >>> b = q.body()
1346  >>> b.arg(0)
1347  f(Var(1), Var(0))
1348  >>> v1 = b.arg(0).arg(0)
1349  >>> v2 = b.arg(0).arg(1)
1350  >>> v1
1351  Var(1)
1352  >>> v2
1353  Var(0)
1354  >>> get_var_index(v1)
1355  1
1356  >>> get_var_index(v2)
1357  0
1358  """
1359  if z3_debug():
1360  _z3_assert(is_var(a), "Z3 bound variable expected")
1361  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1362 
1363 
1364 def is_app_of(a, k):
1365  """Return `True` if `a` is an application of the given kind `k`.
1366 
1367  >>> x = Int('x')
1368  >>> n = x + 1
1369  >>> is_app_of(n, Z3_OP_ADD)
1370  True
1371  >>> is_app_of(n, Z3_OP_MUL)
1372  False
1373  """
1374  return is_app(a) and a.decl().kind() == k
1375 
1376 
1377 def If(a, b, c, ctx=None):
1378  """Create a Z3 if-then-else expression.
1379 
1380  >>> x = Int('x')
1381  >>> y = Int('y')
1382  >>> max = If(x > y, x, y)
1383  >>> max
1384  If(x > y, x, y)
1385  >>> simplify(max)
1386  If(x <= y, y, x)
1387  """
1388  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1389  return Cond(a, b, c, ctx)
1390  else:
1391  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1392  s = BoolSort(ctx)
1393  a = s.cast(a)
1394  b, c = _coerce_exprs(b, c, ctx)
1395  if z3_debug():
1396  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1397  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1398 
1399 
1400 def Distinct(*args):
1401  """Create a Z3 distinct expression.
1402 
1403  >>> x = Int('x')
1404  >>> y = Int('y')
1405  >>> Distinct(x, y)
1406  x != y
1407  >>> z = Int('z')
1408  >>> Distinct(x, y, z)
1409  Distinct(x, y, z)
1410  >>> simplify(Distinct(x, y, z))
1411  Distinct(x, y, z)
1412  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1413  And(Not(x == y), Not(x == z), Not(y == z))
1414  """
1415  args = _get_args(args)
1416  ctx = _ctx_from_ast_arg_list(args)
1417  if z3_debug():
1418  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1419  args = _coerce_expr_list(args, ctx)
1420  _args, sz = _to_ast_array(args)
1421  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1422 
1423 
1424 def _mk_bin(f, a, b):
1425  args = (Ast * 2)()
1426  if z3_debug():
1427  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1428  args[0] = a.as_ast()
1429  args[1] = b.as_ast()
1430  return f(a.ctx.ref(), 2, args)
1431 
1432 
1433 def Const(name, sort):
1434  """Create a constant of the given sort.
1435 
1436  >>> Const('x', IntSort())
1437  x
1438  """
1439  if z3_debug():
1440  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1441  ctx = sort.ctx
1442  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1443 
1444 
1445 def Consts(names, sort):
1446  """Create several constants of the given sort.
1447 
1448  `names` is a string containing the names of all constants to be created.
1449  Blank spaces separate the names of different constants.
1450 
1451  >>> x, y, z = Consts('x y z', IntSort())
1452  >>> x + y + z
1453  x + y + z
1454  """
1455  if isinstance(names, str):
1456  names = names.split(" ")
1457  return [Const(name, sort) for name in names]
1458 
1459 
1460 def FreshConst(sort, prefix="c"):
1461  """Create a fresh constant of a specified sort"""
1462  ctx = _get_ctx(sort.ctx)
1463  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1464 
1465 
1466 def Var(idx, s):
1467  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1468  A free variable with index n is bound when it occurs within the scope of n+1 quantified
1469  declarations.
1470 
1471  >>> Var(0, IntSort())
1472  Var(0)
1473  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1474  False
1475  """
1476  if z3_debug():
1477  _z3_assert(is_sort(s), "Z3 sort expected")
1478  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1479 
1480 
1481 def RealVar(idx, ctx=None):
1482  """
1483  Create a real free variable. Free variables are used to create quantified formulas.
1484  They are also used to create polynomials.
1485 
1486  >>> RealVar(0)
1487  Var(0)
1488  """
1489  return Var(idx, RealSort(ctx))
1490 
1491 
1492 def RealVarVector(n, ctx=None):
1493  """
1494  Create a list of Real free variables.
1495  The variables have ids: 0, 1, ..., n-1
1496 
1497  >>> x0, x1, x2, x3 = RealVarVector(4)
1498  >>> x2
1499  Var(2)
1500  """
1501  return [RealVar(i, ctx) for i in range(n)]
1502 
1503 #########################################
1504 #
1505 # Booleans
1506 #
1507 #########################################
1508 
1509 
1511  """Boolean sort."""
1512 
1513  def cast(self, val):
1514  """Try to cast `val` as a Boolean.
1515 
1516  >>> x = BoolSort().cast(True)
1517  >>> x
1518  True
1519  >>> is_expr(x)
1520  True
1521  >>> is_expr(True)
1522  False
1523  >>> x.sort()
1524  Bool
1525  """
1526  if isinstance(val, bool):
1527  return BoolVal(val, self.ctx)
1528  if z3_debug():
1529  if not is_expr(val):
1530  msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1531  _z3_assert(is_expr(val), msg % (val, type(val)))
1532  if not self.eq(val.sort()):
1533  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1534  return val
1535 
1536  def subsort(self, other):
1537  return isinstance(other, ArithSortRef)
1538 
1539  def is_int(self):
1540  return True
1541 
1542  def is_bool(self):
1543  return True
1544 
1545 
1547  """All Boolean expressions are instances of this class."""
1548 
1549  def sort(self):
1550  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1551 
1552  def __rmul__(self, other):
1553  return self * other
1554 
1555  def __mul__(self, other):
1556  """Create the Z3 expression `self * other`.
1557  """
1558  if isinstance(other, int) and other == 1:
1559  return If(self, 1, 0)
1560  if isinstance(other, int) and other == 0:
1561  return IntVal(0, self.ctx)
1562  if isinstance(other, BoolRef):
1563  other = If(other, 1, 0)
1564  return If(self, other, 0)
1565 
1566 
1567 def is_bool(a):
1568  """Return `True` if `a` is a Z3 Boolean expression.
1569 
1570  >>> p = Bool('p')
1571  >>> is_bool(p)
1572  True
1573  >>> q = Bool('q')
1574  >>> is_bool(And(p, q))
1575  True
1576  >>> x = Real('x')
1577  >>> is_bool(x)
1578  False
1579  >>> is_bool(x == 0)
1580  True
1581  """
1582  return isinstance(a, BoolRef)
1583 
1584 
1585 def is_true(a):
1586  """Return `True` if `a` is the Z3 true expression.
1587 
1588  >>> p = Bool('p')
1589  >>> is_true(p)
1590  False
1591  >>> is_true(simplify(p == p))
1592  True
1593  >>> x = Real('x')
1594  >>> is_true(x == 0)
1595  False
1596  >>> # True is a Python Boolean expression
1597  >>> is_true(True)
1598  False
1599  """
1600  return is_app_of(a, Z3_OP_TRUE)
1601 
1602 
1603 def is_false(a):
1604  """Return `True` if `a` is the Z3 false expression.
1605 
1606  >>> p = Bool('p')
1607  >>> is_false(p)
1608  False
1609  >>> is_false(False)
1610  False
1611  >>> is_false(BoolVal(False))
1612  True
1613  """
1614  return is_app_of(a, Z3_OP_FALSE)
1615 
1616 
1617 def is_and(a):
1618  """Return `True` if `a` is a Z3 and expression.
1619 
1620  >>> p, q = Bools('p q')
1621  >>> is_and(And(p, q))
1622  True
1623  >>> is_and(Or(p, q))
1624  False
1625  """
1626  return is_app_of(a, Z3_OP_AND)
1627 
1628 
1629 def is_or(a):
1630  """Return `True` if `a` is a Z3 or expression.
1631 
1632  >>> p, q = Bools('p q')
1633  >>> is_or(Or(p, q))
1634  True
1635  >>> is_or(And(p, q))
1636  False
1637  """
1638  return is_app_of(a, Z3_OP_OR)
1639 
1640 
1641 def is_implies(a):
1642  """Return `True` if `a` is a Z3 implication expression.
1643 
1644  >>> p, q = Bools('p q')
1645  >>> is_implies(Implies(p, q))
1646  True
1647  >>> is_implies(And(p, q))
1648  False
1649  """
1650  return is_app_of(a, Z3_OP_IMPLIES)
1651 
1652 
1653 def is_not(a):
1654  """Return `True` if `a` is a Z3 not expression.
1655 
1656  >>> p = Bool('p')
1657  >>> is_not(p)
1658  False
1659  >>> is_not(Not(p))
1660  True
1661  """
1662  return is_app_of(a, Z3_OP_NOT)
1663 
1664 
1665 def is_eq(a):
1666  """Return `True` if `a` is a Z3 equality expression.
1667 
1668  >>> x, y = Ints('x y')
1669  >>> is_eq(x == y)
1670  True
1671  """
1672  return is_app_of(a, Z3_OP_EQ)
1673 
1674 
1676  """Return `True` if `a` is a Z3 distinct expression.
1677 
1678  >>> x, y, z = Ints('x y z')
1679  >>> is_distinct(x == y)
1680  False
1681  >>> is_distinct(Distinct(x, y, z))
1682  True
1683  """
1684  return is_app_of(a, Z3_OP_DISTINCT)
1685 
1686 
1687 def BoolSort(ctx=None):
1688  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1689 
1690  >>> BoolSort()
1691  Bool
1692  >>> p = Const('p', BoolSort())
1693  >>> is_bool(p)
1694  True
1695  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1696  >>> r(0, 1)
1697  r(0, 1)
1698  >>> is_bool(r(0, 1))
1699  True
1700  """
1701  ctx = _get_ctx(ctx)
1702  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1703 
1704 
1705 def BoolVal(val, ctx=None):
1706  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1707 
1708  >>> BoolVal(True)
1709  True
1710  >>> is_true(BoolVal(True))
1711  True
1712  >>> is_true(True)
1713  False
1714  >>> is_false(BoolVal(False))
1715  True
1716  """
1717  ctx = _get_ctx(ctx)
1718  if val:
1719  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1720  else:
1721  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1722 
1723 
1724 def Bool(name, ctx=None):
1725  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1726 
1727  >>> p = Bool('p')
1728  >>> q = Bool('q')
1729  >>> And(p, q)
1730  And(p, q)
1731  """
1732  ctx = _get_ctx(ctx)
1733  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1734 
1735 
1736 def Bools(names, ctx=None):
1737  """Return a tuple of Boolean constants.
1738 
1739  `names` is a single string containing all names separated by blank spaces.
1740  If `ctx=None`, then the global context is used.
1741 
1742  >>> p, q, r = Bools('p q r')
1743  >>> And(p, Or(q, r))
1744  And(p, Or(q, r))
1745  """
1746  ctx = _get_ctx(ctx)
1747  if isinstance(names, str):
1748  names = names.split(" ")
1749  return [Bool(name, ctx) for name in names]
1750 
1751 
1752 def BoolVector(prefix, sz, ctx=None):
1753  """Return a list of Boolean constants of size `sz`.
1754 
1755  The constants are named using the given prefix.
1756  If `ctx=None`, then the global context is used.
1757 
1758  >>> P = BoolVector('p', 3)
1759  >>> P
1760  [p__0, p__1, p__2]
1761  >>> And(P)
1762  And(p__0, p__1, p__2)
1763  """
1764  return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1765 
1766 
1767 def FreshBool(prefix="b", ctx=None):
1768  """Return a fresh Boolean constant in the given context using the given prefix.
1769 
1770  If `ctx=None`, then the global context is used.
1771 
1772  >>> b1 = FreshBool()
1773  >>> b2 = FreshBool()
1774  >>> eq(b1, b2)
1775  False
1776  """
1777  ctx = _get_ctx(ctx)
1778  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1779 
1780 
1781 def Implies(a, b, ctx=None):
1782  """Create a Z3 implies expression.
1783 
1784  >>> p, q = Bools('p q')
1785  >>> Implies(p, q)
1786  Implies(p, q)
1787  """
1788  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1789  s = BoolSort(ctx)
1790  a = s.cast(a)
1791  b = s.cast(b)
1792  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1793 
1794 
1795 def Xor(a, b, ctx=None):
1796  """Create a Z3 Xor expression.
1797 
1798  >>> p, q = Bools('p q')
1799  >>> Xor(p, q)
1800  Xor(p, q)
1801  >>> simplify(Xor(p, q))
1802  Not(p == q)
1803  """
1804  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1805  s = BoolSort(ctx)
1806  a = s.cast(a)
1807  b = s.cast(b)
1808  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1809 
1810 
1811 def Not(a, ctx=None):
1812  """Create a Z3 not expression or probe.
1813 
1814  >>> p = Bool('p')
1815  >>> Not(Not(p))
1816  Not(Not(p))
1817  >>> simplify(Not(Not(p)))
1818  p
1819  """
1820  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1821  if is_probe(a):
1822  # Not is also used to build probes
1823  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1824  else:
1825  s = BoolSort(ctx)
1826  a = s.cast(a)
1827  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1828 
1829 
1830 def mk_not(a):
1831  if is_not(a):
1832  return a.arg(0)
1833  else:
1834  return Not(a)
1835 
1836 
1837 def _has_probe(args):
1838  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1839  for arg in args:
1840  if is_probe(arg):
1841  return True
1842  return False
1843 
1844 
1845 def And(*args):
1846  """Create a Z3 and-expression or and-probe.
1847 
1848  >>> p, q, r = Bools('p q r')
1849  >>> And(p, q, r)
1850  And(p, q, r)
1851  >>> P = BoolVector('p', 5)
1852  >>> And(P)
1853  And(p__0, p__1, p__2, p__3, p__4)
1854  """
1855  last_arg = None
1856  if len(args) > 0:
1857  last_arg = args[len(args) - 1]
1858  if isinstance(last_arg, Context):
1859  ctx = args[len(args) - 1]
1860  args = args[:len(args) - 1]
1861  elif len(args) == 1 and isinstance(args[0], AstVector):
1862  ctx = args[0].ctx
1863  args = [a for a in args[0]]
1864  else:
1865  ctx = None
1866  args = _get_args(args)
1867  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1868  if z3_debug():
1869  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1870  if _has_probe(args):
1871  return _probe_and(args, ctx)
1872  else:
1873  args = _coerce_expr_list(args, ctx)
1874  _args, sz = _to_ast_array(args)
1875  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1876 
1877 
1878 def Or(*args):
1879  """Create a Z3 or-expression or or-probe.
1880 
1881  >>> p, q, r = Bools('p q r')
1882  >>> Or(p, q, r)
1883  Or(p, q, r)
1884  >>> P = BoolVector('p', 5)
1885  >>> Or(P)
1886  Or(p__0, p__1, p__2, p__3, p__4)
1887  """
1888  last_arg = None
1889  if len(args) > 0:
1890  last_arg = args[len(args) - 1]
1891  if isinstance(last_arg, Context):
1892  ctx = args[len(args) - 1]
1893  args = args[:len(args) - 1]
1894  elif len(args) == 1 and isinstance(args[0], AstVector):
1895  ctx = args[0].ctx
1896  args = [a for a in args[0]]
1897  else:
1898  ctx = None
1899  args = _get_args(args)
1900  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1901  if z3_debug():
1902  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1903  if _has_probe(args):
1904  return _probe_or(args, ctx)
1905  else:
1906  args = _coerce_expr_list(args, ctx)
1907  _args, sz = _to_ast_array(args)
1908  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1909 
1910 #########################################
1911 #
1912 # Patterns
1913 #
1914 #########################################
1915 
1916 
1917 class PatternRef(ExprRef):
1918  """Patterns are hints for quantifier instantiation.
1919 
1920  """
1921 
1922  def as_ast(self):
1923  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1924 
1925  def get_id(self):
1926  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1927 
1928 
1929 def is_pattern(a):
1930  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1931 
1932  >>> f = Function('f', IntSort(), IntSort())
1933  >>> x = Int('x')
1934  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1935  >>> q
1936  ForAll(x, f(x) == 0)
1937  >>> q.num_patterns()
1938  1
1939  >>> is_pattern(q.pattern(0))
1940  True
1941  >>> q.pattern(0)
1942  f(Var(0))
1943  """
1944  return isinstance(a, PatternRef)
1945 
1946 
1947 def MultiPattern(*args):
1948  """Create a Z3 multi-pattern using the given expressions `*args`
1949 
1950  >>> f = Function('f', IntSort(), IntSort())
1951  >>> g = Function('g', IntSort(), IntSort())
1952  >>> x = Int('x')
1953  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1954  >>> q
1955  ForAll(x, f(x) != g(x))
1956  >>> q.num_patterns()
1957  1
1958  >>> is_pattern(q.pattern(0))
1959  True
1960  >>> q.pattern(0)
1961  MultiPattern(f(Var(0)), g(Var(0)))
1962  """
1963  if z3_debug():
1964  _z3_assert(len(args) > 0, "At least one argument expected")
1965  _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1966  ctx = args[0].ctx
1967  args, sz = _to_ast_array(args)
1968  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1969 
1970 
1971 def _to_pattern(arg):
1972  if is_pattern(arg):
1973  return arg
1974  else:
1975  return MultiPattern(arg)
1976 
1977 #########################################
1978 #
1979 # Quantifiers
1980 #
1981 #########################################
1982 
1983 
1984 class QuantifierRef(BoolRef):
1985  """Universally and Existentially quantified formulas."""
1986 
1987  def as_ast(self):
1988  return self.ast
1989 
1990  def get_id(self):
1991  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1992 
1993  def sort(self):
1994  """Return the Boolean sort or sort of Lambda."""
1995  if self.is_lambda():
1996  return _sort(self.ctx, self.as_ast())
1997  return BoolSort(self.ctx)
1998 
1999  def is_forall(self):
2000  """Return `True` if `self` is a universal quantifier.
2001 
2002  >>> f = Function('f', IntSort(), IntSort())
2003  >>> x = Int('x')
2004  >>> q = ForAll(x, f(x) == 0)
2005  >>> q.is_forall()
2006  True
2007  >>> q = Exists(x, f(x) != 0)
2008  >>> q.is_forall()
2009  False
2010  """
2011  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
2012 
2013  def is_exists(self):
2014  """Return `True` if `self` is an existential quantifier.
2015 
2016  >>> f = Function('f', IntSort(), IntSort())
2017  >>> x = Int('x')
2018  >>> q = ForAll(x, f(x) == 0)
2019  >>> q.is_exists()
2020  False
2021  >>> q = Exists(x, f(x) != 0)
2022  >>> q.is_exists()
2023  True
2024  """
2025  return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
2026 
2027  def is_lambda(self):
2028  """Return `True` if `self` is a lambda expression.
2029 
2030  >>> f = Function('f', IntSort(), IntSort())
2031  >>> x = Int('x')
2032  >>> q = Lambda(x, f(x))
2033  >>> q.is_lambda()
2034  True
2035  >>> q = Exists(x, f(x) != 0)
2036  >>> q.is_lambda()
2037  False
2038  """
2039  return Z3_is_lambda(self.ctx_ref(), self.ast)
2040 
2041  def __getitem__(self, arg):
2042  """Return the Z3 expression `self[arg]`.
2043  """
2044  if z3_debug():
2045  _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2046  return _array_select(self, arg)
2047 
2048  def weight(self):
2049  """Return the weight annotation of `self`.
2050 
2051  >>> f = Function('f', IntSort(), IntSort())
2052  >>> x = Int('x')
2053  >>> q = ForAll(x, f(x) == 0)
2054  >>> q.weight()
2055  1
2056  >>> q = ForAll(x, f(x) == 0, weight=10)
2057  >>> q.weight()
2058  10
2059  """
2060  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
2061 
2062  def num_patterns(self):
2063  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2064 
2065  >>> f = Function('f', IntSort(), IntSort())
2066  >>> g = Function('g', IntSort(), IntSort())
2067  >>> x = Int('x')
2068  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2069  >>> q.num_patterns()
2070  2
2071  """
2072  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
2073 
2074  def pattern(self, idx):
2075  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2076 
2077  >>> f = Function('f', IntSort(), IntSort())
2078  >>> g = Function('g', IntSort(), IntSort())
2079  >>> x = Int('x')
2080  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2081  >>> q.num_patterns()
2082  2
2083  >>> q.pattern(0)
2084  f(Var(0))
2085  >>> q.pattern(1)
2086  g(Var(0))
2087  """
2088  if z3_debug():
2089  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2090  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2091 
2092  def num_no_patterns(self):
2093  """Return the number of no-patterns."""
2094  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
2095 
2096  def no_pattern(self, idx):
2097  """Return a no-pattern."""
2098  if z3_debug():
2099  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2100  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2101 
2102  def body(self):
2103  """Return the expression being quantified.
2104 
2105  >>> f = Function('f', IntSort(), IntSort())
2106  >>> x = Int('x')
2107  >>> q = ForAll(x, f(x) == 0)
2108  >>> q.body()
2109  f(Var(0)) == 0
2110  """
2111  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
2112 
2113  def num_vars(self):
2114  """Return the number of variables bounded by this quantifier.
2115 
2116  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2117  >>> x = Int('x')
2118  >>> y = Int('y')
2119  >>> q = ForAll([x, y], f(x, y) >= x)
2120  >>> q.num_vars()
2121  2
2122  """
2123  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
2124 
2125  def var_name(self, idx):
2126  """Return a string representing a name used when displaying the quantifier.
2127 
2128  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2129  >>> x = Int('x')
2130  >>> y = Int('y')
2131  >>> q = ForAll([x, y], f(x, y) >= x)
2132  >>> q.var_name(0)
2133  'x'
2134  >>> q.var_name(1)
2135  'y'
2136  """
2137  if z3_debug():
2138  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2139  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
2140 
2141  def var_sort(self, idx):
2142  """Return the sort of a bound variable.
2143 
2144  >>> f = Function('f', IntSort(), RealSort(), IntSort())
2145  >>> x = Int('x')
2146  >>> y = Real('y')
2147  >>> q = ForAll([x, y], f(x, y) >= x)
2148  >>> q.var_sort(0)
2149  Int
2150  >>> q.var_sort(1)
2151  Real
2152  """
2153  if z3_debug():
2154  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2155  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
2156 
2157  def children(self):
2158  """Return a list containing a single element self.body()
2159 
2160  >>> f = Function('f', IntSort(), IntSort())
2161  >>> x = Int('x')
2162  >>> q = ForAll(x, f(x) == 0)
2163  >>> q.children()
2164  [f(Var(0)) == 0]
2165  """
2166  return [self.body()]
2167 
2168 
2169 def is_quantifier(a):
2170  """Return `True` if `a` is a Z3 quantifier.
2171 
2172  >>> f = Function('f', IntSort(), IntSort())
2173  >>> x = Int('x')
2174  >>> q = ForAll(x, f(x) == 0)
2175  >>> is_quantifier(q)
2176  True
2177  >>> is_quantifier(f(x))
2178  False
2179  """
2180  return isinstance(a, QuantifierRef)
2181 
2182 
2183 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2184  if z3_debug():
2185  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2186  _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2187  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2188  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2189  if is_app(vs):
2190  ctx = vs.ctx
2191  vs = [vs]
2192  else:
2193  ctx = vs[0].ctx
2194  if not is_expr(body):
2195  body = BoolVal(body, ctx)
2196  num_vars = len(vs)
2197  if num_vars == 0:
2198  return body
2199  _vs = (Ast * num_vars)()
2200  for i in range(num_vars):
2201  # TODO: Check if is constant
2202  _vs[i] = vs[i].as_ast()
2203  patterns = [_to_pattern(p) for p in patterns]
2204  num_pats = len(patterns)
2205  _pats = (Pattern * num_pats)()
2206  for i in range(num_pats):
2207  _pats[i] = patterns[i].ast
2208  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2209  qid = to_symbol(qid, ctx)
2210  skid = to_symbol(skid, ctx)
2211  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2212  num_vars, _vs,
2213  num_pats, _pats,
2214  num_no_pats, _no_pats,
2215  body.as_ast()), ctx)
2216 
2217 
2218 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2219  """Create a Z3 forall formula.
2220 
2221  The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2222 
2223  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2224  >>> x = Int('x')
2225  >>> y = Int('y')
2226  >>> ForAll([x, y], f(x, y) >= x)
2227  ForAll([x, y], f(x, y) >= x)
2228  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2229  ForAll([x, y], f(x, y) >= x)
2230  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2231  ForAll([x, y], f(x, y) >= x)
2232  """
2233  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2234 
2235 
2236 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2237  """Create a Z3 exists formula.
2238 
2239  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2240 
2241 
2242  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2243  >>> x = Int('x')
2244  >>> y = Int('y')
2245  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2246  >>> q
2247  Exists([x, y], f(x, y) >= x)
2248  >>> is_quantifier(q)
2249  True
2250  >>> r = Tactic('nnf')(q).as_expr()
2251  >>> is_quantifier(r)
2252  False
2253  """
2254  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2255 
2256 
2257 def Lambda(vs, body):
2258  """Create a Z3 lambda expression.
2259 
2260  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2261  >>> mem0 = Array('mem0', IntSort(), IntSort())
2262  >>> lo, hi, e, i = Ints('lo hi e i')
2263  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2264  >>> mem1
2265  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2266  """
2267  ctx = body.ctx
2268  if is_app(vs):
2269  vs = [vs]
2270  num_vars = len(vs)
2271  _vs = (Ast * num_vars)()
2272  for i in range(num_vars):
2273  # TODO: Check if is constant
2274  _vs[i] = vs[i].as_ast()
2275  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2276 
2277 #########################################
2278 #
2279 # Arithmetic
2280 #
2281 #########################################
2282 
2283 
2284 class ArithSortRef(SortRef):
2285  """Real and Integer sorts."""
2286 
2287  def is_real(self):
2288  """Return `True` if `self` is of the sort Real.
2289 
2290  >>> x = Real('x')
2291  >>> x.is_real()
2292  True
2293  >>> (x + 1).is_real()
2294  True
2295  >>> x = Int('x')
2296  >>> x.is_real()
2297  False
2298  """
2299  return self.kind() == Z3_REAL_SORT
2300 
2301  def is_int(self):
2302  """Return `True` if `self` is of the sort Integer.
2303 
2304  >>> x = Int('x')
2305  >>> x.is_int()
2306  True
2307  >>> (x + 1).is_int()
2308  True
2309  >>> x = Real('x')
2310  >>> x.is_int()
2311  False
2312  """
2313  return self.kind() == Z3_INT_SORT
2314 
2315  def is_bool(self):
2316  return False
2317 
2318  def subsort(self, other):
2319  """Return `True` if `self` is a subsort of `other`."""
2320  return self.is_int() and is_arith_sort(other) and other.is_real()
2321 
2322  def cast(self, val):
2323  """Try to cast `val` as an Integer or Real.
2324 
2325  >>> IntSort().cast(10)
2326  10
2327  >>> is_int(IntSort().cast(10))
2328  True
2329  >>> is_int(10)
2330  False
2331  >>> RealSort().cast(10)
2332  10
2333  >>> is_real(RealSort().cast(10))
2334  True
2335  """
2336  if is_expr(val):
2337  if z3_debug():
2338  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2339  val_s = val.sort()
2340  if self.eq(val_s):
2341  return val
2342  if val_s.is_int() and self.is_real():
2343  return ToReal(val)
2344  if val_s.is_bool() and self.is_int():
2345  return If(val, 1, 0)
2346  if val_s.is_bool() and self.is_real():
2347  return ToReal(If(val, 1, 0))
2348  if z3_debug():
2349  _z3_assert(False, "Z3 Integer/Real expression expected")
2350  else:
2351  if self.is_int():
2352  return IntVal(val, self.ctx)
2353  if self.is_real():
2354  return RealVal(val, self.ctx)
2355  if z3_debug():
2356  msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2357  _z3_assert(False, msg % self)
2358 
2359 
2360 def is_arith_sort(s):
2361  """Return `True` if s is an arithmetical sort (type).
2362 
2363  >>> is_arith_sort(IntSort())
2364  True
2365  >>> is_arith_sort(RealSort())
2366  True
2367  >>> is_arith_sort(BoolSort())
2368  False
2369  >>> n = Int('x') + 1
2370  >>> is_arith_sort(n.sort())
2371  True
2372  """
2373  return isinstance(s, ArithSortRef)
2374 
2375 
2376 class ArithRef(ExprRef):
2377  """Integer and Real expressions."""
2378 
2379  def sort(self):
2380  """Return the sort (type) of the arithmetical expression `self`.
2381 
2382  >>> Int('x').sort()
2383  Int
2384  >>> (Real('x') + 1).sort()
2385  Real
2386  """
2387  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2388 
2389  def is_int(self):
2390  """Return `True` if `self` is an integer expression.
2391 
2392  >>> x = Int('x')
2393  >>> x.is_int()
2394  True
2395  >>> (x + 1).is_int()
2396  True
2397  >>> y = Real('y')
2398  >>> (x + y).is_int()
2399  False
2400  """
2401  return self.sort().is_int()
2402 
2403  def is_real(self):
2404  """Return `True` if `self` is an real expression.
2405 
2406  >>> x = Real('x')
2407  >>> x.is_real()
2408  True
2409  >>> (x + 1).is_real()
2410  True
2411  """
2412  return self.sort().is_real()
2413 
2414  def __add__(self, other):
2415  """Create the Z3 expression `self + other`.
2416 
2417  >>> x = Int('x')
2418  >>> y = Int('y')
2419  >>> x + y
2420  x + y
2421  >>> (x + y).sort()
2422  Int
2423  """
2424  a, b = _coerce_exprs(self, other)
2425  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2426 
2427  def __radd__(self, other):
2428  """Create the Z3 expression `other + self`.
2429 
2430  >>> x = Int('x')
2431  >>> 10 + x
2432  10 + x
2433  """
2434  a, b = _coerce_exprs(self, other)
2435  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2436 
2437  def __mul__(self, other):
2438  """Create the Z3 expression `self * other`.
2439 
2440  >>> x = Real('x')
2441  >>> y = Real('y')
2442  >>> x * y
2443  x*y
2444  >>> (x * y).sort()
2445  Real
2446  """
2447  if isinstance(other, BoolRef):
2448  return If(other, self, 0)
2449  a, b = _coerce_exprs(self, other)
2450  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2451 
2452  def __rmul__(self, other):
2453  """Create the Z3 expression `other * self`.
2454 
2455  >>> x = Real('x')
2456  >>> 10 * x
2457  10*x
2458  """
2459  a, b = _coerce_exprs(self, other)
2460  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2461 
2462  def __sub__(self, other):
2463  """Create the Z3 expression `self - other`.
2464 
2465  >>> x = Int('x')
2466  >>> y = Int('y')
2467  >>> x - y
2468  x - y
2469  >>> (x - y).sort()
2470  Int
2471  """
2472  a, b = _coerce_exprs(self, other)
2473  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2474 
2475  def __rsub__(self, other):
2476  """Create the Z3 expression `other - self`.
2477 
2478  >>> x = Int('x')
2479  >>> 10 - x
2480  10 - x
2481  """
2482  a, b = _coerce_exprs(self, other)
2483  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2484 
2485  def __pow__(self, other):
2486  """Create the Z3 expression `self**other` (** is the power operator).
2487 
2488  >>> x = Real('x')
2489  >>> x**3
2490  x**3
2491  >>> (x**3).sort()
2492  Real
2493  >>> simplify(IntVal(2)**8)
2494  256
2495  """
2496  a, b = _coerce_exprs(self, other)
2497  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2498 
2499  def __rpow__(self, other):
2500  """Create the Z3 expression `other**self` (** is the power operator).
2501 
2502  >>> x = Real('x')
2503  >>> 2**x
2504  2**x
2505  >>> (2**x).sort()
2506  Real
2507  >>> simplify(2**IntVal(8))
2508  256
2509  """
2510  a, b = _coerce_exprs(self, other)
2511  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2512 
2513  def __div__(self, other):
2514  """Create the Z3 expression `other/self`.
2515 
2516  >>> x = Int('x')
2517  >>> y = Int('y')
2518  >>> x/y
2519  x/y
2520  >>> (x/y).sort()
2521  Int
2522  >>> (x/y).sexpr()
2523  '(div x y)'
2524  >>> x = Real('x')
2525  >>> y = Real('y')
2526  >>> x/y
2527  x/y
2528  >>> (x/y).sort()
2529  Real
2530  >>> (x/y).sexpr()
2531  '(/ x y)'
2532  """
2533  a, b = _coerce_exprs(self, other)
2534  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2535 
2536  def __truediv__(self, other):
2537  """Create the Z3 expression `other/self`."""
2538  return self.__div__(other)
2539 
2540  def __rdiv__(self, other):
2541  """Create the Z3 expression `other/self`.
2542 
2543  >>> x = Int('x')
2544  >>> 10/x
2545  10/x
2546  >>> (10/x).sexpr()
2547  '(div 10 x)'
2548  >>> x = Real('x')
2549  >>> 10/x
2550  10/x
2551  >>> (10/x).sexpr()
2552  '(/ 10.0 x)'
2553  """
2554  a, b = _coerce_exprs(self, other)
2555  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2556 
2557  def __rtruediv__(self, other):
2558  """Create the Z3 expression `other/self`."""
2559  return self.__rdiv__(other)
2560 
2561  def __mod__(self, other):
2562  """Create the Z3 expression `other%self`.
2563 
2564  >>> x = Int('x')
2565  >>> y = Int('y')
2566  >>> x % y
2567  x%y
2568  >>> simplify(IntVal(10) % IntVal(3))
2569  1
2570  """
2571  a, b = _coerce_exprs(self, other)
2572  if z3_debug():
2573  _z3_assert(a.is_int(), "Z3 integer expression expected")
2574  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2575 
2576  def __rmod__(self, other):
2577  """Create the Z3 expression `other%self`.
2578 
2579  >>> x = Int('x')
2580  >>> 10 % x
2581  10%x
2582  """
2583  a, b = _coerce_exprs(self, other)
2584  if z3_debug():
2585  _z3_assert(a.is_int(), "Z3 integer expression expected")
2586  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2587 
2588  def __neg__(self):
2589  """Return an expression representing `-self`.
2590 
2591  >>> x = Int('x')
2592  >>> -x
2593  -x
2594  >>> simplify(-(-x))
2595  x
2596  """
2597  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2598 
2599  def __pos__(self):
2600  """Return `self`.
2601 
2602  >>> x = Int('x')
2603  >>> +x
2604  x
2605  """
2606  return self
2607 
2608  def __le__(self, other):
2609  """Create the Z3 expression `other <= self`.
2610 
2611  >>> x, y = Ints('x y')
2612  >>> x <= y
2613  x <= y
2614  >>> y = Real('y')
2615  >>> x <= y
2616  ToReal(x) <= y
2617  """
2618  a, b = _coerce_exprs(self, other)
2619  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2620 
2621  def __lt__(self, other):
2622  """Create the Z3 expression `other < self`.
2623 
2624  >>> x, y = Ints('x y')
2625  >>> x < y
2626  x < y
2627  >>> y = Real('y')
2628  >>> x < y
2629  ToReal(x) < y
2630  """
2631  a, b = _coerce_exprs(self, other)
2632  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2633 
2634  def __gt__(self, other):
2635  """Create the Z3 expression `other > self`.
2636 
2637  >>> x, y = Ints('x y')
2638  >>> x > y
2639  x > y
2640  >>> y = Real('y')
2641  >>> x > y
2642  ToReal(x) > y
2643  """
2644  a, b = _coerce_exprs(self, other)
2645  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2646 
2647  def __ge__(self, other):
2648  """Create the Z3 expression `other >= self`.
2649 
2650  >>> x, y = Ints('x y')
2651  >>> x >= y
2652  x >= y
2653  >>> y = Real('y')
2654  >>> x >= y
2655  ToReal(x) >= y
2656  """
2657  a, b = _coerce_exprs(self, other)
2658  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2659 
2660 
2661 def is_arith(a):
2662  """Return `True` if `a` is an arithmetical expression.
2663 
2664  >>> x = Int('x')
2665  >>> is_arith(x)
2666  True
2667  >>> is_arith(x + 1)
2668  True
2669  >>> is_arith(1)
2670  False
2671  >>> is_arith(IntVal(1))
2672  True
2673  >>> y = Real('y')
2674  >>> is_arith(y)
2675  True
2676  >>> is_arith(y + 1)
2677  True
2678  """
2679  return isinstance(a, ArithRef)
2680 
2681 
2682 def is_int(a):
2683  """Return `True` if `a` is an integer expression.
2684 
2685  >>> x = Int('x')
2686  >>> is_int(x + 1)
2687  True
2688  >>> is_int(1)
2689  False
2690  >>> is_int(IntVal(1))
2691  True
2692  >>> y = Real('y')
2693  >>> is_int(y)
2694  False
2695  >>> is_int(y + 1)
2696  False
2697  """
2698  return is_arith(a) and a.is_int()
2699 
2700 
2701 def is_real(a):
2702  """Return `True` if `a` is a real expression.
2703 
2704  >>> x = Int('x')
2705  >>> is_real(x + 1)
2706  False
2707  >>> y = Real('y')
2708  >>> is_real(y)
2709  True
2710  >>> is_real(y + 1)
2711  True
2712  >>> is_real(1)
2713  False
2714  >>> is_real(RealVal(1))
2715  True
2716  """
2717  return is_arith(a) and a.is_real()
2718 
2719 
2720 def _is_numeral(ctx, a):
2721  return Z3_is_numeral_ast(ctx.ref(), a)
2722 
2723 
2724 def _is_algebraic(ctx, a):
2725  return Z3_is_algebraic_number(ctx.ref(), a)
2726 
2727 
2728 def is_int_value(a):
2729  """Return `True` if `a` is an integer value of sort Int.
2730 
2731  >>> is_int_value(IntVal(1))
2732  True
2733  >>> is_int_value(1)
2734  False
2735  >>> is_int_value(Int('x'))
2736  False
2737  >>> n = Int('x') + 1
2738  >>> n
2739  x + 1
2740  >>> n.arg(1)
2741  1
2742  >>> is_int_value(n.arg(1))
2743  True
2744  >>> is_int_value(RealVal("1/3"))
2745  False
2746  >>> is_int_value(RealVal(1))
2747  False
2748  """
2749  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2750 
2751 
2752 def is_rational_value(a):
2753  """Return `True` if `a` is rational value of sort Real.
2754 
2755  >>> is_rational_value(RealVal(1))
2756  True
2757  >>> is_rational_value(RealVal("3/5"))
2758  True
2759  >>> is_rational_value(IntVal(1))
2760  False
2761  >>> is_rational_value(1)
2762  False
2763  >>> n = Real('x') + 1
2764  >>> n.arg(1)
2765  1
2766  >>> is_rational_value(n.arg(1))
2767  True
2768  >>> is_rational_value(Real('x'))
2769  False
2770  """
2771  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2772 
2773 
2774 def is_algebraic_value(a):
2775  """Return `True` if `a` is an algebraic value of sort Real.
2776 
2777  >>> is_algebraic_value(RealVal("3/5"))
2778  False
2779  >>> n = simplify(Sqrt(2))
2780  >>> n
2781  1.4142135623?
2782  >>> is_algebraic_value(n)
2783  True
2784  """
2785  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2786 
2787 
2788 def is_add(a):
2789  """Return `True` if `a` is an expression of the form b + c.
2790 
2791  >>> x, y = Ints('x y')
2792  >>> is_add(x + y)
2793  True
2794  >>> is_add(x - y)
2795  False
2796  """
2797  return is_app_of(a, Z3_OP_ADD)
2798 
2799 
2800 def is_mul(a):
2801  """Return `True` if `a` is an expression of the form b * c.
2802 
2803  >>> x, y = Ints('x y')
2804  >>> is_mul(x * y)
2805  True
2806  >>> is_mul(x - y)
2807  False
2808  """
2809  return is_app_of(a, Z3_OP_MUL)
2810 
2811 
2812 def is_sub(a):
2813  """Return `True` if `a` is an expression of the form b - c.
2814 
2815  >>> x, y = Ints('x y')
2816  >>> is_sub(x - y)
2817  True
2818  >>> is_sub(x + y)
2819  False
2820  """
2821  return is_app_of(a, Z3_OP_SUB)
2822 
2823 
2824 def is_div(a):
2825  """Return `True` if `a` is an expression of the form b / c.
2826 
2827  >>> x, y = Reals('x y')
2828  >>> is_div(x / y)
2829  True
2830  >>> is_div(x + y)
2831  False
2832  >>> x, y = Ints('x y')
2833  >>> is_div(x / y)
2834  False
2835  >>> is_idiv(x / y)
2836  True
2837  """
2838  return is_app_of(a, Z3_OP_DIV)
2839 
2840 
2841 def is_idiv(a):
2842  """Return `True` if `a` is an expression of the form b div c.
2843 
2844  >>> x, y = Ints('x y')
2845  >>> is_idiv(x / y)
2846  True
2847  >>> is_idiv(x + y)
2848  False
2849  """
2850  return is_app_of(a, Z3_OP_IDIV)
2851 
2852 
2853 def is_mod(a):
2854  """Return `True` if `a` is an expression of the form b % c.
2855 
2856  >>> x, y = Ints('x y')
2857  >>> is_mod(x % y)
2858  True
2859  >>> is_mod(x + y)
2860  False
2861  """
2862  return is_app_of(a, Z3_OP_MOD)
2863 
2864 
2865 def is_le(a):
2866  """Return `True` if `a` is an expression of the form b <= c.
2867 
2868  >>> x, y = Ints('x y')
2869  >>> is_le(x <= y)
2870  True
2871  >>> is_le(x < y)
2872  False
2873  """
2874  return is_app_of(a, Z3_OP_LE)
2875 
2876 
2877 def is_lt(a):
2878  """Return `True` if `a` is an expression of the form b < c.
2879 
2880  >>> x, y = Ints('x y')
2881  >>> is_lt(x < y)
2882  True
2883  >>> is_lt(x == y)
2884  False
2885  """
2886  return is_app_of(a, Z3_OP_LT)
2887 
2888 
2889 def is_ge(a):
2890  """Return `True` if `a` is an expression of the form b >= c.
2891 
2892  >>> x, y = Ints('x y')
2893  >>> is_ge(x >= y)
2894  True
2895  >>> is_ge(x == y)
2896  False
2897  """
2898  return is_app_of(a, Z3_OP_GE)
2899 
2900 
2901 def is_gt(a):
2902  """Return `True` if `a` is an expression of the form b > c.
2903 
2904  >>> x, y = Ints('x y')
2905  >>> is_gt(x > y)
2906  True
2907  >>> is_gt(x == y)
2908  False
2909  """
2910  return is_app_of(a, Z3_OP_GT)
2911 
2912 
2913 def is_is_int(a):
2914  """Return `True` if `a` is an expression of the form IsInt(b).
2915 
2916  >>> x = Real('x')
2917  >>> is_is_int(IsInt(x))
2918  True
2919  >>> is_is_int(x)
2920  False
2921  """
2922  return is_app_of(a, Z3_OP_IS_INT)
2923 
2924 
2925 def is_to_real(a):
2926  """Return `True` if `a` is an expression of the form ToReal(b).
2927 
2928  >>> x = Int('x')
2929  >>> n = ToReal(x)
2930  >>> n
2931  ToReal(x)
2932  >>> is_to_real(n)
2933  True
2934  >>> is_to_real(x)
2935  False
2936  """
2937  return is_app_of(a, Z3_OP_TO_REAL)
2938 
2939 
2940 def is_to_int(a):
2941  """Return `True` if `a` is an expression of the form ToInt(b).
2942 
2943  >>> x = Real('x')
2944  >>> n = ToInt(x)
2945  >>> n
2946  ToInt(x)
2947  >>> is_to_int(n)
2948  True
2949  >>> is_to_int(x)
2950  False
2951  """
2952  return is_app_of(a, Z3_OP_TO_INT)
2953 
2954 
2955 class IntNumRef(ArithRef):
2956  """Integer values."""
2957 
2958  def as_long(self):
2959  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2960 
2961  >>> v = IntVal(1)
2962  >>> v + 1
2963  1 + 1
2964  >>> v.as_long() + 1
2965  2
2966  """
2967  if z3_debug():
2968  _z3_assert(self.is_int(), "Integer value expected")
2969  return int(self.as_string())
2970 
2971  def as_string(self):
2972  """Return a Z3 integer numeral as a Python string.
2973  >>> v = IntVal(100)
2974  >>> v.as_string()
2975  '100'
2976  """
2977  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2978 
2979  def as_binary_string(self):
2980  """Return a Z3 integer numeral as a Python binary string.
2981  >>> v = IntVal(10)
2982  >>> v.as_binary_string()
2983  '1010'
2984  """
2985  return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast())
2986 
2987 
2988 class RatNumRef(ArithRef):
2989  """Rational values."""
2990 
2991  def numerator(self):
2992  """ Return the numerator of a Z3 rational numeral.
2993 
2994  >>> is_rational_value(RealVal("3/5"))
2995  True
2996  >>> n = RealVal("3/5")
2997  >>> n.numerator()
2998  3
2999  >>> is_rational_value(Q(3,5))
3000  True
3001  >>> Q(3,5).numerator()
3002  3
3003  """
3004  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
3005 
3006  def denominator(self):
3007  """ Return the denominator of a Z3 rational numeral.
3008 
3009  >>> is_rational_value(Q(3,5))
3010  True
3011  >>> n = Q(3,5)
3012  >>> n.denominator()
3013  5
3014  """
3015  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
3016 
3017  def numerator_as_long(self):
3018  """ Return the numerator as a Python long.
3019 
3020  >>> v = RealVal(10000000000)
3021  >>> v
3022  10000000000
3023  >>> v + 1
3024  10000000000 + 1
3025  >>> v.numerator_as_long() + 1 == 10000000001
3026  True
3027  """
3028  return self.numerator().as_long()
3029 
3030  def denominator_as_long(self):
3031  """ Return the denominator as a Python long.
3032 
3033  >>> v = RealVal("1/3")
3034  >>> v
3035  1/3
3036  >>> v.denominator_as_long()
3037  3
3038  """
3039  return self.denominator().as_long()
3040 
3041  def is_int(self):
3042  return False
3043 
3044  def is_real(self):
3045  return True
3046 
3047  def is_int_value(self):
3048  return self.denominator().is_int() and self.denominator_as_long() == 1
3049 
3050  def as_long(self):
3051  _z3_assert(self.is_int_value(), "Expected integer fraction")
3052  return self.numerator_as_long()
3053 
3054  def as_decimal(self, prec):
3055  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3056 
3057  >>> v = RealVal("1/5")
3058  >>> v.as_decimal(3)
3059  '0.2'
3060  >>> v = RealVal("1/3")
3061  >>> v.as_decimal(3)
3062  '0.333?'
3063  """
3064  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
3065 
3066  def as_string(self):
3067  """Return a Z3 rational numeral as a Python string.
3068 
3069  >>> v = Q(3,6)
3070  >>> v.as_string()
3071  '1/2'
3072  """
3073  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3074 
3075  def as_fraction(self):
3076  """Return a Z3 rational as a Python Fraction object.
3077 
3078  >>> v = RealVal("1/5")
3079  >>> v.as_fraction()
3080  Fraction(1, 5)
3081  """
3082  return Fraction(self.numerator_as_long(), self.denominator_as_long())
3083 
3084 
3085 class AlgebraicNumRef(ArithRef):
3086  """Algebraic irrational values."""
3087 
3088  def approx(self, precision=10):
3089  """Return a Z3 rational number that approximates the algebraic number `self`.
3090  The result `r` is such that |r - self| <= 1/10^precision
3091 
3092  >>> x = simplify(Sqrt(2))
3093  >>> x.approx(20)
3094  6838717160008073720548335/4835703278458516698824704
3095  >>> x.approx(5)
3096  2965821/2097152
3097  """
3098  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
3099 
3100  def as_decimal(self, prec):
3101  """Return a string representation of the algebraic number `self` in decimal notation
3102  using `prec` decimal places.
3103 
3104  >>> x = simplify(Sqrt(2))
3105  >>> x.as_decimal(10)
3106  '1.4142135623?'
3107  >>> x.as_decimal(20)
3108  '1.41421356237309504880?'
3109  """
3110  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
3111 
3112  def poly(self):
3113  return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_ast()), self.ctx)
3114 
3115  def index(self):
3116  return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast())
3117 
3118 
3119 def _py2expr(a, ctx=None):
3120  if isinstance(a, bool):
3121  return BoolVal(a, ctx)
3122  if _is_int(a):
3123  return IntVal(a, ctx)
3124  if isinstance(a, float):
3125  return RealVal(a, ctx)
3126  if isinstance(a, str):
3127  return StringVal(a, ctx)
3128  if is_expr(a):
3129  return a
3130  if z3_debug():
3131  _z3_assert(False, "Python bool, int, long or float expected")
3132 
3133 
3134 def IntSort(ctx=None):
3135  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3136 
3137  >>> IntSort()
3138  Int
3139  >>> x = Const('x', IntSort())
3140  >>> is_int(x)
3141  True
3142  >>> x.sort() == IntSort()
3143  True
3144  >>> x.sort() == BoolSort()
3145  False
3146  """
3147  ctx = _get_ctx(ctx)
3148  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3149 
3150 
3151 def RealSort(ctx=None):
3152  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3153 
3154  >>> RealSort()
3155  Real
3156  >>> x = Const('x', RealSort())
3157  >>> is_real(x)
3158  True
3159  >>> is_int(x)
3160  False
3161  >>> x.sort() == RealSort()
3162  True
3163  """
3164  ctx = _get_ctx(ctx)
3165  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3166 
3167 
3168 def _to_int_str(val):
3169  if isinstance(val, float):
3170  return str(int(val))
3171  elif isinstance(val, bool):
3172  if val:
3173  return "1"
3174  else:
3175  return "0"
3176  else:
3177  return str(val)
3178 
3179 
3180 def IntVal(val, ctx=None):
3181  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3182 
3183  >>> IntVal(1)
3184  1
3185  >>> IntVal("100")
3186  100
3187  """
3188  ctx = _get_ctx(ctx)
3189  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3190 
3191 
3192 def RealVal(val, ctx=None):
3193  """Return a Z3 real value.
3194 
3195  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3196  If `ctx=None`, then the global context is used.
3197 
3198  >>> RealVal(1)
3199  1
3200  >>> RealVal(1).sort()
3201  Real
3202  >>> RealVal("3/5")
3203  3/5
3204  >>> RealVal("1.5")
3205  3/2
3206  """
3207  ctx = _get_ctx(ctx)
3208  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3209 
3210 
3211 def RatVal(a, b, ctx=None):
3212  """Return a Z3 rational a/b.
3213 
3214  If `ctx=None`, then the global context is used.
3215 
3216  >>> RatVal(3,5)
3217  3/5
3218  >>> RatVal(3,5).sort()
3219  Real
3220  """
3221  if z3_debug():
3222  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3223  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3224  return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3225 
3226 
3227 def Q(a, b, ctx=None):
3228  """Return a Z3 rational a/b.
3229 
3230  If `ctx=None`, then the global context is used.
3231 
3232  >>> Q(3,5)
3233  3/5
3234  >>> Q(3,5).sort()
3235  Real
3236  """
3237  return simplify(RatVal(a, b, ctx=ctx))
3238 
3239 
3240 def Int(name, ctx=None):
3241  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3242 
3243  >>> x = Int('x')
3244  >>> is_int(x)
3245  True
3246  >>> is_int(x + 1)
3247  True
3248  """
3249  ctx = _get_ctx(ctx)
3250  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3251 
3252 
3253 def Ints(names, ctx=None):
3254  """Return a tuple of Integer constants.
3255 
3256  >>> x, y, z = Ints('x y z')
3257  >>> Sum(x, y, z)
3258  x + y + z
3259  """
3260  ctx = _get_ctx(ctx)
3261  if isinstance(names, str):
3262  names = names.split(" ")
3263  return [Int(name, ctx) for name in names]
3264 
3265 
3266 def IntVector(prefix, sz, ctx=None):
3267  """Return a list of integer constants of size `sz`.
3268 
3269  >>> X = IntVector('x', 3)
3270  >>> X
3271  [x__0, x__1, x__2]
3272  >>> Sum(X)
3273  x__0 + x__1 + x__2
3274  """
3275  ctx = _get_ctx(ctx)
3276  return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3277 
3278 
3279 def FreshInt(prefix="x", ctx=None):
3280  """Return a fresh integer constant in the given context using the given prefix.
3281 
3282  >>> x = FreshInt()
3283  >>> y = FreshInt()
3284  >>> eq(x, y)
3285  False
3286  >>> x.sort()
3287  Int
3288  """
3289  ctx = _get_ctx(ctx)
3290  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3291 
3292 
3293 def Real(name, ctx=None):
3294  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3295 
3296  >>> x = Real('x')
3297  >>> is_real(x)
3298  True
3299  >>> is_real(x + 1)
3300  True
3301  """
3302  ctx = _get_ctx(ctx)
3303  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3304 
3305 
3306 def Reals(names, ctx=None):
3307  """Return a tuple of real constants.
3308 
3309  >>> x, y, z = Reals('x y z')
3310  >>> Sum(x, y, z)
3311  x + y + z
3312  >>> Sum(x, y, z).sort()
3313  Real
3314  """
3315  ctx = _get_ctx(ctx)
3316  if isinstance(names, str):
3317  names = names.split(" ")
3318  return [Real(name, ctx) for name in names]
3319 
3320 
3321 def RealVector(prefix, sz, ctx=None):
3322  """Return a list of real constants of size `sz`.
3323 
3324  >>> X = RealVector('x', 3)
3325  >>> X
3326  [x__0, x__1, x__2]
3327  >>> Sum(X)
3328  x__0 + x__1 + x__2
3329  >>> Sum(X).sort()
3330  Real
3331  """
3332  ctx = _get_ctx(ctx)
3333  return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3334 
3335 
3336 def FreshReal(prefix="b", ctx=None):
3337  """Return a fresh real constant in the given context using the given prefix.
3338 
3339  >>> x = FreshReal()
3340  >>> y = FreshReal()
3341  >>> eq(x, y)
3342  False
3343  >>> x.sort()
3344  Real
3345  """
3346  ctx = _get_ctx(ctx)
3347  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3348 
3349 
3350 def ToReal(a):
3351  """ Return the Z3 expression ToReal(a).
3352 
3353  >>> x = Int('x')
3354  >>> x.sort()
3355  Int
3356  >>> n = ToReal(x)
3357  >>> n
3358  ToReal(x)
3359  >>> n.sort()
3360  Real
3361  """
3362  if z3_debug():
3363  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3364  ctx = a.ctx
3365  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3366 
3367 
3368 def ToInt(a):
3369  """ Return the Z3 expression ToInt(a).
3370 
3371  >>> x = Real('x')
3372  >>> x.sort()
3373  Real
3374  >>> n = ToInt(x)
3375  >>> n
3376  ToInt(x)
3377  >>> n.sort()
3378  Int
3379  """
3380  if z3_debug():
3381  _z3_assert(a.is_real(), "Z3 real expression expected.")
3382  ctx = a.ctx
3383  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3384 
3385 
3386 def IsInt(a):
3387  """ Return the Z3 predicate IsInt(a).
3388 
3389  >>> x = Real('x')
3390  >>> IsInt(x + "1/2")
3391  IsInt(x + 1/2)
3392  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3393  [x = 1/2]
3394  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3395  no solution
3396  """
3397  if z3_debug():
3398  _z3_assert(a.is_real(), "Z3 real expression expected.")
3399  ctx = a.ctx
3400  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3401 
3402 
3403 def Sqrt(a, ctx=None):
3404  """ Return a Z3 expression which represents the square root of a.
3405 
3406  >>> x = Real('x')
3407  >>> Sqrt(x)
3408  x**(1/2)
3409  """
3410  if not is_expr(a):
3411  ctx = _get_ctx(ctx)
3412  a = RealVal(a, ctx)
3413  return a ** "1/2"
3414 
3415 
3416 def Cbrt(a, ctx=None):
3417  """ Return a Z3 expression which represents the cubic root of a.
3418 
3419  >>> x = Real('x')
3420  >>> Cbrt(x)
3421  x**(1/3)
3422  """
3423  if not is_expr(a):
3424  ctx = _get_ctx(ctx)
3425  a = RealVal(a, ctx)
3426  return a ** "1/3"
3427 
3428 #########################################
3429 #
3430 # Bit-Vectors
3431 #
3432 #########################################
3433 
3434 
3435 class BitVecSortRef(SortRef):
3436  """Bit-vector sort."""
3437 
3438  def size(self):
3439  """Return the size (number of bits) of the bit-vector sort `self`.
3440 
3441  >>> b = BitVecSort(32)
3442  >>> b.size()
3443  32
3444  """
3445  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3446 
3447  def subsort(self, other):
3448  return is_bv_sort(other) and self.size() < other.size()
3449 
3450  def cast(self, val):
3451  """Try to cast `val` as a Bit-Vector.
3452 
3453  >>> b = BitVecSort(32)
3454  >>> b.cast(10)
3455  10
3456  >>> b.cast(10).sexpr()
3457  '#x0000000a'
3458  """
3459  if is_expr(val):
3460  if z3_debug():
3461  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3462  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3463  return val
3464  else:
3465  return BitVecVal(val, self)
3466 
3467 
3468 def is_bv_sort(s):
3469  """Return True if `s` is a Z3 bit-vector sort.
3470 
3471  >>> is_bv_sort(BitVecSort(32))
3472  True
3473  >>> is_bv_sort(IntSort())
3474  False
3475  """
3476  return isinstance(s, BitVecSortRef)
3477 
3478 
3479 class BitVecRef(ExprRef):
3480  """Bit-vector expressions."""
3481 
3482  def sort(self):
3483  """Return the sort of the bit-vector expression `self`.
3484 
3485  >>> x = BitVec('x', 32)
3486  >>> x.sort()
3487  BitVec(32)
3488  >>> x.sort() == BitVecSort(32)
3489  True
3490  """
3491  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3492 
3493  def size(self):
3494  """Return the number of bits of the bit-vector expression `self`.
3495 
3496  >>> x = BitVec('x', 32)
3497  >>> (x + 1).size()
3498  32
3499  >>> Concat(x, x).size()
3500  64
3501  """
3502  return self.sort().size()
3503 
3504  def __add__(self, other):
3505  """Create the Z3 expression `self + other`.
3506 
3507  >>> x = BitVec('x', 32)
3508  >>> y = BitVec('y', 32)
3509  >>> x + y
3510  x + y
3511  >>> (x + y).sort()
3512  BitVec(32)
3513  """
3514  a, b = _coerce_exprs(self, other)
3515  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3516 
3517  def __radd__(self, other):
3518  """Create the Z3 expression `other + self`.
3519 
3520  >>> x = BitVec('x', 32)
3521  >>> 10 + x
3522  10 + x
3523  """
3524  a, b = _coerce_exprs(self, other)
3525  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3526 
3527  def __mul__(self, other):
3528  """Create the Z3 expression `self * other`.
3529 
3530  >>> x = BitVec('x', 32)
3531  >>> y = BitVec('y', 32)
3532  >>> x * y
3533  x*y
3534  >>> (x * y).sort()
3535  BitVec(32)
3536  """
3537  a, b = _coerce_exprs(self, other)
3538  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3539 
3540  def __rmul__(self, other):
3541  """Create the Z3 expression `other * self`.
3542 
3543  >>> x = BitVec('x', 32)
3544  >>> 10 * x
3545  10*x
3546  """
3547  a, b = _coerce_exprs(self, other)
3548  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3549 
3550  def __sub__(self, other):
3551  """Create the Z3 expression `self - other`.
3552 
3553  >>> x = BitVec('x', 32)
3554  >>> y = BitVec('y', 32)
3555  >>> x - y
3556  x - y
3557  >>> (x - y).sort()
3558  BitVec(32)
3559  """
3560  a, b = _coerce_exprs(self, other)
3561  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3562 
3563  def __rsub__(self, other):
3564  """Create the Z3 expression `other - self`.
3565 
3566  >>> x = BitVec('x', 32)
3567  >>> 10 - x
3568  10 - x
3569  """
3570  a, b = _coerce_exprs(self, other)
3571  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3572 
3573  def __or__(self, other):
3574  """Create the Z3 expression bitwise-or `self | other`.
3575 
3576  >>> x = BitVec('x', 32)
3577  >>> y = BitVec('y', 32)
3578  >>> x | y
3579  x | y
3580  >>> (x | y).sort()
3581  BitVec(32)
3582  """
3583  a, b = _coerce_exprs(self, other)
3584  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3585 
3586  def __ror__(self, other):
3587  """Create the Z3 expression bitwise-or `other | self`.
3588 
3589  >>> x = BitVec('x', 32)
3590  >>> 10 | x
3591  10 | x
3592  """
3593  a, b = _coerce_exprs(self, other)
3594  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3595 
3596  def __and__(self, other):
3597  """Create the Z3 expression bitwise-and `self & other`.
3598 
3599  >>> x = BitVec('x', 32)
3600  >>> y = BitVec('y', 32)
3601  >>> x & y
3602  x & y
3603  >>> (x & y).sort()
3604  BitVec(32)
3605  """
3606  a, b = _coerce_exprs(self, other)
3607  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3608 
3609  def __rand__(self, other):
3610  """Create the Z3 expression bitwise-or `other & self`.
3611 
3612  >>> x = BitVec('x', 32)
3613  >>> 10 & x
3614  10 & x
3615  """
3616  a, b = _coerce_exprs(self, other)
3617  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3618 
3619  def __xor__(self, other):
3620  """Create the Z3 expression bitwise-xor `self ^ other`.
3621 
3622  >>> x = BitVec('x', 32)
3623  >>> y = BitVec('y', 32)
3624  >>> x ^ y
3625  x ^ y
3626  >>> (x ^ y).sort()
3627  BitVec(32)
3628  """
3629  a, b = _coerce_exprs(self, other)
3630  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3631 
3632  def __rxor__(self, other):
3633  """Create the Z3 expression bitwise-xor `other ^ self`.
3634 
3635  >>> x = BitVec('x', 32)
3636  >>> 10 ^ x
3637  10 ^ x
3638  """
3639  a, b = _coerce_exprs(self, other)
3640  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3641 
3642  def __pos__(self):
3643  """Return `self`.
3644 
3645  >>> x = BitVec('x', 32)
3646  >>> +x
3647  x
3648  """
3649  return self
3650 
3651  def __neg__(self):
3652  """Return an expression representing `-self`.
3653 
3654  >>> x = BitVec('x', 32)
3655  >>> -x
3656  -x
3657  >>> simplify(-(-x))
3658  x
3659  """
3660  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3661 
3662  def __invert__(self):
3663  """Create the Z3 expression bitwise-not `~self`.
3664 
3665  >>> x = BitVec('x', 32)
3666  >>> ~x
3667  ~x
3668  >>> simplify(~(~x))
3669  x
3670  """
3671  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3672 
3673  def __div__(self, other):
3674  """Create the Z3 expression (signed) division `self / other`.
3675 
3676  Use the function UDiv() for unsigned division.
3677 
3678  >>> x = BitVec('x', 32)
3679  >>> y = BitVec('y', 32)
3680  >>> x / y
3681  x/y
3682  >>> (x / y).sort()
3683  BitVec(32)
3684  >>> (x / y).sexpr()
3685  '(bvsdiv x y)'
3686  >>> UDiv(x, y).sexpr()
3687  '(bvudiv x y)'
3688  """
3689  a, b = _coerce_exprs(self, other)
3690  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3691 
3692  def __truediv__(self, other):
3693  """Create the Z3 expression (signed) division `self / other`."""
3694  return self.__div__(other)
3695 
3696  def __rdiv__(self, other):
3697  """Create the Z3 expression (signed) division `other / self`.
3698 
3699  Use the function UDiv() for unsigned division.
3700 
3701  >>> x = BitVec('x', 32)
3702  >>> 10 / x
3703  10/x
3704  >>> (10 / x).sexpr()
3705  '(bvsdiv #x0000000a x)'
3706  >>> UDiv(10, x).sexpr()
3707  '(bvudiv #x0000000a x)'
3708  """
3709  a, b = _coerce_exprs(self, other)
3710  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3711 
3712  def __rtruediv__(self, other):
3713  """Create the Z3 expression (signed) division `other / self`."""
3714  return self.__rdiv__(other)
3715 
3716  def __mod__(self, other):
3717  """Create the Z3 expression (signed) mod `self % other`.
3718 
3719  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3720 
3721  >>> x = BitVec('x', 32)
3722  >>> y = BitVec('y', 32)
3723  >>> x % y
3724  x%y
3725  >>> (x % y).sort()
3726  BitVec(32)
3727  >>> (x % y).sexpr()
3728  '(bvsmod x y)'
3729  >>> URem(x, y).sexpr()
3730  '(bvurem x y)'
3731  >>> SRem(x, y).sexpr()
3732  '(bvsrem x y)'
3733  """
3734  a, b = _coerce_exprs(self, other)
3735  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3736 
3737  def __rmod__(self, other):
3738  """Create the Z3 expression (signed) mod `other % self`.
3739 
3740  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3741 
3742  >>> x = BitVec('x', 32)
3743  >>> 10 % x
3744  10%x
3745  >>> (10 % x).sexpr()
3746  '(bvsmod #x0000000a x)'
3747  >>> URem(10, x).sexpr()
3748  '(bvurem #x0000000a x)'
3749  >>> SRem(10, x).sexpr()
3750  '(bvsrem #x0000000a x)'
3751  """
3752  a, b = _coerce_exprs(self, other)
3753  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3754 
3755  def __le__(self, other):
3756  """Create the Z3 expression (signed) `other <= self`.
3757 
3758  Use the function ULE() for unsigned less than or equal to.
3759 
3760  >>> x, y = BitVecs('x y', 32)
3761  >>> x <= y
3762  x <= y
3763  >>> (x <= y).sexpr()
3764  '(bvsle x y)'
3765  >>> ULE(x, y).sexpr()
3766  '(bvule x y)'
3767  """
3768  a, b = _coerce_exprs(self, other)
3769  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3770 
3771  def __lt__(self, other):
3772  """Create the Z3 expression (signed) `other < self`.
3773 
3774  Use the function ULT() for unsigned less than.
3775 
3776  >>> x, y = BitVecs('x y', 32)
3777  >>> x < y
3778  x < y
3779  >>> (x < y).sexpr()
3780  '(bvslt x y)'
3781  >>> ULT(x, y).sexpr()
3782  '(bvult x y)'
3783  """
3784  a, b = _coerce_exprs(self, other)
3785  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3786 
3787  def __gt__(self, other):
3788  """Create the Z3 expression (signed) `other > self`.
3789 
3790  Use the function UGT() for unsigned greater than.
3791 
3792  >>> x, y = BitVecs('x y', 32)
3793  >>> x > y
3794  x > y
3795  >>> (x > y).sexpr()
3796  '(bvsgt x y)'
3797  >>> UGT(x, y).sexpr()
3798  '(bvugt x y)'
3799  """
3800  a, b = _coerce_exprs(self, other)
3801  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3802 
3803  def __ge__(self, other):
3804  """Create the Z3 expression (signed) `other >= self`.
3805 
3806  Use the function UGE() for unsigned greater than or equal to.
3807 
3808  >>> x, y = BitVecs('x y', 32)
3809  >>> x >= y
3810  x >= y
3811  >>> (x >= y).sexpr()
3812  '(bvsge x y)'
3813  >>> UGE(x, y).sexpr()
3814  '(bvuge x y)'
3815  """
3816  a, b = _coerce_exprs(self, other)
3817  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3818 
3819  def __rshift__(self, other):
3820  """Create the Z3 expression (arithmetical) right shift `self >> other`
3821 
3822  Use the function LShR() for the right logical shift
3823 
3824  >>> x, y = BitVecs('x y', 32)
3825  >>> x >> y
3826  x >> y
3827  >>> (x >> y).sexpr()
3828  '(bvashr x y)'
3829  >>> LShR(x, y).sexpr()
3830  '(bvlshr x y)'
3831  >>> BitVecVal(4, 3)
3832  4
3833  >>> BitVecVal(4, 3).as_signed_long()
3834  -4
3835  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3836  -2
3837  >>> simplify(BitVecVal(4, 3) >> 1)
3838  6
3839  >>> simplify(LShR(BitVecVal(4, 3), 1))
3840  2
3841  >>> simplify(BitVecVal(2, 3) >> 1)
3842  1
3843  >>> simplify(LShR(BitVecVal(2, 3), 1))
3844  1
3845  """
3846  a, b = _coerce_exprs(self, other)
3847  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3848 
3849  def __lshift__(self, other):
3850  """Create the Z3 expression left shift `self << other`
3851 
3852  >>> x, y = BitVecs('x y', 32)
3853  >>> x << y
3854  x << y
3855  >>> (x << y).sexpr()
3856  '(bvshl x y)'
3857  >>> simplify(BitVecVal(2, 3) << 1)
3858  4
3859  """
3860  a, b = _coerce_exprs(self, other)
3861  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3862 
3863  def __rrshift__(self, other):
3864  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3865 
3866  Use the function LShR() for the right logical shift
3867 
3868  >>> x = BitVec('x', 32)
3869  >>> 10 >> x
3870  10 >> x
3871  >>> (10 >> x).sexpr()
3872  '(bvashr #x0000000a x)'
3873  """
3874  a, b = _coerce_exprs(self, other)
3875  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3876 
3877  def __rlshift__(self, other):
3878  """Create the Z3 expression left shift `other << self`.
3879 
3880  Use the function LShR() for the right logical shift
3881 
3882  >>> x = BitVec('x', 32)
3883  >>> 10 << x
3884  10 << x
3885  >>> (10 << x).sexpr()
3886  '(bvshl #x0000000a x)'
3887  """
3888  a, b = _coerce_exprs(self, other)
3889  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3890 
3891 
3892 class BitVecNumRef(BitVecRef):
3893  """Bit-vector values."""
3894 
3895  def as_long(self):
3896  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3897 
3898  >>> v = BitVecVal(0xbadc0de, 32)
3899  >>> v
3900  195936478
3901  >>> print("0x%.8x" % v.as_long())
3902  0x0badc0de
3903  """
3904  return int(self.as_string())
3905 
3906  def as_signed_long(self):
3907  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3908  The most significant bit is assumed to be the sign.
3909 
3910  >>> BitVecVal(4, 3).as_signed_long()
3911  -4
3912  >>> BitVecVal(7, 3).as_signed_long()
3913  -1
3914  >>> BitVecVal(3, 3).as_signed_long()
3915  3
3916  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3917  -1
3918  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3919  -1
3920  """
3921  sz = self.size()
3922  val = self.as_long()
3923  if val >= 2**(sz - 1):
3924  val = val - 2**sz
3925  if val < -2**(sz - 1):
3926  val = val + 2**sz
3927  return int(val)
3928 
3929  def as_string(self):
3930  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3931 
3932  def as_binary_string(self):
3933  return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast())
3934 
3935 
3936 def is_bv(a):
3937  """Return `True` if `a` is a Z3 bit-vector expression.
3938 
3939  >>> b = BitVec('b', 32)
3940  >>> is_bv(b)
3941  True
3942  >>> is_bv(b + 10)
3943  True
3944  >>> is_bv(Int('x'))
3945  False
3946  """
3947  return isinstance(a, BitVecRef)
3948 
3949 
3950 def is_bv_value(a):
3951  """Return `True` if `a` is a Z3 bit-vector numeral value.
3952 
3953  >>> b = BitVec('b', 32)
3954  >>> is_bv_value(b)
3955  False
3956  >>> b = BitVecVal(10, 32)
3957  >>> b
3958  10
3959  >>> is_bv_value(b)
3960  True
3961  """
3962  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3963 
3964 
3965 def BV2Int(a, is_signed=False):
3966  """Return the Z3 expression BV2Int(a).
3967 
3968  >>> b = BitVec('b', 3)
3969  >>> BV2Int(b).sort()
3970  Int
3971  >>> x = Int('x')
3972  >>> x > BV2Int(b)
3973  x > BV2Int(b)
3974  >>> x > BV2Int(b, is_signed=False)
3975  x > BV2Int(b)
3976  >>> x > BV2Int(b, is_signed=True)
3977  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3978  >>> solve(x > BV2Int(b), b == 1, x < 3)
3979  [x = 2, b = 1]
3980  """
3981  if z3_debug():
3982  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3983  ctx = a.ctx
3984  # investigate problem with bv2int
3985  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3986 
3987 
3988 def Int2BV(a, num_bits):
3989  """Return the z3 expression Int2BV(a, num_bits).
3990  It is a bit-vector of width num_bits and represents the
3991  modulo of a by 2^num_bits
3992  """
3993  ctx = a.ctx
3994  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3995 
3996 
3997 def BitVecSort(sz, ctx=None):
3998  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3999 
4000  >>> Byte = BitVecSort(8)
4001  >>> Word = BitVecSort(16)
4002  >>> Byte
4003  BitVec(8)
4004  >>> x = Const('x', Byte)
4005  >>> eq(x, BitVec('x', 8))
4006  True
4007  """
4008  ctx = _get_ctx(ctx)
4009  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4010 
4011 
4012 def BitVecVal(val, bv, ctx=None):
4013  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4014 
4015  >>> v = BitVecVal(10, 32)
4016  >>> v
4017  10
4018  >>> print("0x%.8x" % v.as_long())
4019  0x0000000a
4020  """
4021  if is_bv_sort(bv):
4022  ctx = bv.ctx
4023  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4024  else:
4025  ctx = _get_ctx(ctx)
4026  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4027 
4028 
4029 def BitVec(name, bv, ctx=None):
4030  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4031  If `ctx=None`, then the global context is used.
4032 
4033  >>> x = BitVec('x', 16)
4034  >>> is_bv(x)
4035  True
4036  >>> x.size()
4037  16
4038  >>> x.sort()
4039  BitVec(16)
4040  >>> word = BitVecSort(16)
4041  >>> x2 = BitVec('x', word)
4042  >>> eq(x, x2)
4043  True
4044  """
4045  if isinstance(bv, BitVecSortRef):
4046  ctx = bv.ctx
4047  else:
4048  ctx = _get_ctx(ctx)
4049  bv = BitVecSort(bv, ctx)
4050  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4051 
4052 
4053 def BitVecs(names, bv, ctx=None):
4054  """Return a tuple of bit-vector constants of size bv.
4055 
4056  >>> x, y, z = BitVecs('x y z', 16)
4057  >>> x.size()
4058  16
4059  >>> x.sort()
4060  BitVec(16)
4061  >>> Sum(x, y, z)
4062  0 + x + y + z
4063  >>> Product(x, y, z)
4064  1*x*y*z
4065  >>> simplify(Product(x, y, z))
4066  x*y*z
4067  """
4068  ctx = _get_ctx(ctx)
4069  if isinstance(names, str):
4070  names = names.split(" ")
4071  return [BitVec(name, bv, ctx) for name in names]
4072 
4073 
4074 def Concat(*args):
4075  """Create a Z3 bit-vector concatenation expression.
4076 
4077  >>> v = BitVecVal(1, 4)
4078  >>> Concat(v, v+1, v)
4079  Concat(Concat(1, 1 + 1), 1)
4080  >>> simplify(Concat(v, v+1, v))
4081  289
4082  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4083  121
4084  """
4085  args = _get_args(args)
4086  sz = len(args)
4087  if z3_debug():
4088  _z3_assert(sz >= 2, "At least two arguments expected.")
4089 
4090  ctx = None
4091  for a in args:
4092  if is_expr(a):
4093  ctx = a.ctx
4094  break
4095  if is_seq(args[0]) or isinstance(args[0], str):
4096  args = [_coerce_seq(s, ctx) for s in args]
4097  if z3_debug():
4098  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4099  v = (Ast * sz)()
4100  for i in range(sz):
4101  v[i] = args[i].as_ast()
4102  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4103 
4104  if is_re(args[0]):
4105  if z3_debug():
4106  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4107  v = (Ast * sz)()
4108  for i in range(sz):
4109  v[i] = args[i].as_ast()
4110  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4111 
4112  if z3_debug():
4113  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4114  r = args[0]
4115  for i in range(sz - 1):
4116  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4117  return r
4118 
4119 
4120 def Extract(high, low, a):
4121  """Create a Z3 bit-vector extraction expression.
4122  Extract is overloaded to also work on sequence extraction.
4123  The functions SubString and SubSeq are redirected to Extract.
4124  For this case, the arguments are reinterpreted as:
4125  high - is a sequence (string)
4126  low - is an offset
4127  a - is the length to be extracted
4128 
4129  >>> x = BitVec('x', 8)
4130  >>> Extract(6, 2, x)
4131  Extract(6, 2, x)
4132  >>> Extract(6, 2, x).sort()
4133  BitVec(5)
4134  >>> simplify(Extract(StringVal("abcd"),2,1))
4135  "c"
4136  """
4137  if isinstance(high, str):
4138  high = StringVal(high)
4139  if is_seq(high):
4140  s = high
4141  offset, length = _coerce_exprs(low, a, s.ctx)
4142  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4143  if z3_debug():
4144  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4145  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4146  "First and second arguments must be non negative integers")
4147  _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4148  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4149 
4150 
4151 def _check_bv_args(a, b):
4152  if z3_debug():
4153  _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4154 
4155 
4156 def ULE(a, b):
4157  """Create the Z3 expression (unsigned) `other <= self`.
4158 
4159  Use the operator <= for signed less than or equal to.
4160 
4161  >>> x, y = BitVecs('x y', 32)
4162  >>> ULE(x, y)
4163  ULE(x, y)
4164  >>> (x <= y).sexpr()
4165  '(bvsle x y)'
4166  >>> ULE(x, y).sexpr()
4167  '(bvule x y)'
4168  """
4169  _check_bv_args(a, b)
4170  a, b = _coerce_exprs(a, b)
4171  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4172 
4173 
4174 def ULT(a, b):
4175  """Create the Z3 expression (unsigned) `other < self`.
4176 
4177  Use the operator < for signed less than.
4178 
4179  >>> x, y = BitVecs('x y', 32)
4180  >>> ULT(x, y)
4181  ULT(x, y)
4182  >>> (x < y).sexpr()
4183  '(bvslt x y)'
4184  >>> ULT(x, y).sexpr()
4185  '(bvult x y)'
4186  """
4187  _check_bv_args(a, b)
4188  a, b = _coerce_exprs(a, b)
4189  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4190 
4191 
4192 def UGE(a, b):
4193  """Create the Z3 expression (unsigned) `other >= self`.
4194 
4195  Use the operator >= for signed greater than or equal to.
4196 
4197  >>> x, y = BitVecs('x y', 32)
4198  >>> UGE(x, y)
4199  UGE(x, y)
4200  >>> (x >= y).sexpr()
4201  '(bvsge x y)'
4202  >>> UGE(x, y).sexpr()
4203  '(bvuge x y)'
4204  """
4205  _check_bv_args(a, b)
4206  a, b = _coerce_exprs(a, b)
4207  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4208 
4209 
4210 def UGT(a, b):
4211  """Create the Z3 expression (unsigned) `other > self`.
4212 
4213  Use the operator > for signed greater than.
4214 
4215  >>> x, y = BitVecs('x y', 32)
4216  >>> UGT(x, y)
4217  UGT(x, y)
4218  >>> (x > y).sexpr()
4219  '(bvsgt x y)'
4220  >>> UGT(x, y).sexpr()
4221  '(bvugt x y)'
4222  """
4223  _check_bv_args(a, b)
4224  a, b = _coerce_exprs(a, b)
4225  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4226 
4227 
4228 def UDiv(a, b):
4229  """Create the Z3 expression (unsigned) division `self / other`.
4230 
4231  Use the operator / for signed division.
4232 
4233  >>> x = BitVec('x', 32)
4234  >>> y = BitVec('y', 32)
4235  >>> UDiv(x, y)
4236  UDiv(x, y)
4237  >>> UDiv(x, y).sort()
4238  BitVec(32)
4239  >>> (x / y).sexpr()
4240  '(bvsdiv x y)'
4241  >>> UDiv(x, y).sexpr()
4242  '(bvudiv x y)'
4243  """
4244  _check_bv_args(a, b)
4245  a, b = _coerce_exprs(a, b)
4246  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4247 
4248 
4249 def URem(a, b):
4250  """Create the Z3 expression (unsigned) remainder `self % other`.
4251 
4252  Use the operator % for signed modulus, and SRem() for signed remainder.
4253 
4254  >>> x = BitVec('x', 32)
4255  >>> y = BitVec('y', 32)
4256  >>> URem(x, y)
4257  URem(x, y)
4258  >>> URem(x, y).sort()
4259  BitVec(32)
4260  >>> (x % y).sexpr()
4261  '(bvsmod x y)'
4262  >>> URem(x, y).sexpr()
4263  '(bvurem x y)'
4264  """
4265  _check_bv_args(a, b)
4266  a, b = _coerce_exprs(a, b)
4267  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4268 
4269 
4270 def SRem(a, b):
4271  """Create the Z3 expression signed remainder.
4272 
4273  Use the operator % for signed modulus, and URem() for unsigned remainder.
4274 
4275  >>> x = BitVec('x', 32)
4276  >>> y = BitVec('y', 32)
4277  >>> SRem(x, y)
4278  SRem(x, y)
4279  >>> SRem(x, y).sort()
4280  BitVec(32)
4281  >>> (x % y).sexpr()
4282  '(bvsmod x y)'
4283  >>> SRem(x, y).sexpr()
4284  '(bvsrem x y)'
4285  """
4286  _check_bv_args(a, b)
4287  a, b = _coerce_exprs(a, b)
4288  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4289 
4290 
4291 def LShR(a, b):
4292  """Create the Z3 expression logical right shift.
4293 
4294  Use the operator >> for the arithmetical right shift.
4295 
4296  >>> x, y = BitVecs('x y', 32)
4297  >>> LShR(x, y)
4298  LShR(x, y)
4299  >>> (x >> y).sexpr()
4300  '(bvashr x y)'
4301  >>> LShR(x, y).sexpr()
4302  '(bvlshr x y)'
4303  >>> BitVecVal(4, 3)
4304  4
4305  >>> BitVecVal(4, 3).as_signed_long()
4306  -4
4307  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4308  -2
4309  >>> simplify(BitVecVal(4, 3) >> 1)
4310  6
4311  >>> simplify(LShR(BitVecVal(4, 3), 1))
4312  2
4313  >>> simplify(BitVecVal(2, 3) >> 1)
4314  1
4315  >>> simplify(LShR(BitVecVal(2, 3), 1))
4316  1
4317  """
4318  _check_bv_args(a, b)
4319  a, b = _coerce_exprs(a, b)
4320  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4321 
4322 
4323 def RotateLeft(a, b):
4324  """Return an expression representing `a` rotated to the left `b` times.
4325 
4326  >>> a, b = BitVecs('a b', 16)
4327  >>> RotateLeft(a, b)
4328  RotateLeft(a, b)
4329  >>> simplify(RotateLeft(a, 0))
4330  a
4331  >>> simplify(RotateLeft(a, 16))
4332  a
4333  """
4334  _check_bv_args(a, b)
4335  a, b = _coerce_exprs(a, b)
4336  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4337 
4338 
4339 def RotateRight(a, b):
4340  """Return an expression representing `a` rotated to the right `b` times.
4341 
4342  >>> a, b = BitVecs('a b', 16)
4343  >>> RotateRight(a, b)
4344  RotateRight(a, b)
4345  >>> simplify(RotateRight(a, 0))
4346  a
4347  >>> simplify(RotateRight(a, 16))
4348  a
4349  """
4350  _check_bv_args(a, b)
4351  a, b = _coerce_exprs(a, b)
4352  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4353 
4354 
4355 def SignExt(n, a):
4356  """Return a bit-vector expression with `n` extra sign-bits.
4357 
4358  >>> x = BitVec('x', 16)
4359  >>> n = SignExt(8, x)
4360  >>> n.size()
4361  24
4362  >>> n
4363  SignExt(8, x)
4364  >>> n.sort()
4365  BitVec(24)
4366  >>> v0 = BitVecVal(2, 2)
4367  >>> v0
4368  2
4369  >>> v0.size()
4370  2
4371  >>> v = simplify(SignExt(6, v0))
4372  >>> v
4373  254
4374  >>> v.size()
4375  8
4376  >>> print("%.x" % v.as_long())
4377  fe
4378  """
4379  if z3_debug():
4380  _z3_assert(_is_int(n), "First argument must be an integer")
4381  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4382  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4383 
4384 
4385 def ZeroExt(n, a):
4386  """Return a bit-vector expression with `n` extra zero-bits.
4387 
4388  >>> x = BitVec('x', 16)
4389  >>> n = ZeroExt(8, x)
4390  >>> n.size()
4391  24
4392  >>> n
4393  ZeroExt(8, x)
4394  >>> n.sort()
4395  BitVec(24)
4396  >>> v0 = BitVecVal(2, 2)
4397  >>> v0
4398  2
4399  >>> v0.size()
4400  2
4401  >>> v = simplify(ZeroExt(6, v0))
4402  >>> v
4403  2
4404  >>> v.size()
4405  8
4406  """
4407  if z3_debug():
4408  _z3_assert(_is_int(n), "First argument must be an integer")
4409  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4410  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4411 
4412 
4413 def RepeatBitVec(n, a):
4414  """Return an expression representing `n` copies of `a`.
4415 
4416  >>> x = BitVec('x', 8)
4417  >>> n = RepeatBitVec(4, x)
4418  >>> n
4419  RepeatBitVec(4, x)
4420  >>> n.size()
4421  32
4422  >>> v0 = BitVecVal(10, 4)
4423  >>> print("%.x" % v0.as_long())
4424  a
4425  >>> v = simplify(RepeatBitVec(4, v0))
4426  >>> v.size()
4427  16
4428  >>> print("%.x" % v.as_long())
4429  aaaa
4430  """
4431  if z3_debug():
4432  _z3_assert(_is_int(n), "First argument must be an integer")
4433  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4434  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4435 
4436 
4437 def BVRedAnd(a):
4438  """Return the reduction-and expression of `a`."""
4439  if z3_debug():
4440  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4441  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4442 
4443 
4444 def BVRedOr(a):
4445  """Return the reduction-or expression of `a`."""
4446  if z3_debug():
4447  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4448  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4449 
4450 
4451 def BVAddNoOverflow(a, b, signed):
4452  """A predicate the determines that bit-vector addition does not overflow"""
4453  _check_bv_args(a, b)
4454  a, b = _coerce_exprs(a, b)
4455  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4456 
4457 
4458 def BVAddNoUnderflow(a, b):
4459  """A predicate the determines that signed bit-vector addition does not underflow"""
4460  _check_bv_args(a, b)
4461  a, b = _coerce_exprs(a, b)
4462  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4463 
4464 
4465 def BVSubNoOverflow(a, b):
4466  """A predicate the determines that bit-vector subtraction does not overflow"""
4467  _check_bv_args(a, b)
4468  a, b = _coerce_exprs(a, b)
4469  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4470 
4471 
4472 def BVSubNoUnderflow(a, b, signed):
4473  """A predicate the determines that bit-vector subtraction does not underflow"""
4474  _check_bv_args(a, b)
4475  a, b = _coerce_exprs(a, b)
4476  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4477 
4478 
4479 def BVSDivNoOverflow(a, b):
4480  """A predicate the determines that bit-vector signed division does not overflow"""
4481  _check_bv_args(a, b)
4482  a, b = _coerce_exprs(a, b)
4483  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4484 
4485 
4486 def BVSNegNoOverflow(a):
4487  """A predicate the determines that bit-vector unary negation does not overflow"""
4488  if z3_debug():
4489  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4490  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4491 
4492 
4493 def BVMulNoOverflow(a, b, signed):
4494  """A predicate the determines that bit-vector multiplication does not overflow"""
4495  _check_bv_args(a, b)
4496  a, b = _coerce_exprs(a, b)
4497  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4498 
4499 
4500 def BVMulNoUnderflow(a, b):
4501  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4502  _check_bv_args(a, b)
4503  a, b = _coerce_exprs(a, b)
4504  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4505 
4506 
4507 #########################################
4508 #
4509 # Arrays
4510 #
4511 #########################################
4512 
4513 class ArraySortRef(SortRef):
4514  """Array sorts."""
4515 
4516  def domain(self):
4517  """Return the domain of the array sort `self`.
4518 
4519  >>> A = ArraySort(IntSort(), BoolSort())
4520  >>> A.domain()
4521  Int
4522  """
4523  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4524 
4525  def domain_n(self, i):
4526  """Return the domain of the array sort `self`.
4527  """
4528  return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx)
4529 
4530  def range(self):
4531  """Return the range of the array sort `self`.
4532 
4533  >>> A = ArraySort(IntSort(), BoolSort())
4534  >>> A.range()
4535  Bool
4536  """
4537  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4538 
4539 
4540 class ArrayRef(ExprRef):
4541  """Array expressions. """
4542 
4543  def sort(self):
4544  """Return the array sort of the array expression `self`.
4545 
4546  >>> a = Array('a', IntSort(), BoolSort())
4547  >>> a.sort()
4548  Array(Int, Bool)
4549  """
4550  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4551 
4552  def domain(self):
4553  """Shorthand for `self.sort().domain()`.
4554 
4555  >>> a = Array('a', IntSort(), BoolSort())
4556  >>> a.domain()
4557  Int
4558  """
4559  return self.sort().domain()
4560 
4561  def domain_n(self, i):
4562  """Shorthand for self.sort().domain_n(i)`."""
4563  return self.sort().domain_n(i)
4564 
4565  def range(self):
4566  """Shorthand for `self.sort().range()`.
4567 
4568  >>> a = Array('a', IntSort(), BoolSort())
4569  >>> a.range()
4570  Bool
4571  """
4572  return self.sort().range()
4573 
4574  def __getitem__(self, arg):
4575  """Return the Z3 expression `self[arg]`.
4576 
4577  >>> a = Array('a', IntSort(), BoolSort())
4578  >>> i = Int('i')
4579  >>> a[i]
4580  a[i]
4581  >>> a[i].sexpr()
4582  '(select a i)'
4583  """
4584  return _array_select(self, arg)
4585 
4586  def default(self):
4587  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4588 
4589 
4590 def _array_select(ar, arg):
4591  if isinstance(arg, tuple):
4592  args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))]
4593  _args, sz = _to_ast_array(args)
4594  return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4595  arg = ar.sort().domain().cast(arg)
4596  return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4597 
4598 
4599 def is_array_sort(a):
4600  return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4601 
4602 
4603 def is_array(a):
4604  """Return `True` if `a` is a Z3 array expression.
4605 
4606  >>> a = Array('a', IntSort(), IntSort())
4607  >>> is_array(a)
4608  True
4609  >>> is_array(Store(a, 0, 1))
4610  True
4611  >>> is_array(a[0])
4612  False
4613  """
4614  return isinstance(a, ArrayRef)
4615 
4616 
4617 def is_const_array(a):
4618  """Return `True` if `a` is a Z3 constant array.
4619 
4620  >>> a = K(IntSort(), 10)
4621  >>> is_const_array(a)
4622  True
4623  >>> a = Array('a', IntSort(), IntSort())
4624  >>> is_const_array(a)
4625  False
4626  """
4627  return is_app_of(a, Z3_OP_CONST_ARRAY)
4628 
4629 
4630 def is_K(a):
4631  """Return `True` if `a` is a Z3 constant array.
4632 
4633  >>> a = K(IntSort(), 10)
4634  >>> is_K(a)
4635  True
4636  >>> a = Array('a', IntSort(), IntSort())
4637  >>> is_K(a)
4638  False
4639  """
4640  return is_app_of(a, Z3_OP_CONST_ARRAY)
4641 
4642 
4643 def is_map(a):
4644  """Return `True` if `a` is a Z3 map array expression.
4645 
4646  >>> f = Function('f', IntSort(), IntSort())
4647  >>> b = Array('b', IntSort(), IntSort())
4648  >>> a = Map(f, b)
4649  >>> a
4650  Map(f, b)
4651  >>> is_map(a)
4652  True
4653  >>> is_map(b)
4654  False
4655  """
4656  return is_app_of(a, Z3_OP_ARRAY_MAP)
4657 
4658 
4659 def is_default(a):
4660  """Return `True` if `a` is a Z3 default array expression.
4661  >>> d = Default(K(IntSort(), 10))
4662  >>> is_default(d)
4663  True
4664  """
4665  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4666 
4667 
4668 def get_map_func(a):
4669  """Return the function declaration associated with a Z3 map array expression.
4670 
4671  >>> f = Function('f', IntSort(), IntSort())
4672  >>> b = Array('b', IntSort(), IntSort())
4673  >>> a = Map(f, b)
4674  >>> eq(f, get_map_func(a))
4675  True
4676  >>> get_map_func(a)
4677  f
4678  >>> get_map_func(a)(0)
4679  f(0)
4680  """
4681  if z3_debug():
4682  _z3_assert(is_map(a), "Z3 array map expression expected.")
4683  return FuncDeclRef(
4684  Z3_to_func_decl(
4685  a.ctx_ref(),
4686  Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4687  ),
4688  ctx=a.ctx,
4689  )
4690 
4691 
4692 def ArraySort(*sig):
4693  """Return the Z3 array sort with the given domain and range sorts.
4694 
4695  >>> A = ArraySort(IntSort(), BoolSort())
4696  >>> A
4697  Array(Int, Bool)
4698  >>> A.domain()
4699  Int
4700  >>> A.range()
4701  Bool
4702  >>> AA = ArraySort(IntSort(), A)
4703  >>> AA
4704  Array(Int, Array(Int, Bool))
4705  """
4706  sig = _get_args(sig)
4707  if z3_debug():
4708  _z3_assert(len(sig) > 1, "At least two arguments expected")
4709  arity = len(sig) - 1
4710  r = sig[arity]
4711  d = sig[0]
4712  if z3_debug():
4713  for s in sig:
4714  _z3_assert(is_sort(s), "Z3 sort expected")
4715  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4716  ctx = d.ctx
4717  if len(sig) == 2:
4718  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4719  dom = (Sort * arity)()
4720  for i in range(arity):
4721  dom[i] = sig[i].ast
4722  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4723 
4724 
4725 def Array(name, *sorts):
4726  """Return an array constant named `name` with the given domain and range sorts.
4727 
4728  >>> a = Array('a', IntSort(), IntSort())
4729  >>> a.sort()
4730  Array(Int, Int)
4731  >>> a[0]
4732  a[0]
4733  """
4734  s = ArraySort(sorts)
4735  ctx = s.ctx
4736  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4737 
4738 
4739 def Update(a, *args):
4740  """Return a Z3 store array expression.
4741 
4742  >>> a = Array('a', IntSort(), IntSort())
4743  >>> i, v = Ints('i v')
4744  >>> s = Update(a, i, v)
4745  >>> s.sort()
4746  Array(Int, Int)
4747  >>> prove(s[i] == v)
4748  proved
4749  >>> j = Int('j')
4750  >>> prove(Implies(i != j, s[j] == a[j]))
4751  proved
4752  """
4753  if z3_debug():
4754  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4755  args = _get_args(args)
4756  ctx = a.ctx
4757  if len(args) <= 1:
4758  raise Z3Exception("array update requires index and value arguments")
4759  if len(args) == 2:
4760  i = args[0]
4761  v = args[1]
4762  i = a.sort().domain().cast(i)
4763  v = a.sort().range().cast(v)
4764  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4765  v = a.sort().range().cast(args[-1])
4766  idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
4767  _args, sz = _to_ast_array(idxs)
4768  return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
4769 
4770 
4771 def Default(a):
4772  """ Return a default value for array expression.
4773  >>> b = K(IntSort(), 1)
4774  >>> prove(Default(b) == 1)
4775  proved
4776  """
4777  if z3_debug():
4778  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4779  return a.default()
4780 
4781 
4782 def Store(a, *args):
4783  """Return a Z3 store array expression.
4784 
4785  >>> a = Array('a', IntSort(), IntSort())
4786  >>> i, v = Ints('i v')
4787  >>> s = Store(a, i, v)
4788  >>> s.sort()
4789  Array(Int, Int)
4790  >>> prove(s[i] == v)
4791  proved
4792  >>> j = Int('j')
4793  >>> prove(Implies(i != j, s[j] == a[j]))
4794  proved
4795  """
4796  return Update(a, args)
4797 
4798 
4799 def Select(a, *args):
4800  """Return a Z3 select array expression.
4801 
4802  >>> a = Array('a', IntSort(), IntSort())
4803  >>> i = Int('i')
4804  >>> Select(a, i)
4805  a[i]
4806  >>> eq(Select(a, i), a[i])
4807  True
4808  """
4809  args = _get_args(args)
4810  if z3_debug():
4811  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4812  return a[args]
4813 
4814 
4815 def Map(f, *args):
4816  """Return a Z3 map array expression.
4817 
4818  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4819  >>> a1 = Array('a1', IntSort(), IntSort())
4820  >>> a2 = Array('a2', IntSort(), IntSort())
4821  >>> b = Map(f, a1, a2)
4822  >>> b
4823  Map(f, a1, a2)
4824  >>> prove(b[0] == f(a1[0], a2[0]))
4825  proved
4826  """
4827  args = _get_args(args)
4828  if z3_debug():
4829  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4830  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4831  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4832  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4833  _args, sz = _to_ast_array(args)
4834  ctx = f.ctx
4835  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4836 
4837 
4838 def K(dom, v):
4839  """Return a Z3 constant array expression.
4840 
4841  >>> a = K(IntSort(), 10)
4842  >>> a
4843  K(Int, 10)
4844  >>> a.sort()
4845  Array(Int, Int)
4846  >>> i = Int('i')
4847  >>> a[i]
4848  K(Int, 10)[i]
4849  >>> simplify(a[i])
4850  10
4851  """
4852  if z3_debug():
4853  _z3_assert(is_sort(dom), "Z3 sort expected")
4854  ctx = dom.ctx
4855  if not is_expr(v):
4856  v = _py2expr(v, ctx)
4857  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4858 
4859 
4860 def Ext(a, b):
4861  """Return extensionality index for one-dimensional arrays.
4862  >> a, b = Consts('a b', SetSort(IntSort()))
4863  >> Ext(a, b)
4864  Ext(a, b)
4865  """
4866  ctx = a.ctx
4867  if z3_debug():
4868  _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
4869  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4870 
4871 
4872 def SetHasSize(a, k):
4873  ctx = a.ctx
4874  k = _py2expr(k, ctx)
4875  return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4876 
4877 
4878 def is_select(a):
4879  """Return `True` if `a` is a Z3 array select application.
4880 
4881  >>> a = Array('a', IntSort(), IntSort())
4882  >>> is_select(a)
4883  False
4884  >>> i = Int('i')
4885  >>> is_select(a[i])
4886  True
4887  """
4888  return is_app_of(a, Z3_OP_SELECT)
4889 
4890 
4891 def is_store(a):
4892  """Return `True` if `a` is a Z3 array store application.
4893 
4894  >>> a = Array('a', IntSort(), IntSort())
4895  >>> is_store(a)
4896  False
4897  >>> is_store(Store(a, 0, 1))
4898  True
4899  """
4900  return is_app_of(a, Z3_OP_STORE)
4901 
4902 #########################################
4903 #
4904 # Sets
4905 #
4906 #########################################
4907 
4908 
4909 def SetSort(s):
4910  """ Create a set sort over element sort s"""
4911  return ArraySort(s, BoolSort())
4912 
4913 
4914 def EmptySet(s):
4915  """Create the empty set
4916  >>> EmptySet(IntSort())
4917  K(Int, False)
4918  """
4919  ctx = s.ctx
4920  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4921 
4922 
4923 def FullSet(s):
4924  """Create the full set
4925  >>> FullSet(IntSort())
4926  K(Int, True)
4927  """
4928  ctx = s.ctx
4929  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4930 
4931 
4932 def SetUnion(*args):
4933  """ Take the union of sets
4934  >>> a = Const('a', SetSort(IntSort()))
4935  >>> b = Const('b', SetSort(IntSort()))
4936  >>> SetUnion(a, b)
4937  union(a, b)
4938  """
4939  args = _get_args(args)
4940  ctx = _ctx_from_ast_arg_list(args)
4941  _args, sz = _to_ast_array(args)
4942  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4943 
4944 
4945 def SetIntersect(*args):
4946  """ Take the union of sets
4947  >>> a = Const('a', SetSort(IntSort()))
4948  >>> b = Const('b', SetSort(IntSort()))
4949  >>> SetIntersect(a, b)
4950  intersection(a, b)
4951  """
4952  args = _get_args(args)
4953  ctx = _ctx_from_ast_arg_list(args)
4954  _args, sz = _to_ast_array(args)
4955  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4956 
4957 
4958 def SetAdd(s, e):
4959  """ Add element e to set s
4960  >>> a = Const('a', SetSort(IntSort()))
4961  >>> SetAdd(a, 1)
4962  Store(a, 1, True)
4963  """
4964  ctx = _ctx_from_ast_arg_list([s, e])
4965  e = _py2expr(e, ctx)
4966  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4967 
4968 
4969 def SetDel(s, e):
4970  """ Remove element e to set s
4971  >>> a = Const('a', SetSort(IntSort()))
4972  >>> SetDel(a, 1)
4973  Store(a, 1, False)
4974  """
4975  ctx = _ctx_from_ast_arg_list([s, e])
4976  e = _py2expr(e, ctx)
4977  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4978 
4979 
4980 def SetComplement(s):
4981  """ The complement of set s
4982  >>> a = Const('a', SetSort(IntSort()))
4983  >>> SetComplement(a)
4984  complement(a)
4985  """
4986  ctx = s.ctx
4987  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4988 
4989 
4990 def SetDifference(a, b):
4991  """ The set difference of a and b
4992  >>> a = Const('a', SetSort(IntSort()))
4993  >>> b = Const('b', SetSort(IntSort()))
4994  >>> SetDifference(a, b)
4995  setminus(a, b)
4996  """
4997  ctx = _ctx_from_ast_arg_list([a, b])
4998  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4999 
5000 
5001 def IsMember(e, s):
5002  """ Check if e is a member of set s
5003  >>> a = Const('a', SetSort(IntSort()))
5004  >>> IsMember(1, a)
5005  a[1]
5006  """
5007  ctx = _ctx_from_ast_arg_list([s, e])
5008  e = _py2expr(e, ctx)
5009  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5010 
5011 
5012 def IsSubset(a, b):
5013  """ Check if a is a subset of b
5014  >>> a = Const('a', SetSort(IntSort()))
5015  >>> b = Const('b', SetSort(IntSort()))
5016  >>> IsSubset(a, b)
5017  subset(a, b)
5018  """
5019  ctx = _ctx_from_ast_arg_list([a, b])
5020  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5021 
5022 
5023 #########################################
5024 #
5025 # Datatypes
5026 #
5027 #########################################
5028 
5029 def _valid_accessor(acc):
5030  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5031  if not isinstance(acc, tuple):
5032  return False
5033  if len(acc) != 2:
5034  return False
5035  return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5036 
5037 
5038 class Datatype:
5039  """Helper class for declaring Z3 datatypes.
5040 
5041  >>> List = Datatype('List')
5042  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5043  >>> List.declare('nil')
5044  >>> List = List.create()
5045  >>> # List is now a Z3 declaration
5046  >>> List.nil
5047  nil
5048  >>> List.cons(10, List.nil)
5049  cons(10, nil)
5050  >>> List.cons(10, List.nil).sort()
5051  List
5052  >>> cons = List.cons
5053  >>> nil = List.nil
5054  >>> car = List.car
5055  >>> cdr = List.cdr
5056  >>> n = cons(1, cons(0, nil))
5057  >>> n
5058  cons(1, cons(0, nil))
5059  >>> simplify(cdr(n))
5060  cons(0, nil)
5061  >>> simplify(car(n))
5062  1
5063  """
5064 
5065  def __init__(self, name, ctx=None):
5066  self.ctx = _get_ctx(ctx)
5067  self.name = name
5068  self.constructors = []
5069 
5070  def __deepcopy__(self, memo={}):
5071  r = Datatype(self.name, self.ctx)
5072  r.constructors = copy.deepcopy(self.constructors)
5073  return r
5074 
5075  def declare_core(self, name, rec_name, *args):
5076  if z3_debug():
5077  _z3_assert(isinstance(name, str), "String expected")
5078  _z3_assert(isinstance(rec_name, str), "String expected")
5079  _z3_assert(
5080  all([_valid_accessor(a) for a in args]),
5081  "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5082  )
5083  self.constructors.append((name, rec_name, args))
5084 
5085  def declare(self, name, *args):
5086  """Declare constructor named `name` with the given accessors `args`.
5087  Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5088  or a reference to the datatypes being declared.
5089 
5090  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5091  declares the constructor named `cons` that builds a new List using an integer and a List.
5092  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5093  of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5094  we use the method create() to create the actual datatype in Z3.
5095 
5096  >>> List = Datatype('List')
5097  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5098  >>> List.declare('nil')
5099  >>> List = List.create()
5100  """
5101  if z3_debug():
5102  _z3_assert(isinstance(name, str), "String expected")
5103  _z3_assert(name != "", "Constructor name cannot be empty")
5104  return self.declare_core(name, "is-" + name, *args)
5105 
5106  def __repr__(self):
5107  return "Datatype(%s, %s)" % (self.name, self.constructors)
5108 
5109  def create(self):
5110  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5111 
5112  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5113 
5114  >>> List = Datatype('List')
5115  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5116  >>> List.declare('nil')
5117  >>> List = List.create()
5118  >>> List.nil
5119  nil
5120  >>> List.cons(10, List.nil)
5121  cons(10, nil)
5122  """
5123  return CreateDatatypes([self])[0]
5124 
5125 
5126 class ScopedConstructor:
5127  """Auxiliary object used to create Z3 datatypes."""
5128 
5129  def __init__(self, c, ctx):
5130  self.c = c
5131  self.ctx = ctx
5132 
5133  def __del__(self):
5134  if self.ctx.ref() is not None and Z3_del_constructor is not None:
5135  Z3_del_constructor(self.ctx.ref(), self.c)
5136 
5137 
5138 class ScopedConstructorList:
5139  """Auxiliary object used to create Z3 datatypes."""
5140 
5141  def __init__(self, c, ctx):
5142  self.c = c
5143  self.ctx = ctx
5144 
5145  def __del__(self):
5146  if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5147  Z3_del_constructor_list(self.ctx.ref(), self.c)
5148 
5149 
5150 def CreateDatatypes(*ds):
5151  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5152 
5153  In the following example we define a Tree-List using two mutually recursive datatypes.
5154 
5155  >>> TreeList = Datatype('TreeList')
5156  >>> Tree = Datatype('Tree')
5157  >>> # Tree has two constructors: leaf and node
5158  >>> Tree.declare('leaf', ('val', IntSort()))
5159  >>> # a node contains a list of trees
5160  >>> Tree.declare('node', ('children', TreeList))
5161  >>> TreeList.declare('nil')
5162  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5163  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5164  >>> Tree.val(Tree.leaf(10))
5165  val(leaf(10))
5166  >>> simplify(Tree.val(Tree.leaf(10)))
5167  10
5168  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5169  >>> n1
5170  node(cons(leaf(10), cons(leaf(20), nil)))
5171  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5172  >>> simplify(n2 == n1)
5173  False
5174  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5175  True
5176  """
5177  ds = _get_args(ds)
5178  if z3_debug():
5179  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5180  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5181  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5182  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5183  ctx = ds[0].ctx
5184  num = len(ds)
5185  names = (Symbol * num)()
5186  out = (Sort * num)()
5187  clists = (ConstructorList * num)()
5188  to_delete = []
5189  for i in range(num):
5190  d = ds[i]
5191  names[i] = to_symbol(d.name, ctx)
5192  num_cs = len(d.constructors)
5193  cs = (Constructor * num_cs)()
5194  for j in range(num_cs):
5195  c = d.constructors[j]
5196  cname = to_symbol(c[0], ctx)
5197  rname = to_symbol(c[1], ctx)
5198  fs = c[2]
5199  num_fs = len(fs)
5200  fnames = (Symbol * num_fs)()
5201  sorts = (Sort * num_fs)()
5202  refs = (ctypes.c_uint * num_fs)()
5203  for k in range(num_fs):
5204  fname = fs[k][0]
5205  ftype = fs[k][1]
5206  fnames[k] = to_symbol(fname, ctx)
5207  if isinstance(ftype, Datatype):
5208  if z3_debug():
5209  _z3_assert(
5210  ds.count(ftype) == 1,
5211  "One and only one occurrence of each datatype is expected",
5212  )
5213  sorts[k] = None
5214  refs[k] = ds.index(ftype)
5215  else:
5216  if z3_debug():
5217  _z3_assert(is_sort(ftype), "Z3 sort expected")
5218  sorts[k] = ftype.ast
5219  refs[k] = 0
5220  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5221  to_delete.append(ScopedConstructor(cs[j], ctx))
5222  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5223  to_delete.append(ScopedConstructorList(clists[i], ctx))
5224  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5225  result = []
5226  # Create a field for every constructor, recognizer and accessor
5227  for i in range(num):
5228  dref = DatatypeSortRef(out[i], ctx)
5229  num_cs = dref.num_constructors()
5230  for j in range(num_cs):
5231  cref = dref.constructor(j)
5232  cref_name = cref.name()
5233  cref_arity = cref.arity()
5234  if cref.arity() == 0:
5235  cref = cref()
5236  setattr(dref, cref_name, cref)
5237  rref = dref.recognizer(j)
5238  setattr(dref, "is_" + cref_name, rref)
5239  for k in range(cref_arity):
5240  aref = dref.accessor(j, k)
5241  setattr(dref, aref.name(), aref)
5242  result.append(dref)
5243  return tuple(result)
5244 
5245 
5246 class DatatypeSortRef(SortRef):
5247  """Datatype sorts."""
5248 
5249  def num_constructors(self):
5250  """Return the number of constructors in the given Z3 datatype.
5251 
5252  >>> List = Datatype('List')
5253  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5254  >>> List.declare('nil')
5255  >>> List = List.create()
5256  >>> # List is now a Z3 declaration
5257  >>> List.num_constructors()
5258  2
5259  """
5260  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
5261 
5262  def constructor(self, idx):
5263  """Return a constructor of the datatype `self`.
5264 
5265  >>> List = Datatype('List')
5266  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5267  >>> List.declare('nil')
5268  >>> List = List.create()
5269  >>> # List is now a Z3 declaration
5270  >>> List.num_constructors()
5271  2
5272  >>> List.constructor(0)
5273  cons
5274  >>> List.constructor(1)
5275  nil
5276  """
5277  if z3_debug():
5278  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5279  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
5280 
5281  def recognizer(self, idx):
5282  """In Z3, each constructor has an associated recognizer predicate.
5283 
5284  If the constructor is named `name`, then the recognizer `is_name`.
5285 
5286  >>> List = Datatype('List')
5287  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5288  >>> List.declare('nil')
5289  >>> List = List.create()
5290  >>> # List is now a Z3 declaration
5291  >>> List.num_constructors()
5292  2
5293  >>> List.recognizer(0)
5294  is(cons)
5295  >>> List.recognizer(1)
5296  is(nil)
5297  >>> simplify(List.is_nil(List.cons(10, List.nil)))
5298  False
5299  >>> simplify(List.is_cons(List.cons(10, List.nil)))
5300  True
5301  >>> l = Const('l', List)
5302  >>> simplify(List.is_cons(l))
5303  is(cons, l)
5304  """
5305  if z3_debug():
5306  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5307  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
5308 
5309  def accessor(self, i, j):
5310  """In Z3, each constructor has 0 or more accessor.
5311  The number of accessors is equal to the arity of the constructor.
5312 
5313  >>> List = Datatype('List')
5314  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5315  >>> List.declare('nil')
5316  >>> List = List.create()
5317  >>> List.num_constructors()
5318  2
5319  >>> List.constructor(0)
5320  cons
5321  >>> num_accs = List.constructor(0).arity()
5322  >>> num_accs
5323  2
5324  >>> List.accessor(0, 0)
5325  car
5326  >>> List.accessor(0, 1)
5327  cdr
5328  >>> List.constructor(1)
5329  nil
5330  >>> num_accs = List.constructor(1).arity()
5331  >>> num_accs
5332  0
5333  """
5334  if z3_debug():
5335  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5336  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5337  return FuncDeclRef(
5338  Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j),
5339  ctx=self.ctx,
5340  )
5341 
5342 
5343 class DatatypeRef(ExprRef):
5344  """Datatype expressions."""
5345 
5346  def sort(self):
5347  """Return the datatype sort of the datatype expression `self`."""
5348  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
5349 
5350 def DatatypeSort(name, ctx = None):
5351  """Create a reference to a sort that was declared, or will be declared, as a recursive datatype"""
5352  ctx = _get_ctx(ctx)
5353  return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
5354 
5355 def TupleSort(name, sorts, ctx=None):
5356  """Create a named tuple sort base on a set of underlying sorts
5357  Example:
5358  >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5359  """
5360  tuple = Datatype(name, ctx)
5361  projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5362  tuple.declare(name, *projects)
5363  tuple = tuple.create()
5364  return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5365 
5366 
5367 def DisjointSum(name, sorts, ctx=None):
5368  """Create a named tagged union sort base on a set of underlying sorts
5369  Example:
5370  >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5371  """
5372  sum = Datatype(name, ctx)
5373  for i in range(len(sorts)):
5374  sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5375  sum = sum.create()
5376  return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5377 
5378 
5379 def EnumSort(name, values, ctx=None):
5380  """Return a new enumeration sort named `name` containing the given values.
5381 
5382  The result is a pair (sort, list of constants).
5383  Example:
5384  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5385  """
5386  if z3_debug():
5387  _z3_assert(isinstance(name, str), "Name must be a string")
5388  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5389  _z3_assert(len(values) > 0, "At least one value expected")
5390  ctx = _get_ctx(ctx)
5391  num = len(values)
5392  _val_names = (Symbol * num)()
5393  for i in range(num):
5394  _val_names[i] = to_symbol(values[i])
5395  _values = (FuncDecl * num)()
5396  _testers = (FuncDecl * num)()
5397  name = to_symbol(name)
5398  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5399  V = []
5400  for i in range(num):
5401  V.append(FuncDeclRef(_values[i], ctx))
5402  V = [a() for a in V]
5403  return S, V
5404 
5405 #########################################
5406 #
5407 # Parameter Sets
5408 #
5409 #########################################
5410 
5411 
5412 class ParamsRef:
5413  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5414 
5415  Consider using the function `args2params` to create instances of this object.
5416  """
5417 
5418  def __init__(self, ctx=None, params=None):
5419  self.ctx = _get_ctx(ctx)
5420  if params is None:
5421  self.params = Z3_mk_params(self.ctx.ref())
5422  else:
5423  self.params = params
5424  Z3_params_inc_ref(self.ctx.ref(), self.params)
5425 
5426  def __deepcopy__(self, memo={}):
5427  return ParamsRef(self.ctx, self.params)
5428 
5429  def __del__(self):
5430  if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
5431  Z3_params_dec_ref(self.ctx.ref(), self.params)
5432 
5433  def set(self, name, val):
5434  """Set parameter name with value val."""
5435  if z3_debug():
5436  _z3_assert(isinstance(name, str), "parameter name must be a string")
5437  name_sym = to_symbol(name, self.ctx)
5438  if isinstance(val, bool):
5439  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5440  elif _is_int(val):
5441  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5442  elif isinstance(val, float):
5443  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5444  elif isinstance(val, str):
5445  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5446  else:
5447  if z3_debug():
5448  _z3_assert(False, "invalid parameter value")
5449 
5450  def __repr__(self):
5451  return Z3_params_to_string(self.ctx.ref(), self.params)
5452 
5453  def validate(self, ds):
5454  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5455  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5456 
5457 
5458 def args2params(arguments, keywords, ctx=None):
5459  """Convert python arguments into a Z3_params object.
5460  A ':' is added to the keywords, and '_' is replaced with '-'
5461 
5462  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5463  (params model true relevancy 2 elim_and true)
5464  """
5465  if z3_debug():
5466  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5467  prev = None
5468  r = ParamsRef(ctx)
5469  for a in arguments:
5470  if prev is None:
5471  prev = a
5472  else:
5473  r.set(prev, a)
5474  prev = None
5475  for k in keywords:
5476  v = keywords[k]
5477  r.set(k, v)
5478  return r
5479 
5480 
5481 class ParamDescrsRef:
5482  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5483  """
5484 
5485  def __init__(self, descr, ctx=None):
5486  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5487  self.ctx = _get_ctx(ctx)
5488  self.descr = descr
5489  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5490 
5491  def __deepcopy__(self, memo={}):
5492  return ParamsDescrsRef(self.descr, self.ctx)
5493 
5494  def __del__(self):
5495  if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
5496  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5497 
5498  def size(self):
5499  """Return the size of in the parameter description `self`.
5500  """
5501  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5502 
5503  def __len__(self):
5504  """Return the size of in the parameter description `self`.
5505  """
5506  return self.size()
5507 
5508  def get_name(self, i):
5509  """Return the i-th parameter name in the parameter description `self`.
5510  """
5511  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5512 
5513  def get_kind(self, n):
5514  """Return the kind of the parameter named `n`.
5515  """
5516  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5517 
5518  def get_documentation(self, n):
5519  """Return the documentation string of the parameter named `n`.
5520  """
5521  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5522 
5523  def __getitem__(self, arg):
5524  if _is_int(arg):
5525  return self.get_name(arg)
5526  else:
5527  return self.get_kind(arg)
5528 
5529  def __repr__(self):
5530  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5531 
5532 #########################################
5533 #
5534 # Goals
5535 #
5536 #########################################
5537 
5538 
5539 class Goal(Z3PPObject):
5540  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5541 
5542  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5543  A goal has a solution if one of its subgoals has a solution.
5544  A goal is unsatisfiable if all subgoals are unsatisfiable.
5545  """
5546 
5547  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5548  if z3_debug():
5549  _z3_assert(goal is None or ctx is not None,
5550  "If goal is different from None, then ctx must be also different from None")
5551  self.ctx = _get_ctx(ctx)
5552  self.goal = goal
5553  if self.goal is None:
5554  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5555  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5556 
5557  def __del__(self):
5558  if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
5559  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5560 
5561  def depth(self):
5562  """Return the depth of the goal `self`.
5563  The depth corresponds to the number of tactics applied to `self`.
5564 
5565  >>> x, y = Ints('x y')
5566  >>> g = Goal()
5567  >>> g.add(x == 0, y >= x + 1)
5568  >>> g.depth()
5569  0
5570  >>> r = Then('simplify', 'solve-eqs')(g)
5571  >>> # r has 1 subgoal
5572  >>> len(r)
5573  1
5574  >>> r[0].depth()
5575  2
5576  """
5577  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5578 
5579  def inconsistent(self):
5580  """Return `True` if `self` contains the `False` constraints.
5581 
5582  >>> x, y = Ints('x y')
5583  >>> g = Goal()
5584  >>> g.inconsistent()
5585  False
5586  >>> g.add(x == 0, x == 1)
5587  >>> g
5588  [x == 0, x == 1]
5589  >>> g.inconsistent()
5590  False
5591  >>> g2 = Tactic('propagate-values')(g)[0]
5592  >>> g2.inconsistent()
5593  True
5594  """
5595  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5596 
5597  def prec(self):
5598  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5599 
5600  >>> g = Goal()
5601  >>> g.prec() == Z3_GOAL_PRECISE
5602  True
5603  >>> x, y = Ints('x y')
5604  >>> g.add(x == y + 1)
5605  >>> g.prec() == Z3_GOAL_PRECISE
5606  True
5607  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5608  >>> g2 = t(g)[0]
5609  >>> g2
5610  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5611  >>> g2.prec() == Z3_GOAL_PRECISE
5612  False
5613  >>> g2.prec() == Z3_GOAL_UNDER
5614  True
5615  """
5616  return Z3_goal_precision(self.ctx.ref(), self.goal)
5617 
5618  def precision(self):
5619  """Alias for `prec()`.
5620 
5621  >>> g = Goal()
5622  >>> g.precision() == Z3_GOAL_PRECISE
5623  True
5624  """
5625  return self.prec()
5626 
5627  def size(self):
5628  """Return the number of constraints in the goal `self`.
5629 
5630  >>> g = Goal()
5631  >>> g.size()
5632  0
5633  >>> x, y = Ints('x y')
5634  >>> g.add(x == 0, y > x)
5635  >>> g.size()
5636  2
5637  """
5638  return int(Z3_goal_size(self.ctx.ref(), self.goal))
5639 
5640  def __len__(self):
5641  """Return the number of constraints in the goal `self`.
5642 
5643  >>> g = Goal()
5644  >>> len(g)
5645  0
5646  >>> x, y = Ints('x y')
5647  >>> g.add(x == 0, y > x)
5648  >>> len(g)
5649  2
5650  """
5651  return self.size()
5652 
5653  def get(self, i):
5654  """Return a constraint in the goal `self`.
5655 
5656  >>> g = Goal()
5657  >>> x, y = Ints('x y')
5658  >>> g.add(x == 0, y > x)
5659  >>> g.get(0)
5660  x == 0
5661  >>> g.get(1)
5662  y > x
5663  """
5664  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5665 
5666  def __getitem__(self, arg):
5667  """Return a constraint in the goal `self`.
5668 
5669  >>> g = Goal()
5670  >>> x, y = Ints('x y')
5671  >>> g.add(x == 0, y > x)
5672  >>> g[0]
5673  x == 0
5674  >>> g[1]
5675  y > x
5676  """
5677  if arg >= len(self):
5678  raise IndexError
5679  return self.get(arg)
5680 
5681  def assert_exprs(self, *args):
5682  """Assert constraints into the goal.
5683 
5684  >>> x = Int('x')
5685  >>> g = Goal()
5686  >>> g.assert_exprs(x > 0, x < 2)
5687  >>> g
5688  [x > 0, x < 2]
5689  """
5690  args = _get_args(args)
5691  s = BoolSort(self.ctx)
5692  for arg in args:
5693  arg = s.cast(arg)
5694  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5695 
5696  def append(self, *args):
5697  """Add constraints.
5698 
5699  >>> x = Int('x')
5700  >>> g = Goal()
5701  >>> g.append(x > 0, x < 2)
5702  >>> g
5703  [x > 0, x < 2]
5704  """
5705  self.assert_exprs(*args)
5706 
5707  def insert(self, *args):
5708  """Add constraints.
5709 
5710  >>> x = Int('x')
5711  >>> g = Goal()
5712  >>> g.insert(x > 0, x < 2)
5713  >>> g
5714  [x > 0, x < 2]
5715  """
5716  self.assert_exprs(*args)
5717 
5718  def add(self, *args):
5719  """Add constraints.
5720 
5721  >>> x = Int('x')
5722  >>> g = Goal()
5723  >>> g.add(x > 0, x < 2)
5724  >>> g
5725  [x > 0, x < 2]
5726  """
5727  self.assert_exprs(*args)
5728 
5729  def convert_model(self, model):
5730  """Retrieve model from a satisfiable goal
5731  >>> a, b = Ints('a b')
5732  >>> g = Goal()
5733  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5734  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5735  >>> r = t(g)
5736  >>> r[0]
5737  [Or(b == 0, b == 1), Not(0 <= b)]
5738  >>> r[1]
5739  [Or(b == 0, b == 1), Not(1 <= b)]
5740  >>> # Remark: the subgoal r[0] is unsatisfiable
5741  >>> # Creating a solver for solving the second subgoal
5742  >>> s = Solver()
5743  >>> s.add(r[1])
5744  >>> s.check()
5745  sat
5746  >>> s.model()
5747  [b = 0]
5748  >>> # Model s.model() does not assign a value to `a`
5749  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5750  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5751  >>> r[1].convert_model(s.model())
5752  [b = 0, a = 1]
5753  """
5754  if z3_debug():
5755  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5756  return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5757 
5758  def __repr__(self):
5759  return obj_to_string(self)
5760 
5761  def sexpr(self):
5762  """Return a textual representation of the s-expression representing the goal."""
5763  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5764 
5765  def dimacs(self, include_names=True):
5766  """Return a textual representation of the goal in DIMACS format."""
5767  return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
5768 
5769  def translate(self, target):
5770  """Copy goal `self` to context `target`.
5771 
5772  >>> x = Int('x')
5773  >>> g = Goal()
5774  >>> g.add(x > 10)
5775  >>> g
5776  [x > 10]
5777  >>> c2 = Context()
5778  >>> g2 = g.translate(c2)
5779  >>> g2
5780  [x > 10]
5781  >>> g.ctx == main_ctx()
5782  True
5783  >>> g2.ctx == c2
5784  True
5785  >>> g2.ctx == main_ctx()
5786  False
5787  """
5788  if z3_debug():
5789  _z3_assert(isinstance(target, Context), "target must be a context")
5790  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5791 
5792  def __copy__(self):
5793  return self.translate(self.ctx)
5794 
5795  def __deepcopy__(self, memo={}):
5796  return self.translate(self.ctx)
5797 
5798  def simplify(self, *arguments, **keywords):
5799  """Return a new simplified goal.
5800 
5801  This method is essentially invoking the simplify tactic.
5802 
5803  >>> g = Goal()
5804  >>> x = Int('x')
5805  >>> g.add(x + 1 >= 2)
5806  >>> g
5807  [x + 1 >= 2]
5808  >>> g2 = g.simplify()
5809  >>> g2
5810  [x >= 1]
5811  >>> # g was not modified
5812  >>> g
5813  [x + 1 >= 2]
5814  """
5815  t = Tactic("simplify")
5816  return t.apply(self, *arguments, **keywords)[0]
5817 
5818  def as_expr(self):
5819  """Return goal `self` as a single Z3 expression.
5820 
5821  >>> x = Int('x')
5822  >>> g = Goal()
5823  >>> g.as_expr()
5824  True
5825  >>> g.add(x > 1)
5826  >>> g.as_expr()
5827  x > 1
5828  >>> g.add(x < 10)
5829  >>> g.as_expr()
5830  And(x > 1, x < 10)
5831  """
5832  sz = len(self)
5833  if sz == 0:
5834  return BoolVal(True, self.ctx)
5835  elif sz == 1:
5836  return self.get(0)
5837  else:
5838  return And([self.get(i) for i in range(len(self))], self.ctx)
5839 
5840 #########################################
5841 #
5842 # AST Vector
5843 #
5844 #########################################
5845 
5846 
5847 class AstVector(Z3PPObject):
5848  """A collection (vector) of ASTs."""
5849 
5850  def __init__(self, v=None, ctx=None):
5851  self.vector = None
5852  if v is None:
5853  self.ctx = _get_ctx(ctx)
5854  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5855  else:
5856  self.vector = v
5857  assert ctx is not None
5858  self.ctx = ctx
5859  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5860 
5861  def __del__(self):
5862  if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
5863  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5864 
5865  def __len__(self):
5866  """Return the size of the vector `self`.
5867 
5868  >>> A = AstVector()
5869  >>> len(A)
5870  0
5871  >>> A.push(Int('x'))
5872  >>> A.push(Int('x'))
5873  >>> len(A)
5874  2
5875  """
5876  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5877 
5878  def __getitem__(self, i):
5879  """Return the AST at position `i`.
5880 
5881  >>> A = AstVector()
5882  >>> A.push(Int('x') + 1)
5883  >>> A.push(Int('y'))
5884  >>> A[0]
5885  x + 1
5886  >>> A[1]
5887  y
5888  """
5889 
5890  if isinstance(i, int):
5891  if i < 0:
5892  i += self.__len__()
5893 
5894  if i >= self.__len__():
5895  raise IndexError
5896  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5897 
5898  elif isinstance(i, slice):
5899  result = []
5900  for ii in range(*i.indices(self.__len__())):
5901  result.append(_to_ast_ref(
5902  Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
5903  self.ctx,
5904  ))
5905  return result
5906 
5907  def __setitem__(self, i, v):
5908  """Update AST at position `i`.
5909 
5910  >>> A = AstVector()
5911  >>> A.push(Int('x') + 1)
5912  >>> A.push(Int('y'))
5913  >>> A[0]
5914  x + 1
5915  >>> A[0] = Int('x')
5916  >>> A[0]
5917  x
5918  """
5919  if i >= self.__len__():
5920  raise IndexError
5921  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5922 
5923  def push(self, v):
5924  """Add `v` in the end of the vector.
5925 
5926  >>> A = AstVector()
5927  >>> len(A)
5928  0
5929  >>> A.push(Int('x'))
5930  >>> len(A)
5931  1
5932  """
5933  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5934 
5935  def resize(self, sz):
5936  """Resize the vector to `sz` elements.
5937 
5938  >>> A = AstVector()
5939  >>> A.resize(10)
5940  >>> len(A)
5941  10
5942  >>> for i in range(10): A[i] = Int('x')
5943  >>> A[5]
5944  x
5945  """
5946  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5947 
5948  def __contains__(self, item):
5949  """Return `True` if the vector contains `item`.
5950 
5951  >>> x = Int('x')
5952  >>> A = AstVector()
5953  >>> x in A
5954  False
5955  >>> A.push(x)
5956  >>> x in A
5957  True
5958  >>> (x+1) in A
5959  False
5960  >>> A.push(x+1)
5961  >>> (x+1) in A
5962  True
5963  >>> A
5964  [x, x + 1]
5965  """
5966  for elem in self:
5967  if elem.eq(item):
5968  return True
5969  return False
5970 
5971  def translate(self, other_ctx):
5972  """Copy vector `self` to context `other_ctx`.
5973 
5974  >>> x = Int('x')
5975  >>> A = AstVector()
5976  >>> A.push(x)
5977  >>> c2 = Context()
5978  >>> B = A.translate(c2)
5979  >>> B
5980  [x]
5981  """
5982  return AstVector(
5983  Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
5984  ctx=other_ctx,
5985  )
5986 
5987  def __copy__(self):
5988  return self.translate(self.ctx)
5989 
5990  def __deepcopy__(self, memo={}):
5991  return self.translate(self.ctx)
5992 
5993  def __repr__(self):
5994  return obj_to_string(self)
5995 
5996  def sexpr(self):
5997  """Return a textual representation of the s-expression representing the vector."""
5998  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5999 
6000 #########################################
6001 #
6002 # AST Map
6003 #
6004 #########################################
6005 
6006 
6007 class AstMap:
6008  """A mapping from ASTs to ASTs."""
6009 
6010  def __init__(self, m=None, ctx=None):
6011  self.map = None
6012  if m is None:
6013  self.ctx = _get_ctx(ctx)
6014  self.map = Z3_mk_ast_map(self.ctx.ref())
6015  else:
6016  self.map = m
6017  assert ctx is not None
6018  self.ctx = ctx
6019  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6020 
6021  def __deepcopy__(self, memo={}):
6022  return AstMap(self.map, self.ctx)
6023 
6024  def __del__(self):
6025  if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6026  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6027 
6028  def __len__(self):
6029  """Return the size of the map.
6030 
6031  >>> M = AstMap()
6032  >>> len(M)
6033  0
6034  >>> x = Int('x')
6035  >>> M[x] = IntVal(1)
6036  >>> len(M)
6037  1
6038  """
6039  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6040 
6041  def __contains__(self, key):
6042  """Return `True` if the map contains key `key`.
6043 
6044  >>> M = AstMap()
6045  >>> x = Int('x')
6046  >>> M[x] = x + 1
6047  >>> x in M
6048  True
6049  >>> x+1 in M
6050  False
6051  """
6052  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6053 
6054  def __getitem__(self, key):
6055  """Retrieve the value associated with key `key`.
6056 
6057  >>> M = AstMap()
6058  >>> x = Int('x')
6059  >>> M[x] = x + 1
6060  >>> M[x]
6061  x + 1
6062  """
6063  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6064 
6065  def __setitem__(self, k, v):
6066  """Add/Update key `k` with value `v`.
6067 
6068  >>> M = AstMap()
6069  >>> x = Int('x')
6070  >>> M[x] = x + 1
6071  >>> len(M)
6072  1
6073  >>> M[x]
6074  x + 1
6075  >>> M[x] = IntVal(1)
6076  >>> M[x]
6077  1
6078  """
6079  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6080 
6081  def __repr__(self):
6082  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6083 
6084  def erase(self, k):
6085  """Remove the entry associated with key `k`.
6086 
6087  >>> M = AstMap()
6088  >>> x = Int('x')
6089  >>> M[x] = x + 1
6090  >>> len(M)
6091  1
6092  >>> M.erase(x)
6093  >>> len(M)
6094  0
6095  """
6096  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6097 
6098  def reset(self):
6099  """Remove all entries from the map.
6100 
6101  >>> M = AstMap()
6102  >>> x = Int('x')
6103  >>> M[x] = x + 1
6104  >>> M[x+x] = IntVal(1)
6105  >>> len(M)
6106  2
6107  >>> M.reset()
6108  >>> len(M)
6109  0
6110  """
6111  Z3_ast_map_reset(self.ctx.ref(), self.map)
6112 
6113  def keys(self):
6114  """Return an AstVector containing all keys in the map.
6115 
6116  >>> M = AstMap()
6117  >>> x = Int('x')
6118  >>> M[x] = x + 1
6119  >>> M[x+x] = IntVal(1)
6120  >>> M.keys()
6121  [x, x + x]
6122  """
6123  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6124 
6125 #########################################
6126 #
6127 # Model
6128 #
6129 #########################################
6130 
6131 
6132 class FuncEntry:
6133  """Store the value of the interpretation of a function in a particular point."""
6134 
6135  def __init__(self, entry, ctx):
6136  self.entry = entry
6137  self.ctx = ctx
6138  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6139 
6140  def __deepcopy__(self, memo={}):
6141  return FuncEntry(self.entry, self.ctx)
6142 
6143  def __del__(self):
6144  if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6145  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6146 
6147  def num_args(self):
6148  """Return the number of arguments in the given entry.
6149 
6150  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6151  >>> s = Solver()
6152  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6153  >>> s.check()
6154  sat
6155  >>> m = s.model()
6156  >>> f_i = m[f]
6157  >>> f_i.num_entries()
6158  1
6159  >>> e = f_i.entry(0)
6160  >>> e.num_args()
6161  2
6162  """
6163  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6164 
6165  def arg_value(self, idx):
6166  """Return the value of argument `idx`.
6167 
6168  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6169  >>> s = Solver()
6170  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6171  >>> s.check()
6172  sat
6173  >>> m = s.model()
6174  >>> f_i = m[f]
6175  >>> f_i.num_entries()
6176  1
6177  >>> e = f_i.entry(0)
6178  >>> e
6179  [1, 2, 20]
6180  >>> e.num_args()
6181  2
6182  >>> e.arg_value(0)
6183  1
6184  >>> e.arg_value(1)
6185  2
6186  >>> try:
6187  ... e.arg_value(2)
6188  ... except IndexError:
6189  ... print("index error")
6190  index error
6191  """
6192  if idx >= self.num_args():
6193  raise IndexError
6194  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6195 
6196  def value(self):
6197  """Return the value of the function at point `self`.
6198 
6199  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6200  >>> s = Solver()
6201  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6202  >>> s.check()
6203  sat
6204  >>> m = s.model()
6205  >>> f_i = m[f]
6206  >>> f_i.num_entries()
6207  1
6208  >>> e = f_i.entry(0)
6209  >>> e
6210  [1, 2, 20]
6211  >>> e.num_args()
6212  2
6213  >>> e.value()
6214  20
6215  """
6216  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6217 
6218  def as_list(self):
6219  """Return entry `self` as a Python list.
6220  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6221  >>> s = Solver()
6222  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6223  >>> s.check()
6224  sat
6225  >>> m = s.model()
6226  >>> f_i = m[f]
6227  >>> f_i.num_entries()
6228  1
6229  >>> e = f_i.entry(0)
6230  >>> e.as_list()
6231  [1, 2, 20]
6232  """
6233  args = [self.arg_value(i) for i in range(self.num_args())]
6234  args.append(self.value())
6235  return args
6236 
6237  def __repr__(self):
6238  return repr(self.as_list())
6239 
6240 
6241 class FuncInterp(Z3PPObject):
6242  """Stores the interpretation of a function in a Z3 model."""
6243 
6244  def __init__(self, f, ctx):
6245  self.f = f
6246  self.ctx = ctx
6247  if self.f is not None:
6248  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6249 
6250  def __del__(self):
6251  if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6252  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6253 
6254  def else_value(self):
6255  """
6256  Return the `else` value for a function interpretation.
6257  Return None if Z3 did not specify the `else` value for
6258  this object.
6259 
6260  >>> f = Function('f', IntSort(), IntSort())
6261  >>> s = Solver()
6262  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6263  >>> s.check()
6264  sat
6265  >>> m = s.model()
6266  >>> m[f]
6267  [2 -> 0, else -> 1]
6268  >>> m[f].else_value()
6269  1
6270  """
6271  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6272  if r:
6273  return _to_expr_ref(r, self.ctx)
6274  else:
6275  return None
6276 
6277  def num_entries(self):
6278  """Return the number of entries/points in the function interpretation `self`.
6279 
6280  >>> f = Function('f', IntSort(), IntSort())
6281  >>> s = Solver()
6282  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6283  >>> s.check()
6284  sat
6285  >>> m = s.model()
6286  >>> m[f]
6287  [2 -> 0, else -> 1]
6288  >>> m[f].num_entries()
6289  1
6290  """
6291  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6292 
6293  def arity(self):
6294  """Return the number of arguments for each entry in the function interpretation `self`.
6295 
6296  >>> f = Function('f', IntSort(), IntSort())
6297  >>> s = Solver()
6298  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6299  >>> s.check()
6300  sat
6301  >>> m = s.model()
6302  >>> m[f].arity()
6303  1
6304  """
6305  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6306 
6307  def entry(self, idx):
6308  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6309 
6310  >>> f = Function('f', IntSort(), IntSort())
6311  >>> s = Solver()
6312  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6313  >>> s.check()
6314  sat
6315  >>> m = s.model()
6316  >>> m[f]
6317  [2 -> 0, else -> 1]
6318  >>> m[f].num_entries()
6319  1
6320  >>> m[f].entry(0)
6321  [2, 0]
6322  """
6323  if idx >= self.num_entries():
6324  raise IndexError
6325  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6326 
6327  def translate(self, other_ctx):
6328  """Copy model 'self' to context 'other_ctx'.
6329  """
6330  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6331 
6332  def __copy__(self):
6333  return self.translate(self.ctx)
6334 
6335  def __deepcopy__(self, memo={}):
6336  return self.translate(self.ctx)
6337 
6338  def as_list(self):
6339  """Return the function interpretation as a Python list.
6340  >>> f = Function('f', IntSort(), IntSort())
6341  >>> s = Solver()
6342  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6343  >>> s.check()
6344  sat
6345  >>> m = s.model()
6346  >>> m[f]
6347  [2 -> 0, else -> 1]
6348  >>> m[f].as_list()
6349  [[2, 0], 1]
6350  """
6351  r = [self.entry(i).as_list() for i in range(self.num_entries())]
6352  r.append(self.else_value())
6353  return r
6354 
6355  def __repr__(self):
6356  return obj_to_string(self)
6357 
6358 
6359 class ModelRef(Z3PPObject):
6360  """Model/Solution of a satisfiability problem (aka system of constraints)."""
6361 
6362  def __init__(self, m, ctx):
6363  assert ctx is not None
6364  self.model = m
6365  self.ctx = ctx
6366  Z3_model_inc_ref(self.ctx.ref(), self.model)
6367 
6368  def __del__(self):
6369  if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
6370  Z3_model_dec_ref(self.ctx.ref(), self.model)
6371 
6372  def __repr__(self):
6373  return obj_to_string(self)
6374 
6375  def sexpr(self):
6376  """Return a textual representation of the s-expression representing the model."""
6377  return Z3_model_to_string(self.ctx.ref(), self.model)
6378 
6379  def eval(self, t, model_completion=False):
6380  """Evaluate the expression `t` in the model `self`.
6381  If `model_completion` is enabled, then a default interpretation is automatically added
6382  for symbols that do not have an interpretation in the model `self`.
6383 
6384  >>> x = Int('x')
6385  >>> s = Solver()
6386  >>> s.add(x > 0, x < 2)
6387  >>> s.check()
6388  sat
6389  >>> m = s.model()
6390  >>> m.eval(x + 1)
6391  2
6392  >>> m.eval(x == 1)
6393  True
6394  >>> y = Int('y')
6395  >>> m.eval(y + x)
6396  1 + y
6397  >>> m.eval(y)
6398  y
6399  >>> m.eval(y, model_completion=True)
6400  0
6401  >>> # Now, m contains an interpretation for y
6402  >>> m.eval(y + x)
6403  1
6404  """
6405  r = (Ast * 1)()
6406  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6407  return _to_expr_ref(r[0], self.ctx)
6408  raise Z3Exception("failed to evaluate expression in the model")
6409 
6410  def evaluate(self, t, model_completion=False):
6411  """Alias for `eval`.
6412 
6413  >>> x = Int('x')
6414  >>> s = Solver()
6415  >>> s.add(x > 0, x < 2)
6416  >>> s.check()
6417  sat
6418  >>> m = s.model()
6419  >>> m.evaluate(x + 1)
6420  2
6421  >>> m.evaluate(x == 1)
6422  True
6423  >>> y = Int('y')
6424  >>> m.evaluate(y + x)
6425  1 + y
6426  >>> m.evaluate(y)
6427  y
6428  >>> m.evaluate(y, model_completion=True)
6429  0
6430  >>> # Now, m contains an interpretation for y
6431  >>> m.evaluate(y + x)
6432  1
6433  """
6434  return self.eval(t, model_completion)
6435 
6436  def __len__(self):
6437  """Return the number of constant and function declarations in the model `self`.
6438 
6439  >>> f = Function('f', IntSort(), IntSort())
6440  >>> x = Int('x')
6441  >>> s = Solver()
6442  >>> s.add(x > 0, f(x) != x)
6443  >>> s.check()
6444  sat
6445  >>> m = s.model()
6446  >>> len(m)
6447  2
6448  """
6449  num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
6450  num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6451  return num_consts + num_funcs
6452 
6453  def get_interp(self, decl):
6454  """Return the interpretation for a given declaration or constant.
6455 
6456  >>> f = Function('f', IntSort(), IntSort())
6457  >>> x = Int('x')
6458  >>> s = Solver()
6459  >>> s.add(x > 0, x < 2, f(x) == 0)
6460  >>> s.check()
6461  sat
6462  >>> m = s.model()
6463  >>> m[x]
6464  1
6465  >>> m[f]
6466  [else -> 0]
6467  """
6468  if z3_debug():
6469  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6470  if is_const(decl):
6471  decl = decl.decl()
6472  try:
6473  if decl.arity() == 0:
6474  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6475  if _r.value is None:
6476  return None
6477  r = _to_expr_ref(_r, self.ctx)
6478  if is_as_array(r):
6479  fi = self.get_interp(get_as_array_func(r))
6480  if fi is None:
6481  return fi
6482  e = fi.else_value()
6483  if e is None:
6484  return fi
6485  if fi.arity() != 1:
6486  return fi
6487  srt = decl.range()
6488  dom = srt.domain()
6489  e = K(dom, e)
6490  i = 0
6491  sz = fi.num_entries()
6492  n = fi.arity()
6493  while i < sz:
6494  fe = fi.entry(i)
6495  e = Store(e, fe.arg_value(0), fe.value())
6496  i += 1
6497  return e
6498  else:
6499  return r
6500  else:
6501  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6502  except Z3Exception:
6503  return None
6504 
6505  def num_sorts(self):
6506  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6507 
6508  >>> A = DeclareSort('A')
6509  >>> a, b = Consts('a b', A)
6510  >>> s = Solver()
6511  >>> s.add(a != b)
6512  >>> s.check()
6513  sat
6514  >>> m = s.model()
6515  >>> m.num_sorts()
6516  1
6517  """
6518  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6519 
6520  def get_sort(self, idx):
6521  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6522 
6523  >>> A = DeclareSort('A')
6524  >>> B = DeclareSort('B')
6525  >>> a1, a2 = Consts('a1 a2', A)
6526  >>> b1, b2 = Consts('b1 b2', B)
6527  >>> s = Solver()
6528  >>> s.add(a1 != a2, b1 != b2)
6529  >>> s.check()
6530  sat
6531  >>> m = s.model()
6532  >>> m.num_sorts()
6533  2
6534  >>> m.get_sort(0)
6535  A
6536  >>> m.get_sort(1)
6537  B
6538  """
6539  if idx >= self.num_sorts():
6540  raise IndexError
6541  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6542 
6543  def sorts(self):
6544  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6545 
6546  >>> A = DeclareSort('A')
6547  >>> B = DeclareSort('B')
6548  >>> a1, a2 = Consts('a1 a2', A)
6549  >>> b1, b2 = Consts('b1 b2', B)
6550  >>> s = Solver()
6551  >>> s.add(a1 != a2, b1 != b2)
6552  >>> s.check()
6553  sat
6554  >>> m = s.model()
6555  >>> m.sorts()
6556  [A, B]
6557  """
6558  return [self.get_sort(i) for i in range(self.num_sorts())]
6559 
6560  def get_universe(self, s):
6561  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6562 
6563  >>> A = DeclareSort('A')
6564  >>> a, b = Consts('a b', A)
6565  >>> s = Solver()
6566  >>> s.add(a != b)
6567  >>> s.check()
6568  sat
6569  >>> m = s.model()
6570  >>> m.get_universe(A)
6571  [A!val!1, A!val!0]
6572  """
6573  if z3_debug():
6574  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6575  try:
6576  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6577  except Z3Exception:
6578  return None
6579 
6580  def __getitem__(self, idx):
6581  """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6582  If `idx` is a declaration, then the actual interpretation is returned.
6583 
6584  The elements can be retrieved using position or the actual declaration.
6585 
6586  >>> f = Function('f', IntSort(), IntSort())
6587  >>> x = Int('x')
6588  >>> s = Solver()
6589  >>> s.add(x > 0, x < 2, f(x) == 0)
6590  >>> s.check()
6591  sat
6592  >>> m = s.model()
6593  >>> len(m)
6594  2
6595  >>> m[0]
6596  x
6597  >>> m[1]
6598  f
6599  >>> m[x]
6600  1
6601  >>> m[f]
6602  [else -> 0]
6603  >>> for d in m: print("%s -> %s" % (d, m[d]))
6604  x -> 1
6605  f -> [else -> 0]
6606  """
6607  if _is_int(idx):
6608  if idx >= len(self):
6609  raise IndexError
6610  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6611  if (idx < num_consts):
6612  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6613  else:
6614  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6615  if isinstance(idx, FuncDeclRef):
6616  return self.get_interp(idx)
6617  if is_const(idx):
6618  return self.get_interp(idx.decl())
6619  if isinstance(idx, SortRef):
6620  return self.get_universe(idx)
6621  if z3_debug():
6622  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6623  return None
6624 
6625  def decls(self):
6626  """Return a list with all symbols that have an interpretation in the model `self`.
6627  >>> f = Function('f', IntSort(), IntSort())
6628  >>> x = Int('x')
6629  >>> s = Solver()
6630  >>> s.add(x > 0, x < 2, f(x) == 0)
6631  >>> s.check()
6632  sat
6633  >>> m = s.model()
6634  >>> m.decls()
6635  [x, f]
6636  """
6637  r = []
6638  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6639  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6640  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6641  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6642  return r
6643 
6644  def update_value(self, x, value):
6645  """Update the interpretation of a constant"""
6646  if is_expr(x):
6647  x = x.decl()
6648  if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
6649  fi1 = value.f
6650  fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
6651  fi2 = FuncInterp(fi2, x.ctx)
6652  for i in range(value.num_entries()):
6653  e = value.entry(i)
6654  n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
6655  v = AstVector()
6656  for j in range(n):
6657  v.push(e.arg_value(j))
6658  val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
6659  Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
6660  return
6661  if not is_func_decl(x) or x.arity() != 0:
6662  raise Z3Exception("Expecting 0-ary function or constant expression")
6663  value = _py2expr(value)
6664  Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
6665 
6666  def translate(self, target):
6667  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6668  """
6669  if z3_debug():
6670  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6671  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6672  return ModelRef(model, target)
6673 
6674  def __copy__(self):
6675  return self.translate(self.ctx)
6676 
6677  def __deepcopy__(self, memo={}):
6678  return self.translate(self.ctx)
6679 
6680 
6681 def Model(ctx=None):
6682  ctx = _get_ctx(ctx)
6683  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6684 
6685 
6686 def is_as_array(n):
6687  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6688  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6689 
6690 
6691 def get_as_array_func(n):
6692  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6693  if z3_debug():
6694  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6695  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6696 
6697 #########################################
6698 #
6699 # Statistics
6700 #
6701 #########################################
6702 
6703 
6704 class Statistics:
6705  """Statistics for `Solver.check()`."""
6706 
6707  def __init__(self, stats, ctx):
6708  self.stats = stats
6709  self.ctx = ctx
6710  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6711 
6712  def __deepcopy__(self, memo={}):
6713  return Statistics(self.stats, self.ctx)
6714 
6715  def __del__(self):
6716  if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
6717  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6718 
6719  def __repr__(self):
6720  if in_html_mode():
6721  out = io.StringIO()
6722  even = True
6723  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6724  for k, v in self:
6725  if even:
6726  out.write(u('<tr style="background-color:#CFCFCF">'))
6727  even = False
6728  else:
6729  out.write(u("<tr>"))
6730  even = True
6731  out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6732  out.write(u("</table>"))
6733  return out.getvalue()
6734  else:
6735  return Z3_stats_to_string(self.ctx.ref(), self.stats)
6736 
6737  def __len__(self):
6738  """Return the number of statistical counters.
6739 
6740  >>> x = Int('x')
6741  >>> s = Then('simplify', 'nlsat').solver()
6742  >>> s.add(x > 0)
6743  >>> s.check()
6744  sat
6745  >>> st = s.statistics()
6746  >>> len(st)
6747  6
6748  """
6749  return int(Z3_stats_size(self.ctx.ref(), self.stats))
6750 
6751  def __getitem__(self, idx):
6752  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6753 
6754  >>> x = Int('x')
6755  >>> s = Then('simplify', 'nlsat').solver()
6756  >>> s.add(x > 0)
6757  >>> s.check()
6758  sat
6759  >>> st = s.statistics()
6760  >>> len(st)
6761  6
6762  >>> st[0]
6763  ('nlsat propagations', 2)
6764  >>> st[1]
6765  ('nlsat stages', 2)
6766  """
6767  if idx >= len(self):
6768  raise IndexError
6769  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6770  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6771  else:
6772  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6773  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6774 
6775  def keys(self):
6776  """Return the list of statistical counters.
6777 
6778  >>> x = Int('x')
6779  >>> s = Then('simplify', 'nlsat').solver()
6780  >>> s.add(x > 0)
6781  >>> s.check()
6782  sat
6783  >>> st = s.statistics()
6784  """
6785  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6786 
6787  def get_key_value(self, key):
6788  """Return the value of a particular statistical counter.
6789 
6790  >>> x = Int('x')
6791  >>> s = Then('simplify', 'nlsat').solver()
6792  >>> s.add(x > 0)
6793  >>> s.check()
6794  sat
6795  >>> st = s.statistics()
6796  >>> st.get_key_value('nlsat propagations')
6797  2
6798  """
6799  for idx in range(len(self)):
6800  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6801  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6802  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6803  else:
6804  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6805  raise Z3Exception("unknown key")
6806 
6807  def __getattr__(self, name):
6808  """Access the value of statistical using attributes.
6809 
6810  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6811  we should use '_' (e.g., 'nlsat_propagations').
6812 
6813  >>> x = Int('x')
6814  >>> s = Then('simplify', 'nlsat').solver()
6815  >>> s.add(x > 0)
6816  >>> s.check()
6817  sat
6818  >>> st = s.statistics()
6819  >>> st.nlsat_propagations
6820  2
6821  >>> st.nlsat_stages
6822  2
6823  """
6824  key = name.replace("_", " ")
6825  try:
6826  return self.get_key_value(key)
6827  except Z3Exception:
6828  raise AttributeError
6829 
6830 #########################################
6831 #
6832 # Solver
6833 #
6834 #########################################
6835 
6836 
6837 class CheckSatResult:
6838  """Represents the result of a satisfiability check: sat, unsat, unknown.
6839 
6840  >>> s = Solver()
6841  >>> s.check()
6842  sat
6843  >>> r = s.check()
6844  >>> isinstance(r, CheckSatResult)
6845  True
6846  """
6847 
6848  def __init__(self, r):
6849  self.r = r
6850 
6851  def __deepcopy__(self, memo={}):
6852  return CheckSatResult(self.r)
6853 
6854  def __eq__(self, other):
6855  return isinstance(other, CheckSatResult) and self.r == other.r
6856 
6857  def __ne__(self, other):
6858  return not self.__eq__(other)
6859 
6860  def __repr__(self):
6861  if in_html_mode():
6862  if self.r == Z3_L_TRUE:
6863  return "<b>sat</b>"
6864  elif self.r == Z3_L_FALSE:
6865  return "<b>unsat</b>"
6866  else:
6867  return "<b>unknown</b>"
6868  else:
6869  if self.r == Z3_L_TRUE:
6870  return "sat"
6871  elif self.r == Z3_L_FALSE:
6872  return "unsat"
6873  else:
6874  return "unknown"
6875 
6876  def _repr_html_(self):
6877  in_html = in_html_mode()
6878  set_html_mode(True)
6879  res = repr(self)
6880  set_html_mode(in_html)
6881  return res
6882 
6883 
6884 sat = CheckSatResult(Z3_L_TRUE)
6885 unsat = CheckSatResult(Z3_L_FALSE)
6886 unknown = CheckSatResult(Z3_L_UNDEF)
6887 
6888 
6889 class Solver(Z3PPObject):
6890  """
6891  Solver API provides methods for implementing the main SMT 2.0 commands:
6892  push, pop, check, get-model, etc.
6893  """
6894 
6895  def __init__(self, solver=None, ctx=None, logFile=None):
6896  assert solver is None or ctx is not None
6897  self.ctx = _get_ctx(ctx)
6898  self.backtrack_level = 4000000000
6899  self.solver = None
6900  if solver is None:
6901  self.solver = Z3_mk_solver(self.ctx.ref())
6902  else:
6903  self.solver = solver
6904  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6905  if logFile is not None:
6906  self.set("smtlib2_log", logFile)
6907 
6908  def __del__(self):
6909  if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
6910  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6911 
6912  def set(self, *args, **keys):
6913  """Set a configuration option.
6914  The method `help()` return a string containing all available options.
6915 
6916  >>> s = Solver()
6917  >>> # The option MBQI can be set using three different approaches.
6918  >>> s.set(mbqi=True)
6919  >>> s.set('MBQI', True)
6920  >>> s.set(':mbqi', True)
6921  """
6922  p = args2params(args, keys, self.ctx)
6923  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6924 
6925  def push(self):
6926  """Create a backtracking point.
6927 
6928  >>> x = Int('x')
6929  >>> s = Solver()
6930  >>> s.add(x > 0)
6931  >>> s
6932  [x > 0]
6933  >>> s.push()
6934  >>> s.add(x < 1)
6935  >>> s
6936  [x > 0, x < 1]
6937  >>> s.check()
6938  unsat
6939  >>> s.pop()
6940  >>> s.check()
6941  sat
6942  >>> s
6943  [x > 0]
6944  """
6945  Z3_solver_push(self.ctx.ref(), self.solver)
6946 
6947  def pop(self, num=1):
6948  """Backtrack \\c num backtracking points.
6949 
6950  >>> x = Int('x')
6951  >>> s = Solver()
6952  >>> s.add(x > 0)
6953  >>> s
6954  [x > 0]
6955  >>> s.push()
6956  >>> s.add(x < 1)
6957  >>> s
6958  [x > 0, x < 1]
6959  >>> s.check()
6960  unsat
6961  >>> s.pop()
6962  >>> s.check()
6963  sat
6964  >>> s
6965  [x > 0]
6966  """
6967  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6968 
6969  def num_scopes(self):
6970  """Return the current number of backtracking points.
6971 
6972  >>> s = Solver()
6973  >>> s.num_scopes()
6974  0
6975  >>> s.push()
6976  >>> s.num_scopes()
6977  1
6978  >>> s.push()
6979  >>> s.num_scopes()
6980  2
6981  >>> s.pop()
6982  >>> s.num_scopes()
6983  1
6984  """
6985  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6986 
6987  def reset(self):
6988  """Remove all asserted constraints and backtracking points created using `push()`.
6989 
6990  >>> x = Int('x')
6991  >>> s = Solver()
6992  >>> s.add(x > 0)
6993  >>> s
6994  [x > 0]
6995  >>> s.reset()
6996  >>> s
6997  []
6998  """
6999  Z3_solver_reset(self.ctx.ref(), self.solver)
7000 
7001  def assert_exprs(self, *args):
7002  """Assert constraints into the solver.
7003 
7004  >>> x = Int('x')
7005  >>> s = Solver()
7006  >>> s.assert_exprs(x > 0, x < 2)
7007  >>> s
7008  [x > 0, x < 2]
7009  """
7010  args = _get_args(args)
7011  s = BoolSort(self.ctx)
7012  for arg in args:
7013  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7014  for f in arg:
7015  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7016  else:
7017  arg = s.cast(arg)
7018  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7019 
7020  def add(self, *args):
7021  """Assert constraints into the solver.
7022 
7023  >>> x = Int('x')
7024  >>> s = Solver()
7025  >>> s.add(x > 0, x < 2)
7026  >>> s
7027  [x > 0, x < 2]
7028  """
7029  self.assert_exprs(*args)
7030 
7031  def __iadd__(self, fml):
7032  self.add(fml)
7033  return self
7034 
7035  def append(self, *args):
7036  """Assert constraints into the solver.
7037 
7038  >>> x = Int('x')
7039  >>> s = Solver()
7040  >>> s.append(x > 0, x < 2)
7041  >>> s
7042  [x > 0, x < 2]
7043  """
7044  self.assert_exprs(*args)
7045 
7046  def insert(self, *args):
7047  """Assert constraints into the solver.
7048 
7049  >>> x = Int('x')
7050  >>> s = Solver()
7051  >>> s.insert(x > 0, x < 2)
7052  >>> s
7053  [x > 0, x < 2]
7054  """
7055  self.assert_exprs(*args)
7056 
7057  def assert_and_track(self, a, p):
7058  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7059 
7060  If `p` is a string, it will be automatically converted into a Boolean constant.
7061 
7062  >>> x = Int('x')
7063  >>> p3 = Bool('p3')
7064  >>> s = Solver()
7065  >>> s.set(unsat_core=True)
7066  >>> s.assert_and_track(x > 0, 'p1')
7067  >>> s.assert_and_track(x != 1, 'p2')
7068  >>> s.assert_and_track(x < 0, p3)
7069  >>> print(s.check())
7070  unsat
7071  >>> c = s.unsat_core()
7072  >>> len(c)
7073  2
7074  >>> Bool('p1') in c
7075  True
7076  >>> Bool('p2') in c
7077  False
7078  >>> p3 in c
7079  True
7080  """
7081  if isinstance(p, str):
7082  p = Bool(p, self.ctx)
7083  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7084  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7085  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7086 
7087  def check(self, *assumptions):
7088  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7089 
7090  >>> x = Int('x')
7091  >>> s = Solver()
7092  >>> s.check()
7093  sat
7094  >>> s.add(x > 0, x < 2)
7095  >>> s.check()
7096  sat
7097  >>> s.model().eval(x)
7098  1
7099  >>> s.add(x < 1)
7100  >>> s.check()
7101  unsat
7102  >>> s.reset()
7103  >>> s.add(2**x == 4)
7104  >>> s.check()
7105  unknown
7106  """
7107  s = BoolSort(self.ctx)
7108  assumptions = _get_args(assumptions)
7109  num = len(assumptions)
7110  _assumptions = (Ast * num)()
7111  for i in range(num):
7112  _assumptions[i] = s.cast(assumptions[i]).as_ast()
7113  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7114  return CheckSatResult(r)
7115 
7116  def model(self):
7117  """Return a model for the last `check()`.
7118 
7119  This function raises an exception if
7120  a model is not available (e.g., last `check()` returned unsat).
7121 
7122  >>> s = Solver()
7123  >>> a = Int('a')
7124  >>> s.add(a + 2 == 0)
7125  >>> s.check()
7126  sat
7127  >>> s.model()
7128  [a = -2]
7129  """
7130  try:
7131  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7132  except Z3Exception:
7133  raise Z3Exception("model is not available")
7134 
7135  def import_model_converter(self, other):
7136  """Import model converter from other into the current solver"""
7137  Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7138 
7139  def unsat_core(self):
7140  """Return a subset (as an AST vector) of the assumptions provided to the last check().
7141 
7142  These are the assumptions Z3 used in the unsatisfiability proof.
7143  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7144  They may be also used to "retract" assumptions. Note that, assumptions are not really
7145  "soft constraints", but they can be used to implement them.
7146 
7147  >>> p1, p2, p3 = Bools('p1 p2 p3')
7148  >>> x, y = Ints('x y')
7149  >>> s = Solver()
7150  >>> s.add(Implies(p1, x > 0))
7151  >>> s.add(Implies(p2, y > x))
7152  >>> s.add(Implies(p2, y < 1))
7153  >>> s.add(Implies(p3, y > -3))
7154  >>> s.check(p1, p2, p3)
7155  unsat
7156  >>> core = s.unsat_core()
7157  >>> len(core)
7158  2
7159  >>> p1 in core
7160  True
7161  >>> p2 in core
7162  True
7163  >>> p3 in core
7164  False
7165  >>> # "Retracting" p2
7166  >>> s.check(p1, p3)
7167  sat
7168  """
7169  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7170 
7171  def consequences(self, assumptions, variables):
7172  """Determine fixed values for the variables based on the solver state and assumptions.
7173  >>> s = Solver()
7174  >>> a, b, c, d = Bools('a b c d')
7175  >>> s.add(Implies(a,b), Implies(b, c))
7176  >>> s.consequences([a],[b,c,d])
7177  (sat, [Implies(a, b), Implies(a, c)])
7178  >>> s.consequences([Not(c),d],[a,b,c,d])
7179  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7180  """
7181  if isinstance(assumptions, list):
7182  _asms = AstVector(None, self.ctx)
7183  for a in assumptions:
7184  _asms.push(a)
7185  assumptions = _asms
7186  if isinstance(variables, list):
7187  _vars = AstVector(None, self.ctx)
7188  for a in variables:
7189  _vars.push(a)
7190  variables = _vars
7191  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7192  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7193  consequences = AstVector(None, self.ctx)
7194  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7195  variables.vector, consequences.vector)
7196  sz = len(consequences)
7197  consequences = [consequences[i] for i in range(sz)]
7198  return CheckSatResult(r), consequences
7199 
7200  def from_file(self, filename):
7201  """Parse assertions from a file"""
7202  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7203 
7204  def from_string(self, s):
7205  """Parse assertions from a string"""
7206  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7207 
7208  def cube(self, vars=None):
7209  """Get set of cubes
7210  The method takes an optional set of variables that restrict which
7211  variables may be used as a starting point for cubing.
7212  If vars is not None, then the first case split is based on a variable in
7213  this set.
7214  """
7215  self.cube_vs = AstVector(None, self.ctx)
7216  if vars is not None:
7217  for v in vars:
7218  self.cube_vs.push(v)
7219  while True:
7220  lvl = self.backtrack_level
7221  self.backtrack_level = 4000000000
7222  r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7223  if (len(r) == 1 and is_false(r[0])):
7224  return
7225  yield r
7226  if (len(r) == 0):
7227  return
7228 
7229  def cube_vars(self):
7230  """Access the set of variables that were touched by the most recently generated cube.
7231  This set of variables can be used as a starting point for additional cubes.
7232  The idea is that variables that appear in clauses that are reduced by the most recent
7233  cube are likely more useful to cube on."""
7234  return self.cube_vs
7235 
7236  def root(self, t):
7237  t = _py2expr(t, self.ctx)
7238  """Retrieve congruence closure root of the term t relative to the current search state
7239  The function primarily works for SimpleSolver. Terms and variables that are
7240  eliminated during pre-processing are not visible to the congruence closure.
7241  """
7242  return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
7243 
7244  def next(self, t):
7245  t = _py2expr(t, self.ctx)
7246  """Retrieve congruence closure sibling of the term t relative to the current search state
7247  The function primarily works for SimpleSolver. Terms and variables that are
7248  eliminated during pre-processing are not visible to the congruence closure.
7249  """
7250  return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
7251 
7252  def proof(self):
7253  """Return a proof for the last `check()`. Proof construction must be enabled."""
7254  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7255 
7256  def assertions(self):
7257  """Return an AST vector containing all added constraints.
7258 
7259  >>> s = Solver()
7260  >>> s.assertions()
7261  []
7262  >>> a = Int('a')
7263  >>> s.add(a > 0)
7264  >>> s.add(a < 10)
7265  >>> s.assertions()
7266  [a > 0, a < 10]
7267  """
7268  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7269 
7270  def units(self):
7271  """Return an AST vector containing all currently inferred units.
7272  """
7273  return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7274 
7275  def non_units(self):
7276  """Return an AST vector containing all atomic formulas in solver state that are not units.
7277  """
7278  return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7279 
7280  def trail_levels(self):
7281  """Return trail and decision levels of the solver state after a check() call.
7282  """
7283  trail = self.trail()
7284  levels = (ctypes.c_uint * len(trail))()
7285  Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7286  return trail, levels
7287 
7288  def trail(self):
7289  """Return trail of the solver state after a check() call.
7290  """
7291  return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7292 
7293  def statistics(self):
7294  """Return statistics for the last `check()`.
7295 
7296  >>> s = SimpleSolver()
7297  >>> x = Int('x')
7298  >>> s.add(x > 0)
7299  >>> s.check()
7300  sat
7301  >>> st = s.statistics()
7302  >>> st.get_key_value('final checks')
7303  1
7304  >>> len(st) > 0
7305  True
7306  >>> st[0] != 0
7307  True
7308  """
7309  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
7310 
7311  def reason_unknown(self):
7312  """Return a string describing why the last `check()` returned `unknown`.
7313 
7314  >>> x = Int('x')
7315  >>> s = SimpleSolver()
7316  >>> s.add(2**x == 4)
7317  >>> s.check()
7318  unknown
7319  >>> s.reason_unknown()
7320  '(incomplete (theory arithmetic))'
7321  """
7322  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
7323 
7324  def help(self):
7325  """Display a string describing all available options."""
7326  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
7327 
7328  def param_descrs(self):
7329  """Return the parameter description set."""
7330  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
7331 
7332  def __repr__(self):
7333  """Return a formatted string with all added constraints."""
7334  return obj_to_string(self)
7335 
7336  def translate(self, target):
7337  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7338 
7339  >>> c1 = Context()
7340  >>> c2 = Context()
7341  >>> s1 = Solver(ctx=c1)
7342  >>> s2 = s1.translate(c2)
7343  """
7344  if z3_debug():
7345  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7346  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
7347  return Solver(solver, target)
7348 
7349  def __copy__(self):
7350  return self.translate(self.ctx)
7351 
7352  def __deepcopy__(self, memo={}):
7353  return self.translate(self.ctx)
7354 
7355  def sexpr(self):
7356  """Return a formatted string (in Lisp-like format) with all added constraints.
7357  We say the string is in s-expression format.
7358 
7359  >>> x = Int('x')
7360  >>> s = Solver()
7361  >>> s.add(x > 0)
7362  >>> s.add(x < 2)
7363  >>> r = s.sexpr()
7364  """
7365  return Z3_solver_to_string(self.ctx.ref(), self.solver)
7366 
7367  def dimacs(self, include_names=True):
7368  """Return a textual representation of the solver in DIMACS format."""
7369  return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
7370 
7371  def to_smt2(self):
7372  """return SMTLIB2 formatted benchmark for solver's assertions"""
7373  es = self.assertions()
7374  sz = len(es)
7375  sz1 = sz
7376  if sz1 > 0:
7377  sz1 -= 1
7378  v = (Ast * sz1)()
7379  for i in range(sz1):
7380  v[i] = es[i].as_ast()
7381  if sz > 0:
7382  e = es[sz1].as_ast()
7383  else:
7384  e = BoolVal(True, self.ctx).as_ast()
7386  self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7387  )
7388 
7389 
7390 def SolverFor(logic, ctx=None, logFile=None):
7391  """Create a solver customized for the given logic.
7392 
7393  The parameter `logic` is a string. It should be contains
7394  the name of a SMT-LIB logic.
7395  See http://www.smtlib.org/ for the name of all available logics.
7396 
7397  >>> s = SolverFor("QF_LIA")
7398  >>> x = Int('x')
7399  >>> s.add(x > 0)
7400  >>> s.add(x < 2)
7401  >>> s.check()
7402  sat
7403  >>> s.model()
7404  [x = 1]
7405  """
7406  ctx = _get_ctx(ctx)
7407  logic = to_symbol(logic)
7408  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7409 
7410 
7411 def SimpleSolver(ctx=None, logFile=None):
7412  """Return a simple general purpose solver with limited amount of preprocessing.
7413 
7414  >>> s = SimpleSolver()
7415  >>> x = Int('x')
7416  >>> s.add(x > 0)
7417  >>> s.check()
7418  sat
7419  """
7420  ctx = _get_ctx(ctx)
7421  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7422 
7423 #########################################
7424 #
7425 # Fixedpoint
7426 #
7427 #########################################
7428 
7429 
7431  """Fixedpoint API provides methods for solving with recursive predicates"""
7432 
7433  def __init__(self, fixedpoint=None, ctx=None):
7434  assert fixedpoint is None or ctx is not None
7435  self.ctx = _get_ctx(ctx)
7436  self.fixedpoint = None
7437  if fixedpoint is None:
7438  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
7439  else:
7440  self.fixedpoint = fixedpoint
7441  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
7442  self.vars = []
7443 
7444  def __deepcopy__(self, memo={}):
7445  return FixedPoint(self.fixedpoint, self.ctx)
7446 
7447  def __del__(self):
7448  if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
7449  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
7450 
7451  def set(self, *args, **keys):
7452  """Set a configuration option. The method `help()` return a string containing all available options.
7453  """
7454  p = args2params(args, keys, self.ctx)
7455  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
7456 
7457  def help(self):
7458  """Display a string describing all available options."""
7459  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
7460 
7461  def param_descrs(self):
7462  """Return the parameter description set."""
7463  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
7464 
7465  def assert_exprs(self, *args):
7466  """Assert constraints as background axioms for the fixedpoint solver."""
7467  args = _get_args(args)
7468  s = BoolSort(self.ctx)
7469  for arg in args:
7470  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7471  for f in arg:
7472  f = self.abstract(f)
7473  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
7474  else:
7475  arg = s.cast(arg)
7476  arg = self.abstract(arg)
7477  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
7478 
7479  def add(self, *args):
7480  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7481  self.assert_exprs(*args)
7482 
7483  def __iadd__(self, fml):
7484  self.add(fml)
7485  return self
7486 
7487  def append(self, *args):
7488  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7489  self.assert_exprs(*args)
7490 
7491  def insert(self, *args):
7492  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7493  self.assert_exprs(*args)
7494 
7495  def add_rule(self, head, body=None, name=None):
7496  """Assert rules defining recursive predicates to the fixedpoint solver.
7497  >>> a = Bool('a')
7498  >>> b = Bool('b')
7499  >>> s = Fixedpoint()
7500  >>> s.register_relation(a.decl())
7501  >>> s.register_relation(b.decl())
7502  >>> s.fact(a)
7503  >>> s.rule(b, a)
7504  >>> s.query(b)
7505  sat
7506  """
7507  if name is None:
7508  name = ""
7509  name = to_symbol(name, self.ctx)
7510  if body is None:
7511  head = self.abstract(head)
7512  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7513  else:
7514  body = _get_args(body)
7515  f = self.abstract(Implies(And(body, self.ctx), head))
7516  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7517 
7518  def rule(self, head, body=None, name=None):
7519  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7520  self.add_rule(head, body, name)
7521 
7522  def fact(self, head, name=None):
7523  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7524  self.add_rule(head, None, name)
7525 
7526  def query(self, *query):
7527  """Query the fixedpoint engine whether formula is derivable.
7528  You can also pass an tuple or list of recursive predicates.
7529  """
7530  query = _get_args(query)
7531  sz = len(query)
7532  if sz >= 1 and isinstance(query[0], FuncDeclRef):
7533  _decls = (FuncDecl * sz)()
7534  i = 0
7535  for q in query:
7536  _decls[i] = q.ast
7537  i = i + 1
7538  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7539  else:
7540  if sz == 1:
7541  query = query[0]
7542  else:
7543  query = And(query, self.ctx)
7544  query = self.abstract(query, False)
7545  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7546  return CheckSatResult(r)
7547 
7548  def query_from_lvl(self, lvl, *query):
7549  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7550  """
7551  query = _get_args(query)
7552  sz = len(query)
7553  if sz >= 1 and isinstance(query[0], FuncDecl):
7554  _z3_assert(False, "unsupported")
7555  else:
7556  if sz == 1:
7557  query = query[0]
7558  else:
7559  query = And(query)
7560  query = self.abstract(query, False)
7561  r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7562  return CheckSatResult(r)
7563 
7564  def update_rule(self, head, body, name):
7565  """update rule"""
7566  if name is None:
7567  name = ""
7568  name = to_symbol(name, self.ctx)
7569  body = _get_args(body)
7570  f = self.abstract(Implies(And(body, self.ctx), head))
7571  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7572 
7573  def get_answer(self):
7574  """Retrieve answer from last query call."""
7575  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7576  return _to_expr_ref(r, self.ctx)
7577 
7579  """Retrieve a ground cex from last query call."""
7580  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7581  return _to_expr_ref(r, self.ctx)
7582 
7584  """retrieve rules along the counterexample trace"""
7585  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7586 
7588  """retrieve rule names along the counterexample trace"""
7589  # this is a hack as I don't know how to return a list of symbols from C++;
7590  # obtain names as a single string separated by semicolons
7591  names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7592  # split into individual names
7593  return names.split(";")
7594 
7595  def get_num_levels(self, predicate):
7596  """Retrieve number of levels used for predicate in PDR engine"""
7597  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7598 
7599  def get_cover_delta(self, level, predicate):
7600  """Retrieve properties known about predicate for the level'th unfolding.
7601  -1 is treated as the limit (infinity)
7602  """
7603  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7604  return _to_expr_ref(r, self.ctx)
7605 
7606  def add_cover(self, level, predicate, property):
7607  """Add property to predicate for the level'th unfolding.
7608  -1 is treated as infinity (infinity)
7609  """
7610  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7611 
7612  def register_relation(self, *relations):
7613  """Register relation as recursive"""
7614  relations = _get_args(relations)
7615  for f in relations:
7616  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7617 
7618  def set_predicate_representation(self, f, *representations):
7619  """Control how relation is represented"""
7620  representations = _get_args(representations)
7621  representations = [to_symbol(s) for s in representations]
7622  sz = len(representations)
7623  args = (Symbol * sz)()
7624  for i in range(sz):
7625  args[i] = representations[i]
7626  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7627 
7628  def parse_string(self, s):
7629  """Parse rules and queries from a string"""
7630  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7631 
7632  def parse_file(self, f):
7633  """Parse rules and queries from a file"""
7634  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7635 
7636  def get_rules(self):
7637  """retrieve rules that have been added to fixedpoint context"""
7638  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7639 
7640  def get_assertions(self):
7641  """retrieve assertions that have been added to fixedpoint context"""
7642  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7643 
7644  def __repr__(self):
7645  """Return a formatted string with all added rules and constraints."""
7646  return self.sexpr()
7647 
7648  def sexpr(self):
7649  """Return a formatted string (in Lisp-like format) with all added constraints.
7650  We say the string is in s-expression format.
7651  """
7652  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7653 
7654  def to_string(self, queries):
7655  """Return a formatted string (in Lisp-like format) with all added constraints.
7656  We say the string is in s-expression format.
7657  Include also queries.
7658  """
7659  args, len = _to_ast_array(queries)
7660  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7661 
7662  def statistics(self):
7663  """Return statistics for the last `query()`.
7664  """
7665  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7666 
7667  def reason_unknown(self):
7668  """Return a string describing why the last `query()` returned `unknown`.
7669  """
7670  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7671 
7672  def declare_var(self, *vars):
7673  """Add variable or several variables.
7674  The added variable or variables will be bound in the rules
7675  and queries
7676  """
7677  vars = _get_args(vars)
7678  for v in vars:
7679  self.vars += [v]
7680 
7681  def abstract(self, fml, is_forall=True):
7682  if self.vars == []:
7683  return fml
7684  if is_forall:
7685  return ForAll(self.vars, fml)
7686  else:
7687  return Exists(self.vars, fml)
7688 
7689 
7690 #########################################
7691 #
7692 # Finite domains
7693 #
7694 #########################################
7695 
7697  """Finite domain sort."""
7698 
7699  def size(self):
7700  """Return the size of the finite domain sort"""
7701  r = (ctypes.c_ulonglong * 1)()
7702  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7703  return r[0]
7704  else:
7705  raise Z3Exception("Failed to retrieve finite domain sort size")
7706 
7707 
7708 def FiniteDomainSort(name, sz, ctx=None):
7709  """Create a named finite domain sort of a given size sz"""
7710  if not isinstance(name, Symbol):
7711  name = to_symbol(name)
7712  ctx = _get_ctx(ctx)
7713  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7714 
7715 
7717  """Return True if `s` is a Z3 finite-domain sort.
7718 
7719  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7720  True
7721  >>> is_finite_domain_sort(IntSort())
7722  False
7723  """
7724  return isinstance(s, FiniteDomainSortRef)
7725 
7726 
7728  """Finite-domain expressions."""
7729 
7730  def sort(self):
7731  """Return the sort of the finite-domain expression `self`."""
7732  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7733 
7734  def as_string(self):
7735  """Return a Z3 floating point expression as a Python string."""
7736  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7737 
7738 
7740  """Return `True` if `a` is a Z3 finite-domain expression.
7741 
7742  >>> s = FiniteDomainSort('S', 100)
7743  >>> b = Const('b', s)
7744  >>> is_finite_domain(b)
7745  True
7746  >>> is_finite_domain(Int('x'))
7747  False
7748  """
7749  return isinstance(a, FiniteDomainRef)
7750 
7751 
7753  """Integer values."""
7754 
7755  def as_long(self):
7756  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7757 
7758  >>> s = FiniteDomainSort('S', 100)
7759  >>> v = FiniteDomainVal(3, s)
7760  >>> v
7761  3
7762  >>> v.as_long() + 1
7763  4
7764  """
7765  return int(self.as_string())
7766 
7767  def as_string(self):
7768  """Return a Z3 finite-domain numeral as a Python string.
7769 
7770  >>> s = FiniteDomainSort('S', 100)
7771  >>> v = FiniteDomainVal(42, s)
7772  >>> v.as_string()
7773  '42'
7774  """
7775  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
7776 
7777 
7778 def FiniteDomainVal(val, sort, ctx=None):
7779  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7780 
7781  >>> s = FiniteDomainSort('S', 256)
7782  >>> FiniteDomainVal(255, s)
7783  255
7784  >>> FiniteDomainVal('100', s)
7785  100
7786  """
7787  if z3_debug():
7788  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7789  ctx = sort.ctx
7790  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7791 
7792 
7794  """Return `True` if `a` is a Z3 finite-domain value.
7795 
7796  >>> s = FiniteDomainSort('S', 100)
7797  >>> b = Const('b', s)
7798  >>> is_finite_domain_value(b)
7799  False
7800  >>> b = FiniteDomainVal(10, s)
7801  >>> b
7802  10
7803  >>> is_finite_domain_value(b)
7804  True
7805  """
7806  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7807 
7808 
7809 #########################################
7810 #
7811 # Optimize
7812 #
7813 #########################################
7814 
7816  def __init__(self, opt, value, is_max):
7817  self._opt = opt
7818  self._value = value
7819  self._is_max = is_max
7820 
7821  def lower(self):
7822  opt = self._opt
7823  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7824 
7825  def upper(self):
7826  opt = self._opt
7827  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7828 
7829  def lower_values(self):
7830  opt = self._opt
7831  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7832 
7833  def upper_values(self):
7834  opt = self._opt
7835  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7836 
7837  def value(self):
7838  if self._is_max:
7839  return self.upper()
7840  else:
7841  return self.lower()
7842 
7843  def __str__(self):
7844  return "%s:%s" % (self._value, self._is_max)
7845 
7846 
7847 _on_models = {}
7848 
7849 
7850 def _global_on_model(ctx):
7851  (fn, mdl) = _on_models[ctx]
7852  fn(mdl)
7853 
7854 
7855 _on_model_eh = on_model_eh_type(_global_on_model)
7856 
7857 
7859  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7860 
7861  def __init__(self, ctx=None):
7862  self.ctx = _get_ctx(ctx)
7863  self.optimize = Z3_mk_optimize(self.ctx.ref())
7864  self._on_models_id = None
7865  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7866 
7867  def __deepcopy__(self, memo={}):
7868  return Optimize(self.optimize, self.ctx)
7869 
7870  def __del__(self):
7871  if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
7872  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7873  if self._on_models_id is not None:
7874  del _on_models[self._on_models_id]
7875 
7876  def set(self, *args, **keys):
7877  """Set a configuration option.
7878  The method `help()` return a string containing all available options.
7879  """
7880  p = args2params(args, keys, self.ctx)
7881  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7882 
7883  def help(self):
7884  """Display a string describing all available options."""
7885  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7886 
7887  def param_descrs(self):
7888  """Return the parameter description set."""
7889  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7890 
7891  def assert_exprs(self, *args):
7892  """Assert constraints as background axioms for the optimize solver."""
7893  args = _get_args(args)
7894  s = BoolSort(self.ctx)
7895  for arg in args:
7896  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7897  for f in arg:
7898  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7899  else:
7900  arg = s.cast(arg)
7901  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7902 
7903  def add(self, *args):
7904  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7905  self.assert_exprs(*args)
7906 
7907  def __iadd__(self, fml):
7908  self.add(fml)
7909  return self
7910 
7911  def assert_and_track(self, a, p):
7912  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7913 
7914  If `p` is a string, it will be automatically converted into a Boolean constant.
7915 
7916  >>> x = Int('x')
7917  >>> p3 = Bool('p3')
7918  >>> s = Optimize()
7919  >>> s.assert_and_track(x > 0, 'p1')
7920  >>> s.assert_and_track(x != 1, 'p2')
7921  >>> s.assert_and_track(x < 0, p3)
7922  >>> print(s.check())
7923  unsat
7924  >>> c = s.unsat_core()
7925  >>> len(c)
7926  2
7927  >>> Bool('p1') in c
7928  True
7929  >>> Bool('p2') in c
7930  False
7931  >>> p3 in c
7932  True
7933  """
7934  if isinstance(p, str):
7935  p = Bool(p, self.ctx)
7936  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7937  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7938  Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7939 
7940  def add_soft(self, arg, weight="1", id=None):
7941  """Add soft constraint with optional weight and optional identifier.
7942  If no weight is supplied, then the penalty for violating the soft constraint
7943  is 1.
7944  Soft constraints are grouped by identifiers. Soft constraints that are
7945  added without identifiers are grouped by default.
7946  """
7947  if _is_int(weight):
7948  weight = "%d" % weight
7949  elif isinstance(weight, float):
7950  weight = "%f" % weight
7951  if not isinstance(weight, str):
7952  raise Z3Exception("weight should be a string or an integer")
7953  if id is None:
7954  id = ""
7955  id = to_symbol(id, self.ctx)
7956 
7957  def asoft(a):
7958  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
7959  return OptimizeObjective(self, v, False)
7960  if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7961  return [asoft(a) for a in arg]
7962  return asoft(arg)
7963 
7964  def maximize(self, arg):
7965  """Add objective function to maximize."""
7966  return OptimizeObjective(
7967  self,
7968  Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
7969  is_max=True,
7970  )
7971 
7972  def minimize(self, arg):
7973  """Add objective function to minimize."""
7974  return OptimizeObjective(
7975  self,
7976  Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
7977  is_max=False,
7978  )
7979 
7980  def push(self):
7981  """create a backtracking point for added rules, facts and assertions"""
7982  Z3_optimize_push(self.ctx.ref(), self.optimize)
7983 
7984  def pop(self):
7985  """restore to previously created backtracking point"""
7986  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7987 
7988  def check(self, *assumptions):
7989  """Check satisfiability while optimizing objective functions."""
7990  assumptions = _get_args(assumptions)
7991  num = len(assumptions)
7992  _assumptions = (Ast * num)()
7993  for i in range(num):
7994  _assumptions[i] = assumptions[i].as_ast()
7995  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7996 
7997  def reason_unknown(self):
7998  """Return a string that describes why the last `check()` returned `unknown`."""
7999  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8000 
8001  def model(self):
8002  """Return a model for the last check()."""
8003  try:
8004  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8005  except Z3Exception:
8006  raise Z3Exception("model is not available")
8007 
8008  def unsat_core(self):
8009  return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8010 
8011  def lower(self, obj):
8012  if not isinstance(obj, OptimizeObjective):
8013  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8014  return obj.lower()
8015 
8016  def upper(self, obj):
8017  if not isinstance(obj, OptimizeObjective):
8018  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8019  return obj.upper()
8020 
8021  def lower_values(self, obj):
8022  if not isinstance(obj, OptimizeObjective):
8023  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8024  return obj.lower_values()
8025 
8026  def upper_values(self, obj):
8027  if not isinstance(obj, OptimizeObjective):
8028  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8029  return obj.upper_values()
8030 
8031  def from_file(self, filename):
8032  """Parse assertions and objectives from a file"""
8033  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8034 
8035  def from_string(self, s):
8036  """Parse assertions and objectives from a string"""
8037  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8038 
8039  def assertions(self):
8040  """Return an AST vector containing all added constraints."""
8041  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8042 
8043  def objectives(self):
8044  """returns set of objective functions"""
8045  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8046 
8047  def __repr__(self):
8048  """Return a formatted string with all added rules and constraints."""
8049  return self.sexpr()
8050 
8051  def sexpr(self):
8052  """Return a formatted string (in Lisp-like format) with all added constraints.
8053  We say the string is in s-expression format.
8054  """
8055  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8056 
8057  def statistics(self):
8058  """Return statistics for the last check`.
8059  """
8060  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8061 
8062  def set_on_model(self, on_model):
8063  """Register a callback that is invoked with every incremental improvement to
8064  objective values. The callback takes a model as argument.
8065  The life-time of the model is limited to the callback so the
8066  model has to be (deep) copied if it is to be used after the callback
8067  """
8068  id = len(_on_models) + 41
8069  mdl = Model(self.ctx)
8070  _on_models[id] = (on_model, mdl)
8071  self._on_models_id = id
8073  self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8074  )
8075 
8076 
8077 #########################################
8078 #
8079 # ApplyResult
8080 #
8081 #########################################
8083  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8084  It also contains model and proof converters.
8085  """
8086 
8087  def __init__(self, result, ctx):
8088  self.result = result
8089  self.ctx = ctx
8090  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8091 
8092  def __deepcopy__(self, memo={}):
8093  return ApplyResult(self.result, self.ctx)
8094 
8095  def __del__(self):
8096  if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8097  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8098 
8099  def __len__(self):
8100  """Return the number of subgoals in `self`.
8101 
8102  >>> a, b = Ints('a b')
8103  >>> g = Goal()
8104  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8105  >>> t = Tactic('split-clause')
8106  >>> r = t(g)
8107  >>> len(r)
8108  2
8109  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8110  >>> len(t(g))
8111  4
8112  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8113  >>> len(t(g))
8114  1
8115  """
8116  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8117 
8118  def __getitem__(self, idx):
8119  """Return one of the subgoals stored in ApplyResult object `self`.
8120 
8121  >>> a, b = Ints('a b')
8122  >>> g = Goal()
8123  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8124  >>> t = Tactic('split-clause')
8125  >>> r = t(g)
8126  >>> r[0]
8127  [a == 0, Or(b == 0, b == 1), a > b]
8128  >>> r[1]
8129  [a == 1, Or(b == 0, b == 1), a > b]
8130  """
8131  if idx >= len(self):
8132  raise IndexError
8133  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8134 
8135  def __repr__(self):
8136  return obj_to_string(self)
8137 
8138  def sexpr(self):
8139  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8140  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8141 
8142  def as_expr(self):
8143  """Return a Z3 expression consisting of all subgoals.
8144 
8145  >>> x = Int('x')
8146  >>> g = Goal()
8147  >>> g.add(x > 1)
8148  >>> g.add(Or(x == 2, x == 3))
8149  >>> r = Tactic('simplify')(g)
8150  >>> r
8151  [[Not(x <= 1), Or(x == 2, x == 3)]]
8152  >>> r.as_expr()
8153  And(Not(x <= 1), Or(x == 2, x == 3))
8154  >>> r = Tactic('split-clause')(g)
8155  >>> r
8156  [[x > 1, x == 2], [x > 1, x == 3]]
8157  >>> r.as_expr()
8158  Or(And(x > 1, x == 2), And(x > 1, x == 3))
8159  """
8160  sz = len(self)
8161  if sz == 0:
8162  return BoolVal(False, self.ctx)
8163  elif sz == 1:
8164  return self[0].as_expr()
8165  else:
8166  return Or([self[i].as_expr() for i in range(len(self))])
8167 
8168 #########################################
8169 #
8170 # Simplifiers
8171 #
8172 #########################################
8173 
8175  """Simplifiers act as pre-processing utilities for solvers.
8176  Build a custom simplifier and add it to a solver"""
8177 
8178  def __init__(self, simplifier, ctx=None):
8179  self.ctx = _get_ctx(ctx)
8180  self.simplifier = None
8181  if isinstance(simplifier, SimplifierObj):
8182  self.simplifier = simplifier
8183  elif isinstance(simplifier, list):
8184  simps = [Simplifier(s, ctx) for s in simplifier]
8185  self.simplifier = simps[0].simplifier
8186  for i in range(1, len(simps)):
8187  self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
8188  Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8189  return
8190  else:
8191  if z3_debug():
8192  _z3_assert(isinstance(simplifier, str), "simplifier name expected")
8193  try:
8194  self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
8195  except Z3Exception:
8196  raise Z3Exception("unknown simplifier '%s'" % simplifier)
8197  Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8198 
8199  def __deepcopy__(self, memo={}):
8200  return Simplifier(self.simplifier, self.ctx)
8201 
8202  def __del__(self):
8203  if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
8204  Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
8205 
8206  def using_params(self, *args, **keys):
8207  """Return a simplifier that uses the given configuration options"""
8208  p = args2params(args, keys, self.ctx)
8209  return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
8210 
8211  def add(self, solver):
8212  """Return a solver that applies the simplification pre-processing specified by the simplifier"""
8213  return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
8214 
8215  def help(self):
8216  """Display a string containing a description of the available options for the `self` simplifier."""
8217  print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
8218 
8219  def param_descrs(self):
8220  """Return the parameter description set."""
8221  return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
8222 
8223 
8224 #########################################
8225 #
8226 # Tactics
8227 #
8228 #########################################
8229 
8230 
8231 class Tactic:
8232  """Tactics transform, solver and/or simplify sets of constraints (Goal).
8233  A Tactic can be converted into a Solver using the method solver().
8234 
8235  Several combinators are available for creating new tactics using the built-in ones:
8236  Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8237  """
8238 
8239  def __init__(self, tactic, ctx=None):
8240  self.ctx = _get_ctx(ctx)
8241  self.tactic = None
8242  if isinstance(tactic, TacticObj):
8243  self.tactic = tactic
8244  else:
8245  if z3_debug():
8246  _z3_assert(isinstance(tactic, str), "tactic name expected")
8247  try:
8248  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
8249  except Z3Exception:
8250  raise Z3Exception("unknown tactic '%s'" % tactic)
8251  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
8252 
8253  def __deepcopy__(self, memo={}):
8254  return Tactic(self.tactic, self.ctx)
8255 
8256  def __del__(self):
8257  if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
8258  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
8259 
8260  def solver(self, logFile=None):
8261  """Create a solver using the tactic `self`.
8262 
8263  The solver supports the methods `push()` and `pop()`, but it
8264  will always solve each `check()` from scratch.
8265 
8266  >>> t = Then('simplify', 'nlsat')
8267  >>> s = t.solver()
8268  >>> x = Real('x')
8269  >>> s.add(x**2 == 2, x > 0)
8270  >>> s.check()
8271  sat
8272  >>> s.model()
8273  [x = 1.4142135623?]
8274  """
8275  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
8276 
8277  def apply(self, goal, *arguments, **keywords):
8278  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8279 
8280  >>> x, y = Ints('x y')
8281  >>> t = Tactic('solve-eqs')
8282  >>> t.apply(And(x == 0, y >= x + 1))
8283  [[y >= 1]]
8284  """
8285  if z3_debug():
8286  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8287  goal = _to_goal(goal)
8288  if len(arguments) > 0 or len(keywords) > 0:
8289  p = args2params(arguments, keywords, self.ctx)
8290  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
8291  else:
8292  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
8293 
8294  def __call__(self, goal, *arguments, **keywords):
8295  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8296 
8297  >>> x, y = Ints('x y')
8298  >>> t = Tactic('solve-eqs')
8299  >>> t(And(x == 0, y >= x + 1))
8300  [[y >= 1]]
8301  """
8302  return self.apply(goal, *arguments, **keywords)
8303 
8304  def help(self):
8305  """Display a string containing a description of the available options for the `self` tactic."""
8306  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
8307 
8308  def param_descrs(self):
8309  """Return the parameter description set."""
8310  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
8311 
8312 
8313 def _to_goal(a):
8314  if isinstance(a, BoolRef):
8315  goal = Goal(ctx=a.ctx)
8316  goal.add(a)
8317  return goal
8318  else:
8319  return a
8320 
8321 
8322 def _to_tactic(t, ctx=None):
8323  if isinstance(t, Tactic):
8324  return t
8325  else:
8326  return Tactic(t, ctx)
8327 
8328 
8329 def _and_then(t1, t2, ctx=None):
8330  t1 = _to_tactic(t1, ctx)
8331  t2 = _to_tactic(t2, ctx)
8332  if z3_debug():
8333  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8334  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8335 
8336 
8337 def _or_else(t1, t2, ctx=None):
8338  t1 = _to_tactic(t1, ctx)
8339  t2 = _to_tactic(t2, ctx)
8340  if z3_debug():
8341  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8342  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8343 
8344 
8345 def AndThen(*ts, **ks):
8346  """Return a tactic that applies the tactics in `*ts` in sequence.
8347 
8348  >>> x, y = Ints('x y')
8349  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8350  >>> t(And(x == 0, y > x + 1))
8351  [[Not(y <= 1)]]
8352  >>> t(And(x == 0, y > x + 1)).as_expr()
8353  Not(y <= 1)
8354  """
8355  if z3_debug():
8356  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8357  ctx = ks.get("ctx", None)
8358  num = len(ts)
8359  r = ts[0]
8360  for i in range(num - 1):
8361  r = _and_then(r, ts[i + 1], ctx)
8362  return r
8363 
8364 
8365 def Then(*ts, **ks):
8366  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8367 
8368  >>> x, y = Ints('x y')
8369  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8370  >>> t(And(x == 0, y > x + 1))
8371  [[Not(y <= 1)]]
8372  >>> t(And(x == 0, y > x + 1)).as_expr()
8373  Not(y <= 1)
8374  """
8375  return AndThen(*ts, **ks)
8376 
8377 
8378 def OrElse(*ts, **ks):
8379  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8380 
8381  >>> x = Int('x')
8382  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8383  >>> # Tactic split-clause fails if there is no clause in the given goal.
8384  >>> t(x == 0)
8385  [[x == 0]]
8386  >>> t(Or(x == 0, x == 1))
8387  [[x == 0], [x == 1]]
8388  """
8389  if z3_debug():
8390  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8391  ctx = ks.get("ctx", None)
8392  num = len(ts)
8393  r = ts[0]
8394  for i in range(num - 1):
8395  r = _or_else(r, ts[i + 1], ctx)
8396  return r
8397 
8398 
8399 def ParOr(*ts, **ks):
8400  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8401 
8402  >>> x = Int('x')
8403  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8404  >>> t(x + 1 == 2)
8405  [[x == 1]]
8406  """
8407  if z3_debug():
8408  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8409  ctx = _get_ctx(ks.get("ctx", None))
8410  ts = [_to_tactic(t, ctx) for t in ts]
8411  sz = len(ts)
8412  _args = (TacticObj * sz)()
8413  for i in range(sz):
8414  _args[i] = ts[i].tactic
8415  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8416 
8417 
8418 def ParThen(t1, t2, ctx=None):
8419  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8420  The subgoals are processed in parallel.
8421 
8422  >>> x, y = Ints('x y')
8423  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8424  >>> t(And(Or(x == 1, x == 2), y == x + 1))
8425  [[x == 1, y == 2], [x == 2, y == 3]]
8426  """
8427  t1 = _to_tactic(t1, ctx)
8428  t2 = _to_tactic(t2, ctx)
8429  if z3_debug():
8430  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8431  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8432 
8433 
8434 def ParAndThen(t1, t2, ctx=None):
8435  """Alias for ParThen(t1, t2, ctx)."""
8436  return ParThen(t1, t2, ctx)
8437 
8438 
8439 def With(t, *args, **keys):
8440  """Return a tactic that applies tactic `t` using the given configuration options.
8441 
8442  >>> x, y = Ints('x y')
8443  >>> t = With(Tactic('simplify'), som=True)
8444  >>> t((x + 1)*(y + 2) == 0)
8445  [[2*x + y + x*y == -2]]
8446  """
8447  ctx = keys.pop("ctx", None)
8448  t = _to_tactic(t, ctx)
8449  p = args2params(args, keys, t.ctx)
8450  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8451 
8452 
8453 def WithParams(t, p):
8454  """Return a tactic that applies tactic `t` using the given configuration options.
8455 
8456  >>> x, y = Ints('x y')
8457  >>> p = ParamsRef()
8458  >>> p.set("som", True)
8459  >>> t = WithParams(Tactic('simplify'), p)
8460  >>> t((x + 1)*(y + 2) == 0)
8461  [[2*x + y + x*y == -2]]
8462  """
8463  t = _to_tactic(t, None)
8464  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8465 
8466 
8467 def Repeat(t, max=4294967295, ctx=None):
8468  """Return a tactic that keeps applying `t` until the goal is not modified anymore
8469  or the maximum number of iterations `max` is reached.
8470 
8471  >>> x, y = Ints('x y')
8472  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8473  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8474  >>> r = t(c)
8475  >>> for subgoal in r: print(subgoal)
8476  [x == 0, y == 0, x > y]
8477  [x == 0, y == 1, x > y]
8478  [x == 1, y == 0, x > y]
8479  [x == 1, y == 1, x > y]
8480  >>> t = Then(t, Tactic('propagate-values'))
8481  >>> t(c)
8482  [[x == 1, y == 0]]
8483  """
8484  t = _to_tactic(t, ctx)
8485  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8486 
8487 
8488 def TryFor(t, ms, ctx=None):
8489  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8490 
8491  If `t` does not terminate in `ms` milliseconds, then it fails.
8492  """
8493  t = _to_tactic(t, ctx)
8494  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8495 
8496 
8497 def tactics(ctx=None):
8498  """Return a list of all available tactics in Z3.
8499 
8500  >>> l = tactics()
8501  >>> l.count('simplify') == 1
8502  True
8503  """
8504  ctx = _get_ctx(ctx)
8505  return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8506 
8507 
8508 def tactic_description(name, ctx=None):
8509  """Return a short description for the tactic named `name`.
8510 
8511  >>> d = tactic_description('simplify')
8512  """
8513  ctx = _get_ctx(ctx)
8514  return Z3_tactic_get_descr(ctx.ref(), name)
8515 
8516 
8518  """Display a (tabular) description of all available tactics in Z3."""
8519  if in_html_mode():
8520  even = True
8521  print('<table border="1" cellpadding="2" cellspacing="0">')
8522  for t in tactics():
8523  if even:
8524  print('<tr style="background-color:#CFCFCF">')
8525  even = False
8526  else:
8527  print("<tr>")
8528  even = True
8529  print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8530  print("</table>")
8531  else:
8532  for t in tactics():
8533  print("%s : %s" % (t, tactic_description(t)))
8534 
8535 
8536 class Probe:
8537  """Probes are used to inspect a goal (aka problem) and collect information that may be used
8538  to decide which solver and/or preprocessing step will be used.
8539  """
8540 
8541  def __init__(self, probe, ctx=None):
8542  self.ctx = _get_ctx(ctx)
8543  self.probe = None
8544  if isinstance(probe, ProbeObj):
8545  self.probe = probe
8546  elif isinstance(probe, float):
8547  self.probe = Z3_probe_const(self.ctx.ref(), probe)
8548  elif _is_int(probe):
8549  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
8550  elif isinstance(probe, bool):
8551  if probe:
8552  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
8553  else:
8554  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
8555  else:
8556  if z3_debug():
8557  _z3_assert(isinstance(probe, str), "probe name expected")
8558  try:
8559  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
8560  except Z3Exception:
8561  raise Z3Exception("unknown probe '%s'" % probe)
8562  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
8563 
8564  def __deepcopy__(self, memo={}):
8565  return Probe(self.probe, self.ctx)
8566 
8567  def __del__(self):
8568  if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
8569  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
8570 
8571  def __lt__(self, other):
8572  """Return a probe that evaluates to "true" when the value returned by `self`
8573  is less than the value returned by `other`.
8574 
8575  >>> p = Probe('size') < 10
8576  >>> x = Int('x')
8577  >>> g = Goal()
8578  >>> g.add(x > 0)
8579  >>> g.add(x < 10)
8580  >>> p(g)
8581  1.0
8582  """
8583  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8584 
8585  def __gt__(self, other):
8586  """Return a probe that evaluates to "true" when the value returned by `self`
8587  is greater than the value returned by `other`.
8588 
8589  >>> p = Probe('size') > 10
8590  >>> x = Int('x')
8591  >>> g = Goal()
8592  >>> g.add(x > 0)
8593  >>> g.add(x < 10)
8594  >>> p(g)
8595  0.0
8596  """
8597  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8598 
8599  def __le__(self, other):
8600  """Return a probe that evaluates to "true" when the value returned by `self`
8601  is less than or equal to the value returned by `other`.
8602 
8603  >>> p = Probe('size') <= 2
8604  >>> x = Int('x')
8605  >>> g = Goal()
8606  >>> g.add(x > 0)
8607  >>> g.add(x < 10)
8608  >>> p(g)
8609  1.0
8610  """
8611  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8612 
8613  def __ge__(self, other):
8614  """Return a probe that evaluates to "true" when the value returned by `self`
8615  is greater than or equal to the value returned by `other`.
8616 
8617  >>> p = Probe('size') >= 2
8618  >>> x = Int('x')
8619  >>> g = Goal()
8620  >>> g.add(x > 0)
8621  >>> g.add(x < 10)
8622  >>> p(g)
8623  1.0
8624  """
8625  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8626 
8627  def __eq__(self, other):
8628  """Return a probe that evaluates to "true" when the value returned by `self`
8629  is equal to the value returned by `other`.
8630 
8631  >>> p = Probe('size') == 2
8632  >>> x = Int('x')
8633  >>> g = Goal()
8634  >>> g.add(x > 0)
8635  >>> g.add(x < 10)
8636  >>> p(g)
8637  1.0
8638  """
8639  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8640 
8641  def __ne__(self, other):
8642  """Return a probe that evaluates to "true" when the value returned by `self`
8643  is not equal to the value returned by `other`.
8644 
8645  >>> p = Probe('size') != 2
8646  >>> x = Int('x')
8647  >>> g = Goal()
8648  >>> g.add(x > 0)
8649  >>> g.add(x < 10)
8650  >>> p(g)
8651  0.0
8652  """
8653  p = self.__eq__(other)
8654  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8655 
8656  def __call__(self, goal):
8657  """Evaluate the probe `self` in the given goal.
8658 
8659  >>> p = Probe('size')
8660  >>> x = Int('x')
8661  >>> g = Goal()
8662  >>> g.add(x > 0)
8663  >>> g.add(x < 10)
8664  >>> p(g)
8665  2.0
8666  >>> g.add(x < 20)
8667  >>> p(g)
8668  3.0
8669  >>> p = Probe('num-consts')
8670  >>> p(g)
8671  1.0
8672  >>> p = Probe('is-propositional')
8673  >>> p(g)
8674  0.0
8675  >>> p = Probe('is-qflia')
8676  >>> p(g)
8677  1.0
8678  """
8679  if z3_debug():
8680  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8681  goal = _to_goal(goal)
8682  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8683 
8684 
8685 def is_probe(p):
8686  """Return `True` if `p` is a Z3 probe.
8687 
8688  >>> is_probe(Int('x'))
8689  False
8690  >>> is_probe(Probe('memory'))
8691  True
8692  """
8693  return isinstance(p, Probe)
8694 
8695 
8696 def _to_probe(p, ctx=None):
8697  if is_probe(p):
8698  return p
8699  else:
8700  return Probe(p, ctx)
8701 
8702 
8703 def probes(ctx=None):
8704  """Return a list of all available probes in Z3.
8705 
8706  >>> l = probes()
8707  >>> l.count('memory') == 1
8708  True
8709  """
8710  ctx = _get_ctx(ctx)
8711  return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8712 
8713 
8714 def probe_description(name, ctx=None):
8715  """Return a short description for the probe named `name`.
8716 
8717  >>> d = probe_description('memory')
8718  """
8719  ctx = _get_ctx(ctx)
8720  return Z3_probe_get_descr(ctx.ref(), name)
8721 
8722 
8724  """Display a (tabular) description of all available probes in Z3."""
8725  if in_html_mode():
8726  even = True
8727  print('<table border="1" cellpadding="2" cellspacing="0">')
8728  for p in probes():
8729  if even:
8730  print('<tr style="background-color:#CFCFCF">')
8731  even = False
8732  else:
8733  print("<tr>")
8734  even = True
8735  print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8736  print("</table>")
8737  else:
8738  for p in probes():
8739  print("%s : %s" % (p, probe_description(p)))
8740 
8741 
8742 def _probe_nary(f, args, ctx):
8743  if z3_debug():
8744  _z3_assert(len(args) > 0, "At least one argument expected")
8745  num = len(args)
8746  r = _to_probe(args[0], ctx)
8747  for i in range(num - 1):
8748  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8749  return r
8750 
8751 
8752 def _probe_and(args, ctx):
8753  return _probe_nary(Z3_probe_and, args, ctx)
8754 
8755 
8756 def _probe_or(args, ctx):
8757  return _probe_nary(Z3_probe_or, args, ctx)
8758 
8759 
8760 def FailIf(p, ctx=None):
8761  """Return a tactic that fails if the probe `p` evaluates to true.
8762  Otherwise, it returns the input goal unmodified.
8763 
8764  In the following example, the tactic applies 'simplify' if and only if there are
8765  more than 2 constraints in the goal.
8766 
8767  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8768  >>> x, y = Ints('x y')
8769  >>> g = Goal()
8770  >>> g.add(x > 0)
8771  >>> g.add(y > 0)
8772  >>> t(g)
8773  [[x > 0, y > 0]]
8774  >>> g.add(x == y + 1)
8775  >>> t(g)
8776  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8777  """
8778  p = _to_probe(p, ctx)
8779  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8780 
8781 
8782 def When(p, t, ctx=None):
8783  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8784  Otherwise, it returns the input goal unmodified.
8785 
8786  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8787  >>> x, y = Ints('x y')
8788  >>> g = Goal()
8789  >>> g.add(x > 0)
8790  >>> g.add(y > 0)
8791  >>> t(g)
8792  [[x > 0, y > 0]]
8793  >>> g.add(x == y + 1)
8794  >>> t(g)
8795  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8796  """
8797  p = _to_probe(p, ctx)
8798  t = _to_tactic(t, ctx)
8799  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8800 
8801 
8802 def Cond(p, t1, t2, ctx=None):
8803  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8804 
8805  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8806  """
8807  p = _to_probe(p, ctx)
8808  t1 = _to_tactic(t1, ctx)
8809  t2 = _to_tactic(t2, ctx)
8810  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8811 
8812 #########################################
8813 #
8814 # Utils
8815 #
8816 #########################################
8817 
8818 
8819 def simplify(a, *arguments, **keywords):
8820  """Simplify the expression `a` using the given options.
8821 
8822  This function has many options. Use `help_simplify` to obtain the complete list.
8823 
8824  >>> x = Int('x')
8825  >>> y = Int('y')
8826  >>> simplify(x + 1 + y + x + 1)
8827  2 + 2*x + y
8828  >>> simplify((x + 1)*(y + 1), som=True)
8829  1 + x + y + x*y
8830  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8831  And(Not(x == y), Not(x == 1), Not(y == 1))
8832  >>> simplify(And(x == 0, y == 1), elim_and=True)
8833  Not(Or(Not(x == 0), Not(y == 1)))
8834  """
8835  if z3_debug():
8836  _z3_assert(is_expr(a), "Z3 expression expected")
8837  if len(arguments) > 0 or len(keywords) > 0:
8838  p = args2params(arguments, keywords, a.ctx)
8839  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8840  else:
8841  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8842 
8843 
8845  """Return a string describing all options available for Z3 `simplify` procedure."""
8846  print(Z3_simplify_get_help(main_ctx().ref()))
8847 
8848 
8850  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8852 
8853 
8854 def substitute(t, *m):
8855  """Apply substitution m on t, m is a list of pairs of the form (from, to).
8856  Every occurrence in t of from is replaced with to.
8857 
8858  >>> x = Int('x')
8859  >>> y = Int('y')
8860  >>> substitute(x + 1, (x, y + 1))
8861  y + 1 + 1
8862  >>> f = Function('f', IntSort(), IntSort())
8863  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8864  1 + 1
8865  """
8866  if isinstance(m, tuple):
8867  m1 = _get_args(m)
8868  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8869  m = m1
8870  if z3_debug():
8871  _z3_assert(is_expr(t), "Z3 expression expected")
8872  _z3_assert(
8873  all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
8874  "Z3 invalid substitution, expression pairs expected.")
8875  _z3_assert(
8876  all([p[0].sort().eq(p[1].sort()) for p in m]),
8877  'Z3 invalid substitution, mismatching "from" and "to" sorts.')
8878  num = len(m)
8879  _from = (Ast * num)()
8880  _to = (Ast * num)()
8881  for i in range(num):
8882  _from[i] = m[i][0].as_ast()
8883  _to[i] = m[i][1].as_ast()
8884  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8885 
8886 
8887 def substitute_vars(t, *m):
8888  """Substitute the free variables in t with the expression in m.
8889 
8890  >>> v0 = Var(0, IntSort())
8891  >>> v1 = Var(1, IntSort())
8892  >>> x = Int('x')
8893  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8894  >>> # replace v0 with x+1 and v1 with x
8895  >>> substitute_vars(f(v0, v1), x + 1, x)
8896  f(x + 1, x)
8897  """
8898  if z3_debug():
8899  _z3_assert(is_expr(t), "Z3 expression expected")
8900  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8901  num = len(m)
8902  _to = (Ast * num)()
8903  for i in range(num):
8904  _to[i] = m[i].as_ast()
8905  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8906 
8907 def substitute_funs(t, *m):
8908  """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
8909  Every occurrence in to of the function from is replaced with the expression to.
8910  The expression to can have free variables, that refer to the arguments of from.
8911  For examples, see
8912  """
8913  if isinstance(m, tuple):
8914  m1 = _get_args(m)
8915  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8916  m = m1
8917  if z3_debug():
8918  _z3_assert(is_expr(t), "Z3 expression expected")
8919  _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, funcion pairs expected.")
8920  num = len(m)
8921  _from = (FuncDecl * num)()
8922  _to = (Ast * num)()
8923  for i in range(num):
8924  _from[i] = m[i][0].as_func_decl()
8925  _to[i] = m[i][1].as_ast()
8926  return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8927 
8928 
8929 def Sum(*args):
8930  """Create the sum of the Z3 expressions.
8931 
8932  >>> a, b, c = Ints('a b c')
8933  >>> Sum(a, b, c)
8934  a + b + c
8935  >>> Sum([a, b, c])
8936  a + b + c
8937  >>> A = IntVector('a', 5)
8938  >>> Sum(A)
8939  a__0 + a__1 + a__2 + a__3 + a__4
8940  """
8941  args = _get_args(args)
8942  if len(args) == 0:
8943  return 0
8944  ctx = _ctx_from_ast_arg_list(args)
8945  if ctx is None:
8946  return _reduce(lambda a, b: a + b, args, 0)
8947  args = _coerce_expr_list(args, ctx)
8948  if is_bv(args[0]):
8949  return _reduce(lambda a, b: a + b, args, 0)
8950  else:
8951  _args, sz = _to_ast_array(args)
8952  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8953 
8954 
8955 def Product(*args):
8956  """Create the product of the Z3 expressions.
8957 
8958  >>> a, b, c = Ints('a b c')
8959  >>> Product(a, b, c)
8960  a*b*c
8961  >>> Product([a, b, c])
8962  a*b*c
8963  >>> A = IntVector('a', 5)
8964  >>> Product(A)
8965  a__0*a__1*a__2*a__3*a__4
8966  """
8967  args = _get_args(args)
8968  if len(args) == 0:
8969  return 1
8970  ctx = _ctx_from_ast_arg_list(args)
8971  if ctx is None:
8972  return _reduce(lambda a, b: a * b, args, 1)
8973  args = _coerce_expr_list(args, ctx)
8974  if is_bv(args[0]):
8975  return _reduce(lambda a, b: a * b, args, 1)
8976  else:
8977  _args, sz = _to_ast_array(args)
8978  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8979 
8980 def Abs(arg):
8981  """Create the absolute value of an arithmetic expression"""
8982  return If(arg > 0, arg, -arg)
8983 
8984 
8985 def AtMost(*args):
8986  """Create an at-most Pseudo-Boolean k constraint.
8987 
8988  >>> a, b, c = Bools('a b c')
8989  >>> f = AtMost(a, b, c, 2)
8990  """
8991  args = _get_args(args)
8992  if z3_debug():
8993  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8994  ctx = _ctx_from_ast_arg_list(args)
8995  if z3_debug():
8996  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8997  args1 = _coerce_expr_list(args[:-1], ctx)
8998  k = args[-1]
8999  _args, sz = _to_ast_array(args1)
9000  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9001 
9002 
9003 def AtLeast(*args):
9004  """Create an at-most Pseudo-Boolean k constraint.
9005 
9006  >>> a, b, c = Bools('a b c')
9007  >>> f = AtLeast(a, b, c, 2)
9008  """
9009  args = _get_args(args)
9010  if z3_debug():
9011  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9012  ctx = _ctx_from_ast_arg_list(args)
9013  if z3_debug():
9014  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9015  args1 = _coerce_expr_list(args[:-1], ctx)
9016  k = args[-1]
9017  _args, sz = _to_ast_array(args1)
9018  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9019 
9020 
9021 def _reorder_pb_arg(arg):
9022  a, b = arg
9023  if not _is_int(b) and _is_int(a):
9024  return b, a
9025  return arg
9026 
9027 
9028 def _pb_args_coeffs(args, default_ctx=None):
9029  args = _get_args_ast_list(args)
9030  if len(args) == 0:
9031  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9032  args = [_reorder_pb_arg(arg) for arg in args]
9033  args, coeffs = zip(*args)
9034  if z3_debug():
9035  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9036  ctx = _ctx_from_ast_arg_list(args)
9037  if z3_debug():
9038  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9039  args = _coerce_expr_list(args, ctx)
9040  _args, sz = _to_ast_array(args)
9041  _coeffs = (ctypes.c_int * len(coeffs))()
9042  for i in range(len(coeffs)):
9043  _z3_check_cint_overflow(coeffs[i], "coefficient")
9044  _coeffs[i] = coeffs[i]
9045  return ctx, sz, _args, _coeffs, args
9046 
9047 
9048 def PbLe(args, k):
9049  """Create a Pseudo-Boolean inequality k constraint.
9050 
9051  >>> a, b, c = Bools('a b c')
9052  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9053  """
9054  _z3_check_cint_overflow(k, "k")
9055  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9056  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9057 
9058 
9059 def PbGe(args, k):
9060  """Create a Pseudo-Boolean inequality k constraint.
9061 
9062  >>> a, b, c = Bools('a b c')
9063  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9064  """
9065  _z3_check_cint_overflow(k, "k")
9066  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9067  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9068 
9069 
9070 def PbEq(args, k, ctx=None):
9071  """Create a Pseudo-Boolean equality k constraint.
9072 
9073  >>> a, b, c = Bools('a b c')
9074  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9075  """
9076  _z3_check_cint_overflow(k, "k")
9077  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9078  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9079 
9080 
9081 def solve(*args, **keywords):
9082  """Solve the constraints `*args`.
9083 
9084  This is a simple function for creating demonstrations. It creates a solver,
9085  configure it using the options in `keywords`, adds the constraints
9086  in `args`, and invokes check.
9087 
9088  >>> a = Int('a')
9089  >>> solve(a > 0, a < 2)
9090  [a = 1]
9091  """
9092  show = keywords.pop("show", False)
9093  s = Solver()
9094  s.set(**keywords)
9095  s.add(*args)
9096  if show:
9097  print(s)
9098  r = s.check()
9099  if r == unsat:
9100  print("no solution")
9101  elif r == unknown:
9102  print("failed to solve")
9103  try:
9104  print(s.model())
9105  except Z3Exception:
9106  return
9107  else:
9108  print(s.model())
9109 
9110 
9111 def solve_using(s, *args, **keywords):
9112  """Solve the constraints `*args` using solver `s`.
9113 
9114  This is a simple function for creating demonstrations. It is similar to `solve`,
9115  but it uses the given solver `s`.
9116  It configures solver `s` using the options in `keywords`, adds the constraints
9117  in `args`, and invokes check.
9118  """
9119  show = keywords.pop("show", False)
9120  if z3_debug():
9121  _z3_assert(isinstance(s, Solver), "Solver object expected")
9122  s.set(**keywords)
9123  s.add(*args)
9124  if show:
9125  print("Problem:")
9126  print(s)
9127  r = s.check()
9128  if r == unsat:
9129  print("no solution")
9130  elif r == unknown:
9131  print("failed to solve")
9132  try:
9133  print(s.model())
9134  except Z3Exception:
9135  return
9136  else:
9137  if show:
9138  print("Solution:")
9139  print(s.model())
9140 
9141 
9142 def prove(claim, show=False, **keywords):
9143  """Try to prove the given claim.
9144 
9145  This is a simple function for creating demonstrations. It tries to prove
9146  `claim` by showing the negation is unsatisfiable.
9147 
9148  >>> p, q = Bools('p q')
9149  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9150  proved
9151  """
9152  if z3_debug():
9153  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9154  s = Solver()
9155  s.set(**keywords)
9156  s.add(Not(claim))
9157  if show:
9158  print(s)
9159  r = s.check()
9160  if r == unsat:
9161  print("proved")
9162  elif r == unknown:
9163  print("failed to prove")
9164  print(s.model())
9165  else:
9166  print("counterexample")
9167  print(s.model())
9168 
9169 
9170 def _solve_html(*args, **keywords):
9171  """Version of function `solve` that renders HTML output."""
9172  show = keywords.pop("show", False)
9173  s = Solver()
9174  s.set(**keywords)
9175  s.add(*args)
9176  if show:
9177  print("<b>Problem:</b>")
9178  print(s)
9179  r = s.check()
9180  if r == unsat:
9181  print("<b>no solution</b>")
9182  elif r == unknown:
9183  print("<b>failed to solve</b>")
9184  try:
9185  print(s.model())
9186  except Z3Exception:
9187  return
9188  else:
9189  if show:
9190  print("<b>Solution:</b>")
9191  print(s.model())
9192 
9193 
9194 def _solve_using_html(s, *args, **keywords):
9195  """Version of function `solve_using` that renders HTML."""
9196  show = keywords.pop("show", False)
9197  if z3_debug():
9198  _z3_assert(isinstance(s, Solver), "Solver object expected")
9199  s.set(**keywords)
9200  s.add(*args)
9201  if show:
9202  print("<b>Problem:</b>")
9203  print(s)
9204  r = s.check()
9205  if r == unsat:
9206  print("<b>no solution</b>")
9207  elif r == unknown:
9208  print("<b>failed to solve</b>")
9209  try:
9210  print(s.model())
9211  except Z3Exception:
9212  return
9213  else:
9214  if show:
9215  print("<b>Solution:</b>")
9216  print(s.model())
9217 
9218 
9219 def _prove_html(claim, show=False, **keywords):
9220  """Version of function `prove` that renders HTML."""
9221  if z3_debug():
9222  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9223  s = Solver()
9224  s.set(**keywords)
9225  s.add(Not(claim))
9226  if show:
9227  print(s)
9228  r = s.check()
9229  if r == unsat:
9230  print("<b>proved</b>")
9231  elif r == unknown:
9232  print("<b>failed to prove</b>")
9233  print(s.model())
9234  else:
9235  print("<b>counterexample</b>")
9236  print(s.model())
9237 
9238 
9239 def _dict2sarray(sorts, ctx):
9240  sz = len(sorts)
9241  _names = (Symbol * sz)()
9242  _sorts = (Sort * sz)()
9243  i = 0
9244  for k in sorts:
9245  v = sorts[k]
9246  if z3_debug():
9247  _z3_assert(isinstance(k, str), "String expected")
9248  _z3_assert(is_sort(v), "Z3 sort expected")
9249  _names[i] = to_symbol(k, ctx)
9250  _sorts[i] = v.ast
9251  i = i + 1
9252  return sz, _names, _sorts
9253 
9254 
9255 def _dict2darray(decls, ctx):
9256  sz = len(decls)
9257  _names = (Symbol * sz)()
9258  _decls = (FuncDecl * sz)()
9259  i = 0
9260  for k in decls:
9261  v = decls[k]
9262  if z3_debug():
9263  _z3_assert(isinstance(k, str), "String expected")
9264  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9265  _names[i] = to_symbol(k, ctx)
9266  if is_const(v):
9267  _decls[i] = v.decl().ast
9268  else:
9269  _decls[i] = v.ast
9270  i = i + 1
9271  return sz, _names, _decls
9272 
9274  def __init__(self, ctx= None):
9275  self.ctx = _get_ctx(ctx)
9276  self.pctx = Z3_mk_parser_context(self.ctx.ref())
9277  Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
9278 
9279  def __del__(self):
9280  if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
9281  Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
9282  self.pctx = None
9283 
9284  def add_sort(self, sort):
9285  Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
9286 
9287  def add_decl(self, decl):
9288  Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
9289 
9290  def from_string(self, s):
9291  return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
9292 
9293 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9294  """Parse a string in SMT 2.0 format using the given sorts and decls.
9295 
9296  The arguments sorts and decls are Python dictionaries used to initialize
9297  the symbol table used for the SMT 2.0 parser.
9298 
9299  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9300  [x > 0, x < 10]
9301  >>> x, y = Ints('x y')
9302  >>> f = Function('f', IntSort(), IntSort())
9303  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9304  [x + f(y) > 0]
9305  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9306  [a > 0]
9307  """
9308  ctx = _get_ctx(ctx)
9309  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9310  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9311  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9312 
9313 
9314 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9315  """Parse a file in SMT 2.0 format using the given sorts and decls.
9316 
9317  This function is similar to parse_smt2_string().
9318  """
9319  ctx = _get_ctx(ctx)
9320  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9321  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9322  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9323 
9324 
9325 #########################################
9326 #
9327 # Floating-Point Arithmetic
9328 #
9329 #########################################
9330 
9331 
9332 # Global default rounding mode
9333 _dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
9334 _dflt_fpsort_ebits = 11
9335 _dflt_fpsort_sbits = 53
9336 
9337 
9338 def get_default_rounding_mode(ctx=None):
9339  """Retrieves the global default rounding mode."""
9340  global _dflt_rounding_mode
9341  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9342  return RTZ(ctx)
9343  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9344  return RTN(ctx)
9345  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9346  return RTP(ctx)
9347  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9348  return RNE(ctx)
9349  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9350  return RNA(ctx)
9351 
9352 
9353 _ROUNDING_MODES = frozenset({
9354  Z3_OP_FPA_RM_TOWARD_ZERO,
9355  Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9356  Z3_OP_FPA_RM_TOWARD_POSITIVE,
9357  Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9358  Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9359 })
9360 
9361 
9362 def set_default_rounding_mode(rm, ctx=None):
9363  global _dflt_rounding_mode
9364  if is_fprm_value(rm):
9365  _dflt_rounding_mode = rm.decl().kind()
9366  else:
9367  _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9368  _dflt_rounding_mode = rm
9369 
9370 
9371 def get_default_fp_sort(ctx=None):
9372  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9373 
9374 
9375 def set_default_fp_sort(ebits, sbits, ctx=None):
9376  global _dflt_fpsort_ebits
9377  global _dflt_fpsort_sbits
9378  _dflt_fpsort_ebits = ebits
9379  _dflt_fpsort_sbits = sbits
9380 
9381 
9382 def _dflt_rm(ctx=None):
9383  return get_default_rounding_mode(ctx)
9384 
9385 
9386 def _dflt_fps(ctx=None):
9387  return get_default_fp_sort(ctx)
9388 
9389 
9390 def _coerce_fp_expr_list(alist, ctx):
9391  first_fp_sort = None
9392  for a in alist:
9393  if is_fp(a):
9394  if first_fp_sort is None:
9395  first_fp_sort = a.sort()
9396  elif first_fp_sort == a.sort():
9397  pass # OK, same as before
9398  else:
9399  # we saw at least 2 different float sorts; something will
9400  # throw a sort mismatch later, for now assume None.
9401  first_fp_sort = None
9402  break
9403 
9404  r = []
9405  for i in range(len(alist)):
9406  a = alist[i]
9407  is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9408  if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9409  r.append(FPVal(a, None, first_fp_sort, ctx))
9410  else:
9411  r.append(a)
9412  return _coerce_expr_list(r, ctx)
9413 
9414 
9415 # FP Sorts
9416 
9417 class FPSortRef(SortRef):
9418  """Floating-point sort."""
9419 
9420  def ebits(self):
9421  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9422  >>> b = FPSort(8, 24)
9423  >>> b.ebits()
9424  8
9425  """
9426  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
9427 
9428  def sbits(self):
9429  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9430  >>> b = FPSort(8, 24)
9431  >>> b.sbits()
9432  24
9433  """
9434  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
9435 
9436  def cast(self, val):
9437  """Try to cast `val` as a floating-point expression.
9438  >>> b = FPSort(8, 24)
9439  >>> b.cast(1.0)
9440  1
9441  >>> b.cast(1.0).sexpr()
9442  '(fp #b0 #x7f #b00000000000000000000000)'
9443  """
9444  if is_expr(val):
9445  if z3_debug():
9446  _z3_assert(self.ctx == val.ctx, "Context mismatch")
9447  return val
9448  else:
9449  return FPVal(val, None, self, self.ctx)
9450 
9451 
9452 def Float16(ctx=None):
9453  """Floating-point 16-bit (half) sort."""
9454  ctx = _get_ctx(ctx)
9455  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9456 
9457 
9458 def FloatHalf(ctx=None):
9459  """Floating-point 16-bit (half) sort."""
9460  ctx = _get_ctx(ctx)
9461  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9462 
9463 
9464 def Float32(ctx=None):
9465  """Floating-point 32-bit (single) sort."""
9466  ctx = _get_ctx(ctx)
9467  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9468 
9469 
9470 def FloatSingle(ctx=None):
9471  """Floating-point 32-bit (single) sort."""
9472  ctx = _get_ctx(ctx)
9473  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9474 
9475 
9476 def Float64(ctx=None):
9477  """Floating-point 64-bit (double) sort."""
9478  ctx = _get_ctx(ctx)
9479  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9480 
9481 
9482 def FloatDouble(ctx=None):
9483  """Floating-point 64-bit (double) sort."""
9484  ctx = _get_ctx(ctx)
9485  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9486 
9487 
9488 def Float128(ctx=None):
9489  """Floating-point 128-bit (quadruple) sort."""
9490  ctx = _get_ctx(ctx)
9491  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9492 
9493 
9494 def FloatQuadruple(ctx=None):
9495  """Floating-point 128-bit (quadruple) sort."""
9496  ctx = _get_ctx(ctx)
9497  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9498 
9499 
9500 class FPRMSortRef(SortRef):
9501  """"Floating-point rounding mode sort."""
9502 
9503 
9504 def is_fp_sort(s):
9505  """Return True if `s` is a Z3 floating-point sort.
9506 
9507  >>> is_fp_sort(FPSort(8, 24))
9508  True
9509  >>> is_fp_sort(IntSort())
9510  False
9511  """
9512  return isinstance(s, FPSortRef)
9513 
9514 
9515 def is_fprm_sort(s):
9516  """Return True if `s` is a Z3 floating-point rounding mode sort.
9517 
9518  >>> is_fprm_sort(FPSort(8, 24))
9519  False
9520  >>> is_fprm_sort(RNE().sort())
9521  True
9522  """
9523  return isinstance(s, FPRMSortRef)
9524 
9525 # FP Expressions
9526 
9527 
9528 class FPRef(ExprRef):
9529  """Floating-point expressions."""
9530 
9531  def sort(self):
9532  """Return the sort of the floating-point expression `self`.
9533 
9534  >>> x = FP('1.0', FPSort(8, 24))
9535  >>> x.sort()
9536  FPSort(8, 24)
9537  >>> x.sort() == FPSort(8, 24)
9538  True
9539  """
9540  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9541 
9542  def ebits(self):
9543  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9544  >>> b = FPSort(8, 24)
9545  >>> b.ebits()
9546  8
9547  """
9548  return self.sort().ebits()
9549 
9550  def sbits(self):
9551  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9552  >>> b = FPSort(8, 24)
9553  >>> b.sbits()
9554  24
9555  """
9556  return self.sort().sbits()
9557 
9558  def as_string(self):
9559  """Return a Z3 floating point expression as a Python string."""
9560  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9561 
9562  def __le__(self, other):
9563  return fpLEQ(self, other, self.ctx)
9564 
9565  def __lt__(self, other):
9566  return fpLT(self, other, self.ctx)
9567 
9568  def __ge__(self, other):
9569  return fpGEQ(self, other, self.ctx)
9570 
9571  def __gt__(self, other):
9572  return fpGT(self, other, self.ctx)
9573 
9574  def __add__(self, other):
9575  """Create the Z3 expression `self + other`.
9576 
9577  >>> x = FP('x', FPSort(8, 24))
9578  >>> y = FP('y', FPSort(8, 24))
9579  >>> x + y
9580  x + y
9581  >>> (x + y).sort()
9582  FPSort(8, 24)
9583  """
9584  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9585  return fpAdd(_dflt_rm(), a, b, self.ctx)
9586 
9587  def __radd__(self, other):
9588  """Create the Z3 expression `other + self`.
9589 
9590  >>> x = FP('x', FPSort(8, 24))
9591  >>> 10 + x
9592  1.25*(2**3) + x
9593  """
9594  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9595  return fpAdd(_dflt_rm(), a, b, self.ctx)
9596 
9597  def __sub__(self, other):
9598  """Create the Z3 expression `self - other`.
9599 
9600  >>> x = FP('x', FPSort(8, 24))
9601  >>> y = FP('y', FPSort(8, 24))
9602  >>> x - y
9603  x - y
9604  >>> (x - y).sort()
9605  FPSort(8, 24)
9606  """
9607  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9608  return fpSub(_dflt_rm(), a, b, self.ctx)
9609 
9610  def __rsub__(self, other):
9611  """Create the Z3 expression `other - self`.
9612 
9613  >>> x = FP('x', FPSort(8, 24))
9614  >>> 10 - x
9615  1.25*(2**3) - x
9616  """
9617  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9618  return fpSub(_dflt_rm(), a, b, self.ctx)
9619 
9620  def __mul__(self, other):
9621  """Create the Z3 expression `self * other`.
9622 
9623  >>> x = FP('x', FPSort(8, 24))
9624  >>> y = FP('y', FPSort(8, 24))
9625  >>> x * y
9626  x * y
9627  >>> (x * y).sort()
9628  FPSort(8, 24)
9629  >>> 10 * y
9630  1.25*(2**3) * y
9631  """
9632  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9633  return fpMul(_dflt_rm(), a, b, self.ctx)
9634 
9635  def __rmul__(self, other):
9636  """Create the Z3 expression `other * self`.
9637 
9638  >>> x = FP('x', FPSort(8, 24))
9639  >>> y = FP('y', FPSort(8, 24))
9640  >>> x * y
9641  x * y
9642  >>> x * 10
9643  x * 1.25*(2**3)
9644  """
9645  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9646  return fpMul(_dflt_rm(), a, b, self.ctx)
9647 
9648  def __pos__(self):
9649  """Create the Z3 expression `+self`."""
9650  return self
9651 
9652  def __neg__(self):
9653  """Create the Z3 expression `-self`.
9654 
9655  >>> x = FP('x', Float32())
9656  >>> -x
9657  -x
9658  """
9659  return fpNeg(self)
9660 
9661  def __div__(self, other):
9662  """Create the Z3 expression `self / other`.
9663 
9664  >>> x = FP('x', FPSort(8, 24))
9665  >>> y = FP('y', FPSort(8, 24))
9666  >>> x / y
9667  x / y
9668  >>> (x / y).sort()
9669  FPSort(8, 24)
9670  >>> 10 / y
9671  1.25*(2**3) / y
9672  """
9673  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9674  return fpDiv(_dflt_rm(), a, b, self.ctx)
9675 
9676  def __rdiv__(self, other):
9677  """Create the Z3 expression `other / self`.
9678 
9679  >>> x = FP('x', FPSort(8, 24))
9680  >>> y = FP('y', FPSort(8, 24))
9681  >>> x / y
9682  x / y
9683  >>> x / 10
9684  x / 1.25*(2**3)
9685  """
9686  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9687  return fpDiv(_dflt_rm(), a, b, self.ctx)
9688 
9689  def __truediv__(self, other):
9690  """Create the Z3 expression division `self / other`."""
9691  return self.__div__(other)
9692 
9693  def __rtruediv__(self, other):
9694  """Create the Z3 expression division `other / self`."""
9695  return self.__rdiv__(other)
9696 
9697  def __mod__(self, other):
9698  """Create the Z3 expression mod `self % other`."""
9699  return fpRem(self, other)
9700 
9701  def __rmod__(self, other):
9702  """Create the Z3 expression mod `other % self`."""
9703  return fpRem(other, self)
9704 
9705 
9706 class FPRMRef(ExprRef):
9707  """Floating-point rounding mode expressions"""
9708 
9709  def as_string(self):
9710  """Return a Z3 floating point expression as a Python string."""
9711  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9712 
9713 
9714 def RoundNearestTiesToEven(ctx=None):
9715  ctx = _get_ctx(ctx)
9716  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9717 
9718 
9719 def RNE(ctx=None):
9720  ctx = _get_ctx(ctx)
9721  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9722 
9723 
9724 def RoundNearestTiesToAway(ctx=None):
9725  ctx = _get_ctx(ctx)
9726  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9727 
9728 
9729 def RNA(ctx=None):
9730  ctx = _get_ctx(ctx)
9731  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9732 
9733 
9734 def RoundTowardPositive(ctx=None):
9735  ctx = _get_ctx(ctx)
9736  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9737 
9738 
9739 def RTP(ctx=None):
9740  ctx = _get_ctx(ctx)
9741  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9742 
9743 
9744 def RoundTowardNegative(ctx=None):
9745  ctx = _get_ctx(ctx)
9746  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9747 
9748 
9749 def RTN(ctx=None):
9750  ctx = _get_ctx(ctx)
9751  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9752 
9753 
9754 def RoundTowardZero(ctx=None):
9755  ctx = _get_ctx(ctx)
9756  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9757 
9758 
9759 def RTZ(ctx=None):
9760  ctx = _get_ctx(ctx)
9761  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9762 
9763 
9764 def is_fprm(a):
9765  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9766 
9767  >>> rm = RNE()
9768  >>> is_fprm(rm)
9769  True
9770  >>> rm = 1.0
9771  >>> is_fprm(rm)
9772  False
9773  """
9774  return isinstance(a, FPRMRef)
9775 
9776 
9777 def is_fprm_value(a):
9778  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9779  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9780 
9781 # FP Numerals
9782 
9783 
9784 class FPNumRef(FPRef):
9785  """The sign of the numeral.
9786 
9787  >>> x = FPVal(+1.0, FPSort(8, 24))
9788  >>> x.sign()
9789  False
9790  >>> x = FPVal(-1.0, FPSort(8, 24))
9791  >>> x.sign()
9792  True
9793  """
9794 
9795  def sign(self):
9796  num = (ctypes.c_int)()
9797  nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
9798  if nsign is False:
9799  raise Z3Exception("error retrieving the sign of a numeral.")
9800  return num.value != 0
9801 
9802  """The sign of a floating-point numeral as a bit-vector expression.
9803 
9804  Remark: NaN's are invalid arguments.
9805  """
9806 
9807  def sign_as_bv(self):
9808  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9809 
9810  """The significand of the numeral.
9811 
9812  >>> x = FPVal(2.5, FPSort(8, 24))
9813  >>> x.significand()
9814  1.25
9815  """
9816 
9817  def significand(self):
9818  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
9819 
9820  """The significand of the numeral as a long.
9821 
9822  >>> x = FPVal(2.5, FPSort(8, 24))
9823  >>> x.significand_as_long()
9824  1.25
9825  """
9826 
9827  def significand_as_long(self):
9828  ptr = (ctypes.c_ulonglong * 1)()
9829  if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
9830  raise Z3Exception("error retrieving the significand of a numeral.")
9831  return ptr[0]
9832 
9833  """The significand of the numeral as a bit-vector expression.
9834 
9835  Remark: NaN are invalid arguments.
9836  """
9837 
9838  def significand_as_bv(self):
9839  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9840 
9841  """The exponent of the numeral.
9842 
9843  >>> x = FPVal(2.5, FPSort(8, 24))
9844  >>> x.exponent()
9845  1
9846  """
9847 
9848  def exponent(self, biased=True):
9849  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
9850 
9851  """The exponent of the numeral as a long.
9852 
9853  >>> x = FPVal(2.5, FPSort(8, 24))
9854  >>> x.exponent_as_long()
9855  1
9856  """
9857 
9858  def exponent_as_long(self, biased=True):
9859  ptr = (ctypes.c_longlong * 1)()
9860  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
9861  raise Z3Exception("error retrieving the exponent of a numeral.")
9862  return ptr[0]
9863 
9864  """The exponent of the numeral as a bit-vector expression.
9865 
9866  Remark: NaNs are invalid arguments.
9867  """
9868 
9869  def exponent_as_bv(self, biased=True):
9870  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
9871 
9872  """Indicates whether the numeral is a NaN."""
9873 
9874  def isNaN(self):
9875  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
9876 
9877  """Indicates whether the numeral is +oo or -oo."""
9878 
9879  def isInf(self):
9880  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
9881 
9882  """Indicates whether the numeral is +zero or -zero."""
9883 
9884  def isZero(self):
9885  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
9886 
9887  """Indicates whether the numeral is normal."""
9888 
9889  def isNormal(self):
9890  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
9891 
9892  """Indicates whether the numeral is subnormal."""
9893 
9894  def isSubnormal(self):
9895  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
9896 
9897  """Indicates whether the numeral is positive."""
9898 
9899  def isPositive(self):
9900  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
9901 
9902  """Indicates whether the numeral is negative."""
9903 
9904  def isNegative(self):
9905  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
9906 
9907  """
9908  The string representation of the numeral.
9909 
9910  >>> x = FPVal(20, FPSort(8, 24))
9911  >>> x.as_string()
9912  1.25*(2**4)
9913  """
9914 
9915  def as_string(self):
9916  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
9917  return ("FPVal(%s, %s)" % (s, self.sort()))
9918 
9919 
9920 def is_fp(a):
9921  """Return `True` if `a` is a Z3 floating-point expression.
9922 
9923  >>> b = FP('b', FPSort(8, 24))
9924  >>> is_fp(b)
9925  True
9926  >>> is_fp(b + 1.0)
9927  True
9928  >>> is_fp(Int('x'))
9929  False
9930  """
9931  return isinstance(a, FPRef)
9932 
9933 
9934 def is_fp_value(a):
9935  """Return `True` if `a` is a Z3 floating-point numeral value.
9936 
9937  >>> b = FP('b', FPSort(8, 24))
9938  >>> is_fp_value(b)
9939  False
9940  >>> b = FPVal(1.0, FPSort(8, 24))
9941  >>> b
9942  1
9943  >>> is_fp_value(b)
9944  True
9945  """
9946  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9947 
9948 
9949 def FPSort(ebits, sbits, ctx=None):
9950  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9951 
9952  >>> Single = FPSort(8, 24)
9953  >>> Double = FPSort(11, 53)
9954  >>> Single
9955  FPSort(8, 24)
9956  >>> x = Const('x', Single)
9957  >>> eq(x, FP('x', FPSort(8, 24)))
9958  True
9959  """
9960  ctx = _get_ctx(ctx)
9961  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9962 
9963 
9964 def _to_float_str(val, exp=0):
9965  if isinstance(val, float):
9966  if math.isnan(val):
9967  res = "NaN"
9968  elif val == 0.0:
9969  sone = math.copysign(1.0, val)
9970  if sone < 0.0:
9971  return "-0.0"
9972  else:
9973  return "+0.0"
9974  elif val == float("+inf"):
9975  res = "+oo"
9976  elif val == float("-inf"):
9977  res = "-oo"
9978  else:
9979  v = val.as_integer_ratio()
9980  num = v[0]
9981  den = v[1]
9982  rvs = str(num) + "/" + str(den)
9983  res = rvs + "p" + _to_int_str(exp)
9984  elif isinstance(val, bool):
9985  if val:
9986  res = "1.0"
9987  else:
9988  res = "0.0"
9989  elif _is_int(val):
9990  res = str(val)
9991  elif isinstance(val, str):
9992  inx = val.find("*(2**")
9993  if inx == -1:
9994  res = val
9995  elif val[-1] == ")":
9996  res = val[0:inx]
9997  exp = str(int(val[inx + 5:-1]) + int(exp))
9998  else:
9999  _z3_assert(False, "String does not have floating-point numeral form.")
10000  elif z3_debug():
10001  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10002  if exp == 0:
10003  return res
10004  else:
10005  return res + "p" + exp
10006 
10007 
10008 def fpNaN(s):
10009  """Create a Z3 floating-point NaN term.
10010 
10011  >>> s = FPSort(8, 24)
10012  >>> set_fpa_pretty(True)
10013  >>> fpNaN(s)
10014  NaN
10015  >>> pb = get_fpa_pretty()
10016  >>> set_fpa_pretty(False)
10017  >>> fpNaN(s)
10018  fpNaN(FPSort(8, 24))
10019  >>> set_fpa_pretty(pb)
10020  """
10021  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10022  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10023 
10024 
10025 def fpPlusInfinity(s):
10026  """Create a Z3 floating-point +oo term.
10027 
10028  >>> s = FPSort(8, 24)
10029  >>> pb = get_fpa_pretty()
10030  >>> set_fpa_pretty(True)
10031  >>> fpPlusInfinity(s)
10032  +oo
10033  >>> set_fpa_pretty(False)
10034  >>> fpPlusInfinity(s)
10035  fpPlusInfinity(FPSort(8, 24))
10036  >>> set_fpa_pretty(pb)
10037  """
10038  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10039  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10040 
10041 
10042 def fpMinusInfinity(s):
10043  """Create a Z3 floating-point -oo term."""
10044  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10045  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10046 
10047 
10048 def fpInfinity(s, negative):
10049  """Create a Z3 floating-point +oo or -oo term."""
10050  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10051  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10052  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10053 
10054 
10055 def fpPlusZero(s):
10056  """Create a Z3 floating-point +0.0 term."""
10057  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10058  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10059 
10060 
10061 def fpMinusZero(s):
10062  """Create a Z3 floating-point -0.0 term."""
10063  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10064  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10065 
10066 
10067 def fpZero(s, negative):
10068  """Create a Z3 floating-point +0.0 or -0.0 term."""
10069  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10070  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10071  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10072 
10073 
10074 def FPVal(sig, exp=None, fps=None, ctx=None):
10075  """Return a floating-point value of value `val` and sort `fps`.
10076  If `ctx=None`, then the global context is used.
10077 
10078  >>> v = FPVal(20.0, FPSort(8, 24))
10079  >>> v
10080  1.25*(2**4)
10081  >>> print("0x%.8x" % v.exponent_as_long(False))
10082  0x00000004
10083  >>> v = FPVal(2.25, FPSort(8, 24))
10084  >>> v
10085  1.125*(2**1)
10086  >>> v = FPVal(-2.25, FPSort(8, 24))
10087  >>> v
10088  -1.125*(2**1)
10089  >>> FPVal(-0.0, FPSort(8, 24))
10090  -0.0
10091  >>> FPVal(0.0, FPSort(8, 24))
10092  +0.0
10093  >>> FPVal(+0.0, FPSort(8, 24))
10094  +0.0
10095  """
10096  ctx = _get_ctx(ctx)
10097  if is_fp_sort(exp):
10098  fps = exp
10099  exp = None
10100  elif fps is None:
10101  fps = _dflt_fps(ctx)
10102  _z3_assert(is_fp_sort(fps), "sort mismatch")
10103  if exp is None:
10104  exp = 0
10105  val = _to_float_str(sig)
10106  if val == "NaN" or val == "nan":
10107  return fpNaN(fps)
10108  elif val == "-0.0":
10109  return fpMinusZero(fps)
10110  elif val == "0.0" or val == "+0.0":
10111  return fpPlusZero(fps)
10112  elif val == "+oo" or val == "+inf" or val == "+Inf":
10113  return fpPlusInfinity(fps)
10114  elif val == "-oo" or val == "-inf" or val == "-Inf":
10115  return fpMinusInfinity(fps)
10116  else:
10117  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10118 
10119 
10120 def FP(name, fpsort, ctx=None):
10121  """Return a floating-point constant named `name`.
10122  `fpsort` is the floating-point sort.
10123  If `ctx=None`, then the global context is used.
10124 
10125  >>> x = FP('x', FPSort(8, 24))
10126  >>> is_fp(x)
10127  True
10128  >>> x.ebits()
10129  8
10130  >>> x.sort()
10131  FPSort(8, 24)
10132  >>> word = FPSort(8, 24)
10133  >>> x2 = FP('x', word)
10134  >>> eq(x, x2)
10135  True
10136  """
10137  if isinstance(fpsort, FPSortRef) and ctx is None:
10138  ctx = fpsort.ctx
10139  else:
10140  ctx = _get_ctx(ctx)
10141  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10142 
10143 
10144 def FPs(names, fpsort, ctx=None):
10145  """Return an array of floating-point constants.
10146 
10147  >>> x, y, z = FPs('x y z', FPSort(8, 24))
10148  >>> x.sort()
10149  FPSort(8, 24)
10150  >>> x.sbits()
10151  24
10152  >>> x.ebits()
10153  8
10154  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10155  x + y * z
10156  """
10157  ctx = _get_ctx(ctx)
10158  if isinstance(names, str):
10159  names = names.split(" ")
10160  return [FP(name, fpsort, ctx) for name in names]
10161 
10162 
10163 def fpAbs(a, ctx=None):
10164  """Create a Z3 floating-point absolute value expression.
10165 
10166  >>> s = FPSort(8, 24)
10167  >>> rm = RNE()
10168  >>> x = FPVal(1.0, s)
10169  >>> fpAbs(x)
10170  fpAbs(1)
10171  >>> y = FPVal(-20.0, s)
10172  >>> y
10173  -1.25*(2**4)
10174  >>> fpAbs(y)
10175  fpAbs(-1.25*(2**4))
10176  >>> fpAbs(-1.25*(2**4))
10177  fpAbs(-1.25*(2**4))
10178  >>> fpAbs(x).sort()
10179  FPSort(8, 24)
10180  """
10181  ctx = _get_ctx(ctx)
10182  [a] = _coerce_fp_expr_list([a], ctx)
10183  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10184 
10185 
10186 def fpNeg(a, ctx=None):
10187  """Create a Z3 floating-point addition expression.
10188 
10189  >>> s = FPSort(8, 24)
10190  >>> rm = RNE()
10191  >>> x = FP('x', s)
10192  >>> fpNeg(x)
10193  -x
10194  >>> fpNeg(x).sort()
10195  FPSort(8, 24)
10196  """
10197  ctx = _get_ctx(ctx)
10198  [a] = _coerce_fp_expr_list([a], ctx)
10199  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10200 
10201 
10202 def _mk_fp_unary(f, rm, a, ctx):
10203  ctx = _get_ctx(ctx)
10204  [a] = _coerce_fp_expr_list([a], ctx)
10205  if z3_debug():
10206  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10207  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10208  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10209 
10210 
10211 def _mk_fp_unary_pred(f, a, ctx):
10212  ctx = _get_ctx(ctx)
10213  [a] = _coerce_fp_expr_list([a], ctx)
10214  if z3_debug():
10215  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10216  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10217 
10218 
10219 def _mk_fp_bin(f, rm, a, b, ctx):
10220  ctx = _get_ctx(ctx)
10221  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10222  if z3_debug():
10223  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10224  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10225  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10226 
10227 
10228 def _mk_fp_bin_norm(f, a, b, ctx):
10229  ctx = _get_ctx(ctx)
10230  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10231  if z3_debug():
10232  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10233  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10234 
10235 
10236 def _mk_fp_bin_pred(f, a, b, ctx):
10237  ctx = _get_ctx(ctx)
10238  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10239  if z3_debug():
10240  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10241  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10242 
10243 
10244 def _mk_fp_tern(f, rm, a, b, c, ctx):
10245  ctx = _get_ctx(ctx)
10246  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
10247  if z3_debug():
10248  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10249  _z3_assert(is_fp(a) or is_fp(b) or is_fp(
10250  c), "Second, third or fourth argument must be a Z3 floating-point expression")
10251  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10252 
10253 
10254 def fpAdd(rm, a, b, ctx=None):
10255  """Create a Z3 floating-point addition expression.
10256 
10257  >>> s = FPSort(8, 24)
10258  >>> rm = RNE()
10259  >>> x = FP('x', s)
10260  >>> y = FP('y', s)
10261  >>> fpAdd(rm, x, y)
10262  x + y
10263  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10264  fpAdd(RTZ(), x, y)
10265  >>> fpAdd(rm, x, y).sort()
10266  FPSort(8, 24)
10267  """
10268  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10269 
10270 
10271 def fpSub(rm, a, b, ctx=None):
10272  """Create a Z3 floating-point subtraction expression.
10273 
10274  >>> s = FPSort(8, 24)
10275  >>> rm = RNE()
10276  >>> x = FP('x', s)
10277  >>> y = FP('y', s)
10278  >>> fpSub(rm, x, y)
10279  x - y
10280  >>> fpSub(rm, x, y).sort()
10281  FPSort(8, 24)
10282  """
10283  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10284 
10285 
10286 def fpMul(rm, a, b, ctx=None):
10287  """Create a Z3 floating-point multiplication expression.
10288 
10289  >>> s = FPSort(8, 24)
10290  >>> rm = RNE()
10291  >>> x = FP('x', s)
10292  >>> y = FP('y', s)
10293  >>> fpMul(rm, x, y)
10294  x * y
10295  >>> fpMul(rm, x, y).sort()
10296  FPSort(8, 24)
10297  """
10298  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10299 
10300 
10301 def fpDiv(rm, a, b, ctx=None):
10302  """Create a Z3 floating-point division expression.
10303 
10304  >>> s = FPSort(8, 24)
10305  >>> rm = RNE()
10306  >>> x = FP('x', s)
10307  >>> y = FP('y', s)
10308  >>> fpDiv(rm, x, y)
10309  x / y
10310  >>> fpDiv(rm, x, y).sort()
10311  FPSort(8, 24)
10312  """
10313  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10314 
10315 
10316 def fpRem(a, b, ctx=None):
10317  """Create a Z3 floating-point remainder expression.
10318 
10319  >>> s = FPSort(8, 24)
10320  >>> x = FP('x', s)
10321  >>> y = FP('y', s)
10322  >>> fpRem(x, y)
10323  fpRem(x, y)
10324  >>> fpRem(x, y).sort()
10325  FPSort(8, 24)
10326  """
10327  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10328 
10329 
10330 def fpMin(a, b, ctx=None):
10331  """Create a Z3 floating-point minimum expression.
10332 
10333  >>> s = FPSort(8, 24)
10334  >>> rm = RNE()
10335  >>> x = FP('x', s)
10336  >>> y = FP('y', s)
10337  >>> fpMin(x, y)
10338  fpMin(x, y)
10339  >>> fpMin(x, y).sort()
10340  FPSort(8, 24)
10341  """
10342  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10343 
10344 
10345 def fpMax(a, b, ctx=None):
10346  """Create a Z3 floating-point maximum expression.
10347 
10348  >>> s = FPSort(8, 24)
10349  >>> rm = RNE()
10350  >>> x = FP('x', s)
10351  >>> y = FP('y', s)
10352  >>> fpMax(x, y)
10353  fpMax(x, y)
10354  >>> fpMax(x, y).sort()
10355  FPSort(8, 24)
10356  """
10357  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10358 
10359 
10360 def fpFMA(rm, a, b, c, ctx=None):
10361  """Create a Z3 floating-point fused multiply-add expression.
10362  """
10363  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10364 
10365 
10366 def fpSqrt(rm, a, ctx=None):
10367  """Create a Z3 floating-point square root expression.
10368  """
10369  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10370 
10371 
10372 def fpRoundToIntegral(rm, a, ctx=None):
10373  """Create a Z3 floating-point roundToIntegral expression.
10374  """
10375  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10376 
10377 
10378 def fpIsNaN(a, ctx=None):
10379  """Create a Z3 floating-point isNaN expression.
10380 
10381  >>> s = FPSort(8, 24)
10382  >>> x = FP('x', s)
10383  >>> y = FP('y', s)
10384  >>> fpIsNaN(x)
10385  fpIsNaN(x)
10386  """
10387  return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10388 
10389 
10390 def fpIsInf(a, ctx=None):
10391  """Create a Z3 floating-point isInfinite expression.
10392 
10393  >>> s = FPSort(8, 24)
10394  >>> x = FP('x', s)
10395  >>> fpIsInf(x)
10396  fpIsInf(x)
10397  """
10398  return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10399 
10400 
10401 def fpIsZero(a, ctx=None):
10402  """Create a Z3 floating-point isZero expression.
10403  """
10404  return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10405 
10406 
10407 def fpIsNormal(a, ctx=None):
10408  """Create a Z3 floating-point isNormal expression.
10409  """
10410  return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10411 
10412 
10413 def fpIsSubnormal(a, ctx=None):
10414  """Create a Z3 floating-point isSubnormal expression.
10415  """
10416  return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10417 
10418 
10419 def fpIsNegative(a, ctx=None):
10420  """Create a Z3 floating-point isNegative expression.
10421  """
10422  return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10423 
10424 
10425 def fpIsPositive(a, ctx=None):
10426  """Create a Z3 floating-point isPositive expression.
10427  """
10428  return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10429 
10430 
10431 def _check_fp_args(a, b):
10432  if z3_debug():
10433  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10434 
10435 
10436 def fpLT(a, b, ctx=None):
10437  """Create the Z3 floating-point expression `other < self`.
10438 
10439  >>> x, y = FPs('x y', FPSort(8, 24))
10440  >>> fpLT(x, y)
10441  x < y
10442  >>> (x < y).sexpr()
10443  '(fp.lt x y)'
10444  """
10445  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10446 
10447 
10448 def fpLEQ(a, b, ctx=None):
10449  """Create the Z3 floating-point expression `other <= self`.
10450 
10451  >>> x, y = FPs('x y', FPSort(8, 24))
10452  >>> fpLEQ(x, y)
10453  x <= y
10454  >>> (x <= y).sexpr()
10455  '(fp.leq x y)'
10456  """
10457  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10458 
10459 
10460 def fpGT(a, b, ctx=None):
10461  """Create the Z3 floating-point expression `other > self`.
10462 
10463  >>> x, y = FPs('x y', FPSort(8, 24))
10464  >>> fpGT(x, y)
10465  x > y
10466  >>> (x > y).sexpr()
10467  '(fp.gt x y)'
10468  """
10469  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10470 
10471 
10472 def fpGEQ(a, b, ctx=None):
10473  """Create the Z3 floating-point expression `other >= self`.
10474 
10475  >>> x, y = FPs('x y', FPSort(8, 24))
10476  >>> fpGEQ(x, y)
10477  x >= y
10478  >>> (x >= y).sexpr()
10479  '(fp.geq x y)'
10480  """
10481  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10482 
10483 
10484 def fpEQ(a, b, ctx=None):
10485  """Create the Z3 floating-point expression `fpEQ(other, self)`.
10486 
10487  >>> x, y = FPs('x y', FPSort(8, 24))
10488  >>> fpEQ(x, y)
10489  fpEQ(x, y)
10490  >>> fpEQ(x, y).sexpr()
10491  '(fp.eq x y)'
10492  """
10493  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10494 
10495 
10496 def fpNEQ(a, b, ctx=None):
10497  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10498 
10499  >>> x, y = FPs('x y', FPSort(8, 24))
10500  >>> fpNEQ(x, y)
10501  Not(fpEQ(x, y))
10502  >>> (x != y).sexpr()
10503  '(distinct x y)'
10504  """
10505  return Not(fpEQ(a, b, ctx))
10506 
10507 
10508 def fpFP(sgn, exp, sig, ctx=None):
10509  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10510 
10511  >>> s = FPSort(8, 24)
10512  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10513  >>> print(x)
10514  fpFP(1, 127, 4194304)
10515  >>> xv = FPVal(-1.5, s)
10516  >>> print(xv)
10517  -1.5
10518  >>> slvr = Solver()
10519  >>> slvr.add(fpEQ(x, xv))
10520  >>> slvr.check()
10521  sat
10522  >>> xv = FPVal(+1.5, s)
10523  >>> print(xv)
10524  1.5
10525  >>> slvr = Solver()
10526  >>> slvr.add(fpEQ(x, xv))
10527  >>> slvr.check()
10528  unsat
10529  """
10530  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10531  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10532  ctx = _get_ctx(ctx)
10533  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10534  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10535 
10536 
10537 def fpToFP(a1, a2=None, a3=None, ctx=None):
10538  """Create a Z3 floating-point conversion expression from other term sorts
10539  to floating-point.
10540 
10541  From a bit-vector term in IEEE 754-2008 format:
10542  >>> x = FPVal(1.0, Float32())
10543  >>> x_bv = fpToIEEEBV(x)
10544  >>> simplify(fpToFP(x_bv, Float32()))
10545  1
10546 
10547  From a floating-point term with different precision:
10548  >>> x = FPVal(1.0, Float32())
10549  >>> x_db = fpToFP(RNE(), x, Float64())
10550  >>> x_db.sort()
10551  FPSort(11, 53)
10552 
10553  From a real term:
10554  >>> x_r = RealVal(1.5)
10555  >>> simplify(fpToFP(RNE(), x_r, Float32()))
10556  1.5
10557 
10558  From a signed bit-vector term:
10559  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10560  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10561  -1.25*(2**2)
10562  """
10563  ctx = _get_ctx(ctx)
10564  if is_bv(a1) and is_fp_sort(a2):
10565  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10566  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10567  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10568  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10569  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10570  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10571  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10572  else:
10573  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10574 
10575 
10576 def fpBVToFP(v, sort, ctx=None):
10577  """Create a Z3 floating-point conversion expression that represents the
10578  conversion from a bit-vector term to a floating-point term.
10579 
10580  >>> x_bv = BitVecVal(0x3F800000, 32)
10581  >>> x_fp = fpBVToFP(x_bv, Float32())
10582  >>> x_fp
10583  fpToFP(1065353216)
10584  >>> simplify(x_fp)
10585  1
10586  """
10587  _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10588  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10589  ctx = _get_ctx(ctx)
10590  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10591 
10592 
10593 def fpFPToFP(rm, v, sort, ctx=None):
10594  """Create a Z3 floating-point conversion expression that represents the
10595  conversion from a floating-point term to a floating-point term of different precision.
10596 
10597  >>> x_sgl = FPVal(1.0, Float32())
10598  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10599  >>> x_dbl
10600  fpToFP(RNE(), 1)
10601  >>> simplify(x_dbl)
10602  1
10603  >>> x_dbl.sort()
10604  FPSort(11, 53)
10605  """
10606  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10607  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10608  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10609  ctx = _get_ctx(ctx)
10610  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10611 
10612 
10613 def fpRealToFP(rm, v, sort, ctx=None):
10614  """Create a Z3 floating-point conversion expression that represents the
10615  conversion from a real term to a floating-point term.
10616 
10617  >>> x_r = RealVal(1.5)
10618  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10619  >>> x_fp
10620  fpToFP(RNE(), 3/2)
10621  >>> simplify(x_fp)
10622  1.5
10623  """
10624  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10625  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10626  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10627  ctx = _get_ctx(ctx)
10628  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10629 
10630 
10631 def fpSignedToFP(rm, v, sort, ctx=None):
10632  """Create a Z3 floating-point conversion expression that represents the
10633  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10634 
10635  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10636  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10637  >>> x_fp
10638  fpToFP(RNE(), 4294967291)
10639  >>> simplify(x_fp)
10640  -1.25*(2**2)
10641  """
10642  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10643  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10644  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10645  ctx = _get_ctx(ctx)
10646  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10647 
10648 
10649 def fpUnsignedToFP(rm, v, sort, ctx=None):
10650  """Create a Z3 floating-point conversion expression that represents the
10651  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10652 
10653  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10654  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10655  >>> x_fp
10656  fpToFPUnsigned(RNE(), 4294967291)
10657  >>> simplify(x_fp)
10658  1*(2**32)
10659  """
10660  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10661  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10662  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10663  ctx = _get_ctx(ctx)
10664  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10665 
10666 
10667 def fpToFPUnsigned(rm, x, s, ctx=None):
10668  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10669  if z3_debug():
10670  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10671  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10672  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10673  ctx = _get_ctx(ctx)
10674  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10675 
10676 
10677 def fpToSBV(rm, x, s, ctx=None):
10678  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10679 
10680  >>> x = FP('x', FPSort(8, 24))
10681  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10682  >>> print(is_fp(x))
10683  True
10684  >>> print(is_bv(y))
10685  True
10686  >>> print(is_fp(y))
10687  False
10688  >>> print(is_bv(x))
10689  False
10690  """
10691  if z3_debug():
10692  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10693  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10694  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10695  ctx = _get_ctx(ctx)
10696  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10697 
10698 
10699 def fpToUBV(rm, x, s, ctx=None):
10700  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10701 
10702  >>> x = FP('x', FPSort(8, 24))
10703  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10704  >>> print(is_fp(x))
10705  True
10706  >>> print(is_bv(y))
10707  True
10708  >>> print(is_fp(y))
10709  False
10710  >>> print(is_bv(x))
10711  False
10712  """
10713  if z3_debug():
10714  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10715  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10716  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10717  ctx = _get_ctx(ctx)
10718  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10719 
10720 
10721 def fpToReal(x, ctx=None):
10722  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10723 
10724  >>> x = FP('x', FPSort(8, 24))
10725  >>> y = fpToReal(x)
10726  >>> print(is_fp(x))
10727  True
10728  >>> print(is_real(y))
10729  True
10730  >>> print(is_fp(y))
10731  False
10732  >>> print(is_real(x))
10733  False
10734  """
10735  if z3_debug():
10736  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10737  ctx = _get_ctx(ctx)
10738  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10739 
10740 
10741 def fpToIEEEBV(x, ctx=None):
10742  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10743 
10744  The size of the resulting bit-vector is automatically determined.
10745 
10746  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10747  knows only one NaN and it will always produce the same bit-vector representation of
10748  that NaN.
10749 
10750  >>> x = FP('x', FPSort(8, 24))
10751  >>> y = fpToIEEEBV(x)
10752  >>> print(is_fp(x))
10753  True
10754  >>> print(is_bv(y))
10755  True
10756  >>> print(is_fp(y))
10757  False
10758  >>> print(is_bv(x))
10759  False
10760  """
10761  if z3_debug():
10762  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10763  ctx = _get_ctx(ctx)
10764  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10765 
10766 
10767 #########################################
10768 #
10769 # Strings, Sequences and Regular expressions
10770 #
10771 #########################################
10772 
10773 class SeqSortRef(SortRef):
10774  """Sequence sort."""
10775 
10776  def is_string(self):
10777  """Determine if sort is a string
10778  >>> s = StringSort()
10779  >>> s.is_string()
10780  True
10781  >>> s = SeqSort(IntSort())
10782  >>> s.is_string()
10783  False
10784  """
10785  return Z3_is_string_sort(self.ctx_ref(), self.ast)
10786 
10787  def basis(self):
10788  return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10789 
10790 class CharSortRef(SortRef):
10791  """Character sort."""
10792 
10793 
10794 def StringSort(ctx=None):
10795  """Create a string sort
10796  >>> s = StringSort()
10797  >>> print(s)
10798  String
10799  """
10800  ctx = _get_ctx(ctx)
10801  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10802 
10803 def CharSort(ctx=None):
10804  """Create a character sort
10805  >>> ch = CharSort()
10806  >>> print(ch)
10807  Char
10808  """
10809  ctx = _get_ctx(ctx)
10810  return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
10811 
10812 
10813 def SeqSort(s):
10814  """Create a sequence sort over elements provided in the argument
10815  >>> s = SeqSort(IntSort())
10816  >>> s == Unit(IntVal(1)).sort()
10817  True
10818  """
10819  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10820 
10821 
10822 class SeqRef(ExprRef):
10823  """Sequence expression."""
10824 
10825  def sort(self):
10826  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10827 
10828  def __add__(self, other):
10829  return Concat(self, other)
10830 
10831  def __radd__(self, other):
10832  return Concat(other, self)
10833 
10834  def __getitem__(self, i):
10835  if _is_int(i):
10836  i = IntVal(i, self.ctx)
10837  return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
10838 
10839  def at(self, i):
10840  if _is_int(i):
10841  i = IntVal(i, self.ctx)
10842  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
10843 
10844  def is_string(self):
10845  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
10846 
10847  def is_string_value(self):
10848  return Z3_is_string(self.ctx_ref(), self.as_ast())
10849 
10850  def as_string(self):
10851  """Return a string representation of sequence expression."""
10852  if self.is_string_value():
10853  string_length = ctypes.c_uint()
10854  chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
10855  return string_at(chars, size=string_length.value).decode("latin-1")
10856  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10857 
10858  def __le__(self, other):
10859  return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
10860 
10861  def __lt__(self, other):
10862  return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
10863 
10864  def __ge__(self, other):
10865  return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
10866 
10867  def __gt__(self, other):
10868  return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
10869 
10870 
10871 def _coerce_char(ch, ctx=None):
10872  if isinstance(ch, str):
10873  ctx = _get_ctx(ctx)
10874  ch = CharVal(ch, ctx)
10875  if not is_expr(ch):
10876  raise Z3Exception("Character expression expected")
10877  return ch
10878 
10879 class CharRef(ExprRef):
10880  """Character expression."""
10881 
10882  def __le__(self, other):
10883  other = _coerce_char(other, self.ctx)
10884  return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
10885 
10886  def to_int(self):
10887  return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
10888 
10889  def to_bv(self):
10890  return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
10891 
10892  def is_digit(self):
10893  return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
10894 
10895 
10896 def CharVal(ch, ctx=None):
10897  ctx = _get_ctx(ctx)
10898  if isinstance(ch, str):
10899  ch = ord(ch)
10900  if not isinstance(ch, int):
10901  raise Z3Exception("character value should be an ordinal")
10902  return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
10903 
10904 def CharFromBv(ch, ctx=None):
10905  if not is_expr(ch):
10906  raise Z3Expression("Bit-vector expression needed")
10907  return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
10908 
10909 def CharToBv(ch, ctx=None):
10910  ch = _coerce_char(ch, ctx)
10911  return ch.to_bv()
10912 
10913 def CharToInt(ch, ctx=None):
10914  ch = _coerce_char(ch, ctx)
10915  return ch.to_int()
10916 
10917 def CharIsDigit(ch, ctx=None):
10918  ch = _coerce_char(ch, ctx)
10919  return ch.is_digit()
10920 
10921 def _coerce_seq(s, ctx=None):
10922  if isinstance(s, str):
10923  ctx = _get_ctx(ctx)
10924  s = StringVal(s, ctx)
10925  if not is_expr(s):
10926  raise Z3Exception("Non-expression passed as a sequence")
10927  if not is_seq(s):
10928  raise Z3Exception("Non-sequence passed as a sequence")
10929  return s
10930 
10931 
10932 def _get_ctx2(a, b, ctx=None):
10933  if is_expr(a):
10934  return a.ctx
10935  if is_expr(b):
10936  return b.ctx
10937  if ctx is None:
10938  ctx = main_ctx()
10939  return ctx
10940 
10941 
10942 def is_seq(a):
10943  """Return `True` if `a` is a Z3 sequence expression.
10944  >>> print (is_seq(Unit(IntVal(0))))
10945  True
10946  >>> print (is_seq(StringVal("abc")))
10947  True
10948  """
10949  return isinstance(a, SeqRef)
10950 
10951 
10952 def is_string(a):
10953  """Return `True` if `a` is a Z3 string expression.
10954  >>> print (is_string(StringVal("ab")))
10955  True
10956  """
10957  return isinstance(a, SeqRef) and a.is_string()
10958 
10959 
10960 def is_string_value(a):
10961  """return 'True' if 'a' is a Z3 string constant expression.
10962  >>> print (is_string_value(StringVal("a")))
10963  True
10964  >>> print (is_string_value(StringVal("a") + StringVal("b")))
10965  False
10966  """
10967  return isinstance(a, SeqRef) and a.is_string_value()
10968 
10969 def StringVal(s, ctx=None):
10970  """create a string expression"""
10971  s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
10972  ctx = _get_ctx(ctx)
10973  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
10974 
10975 
10976 def String(name, ctx=None):
10977  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10978 
10979  >>> x = String('x')
10980  """
10981  ctx = _get_ctx(ctx)
10982  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10983 
10984 
10985 def Strings(names, ctx=None):
10986  """Return a tuple of String constants. """
10987  ctx = _get_ctx(ctx)
10988  if isinstance(names, str):
10989  names = names.split(" ")
10990  return [String(name, ctx) for name in names]
10991 
10992 
10993 def SubString(s, offset, length):
10994  """Extract substring or subsequence starting at offset"""
10995  return Extract(s, offset, length)
10996 
10997 
10998 def SubSeq(s, offset, length):
10999  """Extract substring or subsequence starting at offset"""
11000  return Extract(s, offset, length)
11001 
11002 
11003 def Empty(s):
11004  """Create the empty sequence of the given sort
11005  >>> e = Empty(StringSort())
11006  >>> e2 = StringVal("")
11007  >>> print(e.eq(e2))
11008  True
11009  >>> e3 = Empty(SeqSort(IntSort()))
11010  >>> print(e3)
11011  Empty(Seq(Int))
11012  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11013  >>> print(e4)
11014  Empty(ReSort(Seq(Int)))
11015  """
11016  if isinstance(s, SeqSortRef):
11017  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11018  if isinstance(s, ReSortRef):
11019  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11020  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11021 
11022 
11023 def Full(s):
11024  """Create the regular expression that accepts the universal language
11025  >>> e = Full(ReSort(SeqSort(IntSort())))
11026  >>> print(e)
11027  Full(ReSort(Seq(Int)))
11028  >>> e1 = Full(ReSort(StringSort()))
11029  >>> print(e1)
11030  Full(ReSort(String))
11031  """
11032  if isinstance(s, ReSortRef):
11033  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11034  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11035 
11036 
11037 
11038 def Unit(a):
11039  """Create a singleton sequence"""
11040  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11041 
11042 
11043 def PrefixOf(a, b):
11044  """Check if 'a' is a prefix of 'b'
11045  >>> s1 = PrefixOf("ab", "abc")
11046  >>> simplify(s1)
11047  True
11048  >>> s2 = PrefixOf("bc", "abc")
11049  >>> simplify(s2)
11050  False
11051  """
11052  ctx = _get_ctx2(a, b)
11053  a = _coerce_seq(a, ctx)
11054  b = _coerce_seq(b, ctx)
11055  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11056 
11057 
11058 def SuffixOf(a, b):
11059  """Check if 'a' is a suffix of 'b'
11060  >>> s1 = SuffixOf("ab", "abc")
11061  >>> simplify(s1)
11062  False
11063  >>> s2 = SuffixOf("bc", "abc")
11064  >>> simplify(s2)
11065  True
11066  """
11067  ctx = _get_ctx2(a, b)
11068  a = _coerce_seq(a, ctx)
11069  b = _coerce_seq(b, ctx)
11070  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11071 
11072 
11073 def Contains(a, b):
11074  """Check if 'a' contains 'b'
11075  >>> s1 = Contains("abc", "ab")
11076  >>> simplify(s1)
11077  True
11078  >>> s2 = Contains("abc", "bc")
11079  >>> simplify(s2)
11080  True
11081  >>> x, y, z = Strings('x y z')
11082  >>> s3 = Contains(Concat(x,y,z), y)
11083  >>> simplify(s3)
11084  True
11085  """
11086  ctx = _get_ctx2(a, b)
11087  a = _coerce_seq(a, ctx)
11088  b = _coerce_seq(b, ctx)
11089  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11090 
11091 
11092 def Replace(s, src, dst):
11093  """Replace the first occurrence of 'src' by 'dst' in 's'
11094  >>> r = Replace("aaa", "a", "b")
11095  >>> simplify(r)
11096  "baa"
11097  """
11098  ctx = _get_ctx2(dst, s)
11099  if ctx is None and is_expr(src):
11100  ctx = src.ctx
11101  src = _coerce_seq(src, ctx)
11102  dst = _coerce_seq(dst, ctx)
11103  s = _coerce_seq(s, ctx)
11104  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11105 
11106 
11107 def IndexOf(s, substr, offset=None):
11108  """Retrieve the index of substring within a string starting at a specified offset.
11109  >>> simplify(IndexOf("abcabc", "bc", 0))
11110  1
11111  >>> simplify(IndexOf("abcabc", "bc", 2))
11112  4
11113  """
11114  if offset is None:
11115  offset = IntVal(0)
11116  ctx = None
11117  if is_expr(offset):
11118  ctx = offset.ctx
11119  ctx = _get_ctx2(s, substr, ctx)
11120  s = _coerce_seq(s, ctx)
11121  substr = _coerce_seq(substr, ctx)
11122  if _is_int(offset):
11123  offset = IntVal(offset, ctx)
11124  return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11125 
11126 
11127 def LastIndexOf(s, substr):
11128  """Retrieve the last index of substring within a string"""
11129  ctx = None
11130  ctx = _get_ctx2(s, substr, ctx)
11131  s = _coerce_seq(s, ctx)
11132  substr = _coerce_seq(substr, ctx)
11133  return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11134 
11135 
11136 def Length(s):
11137  """Obtain the length of a sequence 's'
11138  >>> l = Length(StringVal("abc"))
11139  >>> simplify(l)
11140  3
11141  """
11142  s = _coerce_seq(s)
11143  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11144 
11145 
11146 def StrToInt(s):
11147  """Convert string expression to integer
11148  >>> a = StrToInt("1")
11149  >>> simplify(1 == a)
11150  True
11151  >>> b = StrToInt("2")
11152  >>> simplify(1 == b)
11153  False
11154  >>> c = StrToInt(IntToStr(2))
11155  >>> simplify(1 == c)
11156  False
11157  """
11158  s = _coerce_seq(s)
11159  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11160 
11161 
11162 def IntToStr(s):
11163  """Convert integer expression to string"""
11164  if not is_expr(s):
11165  s = _py2expr(s)
11166  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11167 
11168 
11169 def StrToCode(s):
11170  """Convert a unit length string to integer code"""
11171  if not is_expr(s):
11172  s = _py2expr(s)
11173  return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
11174 
11175 def StrFromCode(c):
11176  """Convert code to a string"""
11177  if not is_expr(c):
11178  c = _py2expr(c)
11179  return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
11180 
11181 def Re(s, ctx=None):
11182  """The regular expression that accepts sequence 's'
11183  >>> s1 = Re("ab")
11184  >>> s2 = Re(StringVal("ab"))
11185  >>> s3 = Re(Unit(BoolVal(True)))
11186  """
11187  s = _coerce_seq(s, ctx)
11188  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
11189 
11190 
11191 # Regular expressions
11192 
11193 class ReSortRef(SortRef):
11194  """Regular expression sort."""
11195 
11196  def basis(self):
11197  return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11198 
11199 
11200 def ReSort(s):
11201  if is_ast(s):
11202  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
11203  if s is None or isinstance(s, Context):
11204  ctx = _get_ctx(s)
11205  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
11206  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
11207 
11208 
11209 class ReRef(ExprRef):
11210  """Regular expressions."""
11211 
11212  def __add__(self, other):
11213  return Union(self, other)
11214 
11215 
11216 def is_re(s):
11217  return isinstance(s, ReRef)
11218 
11219 
11220 def InRe(s, re):
11221  """Create regular expression membership test
11222  >>> re = Union(Re("a"),Re("b"))
11223  >>> print (simplify(InRe("a", re)))
11224  True
11225  >>> print (simplify(InRe("b", re)))
11226  True
11227  >>> print (simplify(InRe("c", re)))
11228  False
11229  """
11230  s = _coerce_seq(s, re.ctx)
11231  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
11232 
11233 
11234 def Union(*args):
11235  """Create union of regular expressions.
11236  >>> re = Union(Re("a"), Re("b"), Re("c"))
11237  >>> print (simplify(InRe("d", re)))
11238  False
11239  """
11240  args = _get_args(args)
11241  sz = len(args)
11242  if z3_debug():
11243  _z3_assert(sz > 0, "At least one argument expected.")
11244  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11245  if sz == 1:
11246  return args[0]
11247  ctx = args[0].ctx
11248  v = (Ast * sz)()
11249  for i in range(sz):
11250  v[i] = args[i].as_ast()
11251  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
11252 
11253 
11254 def Intersect(*args):
11255  """Create intersection of regular expressions.
11256  >>> re = Intersect(Re("a"), Re("b"), Re("c"))
11257  """
11258  args = _get_args(args)
11259  sz = len(args)
11260  if z3_debug():
11261  _z3_assert(sz > 0, "At least one argument expected.")
11262  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11263  if sz == 1:
11264  return args[0]
11265  ctx = args[0].ctx
11266  v = (Ast * sz)()
11267  for i in range(sz):
11268  v[i] = args[i].as_ast()
11269  return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
11270 
11271 
11272 def Plus(re):
11273  """Create the regular expression accepting one or more repetitions of argument.
11274  >>> re = Plus(Re("a"))
11275  >>> print(simplify(InRe("aa", re)))
11276  True
11277  >>> print(simplify(InRe("ab", re)))
11278  False
11279  >>> print(simplify(InRe("", re)))
11280  False
11281  """
11282  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
11283 
11284 
11285 def Option(re):
11286  """Create the regular expression that optionally accepts the argument.
11287  >>> re = Option(Re("a"))
11288  >>> print(simplify(InRe("a", re)))
11289  True
11290  >>> print(simplify(InRe("", re)))
11291  True
11292  >>> print(simplify(InRe("aa", re)))
11293  False
11294  """
11295  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11296 
11297 
11298 def Complement(re):
11299  """Create the complement regular expression."""
11300  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11301 
11302 
11303 def Star(re):
11304  """Create the regular expression accepting zero or more repetitions of argument.
11305  >>> re = Star(Re("a"))
11306  >>> print(simplify(InRe("aa", re)))
11307  True
11308  >>> print(simplify(InRe("ab", re)))
11309  False
11310  >>> print(simplify(InRe("", re)))
11311  True
11312  """
11313  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11314 
11315 
11316 def Loop(re, lo, hi=0):
11317  """Create the regular expression accepting between a lower and upper bound repetitions
11318  >>> re = Loop(Re("a"), 1, 3)
11319  >>> print(simplify(InRe("aa", re)))
11320  True
11321  >>> print(simplify(InRe("aaaa", re)))
11322  False
11323  >>> print(simplify(InRe("", re)))
11324  False
11325  """
11326  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11327 
11328 
11329 def Range(lo, hi, ctx=None):
11330  """Create the range regular expression over two sequences of length 1
11331  >>> range = Range("a","z")
11332  >>> print(simplify(InRe("b", range)))
11333  True
11334  >>> print(simplify(InRe("bb", range)))
11335  False
11336  """
11337  lo = _coerce_seq(lo, ctx)
11338  hi = _coerce_seq(hi, ctx)
11339  return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11340 
11341 def Diff(a, b, ctx=None):
11342  """Create the difference regular expression
11343  """
11344  return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
11345 
11346 def AllChar(regex_sort, ctx=None):
11347  """Create a regular expression that accepts all single character strings
11348  """
11349  return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
11350 
11351 # Special Relations
11352 
11353 
11354 def PartialOrder(a, index):
11355  return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11356 
11357 
11358 def LinearOrder(a, index):
11359  return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11360 
11361 
11362 def TreeOrder(a, index):
11363  return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11364 
11365 
11366 def PiecewiseLinearOrder(a, index):
11367  return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11368 
11369 
11370 def TransitiveClosure(f):
11371  """Given a binary relation R, such that the two arguments have the same sort
11372  create the transitive closure relation R+.
11373  The transitive closure R+ is a new relation.
11374  """
11375  return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11376 
11377 def to_Ast(ptr,):
11378  ast = Ast(ptr)
11379  super(ctypes.c_void_p, ast).__init__(ptr)
11380  return ast
11381 
11382 def to_ContextObj(ptr,):
11383  ctx = ContextObj(ptr)
11384  super(ctypes.c_void_p, ctx).__init__(ptr)
11385  return ctx
11386 
11387 def to_AstVectorObj(ptr,):
11388  v = AstVectorObj(ptr)
11389  super(ctypes.c_void_p, v).__init__(ptr)
11390  return v
11391 
11392 # NB. my-hacky-class only works for a single instance of OnClause
11393 # it should be replaced with a proper correlation between OnClause
11394 # and object references that can be passed over the FFI.
11395 # for UserPropagator we use a global dictionary, which isn't great code.
11396 
11397 _my_hacky_class = None
11398 def on_clause_eh(ctx, p, clause):
11399  onc = _my_hacky_class
11400  p = _to_expr_ref(to_Ast(p), onc.ctx)
11401  clause = AstVector(to_AstVectorObj(clause), onc.ctx)
11402  onc.on_clause(p, clause)
11403 
11404 _on_clause_eh = Z3_on_clause_eh(on_clause_eh)
11405 
11406 class OnClause:
11407  def __init__(self, s, on_clause):
11408  self.s = s
11409  self.ctx = s.ctx
11410  self.on_clause = on_clause
11411  self.idx = 22
11412  global _my_hacky_class
11413  _my_hacky_class = self
11414  Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
11415 
11416 
11417 class PropClosures:
11418  def __init__(self):
11419  self.bases = {}
11420  self.lock = None
11421 
11422  def set_threaded(self):
11423  if self.lock is None:
11424  import threading
11425  self.lock = threading.Lock()
11426 
11427  def get(self, ctx):
11428  if self.lock:
11429  with self.lock:
11430  r = self.bases[ctx]
11431  else:
11432  r = self.bases[ctx]
11433  return r
11434 
11435  def set(self, ctx, r):
11436  if self.lock:
11437  with self.lock:
11438  self.bases[ctx] = r
11439  else:
11440  self.bases[ctx] = r
11441 
11442  def insert(self, r):
11443  if self.lock:
11444  with self.lock:
11445  id = len(self.bases) + 3
11446  self.bases[id] = r
11447  else:
11448  id = len(self.bases) + 3
11449  self.bases[id] = r
11450  return id
11451 
11452 
11453 _prop_closures = None
11454 
11455 
11456 def ensure_prop_closures():
11457  global _prop_closures
11458  if _prop_closures is None:
11459  _prop_closures = PropClosures()
11460 
11461 
11462 def user_prop_push(ctx, cb):
11463  prop = _prop_closures.get(ctx)
11464  prop.cb = cb
11465  prop.push()
11466 
11467 
11468 def user_prop_pop(ctx, cb, num_scopes):
11469  prop = _prop_closures.get(ctx)
11470  prop.cb = cb
11471  prop.pop(num_scopes)
11472 
11473 
11474 def user_prop_fresh(ctx, _new_ctx):
11475  _prop_closures.set_threaded()
11476  prop = _prop_closures.get(ctx)
11477  nctx = Context()
11478  Z3_del_context(nctx.ctx)
11479  new_ctx = to_ContextObj(_new_ctx)
11480  nctx.ctx = new_ctx
11481  nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
11482  nctx.owner = False
11483  new_prop = prop.fresh(nctx)
11484  _prop_closures.set(new_prop.id, new_prop)
11485  return new_prop.id
11486 
11487 
11488 def user_prop_fixed(ctx, cb, id, value):
11489  prop = _prop_closures.get(ctx)
11490  prop.cb = cb
11491  id = _to_expr_ref(to_Ast(id), prop.ctx())
11492  value = _to_expr_ref(to_Ast(value), prop.ctx())
11493  prop.fixed(id, value)
11494  prop.cb = None
11495 
11496 def user_prop_created(ctx, cb, id):
11497  prop = _prop_closures.get(ctx)
11498  prop.cb = cb
11499  id = _to_expr_ref(to_Ast(id), prop.ctx())
11500  prop.created(id)
11501  prop.cb = None
11502 
11503 def user_prop_final(ctx, cb):
11504  prop = _prop_closures.get(ctx)
11505  prop.cb = cb
11506  prop.final()
11507  prop.cb = None
11508 
11509 def user_prop_eq(ctx, cb, x, y):
11510  prop = _prop_closures.get(ctx)
11511  prop.cb = cb
11512  x = _to_expr_ref(to_Ast(x), prop.ctx())
11513  y = _to_expr_ref(to_Ast(y), prop.ctx())
11514  prop.eq(x, y)
11515  prop.cb = None
11516 
11517 def user_prop_diseq(ctx, cb, x, y):
11518  prop = _prop_closures.get(ctx)
11519  prop.cb = cb
11520  x = _to_expr_ref(to_Ast(x), prop.ctx())
11521  y = _to_expr_ref(to_Ast(y), prop.ctx())
11522  prop.diseq(x, y)
11523  prop.cb = None
11524 
11525 # TODO The decision callback is not fully implemented.
11526 # It needs to handle the ast*, unsigned* idx, and Z3_lbool*
11527 def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref):
11528  prop = _prop_closures.get(ctx)
11529  prop.cb = cb
11530  t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
11531  t, idx, phase = prop.decide(t, idx, phase)
11532  t_ref = t
11533  idx_ref = idx
11534  phase_ref = phase
11535  prop.cb = None
11536 
11537 
11538 _user_prop_push = Z3_push_eh(user_prop_push)
11539 _user_prop_pop = Z3_pop_eh(user_prop_pop)
11540 _user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
11541 _user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
11542 _user_prop_created = Z3_created_eh(user_prop_created)
11543 _user_prop_final = Z3_final_eh(user_prop_final)
11544 _user_prop_eq = Z3_eq_eh(user_prop_eq)
11545 _user_prop_diseq = Z3_eq_eh(user_prop_diseq)
11546 _user_prop_decide = Z3_decide_eh(user_prop_decide)
11547 
11548 
11549 def PropagateFunction(name, *sig):
11550  """Create a function that gets tracked by user propagator.
11551  Every term headed by this function symbol is tracked.
11552  If a term is fixed and the fixed callback is registered a
11553  callback is invoked that the term headed by this function is fixed.
11554  """
11555  sig = _get_args(sig)
11556  if z3_debug():
11557  _z3_assert(len(sig) > 0, "At least two arguments expected")
11558  arity = len(sig) - 1
11559  rng = sig[arity]
11560  if z3_debug():
11561  _z3_assert(is_sort(rng), "Z3 sort expected")
11562  dom = (Sort * arity)()
11563  for i in range(arity):
11564  if z3_debug():
11565  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
11566  dom[i] = sig[i].ast
11567  ctx = rng.ctx
11568  return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
11569 
11570 
11571 
11572 class UserPropagateBase:
11573 
11574  #
11575  # Either solver is set or ctx is set.
11576  # Propagators that are created throuh callbacks
11577  # to "fresh" inherit the context of that is supplied
11578  # as argument to the callback.
11579  # This context should not be deleted. It is owned by the solver.
11580  #
11581  def __init__(self, s, ctx=None):
11582  assert s is None or ctx is None
11583  ensure_prop_closures()
11584  self.solver = s
11585  self._ctx = None
11586  self.fresh_ctx = None
11587  self.cb = None
11588  self.id = _prop_closures.insert(self)
11589  self.fixed = None
11590  self.final = None
11591  self.eq = None
11592  self.diseq = None
11593  self.created = None
11594  if ctx:
11595  self.fresh_ctx = ctx
11596  if s:
11597  Z3_solver_propagate_init(self.ctx_ref(),
11598  s.solver,
11599  ctypes.c_void_p(self.id),
11600  _user_prop_push,
11601  _user_prop_pop,
11602  _user_prop_fresh)
11603 
11604  def __del__(self):
11605  if self._ctx:
11606  self._ctx.ctx = None
11607 
11608  def ctx(self):
11609  if self.fresh_ctx:
11610  return self.fresh_ctx
11611  else:
11612  return self.solver.ctx
11613 
11614  def ctx_ref(self):
11615  return self.ctx().ref()
11616 
11617  def add_fixed(self, fixed):
11618  assert not self.fixed
11619  assert not self._ctx
11620  if self.solver:
11621  Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
11622  self.fixed = fixed
11623 
11624  def add_created(self, created):
11625  assert not self.created
11626  assert not self._ctx
11627  if self.solver:
11628  Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
11629  self.created = created
11630 
11631  def add_final(self, final):
11632  assert not self.final
11633  assert not self._ctx
11634  if self.solver:
11635  Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
11636  self.final = final
11637 
11638  def add_eq(self, eq):
11639  assert not self.eq
11640  assert not self._ctx
11641  if self.solver:
11642  Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
11643  self.eq = eq
11644 
11645  def add_diseq(self, diseq):
11646  assert not self.diseq
11647  assert not self._ctx
11648  if self.solver:
11649  Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
11650  self.diseq = diseq
11651 
11652  def add_decide(self, decide):
11653  assert not self.decide
11654  assert not self._ctx
11655  if self.solver:
11656  Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
11657  self.decide = decide
11658 
11659  def push(self):
11660  raise Z3Exception("push needs to be overwritten")
11661 
11662  def pop(self, num_scopes):
11663  raise Z3Exception("pop needs to be overwritten")
11664 
11665  def fresh(self, new_ctx):
11666  raise Z3Exception("fresh needs to be overwritten")
11667 
11668  def add(self, e):
11669  assert not self._ctx
11670  if self.solver:
11671  Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
11672  else:
11673  Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
11674 
11675  #
11676  # Tell the solver to perform the next split on a given term
11677  # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
11678  # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
11679  #
11680  def next_split(self, t, idx, phase):
11681  Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
11682 
11683  #
11684  # Propagation can only be invoked as during a fixed or final callback.
11685  #
11686  def propagate(self, e, ids, eqs=[]):
11687  _ids, num_fixed = _to_ast_array(ids)
11688  num_eqs = len(eqs)
11689  _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
11690  _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
11691  Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11692  self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11693 
11694  def conflict(self, deps = [], eqs = []):
11695  self.propagate(BoolVal(False, self.ctx()), deps, eqs)
def Not
Definition: z3py.py:1811
def param_descrs(self)
Definition: z3py.py:7887
def value(self)
Definition: z3py.py:7837
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
def lower(self, obj)
Definition: z3py.py:8011
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
def fpUnsignedToFP
Definition: z3py.py:10649
def name(self)
Definition: z3py.py:735
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
def is_lt(a)
Definition: z3py.py:2877
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:8819
def __ge__(self, other)
Definition: z3py.py:8613
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
def RealSort
Definition: z3py.py:3151
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def is_distinct(a)
Definition: z3py.py:1675
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 BV2Int
Definition: z3py.py:3965
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
def __gt__(self, other)
Definition: z3py.py:8585
def Then(ts, ks)
Definition: z3py.py:8365
def fpEQ
Definition: z3py.py:10484
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def SignExt(n, a)
Definition: z3py.py:4355
def update_rule(self, head, body, name)
Definition: z3py.py:7564
def SeqSort(s)
Definition: z3py.py:10813
Fixedpoint.
Definition: z3py.py:7430
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
def upper(self)
Definition: z3py.py:7825
def OrElse(ts, ks)
Definition: z3py.py:8378
def Re
Definition: z3py.py:11181
def FiniteDomainVal
Definition: z3py.py:7778
def is_fprm_sort(s)
Definition: z3py.py:9515
def get_version_string()
Definition: z3py.py:83
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
Quantifiers.
Definition: z3py.py:1984
def AtLeast(args)
Definition: z3py.py:9003
def entry(self, idx)
Definition: z3py.py:6307
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7599
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a variable.
def upper_values(self, obj)
Definition: z3py.py:8026
def DisjointSum
Definition: z3py.py:5367
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:7903
def __getitem__(self, idx)
Definition: z3py.py:8118
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
def BoolVal
Definition: z3py.py:1705
Function Declarations.
Definition: z3py.py:718
def FP
Definition: z3py.py:10120
def TupleSort
Definition: z3py.py:5355
def SetUnion(args)
Definition: z3py.py:4932
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def __deepcopy__
Definition: z3py.py:8092
Booleans.
Definition: z3py.py:1510
def fpMax
Definition: z3py.py:10345
def add_decl(self, decl)
Definition: z3py.py:9287
def IntSort
Definition: z3py.py:3134
def Product(args)
Definition: z3py.py:8955
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def prec(self)
Definition: z3py.py:5597
void Z3_API Z3_simplifier_dec_ref(Z3_context c, Z3_simplifier g)
Decrement the reference counter of the given simplifier.
def IsInt(a)
Definition: z3py.py:3386
def BoolSort
Definition: z3py.py:1687
def fpToFP
Definition: z3py.py:10537
def Sum(args)
Definition: z3py.py:8929
def __repr__(self)
Definition: z3py.py:361
def is_arith_sort(s)
Definition: z3py.py:2360
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
def ReSort(s)
Definition: z3py.py:11200
def Function(name, sig)
Definition: z3py.py:859
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:968
def __iadd__(self, fml)
Definition: z3py.py:7907
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:4085
def get_rules(self)
Definition: z3py.py:7636
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
def sort(self)
Definition: z3py.py:7730
def Real
Definition: z3py.py:3293
def AndThen(ts, ks)
Definition: z3py.py:8345
def ZeroExt(n, a)
Definition: z3py.py:4385
def assertions(self)
Definition: z3py.py:8039
def FreshConst
Definition: z3py.py:1460
def SolverFor
Definition: z3py.py:7390
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def substitute_vars(t, m)
Definition: z3py.py:8887
def param_descrs(self)
Definition: z3py.py:8219
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def Intersect(args)
Definition: z3py.py:11254
def BitVecSort
Definition: z3py.py:3997
def is_int(self)
Definition: z3py.py:2301
def Var(idx, s)
Definition: z3py.py:1466
def __del__(self)
Definition: z3py.py:8567
Z3_simplifier Z3_API Z3_simplifier_and_then(Z3_context c, Z3_simplifier t1, Z3_simplifier t2)
Return a simplifier that applies t1 to a given goal and t2 to every subgoal produced by t1...
def is_bool(self)
Definition: z3py.py:1542
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def ArraySort(sig)
Definition: z3py.py:4692
def fpMul
Definition: z3py.py:10286
def help(self)
Definition: z3py.py:7324
def RealVarVector
Definition: z3py.py:1492
def reset_params()
Definition: z3py.py:295
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def declare(self, name, args)
Definition: z3py.py:5085
def is_string_value(a)
Definition: z3py.py:10960
def as_ast(self)
Definition: z3py.py:392
def Update(a, args)
Definition: z3py.py:4739
def assert_exprs(self, args)
Definition: z3py.py:7891
def LShR(a, b)
Definition: z3py.py:4291
def is_default(a)
Definition: z3py.py:4659
def set_option(args, kws)
Definition: z3py.py:301
Z3_param_descrs Z3_API Z3_simplifier_get_param_descrs(Z3_context c, Z3_simplifier t)
Return the parameter description set for the given simplifier object.
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:3435
def Consts(names, sort)
Definition: z3py.py:1445
def use_pp(self)
Definition: z3py.py:331
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
def add(self, solver)
Definition: z3py.py:8211
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 Implies
Definition: z3py.py:1781
def __nonzero__(self)
Definition: z3py.py:370
def __del__(self)
Definition: z3py.py:8202
def is_and(a)
Definition: z3py.py:1617
def ref(self)
Definition: z3py.py:218
def push(self)
Definition: z3py.py:6925
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def Cbrt
Definition: z3py.py:3416
def sort(self)
Definition: z3py.py:1549
bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
def Store(a, args)
Definition: z3py.py:4782
def ULT(a, b)
Definition: z3py.py:4174
def When
Definition: z3py.py:8782
def BitVecVal
Definition: z3py.py:4012
Arithmetic.
Definition: z3py.py:2284
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
def minimize(self, arg)
Definition: z3py.py:7972
def help(self)
Definition: z3py.py:7883
def sort(self)
Definition: z3py.py:2379
def is_to_real(a)
Definition: z3py.py:2925
def as_ast(self)
Definition: z3py.py:562
def assert_exprs(self, args)
Definition: z3py.py:7465
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 param_descrs(self)
Definition: z3py.py:7461
def is_select(a)
Definition: z3py.py:4878
def is_real(self)
Definition: z3py.py:2403
def RNE
Definition: z3py.py:9719
Z3_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
def is_int(self)
Definition: z3py.py:2389
ASTs base class.
Definition: z3py.py:328
def fpGEQ
Definition: z3py.py:10472
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
def __ne__(self, other)
Definition: z3py.py:1018
def Array(name, sorts)
Definition: z3py.py:4725
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def is_gt(a)
Definition: z3py.py:2901
def lower_values(self, obj)
Definition: z3py.py:8021
def pop(self)
Definition: z3py.py:7984
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
def sexpr(self)
Definition: z3py.py:8138
def set_param(args, kws)
Definition: z3py.py:271
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def __eq__(self, other)
Definition: z3py.py:997
def domain(self, i)
Definition: z3py.py:756
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:7734
def If
Definition: z3py.py:1377
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
def Abs(arg)
Definition: z3py.py:8980
def is_implies(a)
Definition: z3py.py:1641
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
Z3_string Z3_API Z3_simplifier_get_help(Z3_context c, Z3_simplifier t)
Return a string containing a description of parameters accepted by the given simplifier.
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 AtMost(args)
Definition: z3py.py:8985
def RealVector
Definition: z3py.py:3321
def from_string(self, s)
Definition: z3py.py:1106
def register_relation(self, relations)
Definition: z3py.py:7612
def __init__
Definition: z3py.py:8541
def is_app(a)
Definition: z3py.py:1261
def StringVal
Definition: z3py.py:10969
def Select(a, args)
Definition: z3py.py:4799
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
def args2params
Definition: z3py.py:5458
def __len__(self)
Definition: z3py.py:8099
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
def __del__(self)
Definition: z3py.py:9279
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
def And(args)
Definition: z3py.py:1845
def open_log(fname)
Definition: z3py.py:114
void Z3_API Z3_parser_context_dec_ref(Z3_context c, Z3_parser_context pc)
Decrement the reference counter of the given Z3_parser_context object.
def EmptySet(s)
Definition: z3py.py:4914
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
def PrefixOf(a, b)
Definition: z3py.py:11043
def fpRem
Definition: z3py.py:10316
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def range(self)
Definition: z3py.py:4565
def __repr__(self)
Definition: z3py.py:8135
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
def FPVal
Definition: z3py.py:10074
def add_sort(self, sort)
Definition: z3py.py:9284
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def SetDifference(a, b)
Definition: z3py.py:4990
def disable_trace(msg)
Definition: z3py.py:79
def RotateRight(a, b)
Definition: z3py.py:4339
def sort(self)
Definition: z3py.py:3482
def get_ctx(ctx)
Definition: z3py.py:267
void Z3_API Z3_parser_context_add_decl(Z3_context c, Z3_parser_context pc, Z3_func_decl f)
Add a function declaration.
def is_ge(a)
Definition: z3py.py:2889
def is_K(a)
Definition: z3py.py:4630
def __init__
Definition: z3py.py:7433
def serialize(self)
Definition: z3py.py:1109
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:986
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
def is_const(a)
Definition: z3py.py:1287
def Star(re)
Definition: z3py.py:11303
def fpToFPUnsigned
Definition: z3py.py:10667
def InRe(s, re)
Definition: z3py.py:11220
def is_finite_domain_sort(s)
Definition: z3py.py:7716
def FreshBool
Definition: z3py.py:1767
def Ints
Definition: z3py.py:3253
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
def push(self)
Definition: z3py.py:7980
def z3_error_handler(c, e)
Definition: z3py.py:174
def RotateLeft(a, b)
Definition: z3py.py:4323
def Const(name, sort)
Definition: z3py.py:1433
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def substitute(t, m)
Definition: z3py.py:8854
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 Exists
Definition: z3py.py:2236
def fpMin
Definition: z3py.py:10330
def main_ctx()
Definition: z3py.py:239
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
def ForAll
Definition: z3py.py:2218
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def Int
Definition: z3py.py:3240
def get_id(self)
Definition: z3py.py:729
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
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.
void Z3_API Z3_optimize_assert_and_track(Z3_context c, Z3_optimize o, Z3_ast a, Z3_ast t)
Assert tracked hard constraint to the optimization context.
def is_array(a)
Definition: z3py.py:4603
def is_pattern(a)
Definition: z3py.py:1929
Statistics.
Definition: z3py.py:6704
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def __init__
Definition: z3py.py:8239
def String
Definition: z3py.py:10976
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:9934
def help_simplify()
Definition: z3py.py:8844
def IsSubset(a, b)
Definition: z3py.py:5012
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:8016
def get_rule_names_along_trace(self)
Definition: z3py.py:7587
def DeclareSort
Definition: z3py.py:693
def __repr__(self)
Definition: z3py.py:8047
def __repr__(self)
Definition: z3py.py:7644
Arrays.
Definition: z3py.py:4513
def simplify_param_descrs()
Definition: z3py.py:8849
def is_map(a)
Definition: z3py.py:4643
def is_or(a)
Definition: z3py.py:1629
Patterns.
Definition: z3py.py:1917
def SetIntersect(args)
Definition: z3py.py:4945
def is_int_value(a)
Definition: z3py.py:2728
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
def __hash__(self)
Definition: z3py.py:642
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def Default(a)
Definition: z3py.py:4771
def RealVar
Definition: z3py.py:1481
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
def Repeat
Definition: z3py.py:8467
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
def CreateDatatypes(ds)
Definition: z3py.py:5150
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:4249
def PbGe(args, k)
Definition: z3py.py:9059
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def Q
Definition: z3py.py:3227
def Xor
Definition: z3py.py:1795
def Union(args)
Definition: z3py.py:11234
Z3_simplifier Z3_API Z3_simplifier_using_params(Z3_context c, Z3_simplifier t, Z3_params p)
Return a simplifier that applies t using the given set of parameters.
def SuffixOf(a, b)
Definition: z3py.py:11058
def __eq__(self, other)
Definition: z3py.py:364
def abstract
Definition: z3py.py:7681
def __mul__(self, other)
Definition: z3py.py:1555
def is_mod(a)
Definition: z3py.py:2853
def ParThen
Definition: z3py.py:8418
def CharSort
Definition: z3py.py:10803
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
def convert_model(self, model)
Definition: z3py.py:5729
def UGE(a, b)
Definition: z3py.py:4192
def Replace(s, src, dst)
Definition: z3py.py:11092
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the variables in a with the expressions in to. For every i smaller than num_exprs...
def __init__(self, args, kws)
Definition: z3py.py:192
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective.
def fpIsInf
Definition: z3py.py:10390
def lower_values(self)
Definition: z3py.py:7829
def cast(self, val)
Definition: z3py.py:593
def Length(s)
Definition: z3py.py:11136
void Z3_API Z3_optimize_register_model_eh(Z3_context c, Z3_optimize o, Z3_model m, void *ctx, Z3_model_eh model_eh)
register a model event handler for new models.
void Z3_API Z3_parser_context_add_sort(Z3_context c, Z3_parser_context pc, Z3_sort s)
Add a sort declaration.
def decl(self)
Definition: z3py.py:1039
def is_eq(a)
Definition: z3py.py:1665
def using_params(self, args, keys)
Definition: z3py.py:8206
def __del__(self)
Definition: z3py.py:212
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def statistics(self)
Definition: z3py.py:8057
def depth(self)
Definition: z3py.py:5561
def __str__(self)
Definition: z3py.py:7843
def Strings
Definition: z3py.py:10985
def fpLT
Definition: z3py.py:10436
def sort(self)
Definition: z3py.py:974
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural but two different AST objects can m...
def is_real(a)
Definition: z3py.py:2701
def fpIsNaN
Definition: z3py.py:10378
def PbLe(args, k)
Definition: z3py.py:9048
def get_id(self)
Definition: z3py.py:971
def Extract(high, low, a)
Definition: z3py.py:4120
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def solve_using(s, args, keywords)
Definition: z3py.py:9111
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def set_predicate_representation(self, f, representations)
Definition: z3py.py:7618
def maximize(self, arg)
Definition: z3py.py:7964
Z3_ast_vector Z3_API Z3_parser_context_from_string(Z3_context c, Z3_parser_context pc, Z3_string s)
Parse a string of SMTLIB2 commands. Return assertions.
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
def eq(a, b)
Definition: z3py.py:472
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
def RecFunction(name, sig)
Definition: z3py.py:905
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def fpSub
Definition: z3py.py:10271
def help(self)
Definition: z3py.py:8304
def __bool__(self)
Definition: z3py.py:373
def sexpr(self)
Definition: z3py.py:8051
def fpSignedToFP
Definition: z3py.py:10631
def is_le(a)
Definition: z3py.py:2865
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def is_not(a)
Definition: z3py.py:1653
Strings, Sequences and Regular expressions.
Definition: z3py.py:10773
def get_map_func(a)
Definition: z3py.py:4668
def __init__
Definition: z3py.py:345
def Loop
Definition: z3py.py:11316
def probe_description
Definition: z3py.py:8714
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def apply(self, goal, arguments, keywords)
Definition: z3py.py:8277
def Float32
Definition: z3py.py:9464
def solve(args, keywords)
Definition: z3py.py:9081
def is_arith(a)
Definition: z3py.py:2661
def __del__(self)
Definition: z3py.py:8256
def is_sort(s)
Definition: z3py.py:647
def IntVector
Definition: z3py.py:3266
def objectives(self)
Definition: z3py.py:8043
def Or(args)
Definition: z3py.py:1878
def __init__(self, opt, value, is_max)
Definition: z3py.py:7816
def num_sorts(self)
Definition: z3py.py:6505
def add_rule
Definition: z3py.py:7495
def add(self, args)
Definition: z3py.py:7479
def hash(self)
Definition: z3py.py:440
def SetSort(s)
Sets.
Definition: z3py.py:4909
def is_int(a)
Definition: z3py.py:2682
def check(self, assumptions)
Definition: z3py.py:7087
def FreshReal
Definition: z3py.py:3336
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
def fpPlusInfinity(s)
Definition: z3py.py:10025
def insert(self, args)
Definition: z3py.py:7491
def is_quantifier(a)
Definition: z3py.py:2169
def as_string(self)
Definition: z3py.py:7767
def is_string(a)
Definition: z3py.py:10952
def Plus(re)
Definition: z3py.py:11272
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:11146
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:8294
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
def FPs
Definition: z3py.py:10144
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 PbEq
Definition: z3py.py:9070
def params(self)
Definition: z3py.py:1036
def num_args(self)
Definition: z3py.py:1054
def __del__(self)
Definition: z3py.py:8095
def fpFPToFP
Definition: z3py.py:10593
def fpBVToFP
Definition: z3py.py:10576
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def parse_file(self, f)
Definition: z3py.py:7632
def prove(claim, show=False, keywords)
Definition: z3py.py:9142
def is_true(a)
Definition: z3py.py:1585
def Int2BV(a, num_bits)
Definition: z3py.py:3988
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def Contains(a, b)
Definition: z3py.py:11073
def is_finite_domain_value(a)
Definition: z3py.py:7793
def is_real(self)
Definition: z3py.py:2287
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
def get_rules_along_trace(self)
Definition: z3py.py:7583
def __del__(self)
Definition: z3py.py:7870
def Lambda(vs, body)
Definition: z3py.py:2257
def Range
Definition: z3py.py:11329
def param_descrs(self)
Definition: z3py.py:8308
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
def from_string(self, s)
Definition: z3py.py:9290
def is_store(a)
Definition: z3py.py:4891
def get_version()
Definition: z3py.py:92
def from_string(self, s)
Definition: z3py.py:8035
def SetDel(s, e)
Definition: z3py.py:4969
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def SRem(a, b)
Definition: z3py.py:4270
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def assert_and_track(self, a, p)
Definition: z3py.py:7911
def EnumSort
Definition: z3py.py:5379
def Cond
Definition: z3py.py:8802
def __deepcopy__
Definition: z3py.py:8564
def fpToSBV
Definition: z3py.py:10677
def eq(self, other)
Definition: z3py.py:404
def FullSet(s)
Definition: z3py.py:4923
def get_id(self)
Definition: z3py.py:565
def ToReal(a)
Definition: z3py.py:3350
def is_bv_value(a)
Definition: z3py.py:3950
def range(self)
Definition: z3py.py:768
def Reals
Definition: z3py.py:3306
def is_idiv(a)
Definition: z3py.py:2841
def translate(self, target)
Definition: z3py.py:421
def probes
Definition: z3py.py:8703
def from_file(self, filename)
Definition: z3py.py:8031
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate. ...
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def query_from_lvl(self, lvl, query)
Definition: z3py.py:7548
def __deepcopy__
Definition: z3py.py:7867
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
def __ne__(self, other)
Definition: z3py.py:631
def FailIf
Definition: z3py.py:8760
def __le__(self, other)
Definition: z3py.py:8599
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
def __deepcopy__
Definition: z3py.py:7444
def cast(self, val)
Definition: z3py.py:1513
def Bools
Definition: z3py.py:1736
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality. Thus, two ast nodes created by the same context and having the same children and same function symbols have the same identifiers. Ast nodes created in the same context, but having different children or different functions have different identifiers. Variables and quantifiers are also assigned different identifiers according to their structure.
def fpRealToFP
Definition: z3py.py:10613
def as_func_decl(self)
Definition: z3py.py:732
def size(self)
Definition: z3py.py:3493
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def __deepcopy__
Definition: z3py.py:8253
def to_string(self, queries)
Definition: z3py.py:7654
def assertions(self)
Definition: z3py.py:7256
def z3_debug()
Definition: z3py.py:62
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def solver
Definition: z3py.py:8260
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
def get_id(self)
Definition: z3py.py:396
def __lt__(self, other)
Definition: z3py.py:8571
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
def create(self)
Definition: z3py.py:5109
def Full(s)
Definition: z3py.py:11023
def is_const_array(a)
Definition: z3py.py:4617
def fpNaN(s)
Definition: z3py.py:10008
def cast(self, val)
Definition: z3py.py:2322
def as_long(self)
Definition: z3py.py:7755
def Float64
Definition: z3py.py:9476
def sexpr(self)
Definition: z3py.py:383
def reason_unknown(self)
Definition: z3py.py:7997
def __deepcopy__
Definition: z3py.py:355
def Bool
Definition: z3py.py:1724
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
def kind(self)
Definition: z3py.py:568
def Unit(a)
Definition: z3py.py:11038
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def Model
Definition: z3py.py:6681
def set_on_model(self, on_model)
Definition: z3py.py:8062
def parse_string(self, s)
Definition: z3py.py:7628
def is_rational_value(a)
Definition: z3py.py:2752
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def is_finite_domain(a)
Definition: z3py.py:7739
def fpGT
Definition: z3py.py:10460
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...
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def get_ground_sat_answer(self)
Definition: z3py.py:7578
def sexpr(self)
Definition: z3py.py:7648
def __ne__(self, other)
Definition: z3py.py:8641
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
def declare_var(self, vars)
Definition: z3py.py:7672
void Z3_API Z3_parser_context_inc_ref(Z3_context c, Z3_parser_context pc)
Increment the reference counter of the given Z3_parser_context object.
def arg(self, idx)
Definition: z3py.py:1070
def sort(self)
Definition: z3py.py:9531
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
void Z3_API Z3_simplifier_inc_ref(Z3_context c, Z3_simplifier t)
Increment the reference counter of the given simplifier.
def FiniteDomainSort
Definition: z3py.py:7708
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
def IntToStr(s)
Definition: z3py.py:11162
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.
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def __rmul__(self, other)
Definition: z3py.py:1552
Z3_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
def params(self)
Definition: z3py.py:791
def query(self, query)
Definition: z3py.py:7526
def RecAddDefinition(f, args, body)
Definition: z3py.py:923
def fpToIEEEBV
Definition: z3py.py:10741
def get_var_index(a)
Definition: z3py.py:1331
def MultiPattern(args)
Definition: z3py.py:1947
def fpAbs
Definition: z3py.py:10163
def upper_values(self)
Definition: z3py.py:7833
def model(self)
Definition: z3py.py:8001
def is_div(a)
Definition: z3py.py:2824
def help(self)
Definition: z3py.py:8215
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def ctx_ref(self)
Definition: z3py.py:400
def help(self)
Definition: z3py.py:7457
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 RTZ
Definition: z3py.py:9759
def is_fp_sort(s)
Definition: z3py.py:9504
Expressions.
Definition: z3py.py:957
def SetComplement(s)
Definition: z3py.py:4980
def is_app_of(a, k)
Definition: z3py.py:1364
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def is_probe(p)
Definition: z3py.py:8685
def is_mul(a)
Definition: z3py.py:2800
def fpFP
Definition: z3py.py:10508
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def subsort(self, other)
Definition: z3py.py:585
def kind(self)
Definition: z3py.py:778
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
def is_bv_sort(s)
Definition: z3py.py:3468
def With(t, args, keys)
Definition: z3py.py:8439
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
def append_log(s)
Definition: z3py.py:119
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
def statistics(self)
Definition: z3py.py:7662
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
def RealVal
Definition: z3py.py:3192
def is_add(a)
Definition: z3py.py:2788
def parse_smt2_string
Definition: z3py.py:9293
def fpToReal
Definition: z3py.py:10721
def ParOr(ts, ks)
Definition: z3py.py:8399
def K(dom, v)
Definition: z3py.py:4838
def BitVec
Definition: z3py.py:4029
Z3_solver Z3_API Z3_solver_add_simplifier(Z3_context c, Z3_solver solver, Z3_simplifier simplifier)
Attach simplifier to a solver. The solver will use the simplifier for incremental pre-processing...
def Ext(a, b)
Definition: z3py.py:4860
def fpToUBV
Definition: z3py.py:10699
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def __hash__(self)
Definition: z3py.py:1014
def ParAndThen
Definition: z3py.py:8434
def get_assertions(self)
Definition: z3py.py:7640
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def get_num_levels(self, predicate)
Definition: z3py.py:7595
def UGT(a, b)
Definition: z3py.py:4210
def fpNEQ
Definition: z3py.py:10496
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
def get_answer(self)
Definition: z3py.py:7573
def children(self)
Definition: z3py.py:1091
def arity(self)
Definition: z3py.py:6293
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def WithParams(t, p)
Definition: z3py.py:8453
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
def numerator(self)
Definition: z3py.py:2991
def __str__(self)
Definition: z3py.py:358
def is_int(self)
Definition: z3py.py:1539
def is_ast(a)
Definition: z3py.py:451
def domain(self)
Definition: z3py.py:4552
def Empty(s)
Definition: z3py.py:11003
def fpNeg
Definition: z3py.py:10186
def UDiv(a, b)
Definition: z3py.py:4228
def is_expr(a)
Definition: z3py.py:1238
def FreshInt
Definition: z3py.py:3279
def __init__(self, result, ctx)
Definition: z3py.py:8087
def fpAdd
Definition: z3py.py:10254
def set(self, args, keys)
Definition: z3py.py:7451
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).
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
def Map(f, args)
Definition: z3py.py:4815
def __call__(self, args)
Definition: z3py.py:815
def else_value(self)
Definition: z3py.py:6254
def subsort(self, other)
Definition: z3py.py:1536
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:8723
def add_cover(self, level, predicate, property)
Definition: z3py.py:7606
def TryFor
Definition: z3py.py:8488
def describe_tactics()
Definition: z3py.py:8517
def is_bool(a)
Definition: z3py.py:1567
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
def Distinct(args)
Definition: z3py.py:1400
def to_symbol
Definition: z3py.py:124
def __call__(self, goal)
Definition: z3py.py:8656
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_parser_context Z3_API Z3_mk_parser_context(Z3_context c)
Create a parser context.
def unsat_core(self)
Definition: z3py.py:8008
def body(self)
Definition: z3py.py:2102
def as_list(self)
Definition: z3py.py:6338
def IndexOf
Definition: z3py.py:11107
def SimpleSolver
Definition: z3py.py:7411
def arity(self)
Definition: z3py.py:746
def add_soft
Definition: z3py.py:7940
def is_bv(a)
Definition: z3py.py:3936
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def SetAdd(s, e)
Definition: z3py.py:4958
def is_var(a)
Definition: z3py.py:1306
def as_expr(self)
Definition: z3py.py:8142
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def __copy__(self)
Definition: z3py.py:437
def tactic_description
Definition: z3py.py:8508
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def RepeatBitVec(n, a)
Definition: z3py.py:4413
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective. The returned vector ...
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
def __init__
Definition: z3py.py:8178
def FreshFunction(sig)
Definition: z3py.py:882
def get_full_version()
Definition: z3py.py:101
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
def FPSort
Definition: z3py.py:9949
def lower(self)
Definition: z3py.py:7821
def as_ast(self)
Definition: z3py.py:726
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def is_false(a)
Definition: z3py.py:1603
def set(self, args, keys)
Definition: z3py.py:7876
def ULE(a, b)
Definition: z3py.py:4156
def is_is_int(a)
Definition: z3py.py:2913
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
def __init__
Definition: z3py.py:7861
def BitVecs
Definition: z3py.py:4053
def enable_trace(msg)
Definition: z3py.py:75
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 Sqrt
Definition: z3py.py:3403
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
def name(self)
Definition: z3py.py:608
def is_fprm(a)
Definition: z3py.py:9764
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
def substitute_funs(t, m)
Definition: z3py.py:8907
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.
def __deepcopy__
Definition: z3py.py:8199
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def __iadd__(self, fml)
Definition: z3py.py:7483
def Option(re)
Definition: z3py.py:11285
def tactics
Definition: z3py.py:8497
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def check(self, assumptions)
Definition: z3py.py:7988
def as_signed_long(self)
Definition: z3py.py:3906
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
def RatVal
Definition: z3py.py:3211
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def __del__(self)
Definition: z3py.py:7447
def is_func_decl(a)
Definition: z3py.py:846
def interrupt(self)
Definition: z3py.py:222
def is_sub(a)
Definition: z3py.py:2812
def BoolVector
Definition: z3py.py:1752
def Concat(args)
Definition: z3py.py:4074
def IntVal
Definition: z3py.py:3180
def param_descrs(self)
Definition: z3py.py:230
def __hash__(self)
Definition: z3py.py:367
def append(self, args)
Definition: z3py.py:7487
def deserialize(st)
Definition: z3py.py:1115
def is_seq(a)
Definition: z3py.py:10942
def is_algebraic_value(a)
Definition: z3py.py:2774
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def get_param(name)
Definition: z3py.py:307
def is_to_int(a)
Definition: z3py.py:2940
def __eq__(self, other)
Definition: z3py.py:8627
def fpLEQ
Definition: z3py.py:10448
def reason_unknown(self)
Definition: z3py.py:7667
def IsMember(e, s)
Definition: z3py.py:5001
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
Z3_ast Z3_API Z3_substitute_funs(Z3_context c, Z3_ast a, unsigned num_funs, Z3_func_decl const from[], Z3_ast const to[])
Substitute funcions in from with new expressions in to.
def StringSort
Definition: z3py.py:10794
def fpDiv
Definition: z3py.py:10301
Z3_simplifier Z3_API Z3_mk_simplifier(Z3_context c, Z3_string name)
Return a simplifier associated with the given name. The complete list of simplifiers may be obtained ...
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
def ToInt(a)
Definition: z3py.py:3368
def num_entries(self)
Definition: z3py.py:6277
def __del__(self)
Definition: z3py.py:350
def is_fp(a)
Definition: z3py.py:9920
def __eq__(self, other)
Definition: z3py.py:618
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
def domain_n(self, i)
Definition: z3py.py:4561