Z3
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
z3py.py
Go to the documentation of this file.
1 
2 
3 ############################################
4 # Copyright (c) 2012 Microsoft Corporation
5 #
6 # Z3 Python interface
7 #
8 # Author: Leonardo de Moura (leonardo)
9 ############################################
10 
11 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
12 
13 Several online tutorials for Z3Py are available at:
14 http://rise4fun.com/Z3Py/tutorial/guide
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
17 
18 Small example:
19 
20 >>> x = Int('x')
21 >>> y = Int('y')
22 >>> s = Solver()
23 >>> s.add(x > 0)
24 >>> s.add(x < 2)
25 >>> s.add(y == x + 1)
26 >>> s.check()
27 sat
28 >>> m = s.model()
29 >>> m[x]
30 1
31 >>> m[y]
32 2
33 
34 Z3 exceptions:
35 
36 >>> try:
37 ... x = BitVec('x', 32)
38 ... y = Bool('y')
39 ... # the expression x + y is type incorrect
40 ... n = x + y
41 ... except Z3Exception as ex:
42 ... print("failed: %s" % ex)
43 failed: sort mismatch
44 """
45 from . import z3core
46 from .z3core import *
47 from .z3types import *
48 from .z3consts import *
49 from .z3printer import *
50 from fractions import Fraction
51 import sys
52 import io
53 import math
54 import copy
55 
56 Z3_DEBUG = __debug__
57 
58 def z3_debug():
59  global Z3_DEBUG
60  return Z3_DEBUG
61 
62 if sys.version < '3':
63  def _is_int(v):
64  return isinstance(v, (int, long))
65 else:
66  def _is_int(v):
67  return isinstance(v, int)
68 
69 def enable_trace(msg):
70  Z3_enable_trace(msg)
71 
72 def disable_trace(msg):
73  Z3_disable_trace(msg)
74 
76  major = ctypes.c_uint(0)
77  minor = ctypes.c_uint(0)
78  build = ctypes.c_uint(0)
79  rev = ctypes.c_uint(0)
80  Z3_get_version(major, minor, build, rev)
81  return "%s.%s.%s" % (major.value, minor.value, build.value)
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 (major.value, minor.value, build.value, rev.value)
90 
92  return Z3_get_full_version()
93 
94 # We use _z3_assert instead of the assert command because we want to
95 # produce nice error messages in Z3Py at rise4fun.com
96 def _z3_assert(cond, msg):
97  if not cond:
98  raise Z3Exception(msg)
99 
100 def _z3_check_cint_overflow(n, name):
101  _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
102 
103 def open_log(fname):
104  """Log interaction to a file. This function must be invoked immediately after init(). """
105  Z3_open_log(fname)
106 
107 def append_log(s):
108  """Append user-defined string to interaction log. """
109  Z3_append_log(s)
110 
111 def to_symbol(s, ctx=None):
112  """Convert an integer or string into a Z3 symbol."""
113  if _is_int(s):
114  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
115  else:
116  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
117 
118 def _symbol2py(ctx, s):
119  """Convert a Z3 symbol back into a Python object. """
120  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
121  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
122  else:
123  return Z3_get_symbol_string(ctx.ref(), s)
124 
125 # Hack for having nary functions that can receive one argument that is the
126 # list of arguments.
127 # Use this when function takes a single list of arguments
128 def _get_args(args):
129  try:
130  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
131  return args[0]
132  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
133  return [arg for arg in args[0]]
134  else:
135  return args
136  except: # len is not necessarily defined when args is not a sequence (use reflection?)
137  return args
138 
139 # Use this when function takes multiple arguments
140 def _get_args_ast_list(args):
141  try:
142  if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
143  return [arg for arg in args]
144  else:
145  return args
146  except:
147  return args
148 
149 def _to_param_value(val):
150  if isinstance(val, bool):
151  if val == True:
152  return "true"
153  else:
154  return "false"
155  else:
156  return str(val)
157 
159  # Do nothing error handler, just avoid exit(0)
160  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
161  return
162 
163 class Context:
164  """A Context manages all other Z3 objects, global configuration options, etc.
165 
166  Z3Py uses a default global context. For most applications this is sufficient.
167  An application may use multiple Z3 contexts. Objects created in one context
168  cannot be used in another one. However, several objects may be "translated" from
169  one context to another. It is not safe to access Z3 objects from multiple threads.
170  The only exception is the method `interrupt()` that can be used to interrupt() a long
171  computation.
172  The initialization method receives global configuration options for the new context.
173  """
174  def __init__(self, *args, **kws):
175  if z3_debug():
176  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
177  conf = Z3_mk_config()
178  for key in kws:
179  value = kws[key]
180  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
181  prev = None
182  for a in args:
183  if prev is None:
184  prev = a
185  else:
186  Z3_set_param_value(conf, str(prev), _to_param_value(a))
187  prev = None
188  self.ctx = Z3_mk_context_rc(conf)
189  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
190  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
191  Z3_del_config(conf)
192 
193  def __del__(self):
194  Z3_del_context(self.ctx)
195  self.ctx = None
196  self.eh = None
197 
198  def ref(self):
199  """Return a reference to the actual C pointer to the Z3 context."""
200  return self.ctx
201 
202  def interrupt(self):
203  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
204 
205  This method can be invoked from a thread different from the one executing the
206  interruptible procedure.
207  """
208  Z3_interrupt(self.ref())
209 
210 
211 # Global Z3 context
212 _main_ctx = None
213 def main_ctx():
214  """Return a reference to the global Z3 context.
215 
216  >>> x = Real('x')
217  >>> x.ctx == main_ctx()
218  True
219  >>> c = Context()
220  >>> c == main_ctx()
221  False
222  >>> x2 = Real('x', c)
223  >>> x2.ctx == c
224  True
225  >>> eq(x, x2)
226  False
227  """
228  global _main_ctx
229  if _main_ctx is None:
230  _main_ctx = Context()
231  return _main_ctx
232 
233 def _get_ctx(ctx):
234  if ctx is None:
235  return main_ctx()
236  else:
237  return ctx
238 
239 def set_param(*args, **kws):
240  """Set Z3 global (or module) parameters.
241 
242  >>> set_param(precision=10)
243  """
244  if z3_debug():
245  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
246  new_kws = {}
247  for k in kws:
248  v = kws[k]
249  if not set_pp_option(k, v):
250  new_kws[k] = v
251  for key in new_kws:
252  value = new_kws[key]
253  Z3_global_param_set(str(key).upper(), _to_param_value(value))
254  prev = None
255  for a in args:
256  if prev is None:
257  prev = a
258  else:
259  Z3_global_param_set(str(prev), _to_param_value(a))
260  prev = None
261 
263  """Reset all global (or module) parameters.
264  """
266 
267 def set_option(*args, **kws):
268  """Alias for 'set_param' for backward compatibility.
269  """
270  return set_param(*args, **kws)
271 
272 def get_param(name):
273  """Return the value of a Z3 global (or module) parameter
274 
275  >>> get_param('nlsat.reorder')
276  'true'
277  """
278  ptr = (ctypes.c_char_p * 1)()
279  if Z3_global_param_get(str(name), ptr):
280  r = z3core._to_pystr(ptr[0])
281  return r
282  raise Z3Exception("failed to retrieve value for '%s'" % name)
283 
284 #########################################
285 #
286 # ASTs base class
287 #
288 #########################################
289 
290 # Mark objects that use pretty printer
292  """Superclass for all Z3 objects that have support for pretty printing."""
293  def use_pp(self):
294  return True
295 
297  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
298  def __init__(self, ast, ctx=None):
299  self.ast = ast
300  self.ctx = _get_ctx(ctx)
301  Z3_inc_ref(self.ctx.ref(), self.as_ast())
302 
303  def __del__(self):
304  if self.ctx.ref() is not None:
305  Z3_dec_ref(self.ctx.ref(), self.as_ast())
306 
307  def __deepcopy__(self, memo={}):
308  return _to_ast_ref(self.ast, self.ctx)
309 
310  def __str__(self):
311  return obj_to_string(self)
312 
313  def __repr__(self):
314  return obj_to_string(self)
315 
316  def __eq__(self, other):
317  return self.eq(other)
318 
319  def __hash__(self):
320  return self.hash()
321 
322  def __nonzero__(self):
323  return self.__bool__()
324 
325  def __bool__(self):
326  if is_true(self):
327  return True
328  elif is_false(self):
329  return False
330  elif is_eq(self) and self.num_args() == 2:
331  return self.arg(0).eq(self.arg(1))
332  else:
333  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
334 
335  def sexpr(self):
336  """Return a string representing the AST node in s-expression notation.
337 
338  >>> x = Int('x')
339  >>> ((x + 1)*x).sexpr()
340  '(* (+ x 1) x)'
341  """
342  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
343 
344  def as_ast(self):
345  """Return a pointer to the corresponding C Z3_ast object."""
346  return self.ast
347 
348  def get_id(self):
349  """Return unique identifier for object. It can be used for hash-tables and maps."""
350  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
351 
352  def ctx_ref(self):
353  """Return a reference to the C context where this AST node is stored."""
354  return self.ctx.ref()
355 
356  def eq(self, other):
357  """Return `True` if `self` and `other` are structurally identical.
358 
359  >>> x = Int('x')
360  >>> n1 = x + 1
361  >>> n2 = 1 + x
362  >>> n1.eq(n2)
363  False
364  >>> n1 = simplify(n1)
365  >>> n2 = simplify(n2)
366  >>> n1.eq(n2)
367  True
368  """
369  if z3_debug():
370  _z3_assert(is_ast(other), "Z3 AST expected")
371  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
372 
373  def translate(self, target):
374  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
375 
376  >>> c1 = Context()
377  >>> c2 = Context()
378  >>> x = Int('x', c1)
379  >>> y = Int('y', c2)
380  >>> # Nodes in different contexts can't be mixed.
381  >>> # However, we can translate nodes from one context to another.
382  >>> x.translate(c2) + y
383  x + y
384  """
385  if z3_debug():
386  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
387  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
388 
389  def __copy__(self):
390  return self.translate(self.ctx)
391 
392  def hash(self):
393  """Return a hashcode for the `self`.
394 
395  >>> n1 = simplify(Int('x') + 1)
396  >>> n2 = simplify(2 + Int('x') - 1)
397  >>> n1.hash() == n2.hash()
398  True
399  """
400  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
401 
402 def is_ast(a):
403  """Return `True` if `a` is an AST node.
404 
405  >>> is_ast(10)
406  False
407  >>> is_ast(IntVal(10))
408  True
409  >>> is_ast(Int('x'))
410  True
411  >>> is_ast(BoolSort())
412  True
413  >>> is_ast(Function('f', IntSort(), IntSort()))
414  True
415  >>> is_ast("x")
416  False
417  >>> is_ast(Solver())
418  False
419  """
420  return isinstance(a, AstRef)
421 
422 def eq(a, b):
423  """Return `True` if `a` and `b` are structurally identical AST nodes.
424 
425  >>> x = Int('x')
426  >>> y = Int('y')
427  >>> eq(x, y)
428  False
429  >>> eq(x + 1, x + 1)
430  True
431  >>> eq(x + 1, 1 + x)
432  False
433  >>> eq(simplify(x + 1), simplify(1 + x))
434  True
435  """
436  if z3_debug():
437  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
438  return a.eq(b)
439 
440 def _ast_kind(ctx, a):
441  if is_ast(a):
442  a = a.as_ast()
443  return Z3_get_ast_kind(ctx.ref(), a)
444 
445 def _ctx_from_ast_arg_list(args, default_ctx=None):
446  ctx = None
447  for a in args:
448  if is_ast(a) or is_probe(a):
449  if ctx is None:
450  ctx = a.ctx
451  else:
452  if z3_debug():
453  _z3_assert(ctx == a.ctx, "Context mismatch")
454  if ctx is None:
455  ctx = default_ctx
456  return ctx
457 
458 def _ctx_from_ast_args(*args):
459  return _ctx_from_ast_arg_list(args)
460 
461 def _to_func_decl_array(args):
462  sz = len(args)
463  _args = (FuncDecl * sz)()
464  for i in range(sz):
465  _args[i] = args[i].as_func_decl()
466  return _args, sz
467 
468 def _to_ast_array(args):
469  sz = len(args)
470  _args = (Ast * sz)()
471  for i in range(sz):
472  _args[i] = args[i].as_ast()
473  return _args, sz
474 
475 def _to_ref_array(ref, args):
476  sz = len(args)
477  _args = (ref * sz)()
478  for i in range(sz):
479  _args[i] = args[i].as_ast()
480  return _args, sz
481 
482 def _to_ast_ref(a, ctx):
483  k = _ast_kind(ctx, a)
484  if k == Z3_SORT_AST:
485  return _to_sort_ref(a, ctx)
486  elif k == Z3_FUNC_DECL_AST:
487  return _to_func_decl_ref(a, ctx)
488  else:
489  return _to_expr_ref(a, ctx)
490 
491 
492 #########################################
493 #
494 # Sorts
495 #
496 #########################################
497 
498 def _sort_kind(ctx, s):
499  return Z3_get_sort_kind(ctx.ref(), s)
500 
502  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
503  def as_ast(self):
504  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
505 
506  def get_id(self):
507  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
508 
509  def kind(self):
510  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
511 
512  >>> b = BoolSort()
513  >>> b.kind() == Z3_BOOL_SORT
514  True
515  >>> b.kind() == Z3_INT_SORT
516  False
517  >>> A = ArraySort(IntSort(), IntSort())
518  >>> A.kind() == Z3_ARRAY_SORT
519  True
520  >>> A.kind() == Z3_INT_SORT
521  False
522  """
523  return _sort_kind(self.ctx, self.ast)
524 
525  def subsort(self, other):
526  """Return `True` if `self` is a subsort of `other`.
527 
528  >>> IntSort().subsort(RealSort())
529  True
530  """
531  return False
532 
533  def cast(self, val):
534  """Try to cast `val` as an element of sort `self`.
535 
536  This method is used in Z3Py to convert Python objects such as integers,
537  floats, longs and strings into Z3 expressions.
538 
539  >>> x = Int('x')
540  >>> RealSort().cast(x)
541  ToReal(x)
542  """
543  if z3_debug():
544  _z3_assert(is_expr(val), "Z3 expression expected")
545  _z3_assert(self.eq(val.sort()), "Sort mismatch")
546  return val
547 
548  def name(self):
549  """Return the name (string) of sort `self`.
550 
551  >>> BoolSort().name()
552  'Bool'
553  >>> ArraySort(IntSort(), IntSort()).name()
554  'Array'
555  """
556  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
557 
558  def __eq__(self, other):
559  """Return `True` if `self` and `other` are the same Z3 sort.
560 
561  >>> p = Bool('p')
562  >>> p.sort() == BoolSort()
563  True
564  >>> p.sort() == IntSort()
565  False
566  """
567  if other is None:
568  return False
569  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
570 
571  def __ne__(self, other):
572  """Return `True` if `self` and `other` are not the same Z3 sort.
573 
574  >>> p = Bool('p')
575  >>> p.sort() != BoolSort()
576  False
577  >>> p.sort() != IntSort()
578  True
579  """
580  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
581 
582  def __hash__(self):
583  """ Hash code. """
584  return AstRef.__hash__(self)
585 
586 def is_sort(s):
587  """Return `True` if `s` is a Z3 sort.
588 
589  >>> is_sort(IntSort())
590  True
591  >>> is_sort(Int('x'))
592  False
593  >>> is_expr(Int('x'))
594  True
595  """
596  return isinstance(s, SortRef)
597 
598 def _to_sort_ref(s, ctx):
599  if z3_debug():
600  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
601  k = _sort_kind(ctx, s)
602  if k == Z3_BOOL_SORT:
603  return BoolSortRef(s, ctx)
604  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
605  return ArithSortRef(s, ctx)
606  elif k == Z3_BV_SORT:
607  return BitVecSortRef(s, ctx)
608  elif k == Z3_ARRAY_SORT:
609  return ArraySortRef(s, ctx)
610  elif k == Z3_DATATYPE_SORT:
611  return DatatypeSortRef(s, ctx)
612  elif k == Z3_FINITE_DOMAIN_SORT:
613  return FiniteDomainSortRef(s, ctx)
614  elif k == Z3_FLOATING_POINT_SORT:
615  return FPSortRef(s, ctx)
616  elif k == Z3_ROUNDING_MODE_SORT:
617  return FPRMSortRef(s, ctx)
618  elif k == Z3_RE_SORT:
619  return ReSortRef(s, ctx)
620  elif k == Z3_SEQ_SORT:
621  return SeqSortRef(s, ctx)
622  return SortRef(s, ctx)
623 
624 def _sort(ctx, a):
625  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
626 
627 def DeclareSort(name, ctx=None):
628  """Create a new uninterpreted sort named `name`.
629 
630  If `ctx=None`, then the new sort is declared in the global Z3Py context.
631 
632  >>> A = DeclareSort('A')
633  >>> a = Const('a', A)
634  >>> b = Const('b', A)
635  >>> a.sort() == A
636  True
637  >>> b.sort() == A
638  True
639  >>> a == b
640  a == b
641  """
642  ctx = _get_ctx(ctx)
643  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
644 
645 #########################################
646 #
647 # Function Declarations
648 #
649 #########################################
650 
652  """Function declaration. Every constant and function have an associated declaration.
653 
654  The declaration assigns a name, a sort (i.e., type), and for function
655  the sort (i.e., type) of each of its arguments. Note that, in Z3,
656  a constant is a function with 0 arguments.
657  """
658  def as_ast(self):
659  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
660 
661  def get_id(self):
662  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
663 
664  def as_func_decl(self):
665  return self.ast
666 
667  def name(self):
668  """Return the name of the function declaration `self`.
669 
670  >>> f = Function('f', IntSort(), IntSort())
671  >>> f.name()
672  'f'
673  >>> isinstance(f.name(), str)
674  True
675  """
676  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
677 
678  def arity(self):
679  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
680 
681  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
682  >>> f.arity()
683  2
684  """
685  return int(Z3_get_arity(self.ctx_ref(), self.ast))
686 
687  def domain(self, i):
688  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
689 
690  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
691  >>> f.domain(0)
692  Int
693  >>> f.domain(1)
694  Real
695  """
696  if z3_debug():
697  _z3_assert(i < self.arity(), "Index out of bounds")
698  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
699 
700  def range(self):
701  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
702 
703  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
704  >>> f.range()
705  Bool
706  """
707  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
708 
709  def kind(self):
710  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
711 
712  >>> x = Int('x')
713  >>> d = (x + 1).decl()
714  >>> d.kind() == Z3_OP_ADD
715  True
716  >>> d.kind() == Z3_OP_MUL
717  False
718  """
719  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
720 
721  def params(self):
722  ctx = self.ctx
723  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
724  result = [ None for i in range(n) ]
725  for i in range(n):
726  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
727  if k == Z3_PARAMETER_INT:
728  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
729  elif k == Z3_PARAMETER_DOUBLE:
730  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
731  elif k == Z3_PARAMETER_RATIONAL:
732  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
733  elif k == Z3_PARAMETER_SYMBOL:
734  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
735  elif k == Z3_PARAMETER_SORT:
736  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
737  elif k == Z3_PARAMETER_AST:
738  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
739  elif k == Z3_PARAMETER_FUNC_DECL:
740  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
741  else:
742  assert(False)
743  return result
744 
745  def __call__(self, *args):
746  """Create a Z3 application expression using the function `self`, and the given arguments.
747 
748  The arguments must be Z3 expressions. This method assumes that
749  the sorts of the elements in `args` match the sorts of the
750  domain. Limited coercion is supported. For example, if
751  args[0] is a Python integer, and the function expects a Z3
752  integer, then the argument is automatically converted into a
753  Z3 integer.
754 
755  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
756  >>> x = Int('x')
757  >>> y = Real('y')
758  >>> f(x, y)
759  f(x, y)
760  >>> f(x, x)
761  f(x, ToReal(x))
762  """
763  args = _get_args(args)
764  num = len(args)
765  if z3_debug():
766  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
767  _args = (Ast * num)()
768  saved = []
769  for i in range(num):
770  # self.domain(i).cast(args[i]) may create a new Z3 expression,
771  # then we must save in 'saved' to prevent it from being garbage collected.
772  tmp = self.domain(i).cast(args[i])
773  saved.append(tmp)
774  _args[i] = tmp.as_ast()
775  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
776 
778  """Return `True` if `a` is a Z3 function declaration.
779 
780  >>> f = Function('f', IntSort(), IntSort())
781  >>> is_func_decl(f)
782  True
783  >>> x = Real('x')
784  >>> is_func_decl(x)
785  False
786  """
787  return isinstance(a, FuncDeclRef)
788 
789 def Function(name, *sig):
790  """Create a new Z3 uninterpreted function with the given sorts.
791 
792  >>> f = Function('f', IntSort(), IntSort())
793  >>> f(f(0))
794  f(f(0))
795  """
796  sig = _get_args(sig)
797  if z3_debug():
798  _z3_assert(len(sig) > 0, "At least two arguments expected")
799  arity = len(sig) - 1
800  rng = sig[arity]
801  if z3_debug():
802  _z3_assert(is_sort(rng), "Z3 sort expected")
803  dom = (Sort * arity)()
804  for i in range(arity):
805  if z3_debug():
806  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
807  dom[i] = sig[i].ast
808  ctx = rng.ctx
809  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
810 
811 def _to_func_decl_ref(a, ctx):
812  return FuncDeclRef(a, ctx)
813 
814 def RecFunction(name, *sig):
815  """Create a new Z3 recursive with the given sorts."""
816  sig = _get_args(sig)
817  if z3_debug():
818  _z3_assert(len(sig) > 0, "At least two arguments expected")
819  arity = len(sig) - 1
820  rng = sig[arity]
821  if z3_debug():
822  _z3_assert(is_sort(rng), "Z3 sort expected")
823  dom = (Sort * arity)()
824  for i in range(arity):
825  if z3_debug():
826  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
827  dom[i] = sig[i].ast
828  ctx = rng.ctx
829  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
830 
831 def RecAddDefinition(f, args, body):
832  """Set the body of a recursive function.
833  Recursive definitions are only unfolded during search.
834  >>> ctx = Context()
835  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
836  >>> n = Int('n', ctx)
837  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
838  >>> simplify(fac(5))
839  fac(5)
840  >>> s = Solver(ctx=ctx)
841  >>> s.add(fac(n) < 3)
842  >>> s.check()
843  sat
844  >>> s.model().eval(fac(5))
845  120
846  """
847  if is_app(args):
848  args = [args]
849  ctx = body.ctx
850  args = _get_args(args)
851  n = len(args)
852  _args = (Ast * n)()
853  for i in range(n):
854  _args[i] = args[i].ast
855  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
856 
857 #########################################
858 #
859 # Expressions
860 #
861 #########################################
862 
864  """Constraints, formulas and terms are expressions in Z3.
865 
866  Expressions are ASTs. Every expression has a sort.
867  There are three main kinds of expressions:
868  function applications, quantifiers and bounded variables.
869  A constant is a function application with 0 arguments.
870  For quantifier free problems, all expressions are
871  function applications.
872  """
873  def as_ast(self):
874  return self.ast
875 
876  def get_id(self):
877  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
878 
879  def sort(self):
880  """Return the sort of expression `self`.
881 
882  >>> x = Int('x')
883  >>> (x + 1).sort()
884  Int
885  >>> y = Real('y')
886  >>> (x + y).sort()
887  Real
888  """
889  return _sort(self.ctx, self.as_ast())
890 
891  def sort_kind(self):
892  """Shorthand for `self.sort().kind()`.
893 
894  >>> a = Array('a', IntSort(), IntSort())
895  >>> a.sort_kind() == Z3_ARRAY_SORT
896  True
897  >>> a.sort_kind() == Z3_INT_SORT
898  False
899  """
900  return self.sort().kind()
901 
902  def __eq__(self, other):
903  """Return a Z3 expression that represents the constraint `self == other`.
904 
905  If `other` is `None`, then this method simply returns `False`.
906 
907  >>> a = Int('a')
908  >>> b = Int('b')
909  >>> a == b
910  a == b
911  >>> a is None
912  False
913  """
914  if other is None:
915  return False
916  a, b = _coerce_exprs(self, other)
917  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
918 
919  def __hash__(self):
920  """ Hash code. """
921  return AstRef.__hash__(self)
922 
923  def __ne__(self, other):
924  """Return a Z3 expression that represents the constraint `self != other`.
925 
926  If `other` is `None`, then this method simply returns `True`.
927 
928  >>> a = Int('a')
929  >>> b = Int('b')
930  >>> a != b
931  a != b
932  >>> a is not None
933  True
934  """
935  if other is None:
936  return True
937  a, b = _coerce_exprs(self, other)
938  _args, sz = _to_ast_array((a, b))
939  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
940 
941  def params(self):
942  return self.decl().params()
943 
944  def decl(self):
945  """Return the Z3 function declaration associated with a Z3 application.
946 
947  >>> f = Function('f', IntSort(), IntSort())
948  >>> a = Int('a')
949  >>> t = f(a)
950  >>> eq(t.decl(), f)
951  True
952  >>> (a + 1).decl()
953  +
954  """
955  if z3_debug():
956  _z3_assert(is_app(self), "Z3 application expected")
957  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
958 
959  def num_args(self):
960  """Return the number of arguments of a Z3 application.
961 
962  >>> a = Int('a')
963  >>> b = Int('b')
964  >>> (a + b).num_args()
965  2
966  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
967  >>> t = f(a, b, 0)
968  >>> t.num_args()
969  3
970  """
971  if z3_debug():
972  _z3_assert(is_app(self), "Z3 application expected")
973  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
974 
975  def arg(self, idx):
976  """Return argument `idx` of the application `self`.
977 
978  This method assumes that `self` is a function application with at least `idx+1` arguments.
979 
980  >>> a = Int('a')
981  >>> b = Int('b')
982  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
983  >>> t = f(a, b, 0)
984  >>> t.arg(0)
985  a
986  >>> t.arg(1)
987  b
988  >>> t.arg(2)
989  0
990  """
991  if z3_debug():
992  _z3_assert(is_app(self), "Z3 application expected")
993  _z3_assert(idx < self.num_args(), "Invalid argument index")
994  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
995 
996  def children(self):
997  """Return a list containing the children of the given expression
998 
999  >>> a = Int('a')
1000  >>> b = Int('b')
1001  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1002  >>> t = f(a, b, 0)
1003  >>> t.children()
1004  [a, b, 0]
1005  """
1006  if is_app(self):
1007  return [self.arg(i) for i in range(self.num_args())]
1008  else:
1009  return []
1010 
1011 def _to_expr_ref(a, ctx):
1012  if isinstance(a, Pattern):
1013  return PatternRef(a, ctx)
1014  ctx_ref = ctx.ref()
1015  k = Z3_get_ast_kind(ctx_ref, a)
1016  if k == Z3_QUANTIFIER_AST:
1017  return QuantifierRef(a, ctx)
1018  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1019  if sk == Z3_BOOL_SORT:
1020  return BoolRef(a, ctx)
1021  if sk == Z3_INT_SORT:
1022  if k == Z3_NUMERAL_AST:
1023  return IntNumRef(a, ctx)
1024  return ArithRef(a, ctx)
1025  if sk == Z3_REAL_SORT:
1026  if k == Z3_NUMERAL_AST:
1027  return RatNumRef(a, ctx)
1028  if _is_algebraic(ctx, a):
1029  return AlgebraicNumRef(a, ctx)
1030  return ArithRef(a, ctx)
1031  if sk == Z3_BV_SORT:
1032  if k == Z3_NUMERAL_AST:
1033  return BitVecNumRef(a, ctx)
1034  else:
1035  return BitVecRef(a, ctx)
1036  if sk == Z3_ARRAY_SORT:
1037  return ArrayRef(a, ctx)
1038  if sk == Z3_DATATYPE_SORT:
1039  return DatatypeRef(a, ctx)
1040  if sk == Z3_FLOATING_POINT_SORT:
1041  if k == Z3_APP_AST and _is_numeral(ctx, a):
1042  return FPNumRef(a, ctx)
1043  else:
1044  return FPRef(a, ctx)
1045  if sk == Z3_FINITE_DOMAIN_SORT:
1046  if k == Z3_NUMERAL_AST:
1047  return FiniteDomainNumRef(a, ctx)
1048  else:
1049  return FiniteDomainRef(a, ctx)
1050  if sk == Z3_ROUNDING_MODE_SORT:
1051  return FPRMRef(a, ctx)
1052  if sk == Z3_SEQ_SORT:
1053  return SeqRef(a, ctx)
1054  if sk == Z3_RE_SORT:
1055  return ReRef(a, ctx)
1056  return ExprRef(a, ctx)
1057 
1058 def _coerce_expr_merge(s, a):
1059  if is_expr(a):
1060  s1 = a.sort()
1061  if s is None:
1062  return s1
1063  if s1.eq(s):
1064  return s
1065  elif s.subsort(s1):
1066  return s1
1067  elif s1.subsort(s):
1068  return s
1069  else:
1070  if z3_debug():
1071  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1072  _z3_assert(False, "sort mismatch")
1073  else:
1074  return s
1075 
1076 def _coerce_exprs(a, b, ctx=None):
1077  if not is_expr(a) and not is_expr(b):
1078  a = _py2expr(a, ctx)
1079  b = _py2expr(b, ctx)
1080  s = None
1081  s = _coerce_expr_merge(s, a)
1082  s = _coerce_expr_merge(s, b)
1083  a = s.cast(a)
1084  b = s.cast(b)
1085  return (a, b)
1086 
1087 
1088 def _reduce(f, l, a):
1089  r = a
1090  for e in l:
1091  r = f(r, e)
1092  return r
1093 
1094 def _coerce_expr_list(alist, ctx=None):
1095  has_expr = False
1096  for a in alist:
1097  if is_expr(a):
1098  has_expr = True
1099  break
1100  if not has_expr:
1101  alist = [ _py2expr(a, ctx) for a in alist ]
1102  s = _reduce(_coerce_expr_merge, alist, None)
1103  return [ s.cast(a) for a in alist ]
1104 
1105 def is_expr(a):
1106  """Return `True` if `a` is a Z3 expression.
1107 
1108  >>> a = Int('a')
1109  >>> is_expr(a)
1110  True
1111  >>> is_expr(a + 1)
1112  True
1113  >>> is_expr(IntSort())
1114  False
1115  >>> is_expr(1)
1116  False
1117  >>> is_expr(IntVal(1))
1118  True
1119  >>> x = Int('x')
1120  >>> is_expr(ForAll(x, x >= 0))
1121  True
1122  >>> is_expr(FPVal(1.0))
1123  True
1124  """
1125  return isinstance(a, ExprRef)
1126 
1127 def is_app(a):
1128  """Return `True` if `a` is a Z3 function application.
1129 
1130  Note that, constants are function applications with 0 arguments.
1131 
1132  >>> a = Int('a')
1133  >>> is_app(a)
1134  True
1135  >>> is_app(a + 1)
1136  True
1137  >>> is_app(IntSort())
1138  False
1139  >>> is_app(1)
1140  False
1141  >>> is_app(IntVal(1))
1142  True
1143  >>> x = Int('x')
1144  >>> is_app(ForAll(x, x >= 0))
1145  False
1146  """
1147  if not isinstance(a, ExprRef):
1148  return False
1149  k = _ast_kind(a.ctx, a)
1150  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1151 
1152 def is_const(a):
1153  """Return `True` if `a` is Z3 constant/variable expression.
1154 
1155  >>> a = Int('a')
1156  >>> is_const(a)
1157  True
1158  >>> is_const(a + 1)
1159  False
1160  >>> is_const(1)
1161  False
1162  >>> is_const(IntVal(1))
1163  True
1164  >>> x = Int('x')
1165  >>> is_const(ForAll(x, x >= 0))
1166  False
1167  """
1168  return is_app(a) and a.num_args() == 0
1169 
1170 def is_var(a):
1171  """Return `True` if `a` is variable.
1172 
1173  Z3 uses de-Bruijn indices for representing bound variables in
1174  quantifiers.
1175 
1176  >>> x = Int('x')
1177  >>> is_var(x)
1178  False
1179  >>> is_const(x)
1180  True
1181  >>> f = Function('f', IntSort(), IntSort())
1182  >>> # Z3 replaces x with bound variables when ForAll is executed.
1183  >>> q = ForAll(x, f(x) == x)
1184  >>> b = q.body()
1185  >>> b
1186  f(Var(0)) == Var(0)
1187  >>> b.arg(1)
1188  Var(0)
1189  >>> is_var(b.arg(1))
1190  True
1191  """
1192  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1193 
1195  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1196 
1197  >>> x = Int('x')
1198  >>> y = Int('y')
1199  >>> is_var(x)
1200  False
1201  >>> is_const(x)
1202  True
1203  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1204  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1205  >>> q = ForAll([x, y], f(x, y) == x + y)
1206  >>> q.body()
1207  f(Var(1), Var(0)) == Var(1) + Var(0)
1208  >>> b = q.body()
1209  >>> b.arg(0)
1210  f(Var(1), Var(0))
1211  >>> v1 = b.arg(0).arg(0)
1212  >>> v2 = b.arg(0).arg(1)
1213  >>> v1
1214  Var(1)
1215  >>> v2
1216  Var(0)
1217  >>> get_var_index(v1)
1218  1
1219  >>> get_var_index(v2)
1220  0
1221  """
1222  if z3_debug():
1223  _z3_assert(is_var(a), "Z3 bound variable expected")
1224  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1225 
1226 def is_app_of(a, k):
1227  """Return `True` if `a` is an application of the given kind `k`.
1228 
1229  >>> x = Int('x')
1230  >>> n = x + 1
1231  >>> is_app_of(n, Z3_OP_ADD)
1232  True
1233  >>> is_app_of(n, Z3_OP_MUL)
1234  False
1235  """
1236  return is_app(a) and a.decl().kind() == k
1237 
1238 def If(a, b, c, ctx=None):
1239  """Create a Z3 if-then-else expression.
1240 
1241  >>> x = Int('x')
1242  >>> y = Int('y')
1243  >>> max = If(x > y, x, y)
1244  >>> max
1245  If(x > y, x, y)
1246  >>> simplify(max)
1247  If(x <= y, y, x)
1248  """
1249  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1250  return Cond(a, b, c, ctx)
1251  else:
1252  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1253  s = BoolSort(ctx)
1254  a = s.cast(a)
1255  b, c = _coerce_exprs(b, c, ctx)
1256  if z3_debug():
1257  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1258  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1259 
1260 def Distinct(*args):
1261  """Create a Z3 distinct expression.
1262 
1263  >>> x = Int('x')
1264  >>> y = Int('y')
1265  >>> Distinct(x, y)
1266  x != y
1267  >>> z = Int('z')
1268  >>> Distinct(x, y, z)
1269  Distinct(x, y, z)
1270  >>> simplify(Distinct(x, y, z))
1271  Distinct(x, y, z)
1272  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1273  And(Not(x == y), Not(x == z), Not(y == z))
1274  """
1275  args = _get_args(args)
1276  ctx = _ctx_from_ast_arg_list(args)
1277  if z3_debug():
1278  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1279  args = _coerce_expr_list(args, ctx)
1280  _args, sz = _to_ast_array(args)
1281  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1282 
1283 def _mk_bin(f, a, b):
1284  args = (Ast * 2)()
1285  if z3_debug():
1286  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1287  args[0] = a.as_ast()
1288  args[1] = b.as_ast()
1289  return f(a.ctx.ref(), 2, args)
1290 
1291 def Const(name, sort):
1292  """Create a constant of the given sort.
1293 
1294  >>> Const('x', IntSort())
1295  x
1296  """
1297  if z3_debug():
1298  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1299  ctx = sort.ctx
1300  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1301 
1302 def Consts(names, sort):
1303  """Create a several constants of the given sort.
1304 
1305  `names` is a string containing the names of all constants to be created.
1306  Blank spaces separate the names of different constants.
1307 
1308  >>> x, y, z = Consts('x y z', IntSort())
1309  >>> x + y + z
1310  x + y + z
1311  """
1312  if isinstance(names, str):
1313  names = names.split(" ")
1314  return [Const(name, sort) for name in names]
1315 
1316 def FreshConst(sort, prefix='c'):
1317  """Create a fresh constant of a specified sort"""
1318  ctx = _get_ctx(sort.ctx)
1319  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1320 
1321 def Var(idx, s):
1322  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1323 
1324  >>> Var(0, IntSort())
1325  Var(0)
1326  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1327  False
1328  """
1329  if z3_debug():
1330  _z3_assert(is_sort(s), "Z3 sort expected")
1331  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1332 
1333 def RealVar(idx, ctx=None):
1334  """
1335  Create a real free variable. Free variables are used to create quantified formulas.
1336  They are also used to create polynomials.
1337 
1338  >>> RealVar(0)
1339  Var(0)
1340  """
1341  return Var(idx, RealSort(ctx))
1342 
1343 def RealVarVector(n, ctx=None):
1344  """
1345  Create a list of Real free variables.
1346  The variables have ids: 0, 1, ..., n-1
1347 
1348  >>> x0, x1, x2, x3 = RealVarVector(4)
1349  >>> x2
1350  Var(2)
1351  """
1352  return [ RealVar(i, ctx) for i in range(n) ]
1353 
1354 #########################################
1355 #
1356 # Booleans
1357 #
1358 #########################################
1359 
1361  """Boolean sort."""
1362  def cast(self, val):
1363  """Try to cast `val` as a Boolean.
1364 
1365  >>> x = BoolSort().cast(True)
1366  >>> x
1367  True
1368  >>> is_expr(x)
1369  True
1370  >>> is_expr(True)
1371  False
1372  >>> x.sort()
1373  Bool
1374  """
1375  if isinstance(val, bool):
1376  return BoolVal(val, self.ctx)
1377  if z3_debug():
1378  if not is_expr(val):
1379  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1380  if not self.eq(val.sort()):
1381  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1382  return val
1383 
1384  def subsort(self, other):
1385  return isinstance(other, ArithSortRef)
1386 
1387  def is_int(self):
1388  return True
1389 
1390  def is_bool(self):
1391  return True
1392 
1393 
1395  """All Boolean expressions are instances of this class."""
1396  def sort(self):
1397  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1398 
1399  def __rmul__(self, other):
1400  return self * other
1401 
1402  def __mul__(self, other):
1403  """Create the Z3 expression `self * other`.
1404  """
1405  if other == 1:
1406  return self
1407  if other == 0:
1408  return 0
1409  return If(self, other, 0)
1410 
1411 
1412 def is_bool(a):
1413  """Return `True` if `a` is a Z3 Boolean expression.
1414 
1415  >>> p = Bool('p')
1416  >>> is_bool(p)
1417  True
1418  >>> q = Bool('q')
1419  >>> is_bool(And(p, q))
1420  True
1421  >>> x = Real('x')
1422  >>> is_bool(x)
1423  False
1424  >>> is_bool(x == 0)
1425  True
1426  """
1427  return isinstance(a, BoolRef)
1428 
1429 def is_true(a):
1430  """Return `True` if `a` is the Z3 true expression.
1431 
1432  >>> p = Bool('p')
1433  >>> is_true(p)
1434  False
1435  >>> is_true(simplify(p == p))
1436  True
1437  >>> x = Real('x')
1438  >>> is_true(x == 0)
1439  False
1440  >>> # True is a Python Boolean expression
1441  >>> is_true(True)
1442  False
1443  """
1444  return is_app_of(a, Z3_OP_TRUE)
1445 
1446 def is_false(a):
1447  """Return `True` if `a` is the Z3 false expression.
1448 
1449  >>> p = Bool('p')
1450  >>> is_false(p)
1451  False
1452  >>> is_false(False)
1453  False
1454  >>> is_false(BoolVal(False))
1455  True
1456  """
1457  return is_app_of(a, Z3_OP_FALSE)
1458 
1459 def is_and(a):
1460  """Return `True` if `a` is a Z3 and expression.
1461 
1462  >>> p, q = Bools('p q')
1463  >>> is_and(And(p, q))
1464  True
1465  >>> is_and(Or(p, q))
1466  False
1467  """
1468  return is_app_of(a, Z3_OP_AND)
1469 
1470 def is_or(a):
1471  """Return `True` if `a` is a Z3 or expression.
1472 
1473  >>> p, q = Bools('p q')
1474  >>> is_or(Or(p, q))
1475  True
1476  >>> is_or(And(p, q))
1477  False
1478  """
1479  return is_app_of(a, Z3_OP_OR)
1480 
1481 def is_implies(a):
1482  """Return `True` if `a` is a Z3 implication expression.
1483 
1484  >>> p, q = Bools('p q')
1485  >>> is_implies(Implies(p, q))
1486  True
1487  >>> is_implies(And(p, q))
1488  False
1489  """
1490  return is_app_of(a, Z3_OP_IMPLIES)
1491 
1492 def is_not(a):
1493  """Return `True` if `a` is a Z3 not expression.
1494 
1495  >>> p = Bool('p')
1496  >>> is_not(p)
1497  False
1498  >>> is_not(Not(p))
1499  True
1500  """
1501  return is_app_of(a, Z3_OP_NOT)
1502 
1503 def is_eq(a):
1504  """Return `True` if `a` is a Z3 equality expression.
1505 
1506  >>> x, y = Ints('x y')
1507  >>> is_eq(x == y)
1508  True
1509  """
1510  return is_app_of(a, Z3_OP_EQ)
1511 
1513  """Return `True` if `a` is a Z3 distinct expression.
1514 
1515  >>> x, y, z = Ints('x y z')
1516  >>> is_distinct(x == y)
1517  False
1518  >>> is_distinct(Distinct(x, y, z))
1519  True
1520  """
1521  return is_app_of(a, Z3_OP_DISTINCT)
1522 
1523 def BoolSort(ctx=None):
1524  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1525 
1526  >>> BoolSort()
1527  Bool
1528  >>> p = Const('p', BoolSort())
1529  >>> is_bool(p)
1530  True
1531  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1532  >>> r(0, 1)
1533  r(0, 1)
1534  >>> is_bool(r(0, 1))
1535  True
1536  """
1537  ctx = _get_ctx(ctx)
1538  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1539 
1540 def BoolVal(val, ctx=None):
1541  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1542 
1543  >>> BoolVal(True)
1544  True
1545  >>> is_true(BoolVal(True))
1546  True
1547  >>> is_true(True)
1548  False
1549  >>> is_false(BoolVal(False))
1550  True
1551  """
1552  ctx = _get_ctx(ctx)
1553  if val == False:
1554  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1555  else:
1556  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1557 
1558 def Bool(name, ctx=None):
1559  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1560 
1561  >>> p = Bool('p')
1562  >>> q = Bool('q')
1563  >>> And(p, q)
1564  And(p, q)
1565  """
1566  ctx = _get_ctx(ctx)
1567  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1568 
1569 def Bools(names, ctx=None):
1570  """Return a tuple of Boolean constants.
1571 
1572  `names` is a single string containing all names separated by blank spaces.
1573  If `ctx=None`, then the global context is used.
1574 
1575  >>> p, q, r = Bools('p q r')
1576  >>> And(p, Or(q, r))
1577  And(p, Or(q, r))
1578  """
1579  ctx = _get_ctx(ctx)
1580  if isinstance(names, str):
1581  names = names.split(" ")
1582  return [Bool(name, ctx) for name in names]
1583 
1584 def BoolVector(prefix, sz, ctx=None):
1585  """Return a list of Boolean constants of size `sz`.
1586 
1587  The constants are named using the given prefix.
1588  If `ctx=None`, then the global context is used.
1589 
1590  >>> P = BoolVector('p', 3)
1591  >>> P
1592  [p__0, p__1, p__2]
1593  >>> And(P)
1594  And(p__0, p__1, p__2)
1595  """
1596  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1597 
1598 def FreshBool(prefix='b', ctx=None):
1599  """Return a fresh Boolean constant in the given context using the given prefix.
1600 
1601  If `ctx=None`, then the global context is used.
1602 
1603  >>> b1 = FreshBool()
1604  >>> b2 = FreshBool()
1605  >>> eq(b1, b2)
1606  False
1607  """
1608  ctx = _get_ctx(ctx)
1609  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1610 
1611 def Implies(a, b, ctx=None):
1612  """Create a Z3 implies expression.
1613 
1614  >>> p, q = Bools('p q')
1615  >>> Implies(p, q)
1616  Implies(p, q)
1617  >>> simplify(Implies(p, q))
1618  Or(Not(p), q)
1619  """
1620  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1621  s = BoolSort(ctx)
1622  a = s.cast(a)
1623  b = s.cast(b)
1624  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1625 
1626 def Xor(a, b, ctx=None):
1627  """Create a Z3 Xor expression.
1628 
1629  >>> p, q = Bools('p q')
1630  >>> Xor(p, q)
1631  Xor(p, q)
1632  >>> simplify(Xor(p, q))
1633  Not(p) == q
1634  """
1635  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1636  s = BoolSort(ctx)
1637  a = s.cast(a)
1638  b = s.cast(b)
1639  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1640 
1641 def Not(a, ctx=None):
1642  """Create a Z3 not expression or probe.
1643 
1644  >>> p = Bool('p')
1645  >>> Not(Not(p))
1646  Not(Not(p))
1647  >>> simplify(Not(Not(p)))
1648  p
1649  """
1650  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1651  if is_probe(a):
1652  # Not is also used to build probes
1653  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1654  else:
1655  s = BoolSort(ctx)
1656  a = s.cast(a)
1657  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1658 
1659 def mk_not(a):
1660  if is_not(a):
1661  return a.arg(0)
1662  else:
1663  return Not(a)
1664 
1665 def _has_probe(args):
1666  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1667  for arg in args:
1668  if is_probe(arg):
1669  return True
1670  return False
1671 
1672 def And(*args):
1673  """Create a Z3 and-expression or and-probe.
1674 
1675  >>> p, q, r = Bools('p q r')
1676  >>> And(p, q, r)
1677  And(p, q, r)
1678  >>> P = BoolVector('p', 5)
1679  >>> And(P)
1680  And(p__0, p__1, p__2, p__3, p__4)
1681  """
1682  last_arg = None
1683  if len(args) > 0:
1684  last_arg = args[len(args)-1]
1685  if isinstance(last_arg, Context):
1686  ctx = args[len(args)-1]
1687  args = args[:len(args)-1]
1688  elif len(args) == 1 and isinstance(args[0], AstVector):
1689  ctx = args[0].ctx
1690  args = [a for a in args[0]]
1691  else:
1692  ctx = main_ctx()
1693  args = _get_args(args)
1694  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1695  if z3_debug():
1696  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1697  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1698  if _has_probe(args):
1699  return _probe_and(args, ctx)
1700  else:
1701  args = _coerce_expr_list(args, ctx)
1702  _args, sz = _to_ast_array(args)
1703  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1704 
1705 def Or(*args):
1706  """Create a Z3 or-expression or or-probe.
1707 
1708  >>> p, q, r = Bools('p q r')
1709  >>> Or(p, q, r)
1710  Or(p, q, r)
1711  >>> P = BoolVector('p', 5)
1712  >>> Or(P)
1713  Or(p__0, p__1, p__2, p__3, p__4)
1714  """
1715  last_arg = None
1716  if len(args) > 0:
1717  last_arg = args[len(args)-1]
1718  if isinstance(last_arg, Context):
1719  ctx = args[len(args)-1]
1720  args = args[:len(args)-1]
1721  else:
1722  ctx = main_ctx()
1723  args = _get_args(args)
1724  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1725  if z3_debug():
1726  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1727  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1728  if _has_probe(args):
1729  return _probe_or(args, ctx)
1730  else:
1731  args = _coerce_expr_list(args, ctx)
1732  _args, sz = _to_ast_array(args)
1733  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1734 
1735 #########################################
1736 #
1737 # Patterns
1738 #
1739 #########################################
1740 
1741 class PatternRef(ExprRef):
1742  """Patterns are hints for quantifier instantiation.
1743 
1744  """
1745  def as_ast(self):
1746  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1747 
1748  def get_id(self):
1749  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1750 
1751 def is_pattern(a):
1752  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1753 
1754  >>> f = Function('f', IntSort(), IntSort())
1755  >>> x = Int('x')
1756  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1757  >>> q
1758  ForAll(x, f(x) == 0)
1759  >>> q.num_patterns()
1760  1
1761  >>> is_pattern(q.pattern(0))
1762  True
1763  >>> q.pattern(0)
1764  f(Var(0))
1765  """
1766  return isinstance(a, PatternRef)
1767 
1768 def MultiPattern(*args):
1769  """Create a Z3 multi-pattern using the given expressions `*args`
1770 
1771  >>> f = Function('f', IntSort(), IntSort())
1772  >>> g = Function('g', IntSort(), IntSort())
1773  >>> x = Int('x')
1774  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1775  >>> q
1776  ForAll(x, f(x) != g(x))
1777  >>> q.num_patterns()
1778  1
1779  >>> is_pattern(q.pattern(0))
1780  True
1781  >>> q.pattern(0)
1782  MultiPattern(f(Var(0)), g(Var(0)))
1783  """
1784  if z3_debug():
1785  _z3_assert(len(args) > 0, "At least one argument expected")
1786  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1787  ctx = args[0].ctx
1788  args, sz = _to_ast_array(args)
1789  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1790 
1791 def _to_pattern(arg):
1792  if is_pattern(arg):
1793  return arg
1794  else:
1795  return MultiPattern(arg)
1796 
1797 #########################################
1798 #
1799 # Quantifiers
1800 #
1801 #########################################
1802 
1803 class QuantifierRef(BoolRef):
1804  """Universally and Existentially quantified formulas."""
1805 
1806  def as_ast(self):
1807  return self.ast
1808 
1809  def get_id(self):
1810  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1811 
1812  def sort(self):
1813  """Return the Boolean sort or sort of Lambda."""
1814  if self.is_lambda():
1815  return _sort(self.ctx, self.as_ast())
1816  return BoolSort(self.ctx)
1817 
1818  def is_forall(self):
1819  """Return `True` if `self` is a universal quantifier.
1820 
1821  >>> f = Function('f', IntSort(), IntSort())
1822  >>> x = Int('x')
1823  >>> q = ForAll(x, f(x) == 0)
1824  >>> q.is_forall()
1825  True
1826  >>> q = Exists(x, f(x) != 0)
1827  >>> q.is_forall()
1828  False
1829  """
1830  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1831 
1832  def is_exists(self):
1833  """Return `True` if `self` is an existential quantifier.
1834 
1835  >>> f = Function('f', IntSort(), IntSort())
1836  >>> x = Int('x')
1837  >>> q = ForAll(x, f(x) == 0)
1838  >>> q.is_exists()
1839  False
1840  >>> q = Exists(x, f(x) != 0)
1841  >>> q.is_exists()
1842  True
1843  """
1844  return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1845 
1846  def is_lambda(self):
1847  """Return `True` if `self` is a lambda expression.
1848 
1849  >>> f = Function('f', IntSort(), IntSort())
1850  >>> x = Int('x')
1851  >>> q = Lambda(x, f(x))
1852  >>> q.is_lambda()
1853  True
1854  >>> q = Exists(x, f(x) != 0)
1855  >>> q.is_lambda()
1856  False
1857  """
1858  return Z3_is_lambda(self.ctx_ref(), self.ast)
1859 
1860  def weight(self):
1861  """Return the weight annotation of `self`.
1862 
1863  >>> f = Function('f', IntSort(), IntSort())
1864  >>> x = Int('x')
1865  >>> q = ForAll(x, f(x) == 0)
1866  >>> q.weight()
1867  1
1868  >>> q = ForAll(x, f(x) == 0, weight=10)
1869  >>> q.weight()
1870  10
1871  """
1872  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1873 
1874  def num_patterns(self):
1875  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1876 
1877  >>> f = Function('f', IntSort(), IntSort())
1878  >>> g = Function('g', IntSort(), IntSort())
1879  >>> x = Int('x')
1880  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1881  >>> q.num_patterns()
1882  2
1883  """
1884  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1885 
1886  def pattern(self, idx):
1887  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1888 
1889  >>> f = Function('f', IntSort(), IntSort())
1890  >>> g = Function('g', IntSort(), IntSort())
1891  >>> x = Int('x')
1892  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1893  >>> q.num_patterns()
1894  2
1895  >>> q.pattern(0)
1896  f(Var(0))
1897  >>> q.pattern(1)
1898  g(Var(0))
1899  """
1900  if z3_debug():
1901  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1902  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1903 
1904  def num_no_patterns(self):
1905  """Return the number of no-patterns."""
1906  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1907 
1908  def no_pattern(self, idx):
1909  """Return a no-pattern."""
1910  if z3_debug():
1911  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1912  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1913 
1914  def body(self):
1915  """Return the expression being quantified.
1916 
1917  >>> f = Function('f', IntSort(), IntSort())
1918  >>> x = Int('x')
1919  >>> q = ForAll(x, f(x) == 0)
1920  >>> q.body()
1921  f(Var(0)) == 0
1922  """
1923  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1924 
1925  def num_vars(self):
1926  """Return the number of variables bounded by this quantifier.
1927 
1928  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1929  >>> x = Int('x')
1930  >>> y = Int('y')
1931  >>> q = ForAll([x, y], f(x, y) >= x)
1932  >>> q.num_vars()
1933  2
1934  """
1935  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1936 
1937  def var_name(self, idx):
1938  """Return a string representing a name used when displaying the quantifier.
1939 
1940  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1941  >>> x = Int('x')
1942  >>> y = Int('y')
1943  >>> q = ForAll([x, y], f(x, y) >= x)
1944  >>> q.var_name(0)
1945  'x'
1946  >>> q.var_name(1)
1947  'y'
1948  """
1949  if z3_debug():
1950  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1951  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1952 
1953  def var_sort(self, idx):
1954  """Return the sort of a bound variable.
1955 
1956  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1957  >>> x = Int('x')
1958  >>> y = Real('y')
1959  >>> q = ForAll([x, y], f(x, y) >= x)
1960  >>> q.var_sort(0)
1961  Int
1962  >>> q.var_sort(1)
1963  Real
1964  """
1965  if z3_debug():
1966  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1967  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1968 
1969  def children(self):
1970  """Return a list containing a single element self.body()
1971 
1972  >>> f = Function('f', IntSort(), IntSort())
1973  >>> x = Int('x')
1974  >>> q = ForAll(x, f(x) == 0)
1975  >>> q.children()
1976  [f(Var(0)) == 0]
1977  """
1978  return [ self.body() ]
1979 
1980 def is_quantifier(a):
1981  """Return `True` if `a` is a Z3 quantifier.
1982 
1983  >>> f = Function('f', IntSort(), IntSort())
1984  >>> x = Int('x')
1985  >>> q = ForAll(x, f(x) == 0)
1986  >>> is_quantifier(q)
1987  True
1988  >>> is_quantifier(f(x))
1989  False
1990  """
1991  return isinstance(a, QuantifierRef)
1992 
1993 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1994  if z3_debug():
1995  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
1996  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1997  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1998  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1999  if is_app(vs):
2000  ctx = vs.ctx
2001  vs = [vs]
2002  else:
2003  ctx = vs[0].ctx
2004  if not is_expr(body):
2005  body = BoolVal(body, ctx)
2006  num_vars = len(vs)
2007  if num_vars == 0:
2008  return body
2009  _vs = (Ast * num_vars)()
2010  for i in range(num_vars):
2011  ## TODO: Check if is constant
2012  _vs[i] = vs[i].as_ast()
2013  patterns = [ _to_pattern(p) for p in patterns ]
2014  num_pats = len(patterns)
2015  _pats = (Pattern * num_pats)()
2016  for i in range(num_pats):
2017  _pats[i] = patterns[i].ast
2018  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2019  qid = to_symbol(qid, ctx)
2020  skid = to_symbol(skid, ctx)
2021  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2022  num_vars, _vs,
2023  num_pats, _pats,
2024  num_no_pats, _no_pats,
2025  body.as_ast()), ctx)
2026 
2027 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2028  """Create a Z3 forall formula.
2029 
2030  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2031 
2032  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2033  >>> x = Int('x')
2034  >>> y = Int('y')
2035  >>> ForAll([x, y], f(x, y) >= x)
2036  ForAll([x, y], f(x, y) >= x)
2037  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2038  ForAll([x, y], f(x, y) >= x)
2039  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2040  ForAll([x, y], f(x, y) >= x)
2041  """
2042  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2043 
2044 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2045  """Create a Z3 exists formula.
2046 
2047  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2048 
2049 
2050  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2051  >>> x = Int('x')
2052  >>> y = Int('y')
2053  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2054  >>> q
2055  Exists([x, y], f(x, y) >= x)
2056  >>> is_quantifier(q)
2057  True
2058  >>> r = Tactic('nnf')(q).as_expr()
2059  >>> is_quantifier(r)
2060  False
2061  """
2062  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2063 
2064 def Lambda(vs, body):
2065  """Create a Z3 lambda expression.
2066 
2067  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2068  >>> mem0 = Array('mem0', IntSort(), IntSort())
2069  >>> lo, hi, e, i = Ints('lo hi e i')
2070  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2071  >>> mem1
2072  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2073  """
2074  ctx = body.ctx
2075  if is_app(vs):
2076  vs = [vs]
2077  num_vars = len(vs)
2078  _vs = (Ast * num_vars)()
2079  for i in range(num_vars):
2080  ## TODO: Check if is constant
2081  _vs[i] = vs[i].as_ast()
2082  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2083 
2084 #########################################
2085 #
2086 # Arithmetic
2087 #
2088 #########################################
2089 
2090 class ArithSortRef(SortRef):
2091  """Real and Integer sorts."""
2092 
2093  def is_real(self):
2094  """Return `True` if `self` is of the sort Real.
2095 
2096  >>> x = Real('x')
2097  >>> x.is_real()
2098  True
2099  >>> (x + 1).is_real()
2100  True
2101  >>> x = Int('x')
2102  >>> x.is_real()
2103  False
2104  """
2105  return self.kind() == Z3_REAL_SORT
2106 
2107  def is_int(self):
2108  """Return `True` if `self` is of the sort Integer.
2109 
2110  >>> x = Int('x')
2111  >>> x.is_int()
2112  True
2113  >>> (x + 1).is_int()
2114  True
2115  >>> x = Real('x')
2116  >>> x.is_int()
2117  False
2118  """
2119  return self.kind() == Z3_INT_SORT
2120 
2121  def subsort(self, other):
2122  """Return `True` if `self` is a subsort of `other`."""
2123  return self.is_int() and is_arith_sort(other) and other.is_real()
2124 
2125  def cast(self, val):
2126  """Try to cast `val` as an Integer or Real.
2127 
2128  >>> IntSort().cast(10)
2129  10
2130  >>> is_int(IntSort().cast(10))
2131  True
2132  >>> is_int(10)
2133  False
2134  >>> RealSort().cast(10)
2135  10
2136  >>> is_real(RealSort().cast(10))
2137  True
2138  """
2139  if is_expr(val):
2140  if z3_debug():
2141  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2142  val_s = val.sort()
2143  if self.eq(val_s):
2144  return val
2145  if val_s.is_int() and self.is_real():
2146  return ToReal(val)
2147  if val_s.is_bool() and self.is_int():
2148  return If(val, 1, 0)
2149  if val_s.is_bool() and self.is_real():
2150  return ToReal(If(val, 1, 0))
2151  if z3_debug():
2152  _z3_assert(False, "Z3 Integer/Real expression expected" )
2153  else:
2154  if self.is_int():
2155  return IntVal(val, self.ctx)
2156  if self.is_real():
2157  return RealVal(val, self.ctx)
2158  if z3_debug():
2159  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2160 
2161 def is_arith_sort(s):
2162  """Return `True` if s is an arithmetical sort (type).
2163 
2164  >>> is_arith_sort(IntSort())
2165  True
2166  >>> is_arith_sort(RealSort())
2167  True
2168  >>> is_arith_sort(BoolSort())
2169  False
2170  >>> n = Int('x') + 1
2171  >>> is_arith_sort(n.sort())
2172  True
2173  """
2174  return isinstance(s, ArithSortRef)
2175 
2176 class ArithRef(ExprRef):
2177  """Integer and Real expressions."""
2178 
2179  def sort(self):
2180  """Return the sort (type) of the arithmetical expression `self`.
2181 
2182  >>> Int('x').sort()
2183  Int
2184  >>> (Real('x') + 1).sort()
2185  Real
2186  """
2187  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2188 
2189  def is_int(self):
2190  """Return `True` if `self` is an integer expression.
2191 
2192  >>> x = Int('x')
2193  >>> x.is_int()
2194  True
2195  >>> (x + 1).is_int()
2196  True
2197  >>> y = Real('y')
2198  >>> (x + y).is_int()
2199  False
2200  """
2201  return self.sort().is_int()
2202 
2203  def is_real(self):
2204  """Return `True` if `self` is an real expression.
2205 
2206  >>> x = Real('x')
2207  >>> x.is_real()
2208  True
2209  >>> (x + 1).is_real()
2210  True
2211  """
2212  return self.sort().is_real()
2213 
2214  def __add__(self, other):
2215  """Create the Z3 expression `self + other`.
2216 
2217  >>> x = Int('x')
2218  >>> y = Int('y')
2219  >>> x + y
2220  x + y
2221  >>> (x + y).sort()
2222  Int
2223  """
2224  a, b = _coerce_exprs(self, other)
2225  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2226 
2227  def __radd__(self, other):
2228  """Create the Z3 expression `other + self`.
2229 
2230  >>> x = Int('x')
2231  >>> 10 + x
2232  10 + x
2233  """
2234  a, b = _coerce_exprs(self, other)
2235  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2236 
2237  def __mul__(self, other):
2238  """Create the Z3 expression `self * other`.
2239 
2240  >>> x = Real('x')
2241  >>> y = Real('y')
2242  >>> x * y
2243  x*y
2244  >>> (x * y).sort()
2245  Real
2246  """
2247  if isinstance(other, BoolRef):
2248  return If(other, self, 0)
2249  a, b = _coerce_exprs(self, other)
2250  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2251 
2252  def __rmul__(self, other):
2253  """Create the Z3 expression `other * self`.
2254 
2255  >>> x = Real('x')
2256  >>> 10 * x
2257  10*x
2258  """
2259  a, b = _coerce_exprs(self, other)
2260  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2261 
2262  def __sub__(self, other):
2263  """Create the Z3 expression `self - other`.
2264 
2265  >>> x = Int('x')
2266  >>> y = Int('y')
2267  >>> x - y
2268  x - y
2269  >>> (x - y).sort()
2270  Int
2271  """
2272  a, b = _coerce_exprs(self, other)
2273  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2274 
2275  def __rsub__(self, other):
2276  """Create the Z3 expression `other - self`.
2277 
2278  >>> x = Int('x')
2279  >>> 10 - x
2280  10 - x
2281  """
2282  a, b = _coerce_exprs(self, other)
2283  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2284 
2285  def __pow__(self, other):
2286  """Create the Z3 expression `self**other` (** is the power operator).
2287 
2288  >>> x = Real('x')
2289  >>> x**3
2290  x**3
2291  >>> (x**3).sort()
2292  Real
2293  >>> simplify(IntVal(2)**8)
2294  256
2295  """
2296  a, b = _coerce_exprs(self, other)
2297  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2298 
2299  def __rpow__(self, other):
2300  """Create the Z3 expression `other**self` (** is the power operator).
2301 
2302  >>> x = Real('x')
2303  >>> 2**x
2304  2**x
2305  >>> (2**x).sort()
2306  Real
2307  >>> simplify(2**IntVal(8))
2308  256
2309  """
2310  a, b = _coerce_exprs(self, other)
2311  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2312 
2313  def __div__(self, other):
2314  """Create the Z3 expression `other/self`.
2315 
2316  >>> x = Int('x')
2317  >>> y = Int('y')
2318  >>> x/y
2319  x/y
2320  >>> (x/y).sort()
2321  Int
2322  >>> (x/y).sexpr()
2323  '(div x y)'
2324  >>> x = Real('x')
2325  >>> y = Real('y')
2326  >>> x/y
2327  x/y
2328  >>> (x/y).sort()
2329  Real
2330  >>> (x/y).sexpr()
2331  '(/ x y)'
2332  """
2333  a, b = _coerce_exprs(self, other)
2334  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2335 
2336  def __truediv__(self, other):
2337  """Create the Z3 expression `other/self`."""
2338  return self.__div__(other)
2339 
2340  def __rdiv__(self, other):
2341  """Create the Z3 expression `other/self`.
2342 
2343  >>> x = Int('x')
2344  >>> 10/x
2345  10/x
2346  >>> (10/x).sexpr()
2347  '(div 10 x)'
2348  >>> x = Real('x')
2349  >>> 10/x
2350  10/x
2351  >>> (10/x).sexpr()
2352  '(/ 10.0 x)'
2353  """
2354  a, b = _coerce_exprs(self, other)
2355  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2356 
2357  def __rtruediv__(self, other):
2358  """Create the Z3 expression `other/self`."""
2359  return self.__rdiv__(other)
2360 
2361  def __mod__(self, other):
2362  """Create the Z3 expression `other%self`.
2363 
2364  >>> x = Int('x')
2365  >>> y = Int('y')
2366  >>> x % y
2367  x%y
2368  >>> simplify(IntVal(10) % IntVal(3))
2369  1
2370  """
2371  a, b = _coerce_exprs(self, other)
2372  if z3_debug():
2373  _z3_assert(a.is_int(), "Z3 integer expression expected")
2374  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2375 
2376  def __rmod__(self, other):
2377  """Create the Z3 expression `other%self`.
2378 
2379  >>> x = Int('x')
2380  >>> 10 % x
2381  10%x
2382  """
2383  a, b = _coerce_exprs(self, other)
2384  if z3_debug():
2385  _z3_assert(a.is_int(), "Z3 integer expression expected")
2386  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2387 
2388  def __neg__(self):
2389  """Return an expression representing `-self`.
2390 
2391  >>> x = Int('x')
2392  >>> -x
2393  -x
2394  >>> simplify(-(-x))
2395  x
2396  """
2397  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2398 
2399  def __pos__(self):
2400  """Return `self`.
2401 
2402  >>> x = Int('x')
2403  >>> +x
2404  x
2405  """
2406  return self
2407 
2408  def __le__(self, other):
2409  """Create the Z3 expression `other <= self`.
2410 
2411  >>> x, y = Ints('x y')
2412  >>> x <= y
2413  x <= y
2414  >>> y = Real('y')
2415  >>> x <= y
2416  ToReal(x) <= y
2417  """
2418  a, b = _coerce_exprs(self, other)
2419  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2420 
2421  def __lt__(self, other):
2422  """Create the Z3 expression `other < self`.
2423 
2424  >>> x, y = Ints('x y')
2425  >>> x < y
2426  x < y
2427  >>> y = Real('y')
2428  >>> x < y
2429  ToReal(x) < y
2430  """
2431  a, b = _coerce_exprs(self, other)
2432  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2433 
2434  def __gt__(self, other):
2435  """Create the Z3 expression `other > self`.
2436 
2437  >>> x, y = Ints('x y')
2438  >>> x > y
2439  x > y
2440  >>> y = Real('y')
2441  >>> x > y
2442  ToReal(x) > y
2443  """
2444  a, b = _coerce_exprs(self, other)
2445  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2446 
2447  def __ge__(self, other):
2448  """Create the Z3 expression `other >= self`.
2449 
2450  >>> x, y = Ints('x y')
2451  >>> x >= y
2452  x >= y
2453  >>> y = Real('y')
2454  >>> x >= y
2455  ToReal(x) >= y
2456  """
2457  a, b = _coerce_exprs(self, other)
2458  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2459 
2460 def is_arith(a):
2461  """Return `True` if `a` is an arithmetical expression.
2462 
2463  >>> x = Int('x')
2464  >>> is_arith(x)
2465  True
2466  >>> is_arith(x + 1)
2467  True
2468  >>> is_arith(1)
2469  False
2470  >>> is_arith(IntVal(1))
2471  True
2472  >>> y = Real('y')
2473  >>> is_arith(y)
2474  True
2475  >>> is_arith(y + 1)
2476  True
2477  """
2478  return isinstance(a, ArithRef)
2479 
2480 def is_int(a):
2481  """Return `True` if `a` is an integer expression.
2482 
2483  >>> x = Int('x')
2484  >>> is_int(x + 1)
2485  True
2486  >>> is_int(1)
2487  False
2488  >>> is_int(IntVal(1))
2489  True
2490  >>> y = Real('y')
2491  >>> is_int(y)
2492  False
2493  >>> is_int(y + 1)
2494  False
2495  """
2496  return is_arith(a) and a.is_int()
2497 
2498 def is_real(a):
2499  """Return `True` if `a` is a real expression.
2500 
2501  >>> x = Int('x')
2502  >>> is_real(x + 1)
2503  False
2504  >>> y = Real('y')
2505  >>> is_real(y)
2506  True
2507  >>> is_real(y + 1)
2508  True
2509  >>> is_real(1)
2510  False
2511  >>> is_real(RealVal(1))
2512  True
2513  """
2514  return is_arith(a) and a.is_real()
2515 
2516 def _is_numeral(ctx, a):
2517  return Z3_is_numeral_ast(ctx.ref(), a)
2518 
2519 def _is_algebraic(ctx, a):
2520  return Z3_is_algebraic_number(ctx.ref(), a)
2521 
2522 def is_int_value(a):
2523  """Return `True` if `a` is an integer value of sort Int.
2524 
2525  >>> is_int_value(IntVal(1))
2526  True
2527  >>> is_int_value(1)
2528  False
2529  >>> is_int_value(Int('x'))
2530  False
2531  >>> n = Int('x') + 1
2532  >>> n
2533  x + 1
2534  >>> n.arg(1)
2535  1
2536  >>> is_int_value(n.arg(1))
2537  True
2538  >>> is_int_value(RealVal("1/3"))
2539  False
2540  >>> is_int_value(RealVal(1))
2541  False
2542  """
2543  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2544 
2545 def is_rational_value(a):
2546  """Return `True` if `a` is rational value of sort Real.
2547 
2548  >>> is_rational_value(RealVal(1))
2549  True
2550  >>> is_rational_value(RealVal("3/5"))
2551  True
2552  >>> is_rational_value(IntVal(1))
2553  False
2554  >>> is_rational_value(1)
2555  False
2556  >>> n = Real('x') + 1
2557  >>> n.arg(1)
2558  1
2559  >>> is_rational_value(n.arg(1))
2560  True
2561  >>> is_rational_value(Real('x'))
2562  False
2563  """
2564  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2565 
2566 def is_algebraic_value(a):
2567  """Return `True` if `a` is an algebraic value of sort Real.
2568 
2569  >>> is_algebraic_value(RealVal("3/5"))
2570  False
2571  >>> n = simplify(Sqrt(2))
2572  >>> n
2573  1.4142135623?
2574  >>> is_algebraic_value(n)
2575  True
2576  """
2577  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2578 
2579 def is_add(a):
2580  """Return `True` if `a` is an expression of the form b + c.
2581 
2582  >>> x, y = Ints('x y')
2583  >>> is_add(x + y)
2584  True
2585  >>> is_add(x - y)
2586  False
2587  """
2588  return is_app_of(a, Z3_OP_ADD)
2589 
2590 def is_mul(a):
2591  """Return `True` if `a` is an expression of the form b * c.
2592 
2593  >>> x, y = Ints('x y')
2594  >>> is_mul(x * y)
2595  True
2596  >>> is_mul(x - y)
2597  False
2598  """
2599  return is_app_of(a, Z3_OP_MUL)
2600 
2601 def is_sub(a):
2602  """Return `True` if `a` is an expression of the form b - c.
2603 
2604  >>> x, y = Ints('x y')
2605  >>> is_sub(x - y)
2606  True
2607  >>> is_sub(x + y)
2608  False
2609  """
2610  return is_app_of(a, Z3_OP_SUB)
2611 
2612 def is_div(a):
2613  """Return `True` if `a` is an expression of the form b / c.
2614 
2615  >>> x, y = Reals('x y')
2616  >>> is_div(x / y)
2617  True
2618  >>> is_div(x + y)
2619  False
2620  >>> x, y = Ints('x y')
2621  >>> is_div(x / y)
2622  False
2623  >>> is_idiv(x / y)
2624  True
2625  """
2626  return is_app_of(a, Z3_OP_DIV)
2627 
2628 def is_idiv(a):
2629  """Return `True` if `a` is an expression of the form b div c.
2630 
2631  >>> x, y = Ints('x y')
2632  >>> is_idiv(x / y)
2633  True
2634  >>> is_idiv(x + y)
2635  False
2636  """
2637  return is_app_of(a, Z3_OP_IDIV)
2638 
2639 def is_mod(a):
2640  """Return `True` if `a` is an expression of the form b % c.
2641 
2642  >>> x, y = Ints('x y')
2643  >>> is_mod(x % y)
2644  True
2645  >>> is_mod(x + y)
2646  False
2647  """
2648  return is_app_of(a, Z3_OP_MOD)
2649 
2650 def is_le(a):
2651  """Return `True` if `a` is an expression of the form b <= c.
2652 
2653  >>> x, y = Ints('x y')
2654  >>> is_le(x <= y)
2655  True
2656  >>> is_le(x < y)
2657  False
2658  """
2659  return is_app_of(a, Z3_OP_LE)
2660 
2661 def is_lt(a):
2662  """Return `True` if `a` is an expression of the form b < c.
2663 
2664  >>> x, y = Ints('x y')
2665  >>> is_lt(x < y)
2666  True
2667  >>> is_lt(x == y)
2668  False
2669  """
2670  return is_app_of(a, Z3_OP_LT)
2671 
2672 def is_ge(a):
2673  """Return `True` if `a` is an expression of the form b >= c.
2674 
2675  >>> x, y = Ints('x y')
2676  >>> is_ge(x >= y)
2677  True
2678  >>> is_ge(x == y)
2679  False
2680  """
2681  return is_app_of(a, Z3_OP_GE)
2682 
2683 def is_gt(a):
2684  """Return `True` if `a` is an expression of the form b > c.
2685 
2686  >>> x, y = Ints('x y')
2687  >>> is_gt(x > y)
2688  True
2689  >>> is_gt(x == y)
2690  False
2691  """
2692  return is_app_of(a, Z3_OP_GT)
2693 
2694 def is_is_int(a):
2695  """Return `True` if `a` is an expression of the form IsInt(b).
2696 
2697  >>> x = Real('x')
2698  >>> is_is_int(IsInt(x))
2699  True
2700  >>> is_is_int(x)
2701  False
2702  """
2703  return is_app_of(a, Z3_OP_IS_INT)
2704 
2705 def is_to_real(a):
2706  """Return `True` if `a` is an expression of the form ToReal(b).
2707 
2708  >>> x = Int('x')
2709  >>> n = ToReal(x)
2710  >>> n
2711  ToReal(x)
2712  >>> is_to_real(n)
2713  True
2714  >>> is_to_real(x)
2715  False
2716  """
2717  return is_app_of(a, Z3_OP_TO_REAL)
2718 
2719 def is_to_int(a):
2720  """Return `True` if `a` is an expression of the form ToInt(b).
2721 
2722  >>> x = Real('x')
2723  >>> n = ToInt(x)
2724  >>> n
2725  ToInt(x)
2726  >>> is_to_int(n)
2727  True
2728  >>> is_to_int(x)
2729  False
2730  """
2731  return is_app_of(a, Z3_OP_TO_INT)
2732 
2733 class IntNumRef(ArithRef):
2734  """Integer values."""
2735 
2736  def as_long(self):
2737  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2738 
2739  >>> v = IntVal(1)
2740  >>> v + 1
2741  1 + 1
2742  >>> v.as_long() + 1
2743  2
2744  """
2745  if z3_debug():
2746  _z3_assert(self.is_int(), "Integer value expected")
2747  return int(self.as_string())
2748 
2749  def as_string(self):
2750  """Return a Z3 integer numeral as a Python string.
2751  >>> v = IntVal(100)
2752  >>> v.as_string()
2753  '100'
2754  """
2755  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2756 
2757 class RatNumRef(ArithRef):
2758  """Rational values."""
2759 
2760  def numerator(self):
2761  """ Return the numerator of a Z3 rational numeral.
2762 
2763  >>> is_rational_value(RealVal("3/5"))
2764  True
2765  >>> n = RealVal("3/5")
2766  >>> n.numerator()
2767  3
2768  >>> is_rational_value(Q(3,5))
2769  True
2770  >>> Q(3,5).numerator()
2771  3
2772  """
2773  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2774 
2775  def denominator(self):
2776  """ Return the denominator of a Z3 rational numeral.
2777 
2778  >>> is_rational_value(Q(3,5))
2779  True
2780  >>> n = Q(3,5)
2781  >>> n.denominator()
2782  5
2783  """
2784  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2785 
2786  def numerator_as_long(self):
2787  """ Return the numerator as a Python long.
2788 
2789  >>> v = RealVal(10000000000)
2790  >>> v
2791  10000000000
2792  >>> v + 1
2793  10000000000 + 1
2794  >>> v.numerator_as_long() + 1 == 10000000001
2795  True
2796  """
2797  return self.numerator().as_long()
2798 
2799  def denominator_as_long(self):
2800  """ Return the denominator as a Python long.
2801 
2802  >>> v = RealVal("1/3")
2803  >>> v
2804  1/3
2805  >>> v.denominator_as_long()
2806  3
2807  """
2808  return self.denominator().as_long()
2809 
2810  def is_int(self):
2811  return False
2812 
2813  def is_real(self):
2814  return True
2815 
2816  def is_int_value(self):
2817  return self.denominator().is_int() and self.denominator_as_long() == 1
2818 
2819  def as_long(self):
2820  _z3_assert(self.is_int_value(), "Expected integer fraction")
2821  return self.numerator_as_long()
2822 
2823  def as_decimal(self, prec):
2824  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2825 
2826  >>> v = RealVal("1/5")
2827  >>> v.as_decimal(3)
2828  '0.2'
2829  >>> v = RealVal("1/3")
2830  >>> v.as_decimal(3)
2831  '0.333?'
2832  """
2833  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2834 
2835  def as_string(self):
2836  """Return a Z3 rational numeral as a Python string.
2837 
2838  >>> v = Q(3,6)
2839  >>> v.as_string()
2840  '1/2'
2841  """
2842  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2843 
2844  def as_fraction(self):
2845  """Return a Z3 rational as a Python Fraction object.
2846 
2847  >>> v = RealVal("1/5")
2848  >>> v.as_fraction()
2849  Fraction(1, 5)
2850  """
2851  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2852 
2853 class AlgebraicNumRef(ArithRef):
2854  """Algebraic irrational values."""
2855 
2856  def approx(self, precision=10):
2857  """Return a Z3 rational number that approximates the algebraic number `self`.
2858  The result `r` is such that |r - self| <= 1/10^precision
2859 
2860  >>> x = simplify(Sqrt(2))
2861  >>> x.approx(20)
2862  6838717160008073720548335/4835703278458516698824704
2863  >>> x.approx(5)
2864  2965821/2097152
2865  """
2866  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2867  def as_decimal(self, prec):
2868  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2869 
2870  >>> x = simplify(Sqrt(2))
2871  >>> x.as_decimal(10)
2872  '1.4142135623?'
2873  >>> x.as_decimal(20)
2874  '1.41421356237309504880?'
2875  """
2876  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2877 
2878 def _py2expr(a, ctx=None):
2879  if isinstance(a, bool):
2880  return BoolVal(a, ctx)
2881  if _is_int(a):
2882  return IntVal(a, ctx)
2883  if isinstance(a, float):
2884  return RealVal(a, ctx)
2885  if is_expr(a):
2886  return a
2887  if z3_debug():
2888  _z3_assert(False, "Python bool, int, long or float expected")
2889 
2890 def IntSort(ctx=None):
2891  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2892 
2893  >>> IntSort()
2894  Int
2895  >>> x = Const('x', IntSort())
2896  >>> is_int(x)
2897  True
2898  >>> x.sort() == IntSort()
2899  True
2900  >>> x.sort() == BoolSort()
2901  False
2902  """
2903  ctx = _get_ctx(ctx)
2904  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2905 
2906 def RealSort(ctx=None):
2907  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2908 
2909  >>> RealSort()
2910  Real
2911  >>> x = Const('x', RealSort())
2912  >>> is_real(x)
2913  True
2914  >>> is_int(x)
2915  False
2916  >>> x.sort() == RealSort()
2917  True
2918  """
2919  ctx = _get_ctx(ctx)
2920  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2921 
2922 def _to_int_str(val):
2923  if isinstance(val, float):
2924  return str(int(val))
2925  elif isinstance(val, bool):
2926  if val:
2927  return "1"
2928  else:
2929  return "0"
2930  elif _is_int(val):
2931  return str(val)
2932  elif isinstance(val, str):
2933  return val
2934  if z3_debug():
2935  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2936 
2937 def IntVal(val, ctx=None):
2938  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2939 
2940  >>> IntVal(1)
2941  1
2942  >>> IntVal("100")
2943  100
2944  """
2945  ctx = _get_ctx(ctx)
2946  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2947 
2948 def RealVal(val, ctx=None):
2949  """Return a Z3 real value.
2950 
2951  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2952  If `ctx=None`, then the global context is used.
2953 
2954  >>> RealVal(1)
2955  1
2956  >>> RealVal(1).sort()
2957  Real
2958  >>> RealVal("3/5")
2959  3/5
2960  >>> RealVal("1.5")
2961  3/2
2962  """
2963  ctx = _get_ctx(ctx)
2964  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2965 
2966 def RatVal(a, b, ctx=None):
2967  """Return a Z3 rational a/b.
2968 
2969  If `ctx=None`, then the global context is used.
2970 
2971  >>> RatVal(3,5)
2972  3/5
2973  >>> RatVal(3,5).sort()
2974  Real
2975  """
2976  if z3_debug():
2977  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2978  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2979  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2980 
2981 def Q(a, b, ctx=None):
2982  """Return a Z3 rational a/b.
2983 
2984  If `ctx=None`, then the global context is used.
2985 
2986  >>> Q(3,5)
2987  3/5
2988  >>> Q(3,5).sort()
2989  Real
2990  """
2991  return simplify(RatVal(a, b))
2992 
2993 def Int(name, ctx=None):
2994  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2995 
2996  >>> x = Int('x')
2997  >>> is_int(x)
2998  True
2999  >>> is_int(x + 1)
3000  True
3001  """
3002  ctx = _get_ctx(ctx)
3003  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3004 
3005 def Ints(names, ctx=None):
3006  """Return a tuple of Integer constants.
3007 
3008  >>> x, y, z = Ints('x y z')
3009  >>> Sum(x, y, z)
3010  x + y + z
3011  """
3012  ctx = _get_ctx(ctx)
3013  if isinstance(names, str):
3014  names = names.split(" ")
3015  return [Int(name, ctx) for name in names]
3016 
3017 def IntVector(prefix, sz, ctx=None):
3018  """Return a list of integer constants of size `sz`.
3019 
3020  >>> X = IntVector('x', 3)
3021  >>> X
3022  [x__0, x__1, x__2]
3023  >>> Sum(X)
3024  x__0 + x__1 + x__2
3025  """
3026  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
3027 
3028 def FreshInt(prefix='x', ctx=None):
3029  """Return a fresh integer constant in the given context using the given prefix.
3030 
3031  >>> x = FreshInt()
3032  >>> y = FreshInt()
3033  >>> eq(x, y)
3034  False
3035  >>> x.sort()
3036  Int
3037  """
3038  ctx = _get_ctx(ctx)
3039  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3040 
3041 def Real(name, ctx=None):
3042  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3043 
3044  >>> x = Real('x')
3045  >>> is_real(x)
3046  True
3047  >>> is_real(x + 1)
3048  True
3049  """
3050  ctx = _get_ctx(ctx)
3051  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3052 
3053 def Reals(names, ctx=None):
3054  """Return a tuple of real constants.
3055 
3056  >>> x, y, z = Reals('x y z')
3057  >>> Sum(x, y, z)
3058  x + y + z
3059  >>> Sum(x, y, z).sort()
3060  Real
3061  """
3062  ctx = _get_ctx(ctx)
3063  if isinstance(names, str):
3064  names = names.split(" ")
3065  return [Real(name, ctx) for name in names]
3066 
3067 def RealVector(prefix, sz, ctx=None):
3068  """Return a list of real constants of size `sz`.
3069 
3070  >>> X = RealVector('x', 3)
3071  >>> X
3072  [x__0, x__1, x__2]
3073  >>> Sum(X)
3074  x__0 + x__1 + x__2
3075  >>> Sum(X).sort()
3076  Real
3077  """
3078  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
3079 
3080 def FreshReal(prefix='b', ctx=None):
3081  """Return a fresh real constant in the given context using the given prefix.
3082 
3083  >>> x = FreshReal()
3084  >>> y = FreshReal()
3085  >>> eq(x, y)
3086  False
3087  >>> x.sort()
3088  Real
3089  """
3090  ctx = _get_ctx(ctx)
3091  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3092 
3093 def ToReal(a):
3094  """ Return the Z3 expression ToReal(a).
3095 
3096  >>> x = Int('x')
3097  >>> x.sort()
3098  Int
3099  >>> n = ToReal(x)
3100  >>> n
3101  ToReal(x)
3102  >>> n.sort()
3103  Real
3104  """
3105  if z3_debug():
3106  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3107  ctx = a.ctx
3108  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3109 
3110 def ToInt(a):
3111  """ Return the Z3 expression ToInt(a).
3112 
3113  >>> x = Real('x')
3114  >>> x.sort()
3115  Real
3116  >>> n = ToInt(x)
3117  >>> n
3118  ToInt(x)
3119  >>> n.sort()
3120  Int
3121  """
3122  if z3_debug():
3123  _z3_assert(a.is_real(), "Z3 real expression expected.")
3124  ctx = a.ctx
3125  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3126 
3127 def IsInt(a):
3128  """ Return the Z3 predicate IsInt(a).
3129 
3130  >>> x = Real('x')
3131  >>> IsInt(x + "1/2")
3132  IsInt(x + 1/2)
3133  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3134  [x = 1/2]
3135  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3136  no solution
3137  """
3138  if z3_debug():
3139  _z3_assert(a.is_real(), "Z3 real expression expected.")
3140  ctx = a.ctx
3141  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3142 
3143 def Sqrt(a, ctx=None):
3144  """ Return a Z3 expression which represents the square root of a.
3145 
3146  >>> x = Real('x')
3147  >>> Sqrt(x)
3148  x**(1/2)
3149  """
3150  if not is_expr(a):
3151  ctx = _get_ctx(ctx)
3152  a = RealVal(a, ctx)
3153  return a ** "1/2"
3154 
3155 def Cbrt(a, ctx=None):
3156  """ Return a Z3 expression which represents the cubic root of a.
3157 
3158  >>> x = Real('x')
3159  >>> Cbrt(x)
3160  x**(1/3)
3161  """
3162  if not is_expr(a):
3163  ctx = _get_ctx(ctx)
3164  a = RealVal(a, ctx)
3165  return a ** "1/3"
3166 
3167 #########################################
3168 #
3169 # Bit-Vectors
3170 #
3171 #########################################
3172 
3173 class BitVecSortRef(SortRef):
3174  """Bit-vector sort."""
3175 
3176  def size(self):
3177  """Return the size (number of bits) of the bit-vector sort `self`.
3178 
3179  >>> b = BitVecSort(32)
3180  >>> b.size()
3181  32
3182  """
3183  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3184 
3185  def subsort(self, other):
3186  return is_bv_sort(other) and self.size() < other.size()
3187 
3188  def cast(self, val):
3189  """Try to cast `val` as a Bit-Vector.
3190 
3191  >>> b = BitVecSort(32)
3192  >>> b.cast(10)
3193  10
3194  >>> b.cast(10).sexpr()
3195  '#x0000000a'
3196  """
3197  if is_expr(val):
3198  if z3_debug():
3199  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3200  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3201  return val
3202  else:
3203  return BitVecVal(val, self)
3204 
3205 def is_bv_sort(s):
3206  """Return True if `s` is a Z3 bit-vector sort.
3207 
3208  >>> is_bv_sort(BitVecSort(32))
3209  True
3210  >>> is_bv_sort(IntSort())
3211  False
3212  """
3213  return isinstance(s, BitVecSortRef)
3214 
3215 class BitVecRef(ExprRef):
3216  """Bit-vector expressions."""
3217 
3218  def sort(self):
3219  """Return the sort of the bit-vector expression `self`.
3220 
3221  >>> x = BitVec('x', 32)
3222  >>> x.sort()
3223  BitVec(32)
3224  >>> x.sort() == BitVecSort(32)
3225  True
3226  """
3227  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3228 
3229  def size(self):
3230  """Return the number of bits of the bit-vector expression `self`.
3231 
3232  >>> x = BitVec('x', 32)
3233  >>> (x + 1).size()
3234  32
3235  >>> Concat(x, x).size()
3236  64
3237  """
3238  return self.sort().size()
3239 
3240  def __add__(self, other):
3241  """Create the Z3 expression `self + other`.
3242 
3243  >>> x = BitVec('x', 32)
3244  >>> y = BitVec('y', 32)
3245  >>> x + y
3246  x + y
3247  >>> (x + y).sort()
3248  BitVec(32)
3249  """
3250  a, b = _coerce_exprs(self, other)
3251  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3252 
3253  def __radd__(self, other):
3254  """Create the Z3 expression `other + self`.
3255 
3256  >>> x = BitVec('x', 32)
3257  >>> 10 + x
3258  10 + x
3259  """
3260  a, b = _coerce_exprs(self, other)
3261  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3262 
3263  def __mul__(self, other):
3264  """Create the Z3 expression `self * other`.
3265 
3266  >>> x = BitVec('x', 32)
3267  >>> y = BitVec('y', 32)
3268  >>> x * y
3269  x*y
3270  >>> (x * y).sort()
3271  BitVec(32)
3272  """
3273  a, b = _coerce_exprs(self, other)
3274  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3275 
3276  def __rmul__(self, other):
3277  """Create the Z3 expression `other * self`.
3278 
3279  >>> x = BitVec('x', 32)
3280  >>> 10 * x
3281  10*x
3282  """
3283  a, b = _coerce_exprs(self, other)
3284  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3285 
3286  def __sub__(self, other):
3287  """Create the Z3 expression `self - other`.
3288 
3289  >>> x = BitVec('x', 32)
3290  >>> y = BitVec('y', 32)
3291  >>> x - y
3292  x - y
3293  >>> (x - y).sort()
3294  BitVec(32)
3295  """
3296  a, b = _coerce_exprs(self, other)
3297  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3298 
3299  def __rsub__(self, other):
3300  """Create the Z3 expression `other - self`.
3301 
3302  >>> x = BitVec('x', 32)
3303  >>> 10 - x
3304  10 - x
3305  """
3306  a, b = _coerce_exprs(self, other)
3307  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3308 
3309  def __or__(self, other):
3310  """Create the Z3 expression bitwise-or `self | other`.
3311 
3312  >>> x = BitVec('x', 32)
3313  >>> y = BitVec('y', 32)
3314  >>> x | y
3315  x | y
3316  >>> (x | y).sort()
3317  BitVec(32)
3318  """
3319  a, b = _coerce_exprs(self, other)
3320  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3321 
3322  def __ror__(self, other):
3323  """Create the Z3 expression bitwise-or `other | self`.
3324 
3325  >>> x = BitVec('x', 32)
3326  >>> 10 | x
3327  10 | x
3328  """
3329  a, b = _coerce_exprs(self, other)
3330  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3331 
3332  def __and__(self, other):
3333  """Create the Z3 expression bitwise-and `self & other`.
3334 
3335  >>> x = BitVec('x', 32)
3336  >>> y = BitVec('y', 32)
3337  >>> x & y
3338  x & y
3339  >>> (x & y).sort()
3340  BitVec(32)
3341  """
3342  a, b = _coerce_exprs(self, other)
3343  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3344 
3345  def __rand__(self, other):
3346  """Create the Z3 expression bitwise-or `other & self`.
3347 
3348  >>> x = BitVec('x', 32)
3349  >>> 10 & x
3350  10 & x
3351  """
3352  a, b = _coerce_exprs(self, other)
3353  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3354 
3355  def __xor__(self, other):
3356  """Create the Z3 expression bitwise-xor `self ^ other`.
3357 
3358  >>> x = BitVec('x', 32)
3359  >>> y = BitVec('y', 32)
3360  >>> x ^ y
3361  x ^ y
3362  >>> (x ^ y).sort()
3363  BitVec(32)
3364  """
3365  a, b = _coerce_exprs(self, other)
3366  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3367 
3368  def __rxor__(self, other):
3369  """Create the Z3 expression bitwise-xor `other ^ self`.
3370 
3371  >>> x = BitVec('x', 32)
3372  >>> 10 ^ x
3373  10 ^ x
3374  """
3375  a, b = _coerce_exprs(self, other)
3376  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3377 
3378  def __pos__(self):
3379  """Return `self`.
3380 
3381  >>> x = BitVec('x', 32)
3382  >>> +x
3383  x
3384  """
3385  return self
3386 
3387  def __neg__(self):
3388  """Return an expression representing `-self`.
3389 
3390  >>> x = BitVec('x', 32)
3391  >>> -x
3392  -x
3393  >>> simplify(-(-x))
3394  x
3395  """
3396  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3397 
3398  def __invert__(self):
3399  """Create the Z3 expression bitwise-not `~self`.
3400 
3401  >>> x = BitVec('x', 32)
3402  >>> ~x
3403  ~x
3404  >>> simplify(~(~x))
3405  x
3406  """
3407  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3408 
3409  def __div__(self, other):
3410  """Create the Z3 expression (signed) division `self / other`.
3411 
3412  Use the function UDiv() for unsigned division.
3413 
3414  >>> x = BitVec('x', 32)
3415  >>> y = BitVec('y', 32)
3416  >>> x / y
3417  x/y
3418  >>> (x / y).sort()
3419  BitVec(32)
3420  >>> (x / y).sexpr()
3421  '(bvsdiv x y)'
3422  >>> UDiv(x, y).sexpr()
3423  '(bvudiv x y)'
3424  """
3425  a, b = _coerce_exprs(self, other)
3426  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3427 
3428  def __truediv__(self, other):
3429  """Create the Z3 expression (signed) division `self / other`."""
3430  return self.__div__(other)
3431 
3432  def __rdiv__(self, other):
3433  """Create the Z3 expression (signed) division `other / self`.
3434 
3435  Use the function UDiv() for unsigned division.
3436 
3437  >>> x = BitVec('x', 32)
3438  >>> 10 / x
3439  10/x
3440  >>> (10 / x).sexpr()
3441  '(bvsdiv #x0000000a x)'
3442  >>> UDiv(10, x).sexpr()
3443  '(bvudiv #x0000000a x)'
3444  """
3445  a, b = _coerce_exprs(self, other)
3446  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3447 
3448  def __rtruediv__(self, other):
3449  """Create the Z3 expression (signed) division `other / self`."""
3450  return self.__rdiv__(other)
3451 
3452  def __mod__(self, other):
3453  """Create the Z3 expression (signed) mod `self % other`.
3454 
3455  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3456 
3457  >>> x = BitVec('x', 32)
3458  >>> y = BitVec('y', 32)
3459  >>> x % y
3460  x%y
3461  >>> (x % y).sort()
3462  BitVec(32)
3463  >>> (x % y).sexpr()
3464  '(bvsmod x y)'
3465  >>> URem(x, y).sexpr()
3466  '(bvurem x y)'
3467  >>> SRem(x, y).sexpr()
3468  '(bvsrem x y)'
3469  """
3470  a, b = _coerce_exprs(self, other)
3471  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3472 
3473  def __rmod__(self, other):
3474  """Create the Z3 expression (signed) mod `other % self`.
3475 
3476  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3477 
3478  >>> x = BitVec('x', 32)
3479  >>> 10 % x
3480  10%x
3481  >>> (10 % x).sexpr()
3482  '(bvsmod #x0000000a x)'
3483  >>> URem(10, x).sexpr()
3484  '(bvurem #x0000000a x)'
3485  >>> SRem(10, x).sexpr()
3486  '(bvsrem #x0000000a x)'
3487  """
3488  a, b = _coerce_exprs(self, other)
3489  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3490 
3491  def __le__(self, other):
3492  """Create the Z3 expression (signed) `other <= self`.
3493 
3494  Use the function ULE() for unsigned less than or equal to.
3495 
3496  >>> x, y = BitVecs('x y', 32)
3497  >>> x <= y
3498  x <= y
3499  >>> (x <= y).sexpr()
3500  '(bvsle x y)'
3501  >>> ULE(x, y).sexpr()
3502  '(bvule x y)'
3503  """
3504  a, b = _coerce_exprs(self, other)
3505  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3506 
3507  def __lt__(self, other):
3508  """Create the Z3 expression (signed) `other < self`.
3509 
3510  Use the function ULT() for unsigned less than.
3511 
3512  >>> x, y = BitVecs('x y', 32)
3513  >>> x < y
3514  x < y
3515  >>> (x < y).sexpr()
3516  '(bvslt x y)'
3517  >>> ULT(x, y).sexpr()
3518  '(bvult x y)'
3519  """
3520  a, b = _coerce_exprs(self, other)
3521  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3522 
3523  def __gt__(self, other):
3524  """Create the Z3 expression (signed) `other > self`.
3525 
3526  Use the function UGT() for unsigned greater than.
3527 
3528  >>> x, y = BitVecs('x y', 32)
3529  >>> x > y
3530  x > y
3531  >>> (x > y).sexpr()
3532  '(bvsgt x y)'
3533  >>> UGT(x, y).sexpr()
3534  '(bvugt x y)'
3535  """
3536  a, b = _coerce_exprs(self, other)
3537  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3538 
3539  def __ge__(self, other):
3540  """Create the Z3 expression (signed) `other >= self`.
3541 
3542  Use the function UGE() for unsigned greater than or equal to.
3543 
3544  >>> x, y = BitVecs('x y', 32)
3545  >>> x >= y
3546  x >= y
3547  >>> (x >= y).sexpr()
3548  '(bvsge x y)'
3549  >>> UGE(x, y).sexpr()
3550  '(bvuge x y)'
3551  """
3552  a, b = _coerce_exprs(self, other)
3553  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3554 
3555  def __rshift__(self, other):
3556  """Create the Z3 expression (arithmetical) right shift `self >> other`
3557 
3558  Use the function LShR() for the right logical shift
3559 
3560  >>> x, y = BitVecs('x y', 32)
3561  >>> x >> y
3562  x >> y
3563  >>> (x >> y).sexpr()
3564  '(bvashr x y)'
3565  >>> LShR(x, y).sexpr()
3566  '(bvlshr x y)'
3567  >>> BitVecVal(4, 3)
3568  4
3569  >>> BitVecVal(4, 3).as_signed_long()
3570  -4
3571  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3572  -2
3573  >>> simplify(BitVecVal(4, 3) >> 1)
3574  6
3575  >>> simplify(LShR(BitVecVal(4, 3), 1))
3576  2
3577  >>> simplify(BitVecVal(2, 3) >> 1)
3578  1
3579  >>> simplify(LShR(BitVecVal(2, 3), 1))
3580  1
3581  """
3582  a, b = _coerce_exprs(self, other)
3583  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3584 
3585  def __lshift__(self, other):
3586  """Create the Z3 expression left shift `self << other`
3587 
3588  >>> x, y = BitVecs('x y', 32)
3589  >>> x << y
3590  x << y
3591  >>> (x << y).sexpr()
3592  '(bvshl x y)'
3593  >>> simplify(BitVecVal(2, 3) << 1)
3594  4
3595  """
3596  a, b = _coerce_exprs(self, other)
3597  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3598 
3599  def __rrshift__(self, other):
3600  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3601 
3602  Use the function LShR() for the right logical shift
3603 
3604  >>> x = BitVec('x', 32)
3605  >>> 10 >> x
3606  10 >> x
3607  >>> (10 >> x).sexpr()
3608  '(bvashr #x0000000a x)'
3609  """
3610  a, b = _coerce_exprs(self, other)
3611  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3612 
3613  def __rlshift__(self, other):
3614  """Create the Z3 expression left shift `other << self`.
3615 
3616  Use the function LShR() for the right logical shift
3617 
3618  >>> x = BitVec('x', 32)
3619  >>> 10 << x
3620  10 << x
3621  >>> (10 << x).sexpr()
3622  '(bvshl #x0000000a x)'
3623  """
3624  a, b = _coerce_exprs(self, other)
3625  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3626 
3627 class BitVecNumRef(BitVecRef):
3628  """Bit-vector values."""
3629 
3630  def as_long(self):
3631  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3632 
3633  >>> v = BitVecVal(0xbadc0de, 32)
3634  >>> v
3635  195936478
3636  >>> print("0x%.8x" % v.as_long())
3637  0x0badc0de
3638  """
3639  return int(self.as_string())
3640 
3641  def as_signed_long(self):
3642  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3643 
3644  >>> BitVecVal(4, 3).as_signed_long()
3645  -4
3646  >>> BitVecVal(7, 3).as_signed_long()
3647  -1
3648  >>> BitVecVal(3, 3).as_signed_long()
3649  3
3650  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3651  -1
3652  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3653  -1
3654  """
3655  sz = self.size()
3656  val = self.as_long()
3657  if val >= 2**(sz - 1):
3658  val = val - 2**sz
3659  if val < -2**(sz - 1):
3660  val = val + 2**sz
3661  return int(val)
3662 
3663  def as_string(self):
3664  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3665 
3666 def is_bv(a):
3667  """Return `True` if `a` is a Z3 bit-vector expression.
3668 
3669  >>> b = BitVec('b', 32)
3670  >>> is_bv(b)
3671  True
3672  >>> is_bv(b + 10)
3673  True
3674  >>> is_bv(Int('x'))
3675  False
3676  """
3677  return isinstance(a, BitVecRef)
3678 
3679 def is_bv_value(a):
3680  """Return `True` if `a` is a Z3 bit-vector numeral value.
3681 
3682  >>> b = BitVec('b', 32)
3683  >>> is_bv_value(b)
3684  False
3685  >>> b = BitVecVal(10, 32)
3686  >>> b
3687  10
3688  >>> is_bv_value(b)
3689  True
3690  """
3691  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3692 
3693 def BV2Int(a, is_signed=False):
3694  """Return the Z3 expression BV2Int(a).
3695 
3696  >>> b = BitVec('b', 3)
3697  >>> BV2Int(b).sort()
3698  Int
3699  >>> x = Int('x')
3700  >>> x > BV2Int(b)
3701  x > BV2Int(b)
3702  >>> x > BV2Int(b, is_signed=False)
3703  x > BV2Int(b)
3704  >>> x > BV2Int(b, is_signed=True)
3705  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3706  >>> solve(x > BV2Int(b), b == 1, x < 3)
3707  [x = 2, b = 1]
3708  """
3709  if z3_debug():
3710  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3711  ctx = a.ctx
3712  ## investigate problem with bv2int
3713  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3714 
3715 def Int2BV(a, num_bits):
3716  """Return the z3 expression Int2BV(a, num_bits).
3717  It is a bit-vector of width num_bits and represents the
3718  modulo of a by 2^num_bits
3719  """
3720  ctx = a.ctx
3721  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3722 
3723 def BitVecSort(sz, ctx=None):
3724  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3725 
3726  >>> Byte = BitVecSort(8)
3727  >>> Word = BitVecSort(16)
3728  >>> Byte
3729  BitVec(8)
3730  >>> x = Const('x', Byte)
3731  >>> eq(x, BitVec('x', 8))
3732  True
3733  """
3734  ctx = _get_ctx(ctx)
3735  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3736 
3737 def BitVecVal(val, bv, ctx=None):
3738  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3739 
3740  >>> v = BitVecVal(10, 32)
3741  >>> v
3742  10
3743  >>> print("0x%.8x" % v.as_long())
3744  0x0000000a
3745  """
3746  if is_bv_sort(bv):
3747  ctx = bv.ctx
3748  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3749  else:
3750  ctx = _get_ctx(ctx)
3751  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3752 
3753 def BitVec(name, bv, ctx=None):
3754  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3755  If `ctx=None`, then the global context is used.
3756 
3757  >>> x = BitVec('x', 16)
3758  >>> is_bv(x)
3759  True
3760  >>> x.size()
3761  16
3762  >>> x.sort()
3763  BitVec(16)
3764  >>> word = BitVecSort(16)
3765  >>> x2 = BitVec('x', word)
3766  >>> eq(x, x2)
3767  True
3768  """
3769  if isinstance(bv, BitVecSortRef):
3770  ctx = bv.ctx
3771  else:
3772  ctx = _get_ctx(ctx)
3773  bv = BitVecSort(bv, ctx)
3774  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3775 
3776 def BitVecs(names, bv, ctx=None):
3777  """Return a tuple of bit-vector constants of size bv.
3778 
3779  >>> x, y, z = BitVecs('x y z', 16)
3780  >>> x.size()
3781  16
3782  >>> x.sort()
3783  BitVec(16)
3784  >>> Sum(x, y, z)
3785  0 + x + y + z
3786  >>> Product(x, y, z)
3787  1*x*y*z
3788  >>> simplify(Product(x, y, z))
3789  x*y*z
3790  """
3791  ctx = _get_ctx(ctx)
3792  if isinstance(names, str):
3793  names = names.split(" ")
3794  return [BitVec(name, bv, ctx) for name in names]
3795 
3796 def Concat(*args):
3797  """Create a Z3 bit-vector concatenation expression.
3798 
3799  >>> v = BitVecVal(1, 4)
3800  >>> Concat(v, v+1, v)
3801  Concat(Concat(1, 1 + 1), 1)
3802  >>> simplify(Concat(v, v+1, v))
3803  289
3804  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3805  121
3806  """
3807  args = _get_args(args)
3808  sz = len(args)
3809  if z3_debug():
3810  _z3_assert(sz >= 2, "At least two arguments expected.")
3811 
3812  ctx = None
3813  for a in args:
3814  if is_expr(a):
3815  ctx = a.ctx
3816  break
3817  if is_seq(args[0]) or isinstance(args[0], str):
3818  args = [_coerce_seq(s, ctx) for s in args]
3819  if z3_debug():
3820  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3821  v = (Ast * sz)()
3822  for i in range(sz):
3823  v[i] = args[i].as_ast()
3824  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3825 
3826  if is_re(args[0]):
3827  if z3_debug():
3828  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3829  v = (Ast * sz)()
3830  for i in range(sz):
3831  v[i] = args[i].as_ast()
3832  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3833 
3834  if z3_debug():
3835  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3836  r = args[0]
3837  for i in range(sz - 1):
3838  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3839  return r
3840 
3841 def Extract(high, low, a):
3842  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3843 
3844  >>> x = BitVec('x', 8)
3845  >>> Extract(6, 2, x)
3846  Extract(6, 2, x)
3847  >>> Extract(6, 2, x).sort()
3848  BitVec(5)
3849  >>> simplify(Extract(StringVal("abcd"),2,1))
3850  "c"
3851  """
3852  if isinstance(high, str):
3853  high = StringVal(high)
3854  if is_seq(high):
3855  s = high
3856  offset, length = _coerce_exprs(low, a, s.ctx)
3857  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3858  if z3_debug():
3859  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3860  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3861  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3862  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3863 
3864 def _check_bv_args(a, b):
3865  if z3_debug():
3866  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3867 
3868 def ULE(a, b):
3869  """Create the Z3 expression (unsigned) `other <= self`.
3870 
3871  Use the operator <= for signed less than or equal to.
3872 
3873  >>> x, y = BitVecs('x y', 32)
3874  >>> ULE(x, y)
3875  ULE(x, y)
3876  >>> (x <= y).sexpr()
3877  '(bvsle x y)'
3878  >>> ULE(x, y).sexpr()
3879  '(bvule x y)'
3880  """
3881  _check_bv_args(a, b)
3882  a, b = _coerce_exprs(a, b)
3883  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3884 
3885 def ULT(a, b):
3886  """Create the Z3 expression (unsigned) `other < self`.
3887 
3888  Use the operator < for signed less than.
3889 
3890  >>> x, y = BitVecs('x y', 32)
3891  >>> ULT(x, y)
3892  ULT(x, y)
3893  >>> (x < y).sexpr()
3894  '(bvslt x y)'
3895  >>> ULT(x, y).sexpr()
3896  '(bvult x y)'
3897  """
3898  _check_bv_args(a, b)
3899  a, b = _coerce_exprs(a, b)
3900  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3901 
3902 def UGE(a, b):
3903  """Create the Z3 expression (unsigned) `other >= self`.
3904 
3905  Use the operator >= for signed greater than or equal to.
3906 
3907  >>> x, y = BitVecs('x y', 32)
3908  >>> UGE(x, y)
3909  UGE(x, y)
3910  >>> (x >= y).sexpr()
3911  '(bvsge x y)'
3912  >>> UGE(x, y).sexpr()
3913  '(bvuge x y)'
3914  """
3915  _check_bv_args(a, b)
3916  a, b = _coerce_exprs(a, b)
3917  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3918 
3919 def UGT(a, b):
3920  """Create the Z3 expression (unsigned) `other > self`.
3921 
3922  Use the operator > for signed greater than.
3923 
3924  >>> x, y = BitVecs('x y', 32)
3925  >>> UGT(x, y)
3926  UGT(x, y)
3927  >>> (x > y).sexpr()
3928  '(bvsgt x y)'
3929  >>> UGT(x, y).sexpr()
3930  '(bvugt x y)'
3931  """
3932  _check_bv_args(a, b)
3933  a, b = _coerce_exprs(a, b)
3934  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3935 
3936 def UDiv(a, b):
3937  """Create the Z3 expression (unsigned) division `self / other`.
3938 
3939  Use the operator / for signed division.
3940 
3941  >>> x = BitVec('x', 32)
3942  >>> y = BitVec('y', 32)
3943  >>> UDiv(x, y)
3944  UDiv(x, y)
3945  >>> UDiv(x, y).sort()
3946  BitVec(32)
3947  >>> (x / y).sexpr()
3948  '(bvsdiv x y)'
3949  >>> UDiv(x, y).sexpr()
3950  '(bvudiv x y)'
3951  """
3952  _check_bv_args(a, b)
3953  a, b = _coerce_exprs(a, b)
3954  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3955 
3956 def URem(a, b):
3957  """Create the Z3 expression (unsigned) remainder `self % other`.
3958 
3959  Use the operator % for signed modulus, and SRem() for signed remainder.
3960 
3961  >>> x = BitVec('x', 32)
3962  >>> y = BitVec('y', 32)
3963  >>> URem(x, y)
3964  URem(x, y)
3965  >>> URem(x, y).sort()
3966  BitVec(32)
3967  >>> (x % y).sexpr()
3968  '(bvsmod x y)'
3969  >>> URem(x, y).sexpr()
3970  '(bvurem x y)'
3971  """
3972  _check_bv_args(a, b)
3973  a, b = _coerce_exprs(a, b)
3974  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3975 
3976 def SRem(a, b):
3977  """Create the Z3 expression signed remainder.
3978 
3979  Use the operator % for signed modulus, and URem() for unsigned remainder.
3980 
3981  >>> x = BitVec('x', 32)
3982  >>> y = BitVec('y', 32)
3983  >>> SRem(x, y)
3984  SRem(x, y)
3985  >>> SRem(x, y).sort()
3986  BitVec(32)
3987  >>> (x % y).sexpr()
3988  '(bvsmod x y)'
3989  >>> SRem(x, y).sexpr()
3990  '(bvsrem x y)'
3991  """
3992  _check_bv_args(a, b)
3993  a, b = _coerce_exprs(a, b)
3994  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3995 
3996 def LShR(a, b):
3997  """Create the Z3 expression logical right shift.
3998 
3999  Use the operator >> for the arithmetical right shift.
4000 
4001  >>> x, y = BitVecs('x y', 32)
4002  >>> LShR(x, y)
4003  LShR(x, y)
4004  >>> (x >> y).sexpr()
4005  '(bvashr x y)'
4006  >>> LShR(x, y).sexpr()
4007  '(bvlshr x y)'
4008  >>> BitVecVal(4, 3)
4009  4
4010  >>> BitVecVal(4, 3).as_signed_long()
4011  -4
4012  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4013  -2
4014  >>> simplify(BitVecVal(4, 3) >> 1)
4015  6
4016  >>> simplify(LShR(BitVecVal(4, 3), 1))
4017  2
4018  >>> simplify(BitVecVal(2, 3) >> 1)
4019  1
4020  >>> simplify(LShR(BitVecVal(2, 3), 1))
4021  1
4022  """
4023  _check_bv_args(a, b)
4024  a, b = _coerce_exprs(a, b)
4025  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4026 
4027 def RotateLeft(a, b):
4028  """Return an expression representing `a` rotated to the left `b` times.
4029 
4030  >>> a, b = BitVecs('a b', 16)
4031  >>> RotateLeft(a, b)
4032  RotateLeft(a, b)
4033  >>> simplify(RotateLeft(a, 0))
4034  a
4035  >>> simplify(RotateLeft(a, 16))
4036  a
4037  """
4038  _check_bv_args(a, b)
4039  a, b = _coerce_exprs(a, b)
4040  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4041 
4042 def RotateRight(a, b):
4043  """Return an expression representing `a` rotated to the right `b` times.
4044 
4045  >>> a, b = BitVecs('a b', 16)
4046  >>> RotateRight(a, b)
4047  RotateRight(a, b)
4048  >>> simplify(RotateRight(a, 0))
4049  a
4050  >>> simplify(RotateRight(a, 16))
4051  a
4052  """
4053  _check_bv_args(a, b)
4054  a, b = _coerce_exprs(a, b)
4055  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4056 
4057 def SignExt(n, a):
4058  """Return a bit-vector expression with `n` extra sign-bits.
4059 
4060  >>> x = BitVec('x', 16)
4061  >>> n = SignExt(8, x)
4062  >>> n.size()
4063  24
4064  >>> n
4065  SignExt(8, x)
4066  >>> n.sort()
4067  BitVec(24)
4068  >>> v0 = BitVecVal(2, 2)
4069  >>> v0
4070  2
4071  >>> v0.size()
4072  2
4073  >>> v = simplify(SignExt(6, v0))
4074  >>> v
4075  254
4076  >>> v.size()
4077  8
4078  >>> print("%.x" % v.as_long())
4079  fe
4080  """
4081  if z3_debug():
4082  _z3_assert(_is_int(n), "First argument must be an integer")
4083  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4084  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4085 
4086 def ZeroExt(n, a):
4087  """Return a bit-vector expression with `n` extra zero-bits.
4088 
4089  >>> x = BitVec('x', 16)
4090  >>> n = ZeroExt(8, x)
4091  >>> n.size()
4092  24
4093  >>> n
4094  ZeroExt(8, x)
4095  >>> n.sort()
4096  BitVec(24)
4097  >>> v0 = BitVecVal(2, 2)
4098  >>> v0
4099  2
4100  >>> v0.size()
4101  2
4102  >>> v = simplify(ZeroExt(6, v0))
4103  >>> v
4104  2
4105  >>> v.size()
4106  8
4107  """
4108  if z3_debug():
4109  _z3_assert(_is_int(n), "First argument must be an integer")
4110  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4111  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4112 
4113 def RepeatBitVec(n, a):
4114  """Return an expression representing `n` copies of `a`.
4115 
4116  >>> x = BitVec('x', 8)
4117  >>> n = RepeatBitVec(4, x)
4118  >>> n
4119  RepeatBitVec(4, x)
4120  >>> n.size()
4121  32
4122  >>> v0 = BitVecVal(10, 4)
4123  >>> print("%.x" % v0.as_long())
4124  a
4125  >>> v = simplify(RepeatBitVec(4, v0))
4126  >>> v.size()
4127  16
4128  >>> print("%.x" % v.as_long())
4129  aaaa
4130  """
4131  if z3_debug():
4132  _z3_assert(_is_int(n), "First argument must be an integer")
4133  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4134  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4135 
4136 def BVRedAnd(a):
4137  """Return the reduction-and expression of `a`."""
4138  if z3_debug():
4139  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4140  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4141 
4142 def BVRedOr(a):
4143  """Return the reduction-or expression of `a`."""
4144  if z3_debug():
4145  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4146  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4147 
4148 def BVAddNoOverflow(a, b, signed):
4149  """A predicate the determines that bit-vector addition does not overflow"""
4150  _check_bv_args(a, b)
4151  a, b = _coerce_exprs(a, b)
4152  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4153 
4154 def BVAddNoUnderflow(a, b):
4155  """A predicate the determines that signed bit-vector addition does not underflow"""
4156  _check_bv_args(a, b)
4157  a, b = _coerce_exprs(a, b)
4158  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4159 
4160 def BVSubNoOverflow(a, b):
4161  """A predicate the determines that bit-vector subtraction does not overflow"""
4162  _check_bv_args(a, b)
4163  a, b = _coerce_exprs(a, b)
4164  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4165 
4166 
4167 def BVSubNoUnderflow(a, b, signed):
4168  """A predicate the determines that bit-vector subtraction does not underflow"""
4169  _check_bv_args(a, b)
4170  a, b = _coerce_exprs(a, b)
4171  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4172 
4173 def BVSDivNoOverflow(a, b):
4174  """A predicate the determines that bit-vector signed division does not overflow"""
4175  _check_bv_args(a, b)
4176  a, b = _coerce_exprs(a, b)
4177  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4178 
4179 def BVSNegNoOverflow(a):
4180  """A predicate the determines that bit-vector unary negation does not overflow"""
4181  if z3_debug():
4182  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4183  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4184 
4185 def BVMulNoOverflow(a, b, signed):
4186  """A predicate the determines that bit-vector multiplication does not overflow"""
4187  _check_bv_args(a, b)
4188  a, b = _coerce_exprs(a, b)
4189  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4190 
4191 
4192 def BVMulNoUnderflow(a, b):
4193  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4194  _check_bv_args(a, b)
4195  a, b = _coerce_exprs(a, b)
4196  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4197 
4198 
4199 
4200 #########################################
4201 #
4202 # Arrays
4203 #
4204 #########################################
4205 
4206 class ArraySortRef(SortRef):
4207  """Array sorts."""
4208 
4209  def domain(self):
4210  """Return the domain of the array sort `self`.
4211 
4212  >>> A = ArraySort(IntSort(), BoolSort())
4213  >>> A.domain()
4214  Int
4215  """
4216  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4217 
4218  def range(self):
4219  """Return the range of the array sort `self`.
4220 
4221  >>> A = ArraySort(IntSort(), BoolSort())
4222  >>> A.range()
4223  Bool
4224  """
4225  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4226 
4227 class ArrayRef(ExprRef):
4228  """Array expressions. """
4229 
4230  def sort(self):
4231  """Return the array sort of the array expression `self`.
4232 
4233  >>> a = Array('a', IntSort(), BoolSort())
4234  >>> a.sort()
4235  Array(Int, Bool)
4236  """
4237  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4238 
4239  def domain(self):
4240  """Shorthand for `self.sort().domain()`.
4241 
4242  >>> a = Array('a', IntSort(), BoolSort())
4243  >>> a.domain()
4244  Int
4245  """
4246  return self.sort().domain()
4247 
4248  def range(self):
4249  """Shorthand for `self.sort().range()`.
4250 
4251  >>> a = Array('a', IntSort(), BoolSort())
4252  >>> a.range()
4253  Bool
4254  """
4255  return self.sort().range()
4256 
4257  def __getitem__(self, arg):
4258  """Return the Z3 expression `self[arg]`.
4259 
4260  >>> a = Array('a', IntSort(), BoolSort())
4261  >>> i = Int('i')
4262  >>> a[i]
4263  a[i]
4264  >>> a[i].sexpr()
4265  '(select a i)'
4266  """
4267  arg = self.domain().cast(arg)
4268  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4269 
4270  def default(self):
4271  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4272 
4273 
4274 def is_array(a):
4275  """Return `True` if `a` is a Z3 array expression.
4276 
4277  >>> a = Array('a', IntSort(), IntSort())
4278  >>> is_array(a)
4279  True
4280  >>> is_array(Store(a, 0, 1))
4281  True
4282  >>> is_array(a[0])
4283  False
4284  """
4285  return isinstance(a, ArrayRef)
4286 
4287 def is_const_array(a):
4288  """Return `True` if `a` is a Z3 constant array.
4289 
4290  >>> a = K(IntSort(), 10)
4291  >>> is_const_array(a)
4292  True
4293  >>> a = Array('a', IntSort(), IntSort())
4294  >>> is_const_array(a)
4295  False
4296  """
4297  return is_app_of(a, Z3_OP_CONST_ARRAY)
4298 
4299 def is_K(a):
4300  """Return `True` if `a` is a Z3 constant array.
4301 
4302  >>> a = K(IntSort(), 10)
4303  >>> is_K(a)
4304  True
4305  >>> a = Array('a', IntSort(), IntSort())
4306  >>> is_K(a)
4307  False
4308  """
4309  return is_app_of(a, Z3_OP_CONST_ARRAY)
4310 
4311 def is_map(a):
4312  """Return `True` if `a` is a Z3 map array expression.
4313 
4314  >>> f = Function('f', IntSort(), IntSort())
4315  >>> b = Array('b', IntSort(), IntSort())
4316  >>> a = Map(f, b)
4317  >>> a
4318  Map(f, b)
4319  >>> is_map(a)
4320  True
4321  >>> is_map(b)
4322  False
4323  """
4324  return is_app_of(a, Z3_OP_ARRAY_MAP)
4325 
4326 def is_default(a):
4327  """Return `True` if `a` is a Z3 default array expression.
4328  >>> d = Default(K(IntSort(), 10))
4329  >>> is_default(d)
4330  True
4331  """
4332  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4333 
4334 def get_map_func(a):
4335  """Return the function declaration associated with a Z3 map array expression.
4336 
4337  >>> f = Function('f', IntSort(), IntSort())
4338  >>> b = Array('b', IntSort(), IntSort())
4339  >>> a = Map(f, b)
4340  >>> eq(f, get_map_func(a))
4341  True
4342  >>> get_map_func(a)
4343  f
4344  >>> get_map_func(a)(0)
4345  f(0)
4346  """
4347  if z3_debug():
4348  _z3_assert(is_map(a), "Z3 array map expression expected.")
4349  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4350 
4351 def ArraySort(*sig):
4352  """Return the Z3 array sort with the given domain and range sorts.
4353 
4354  >>> A = ArraySort(IntSort(), BoolSort())
4355  >>> A
4356  Array(Int, Bool)
4357  >>> A.domain()
4358  Int
4359  >>> A.range()
4360  Bool
4361  >>> AA = ArraySort(IntSort(), A)
4362  >>> AA
4363  Array(Int, Array(Int, Bool))
4364  """
4365  sig = _get_args(sig)
4366  if z3_debug():
4367  _z3_assert(len(sig) > 1, "At least two arguments expected")
4368  arity = len(sig) - 1
4369  r = sig[arity]
4370  d = sig[0]
4371  if z3_debug():
4372  for s in sig:
4373  _z3_assert(is_sort(s), "Z3 sort expected")
4374  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4375  ctx = d.ctx
4376  if len(sig) == 2:
4377  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4378  dom = (Sort * arity)()
4379  for i in range(arity):
4380  dom[i] = sig[i].ast
4381  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4382 
4383 def Array(name, dom, rng):
4384  """Return an array constant named `name` with the given domain and range sorts.
4385 
4386  >>> a = Array('a', IntSort(), IntSort())
4387  >>> a.sort()
4388  Array(Int, Int)
4389  >>> a[0]
4390  a[0]
4391  """
4392  s = ArraySort(dom, rng)
4393  ctx = s.ctx
4394  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4395 
4396 def Update(a, i, v):
4397  """Return a Z3 store array expression.
4398 
4399  >>> a = Array('a', IntSort(), IntSort())
4400  >>> i, v = Ints('i v')
4401  >>> s = Update(a, i, v)
4402  >>> s.sort()
4403  Array(Int, Int)
4404  >>> prove(s[i] == v)
4405  proved
4406  >>> j = Int('j')
4407  >>> prove(Implies(i != j, s[j] == a[j]))
4408  proved
4409  """
4410  if z3_debug():
4411  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4412  i = a.domain().cast(i)
4413  v = a.range().cast(v)
4414  ctx = a.ctx
4415  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4416 
4417 def Default(a):
4418  """ Return a default value for array expression.
4419  >>> b = K(IntSort(), 1)
4420  >>> prove(Default(b) == 1)
4421  proved
4422  """
4423  if z3_debug():
4424  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4425  return a.default()
4426 
4427 
4428 def Store(a, i, v):
4429  """Return a Z3 store array expression.
4430 
4431  >>> a = Array('a', IntSort(), IntSort())
4432  >>> i, v = Ints('i v')
4433  >>> s = Store(a, i, v)
4434  >>> s.sort()
4435  Array(Int, Int)
4436  >>> prove(s[i] == v)
4437  proved
4438  >>> j = Int('j')
4439  >>> prove(Implies(i != j, s[j] == a[j]))
4440  proved
4441  """
4442  return Update(a, i, v)
4443 
4444 def Select(a, i):
4445  """Return a Z3 select array expression.
4446 
4447  >>> a = Array('a', IntSort(), IntSort())
4448  >>> i = Int('i')
4449  >>> Select(a, i)
4450  a[i]
4451  >>> eq(Select(a, i), a[i])
4452  True
4453  """
4454  if z3_debug():
4455  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4456  return a[i]
4457 
4458 
4459 def Map(f, *args):
4460  """Return a Z3 map array expression.
4461 
4462  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4463  >>> a1 = Array('a1', IntSort(), IntSort())
4464  >>> a2 = Array('a2', IntSort(), IntSort())
4465  >>> b = Map(f, a1, a2)
4466  >>> b
4467  Map(f, a1, a2)
4468  >>> prove(b[0] == f(a1[0], a2[0]))
4469  proved
4470  """
4471  args = _get_args(args)
4472  if z3_debug():
4473  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4474  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4475  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4476  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4477  _args, sz = _to_ast_array(args)
4478  ctx = f.ctx
4479  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4480 
4481 def K(dom, v):
4482  """Return a Z3 constant array expression.
4483 
4484  >>> a = K(IntSort(), 10)
4485  >>> a
4486  K(Int, 10)
4487  >>> a.sort()
4488  Array(Int, Int)
4489  >>> i = Int('i')
4490  >>> a[i]
4491  K(Int, 10)[i]
4492  >>> simplify(a[i])
4493  10
4494  """
4495  if z3_debug():
4496  _z3_assert(is_sort(dom), "Z3 sort expected")
4497  ctx = dom.ctx
4498  if not is_expr(v):
4499  v = _py2expr(v, ctx)
4500  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4501 
4502 def Ext(a, b):
4503  """Return extensionality index for one-dimensional arrays.
4504  >> a, b = Consts('a b', SetSort(IntSort()))
4505  >> Ext(a, b)
4506  Ext(a, b)
4507  """
4508  ctx = a.ctx
4509  if z3_debug():
4510  _z3_assert(is_array(a) and is_array(b), "arguments must be arrays")
4511  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4512 
4513 def SetHasSize(a, k):
4514  ctx = a.ctx
4515  k = _py2expr(k, ctx)
4516  return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4517 
4518 def is_select(a):
4519  """Return `True` if `a` is a Z3 array select application.
4520 
4521  >>> a = Array('a', IntSort(), IntSort())
4522  >>> is_select(a)
4523  False
4524  >>> i = Int('i')
4525  >>> is_select(a[i])
4526  True
4527  """
4528  return is_app_of(a, Z3_OP_SELECT)
4529 
4530 def is_store(a):
4531  """Return `True` if `a` is a Z3 array store application.
4532 
4533  >>> a = Array('a', IntSort(), IntSort())
4534  >>> is_store(a)
4535  False
4536  >>> is_store(Store(a, 0, 1))
4537  True
4538  """
4539  return is_app_of(a, Z3_OP_STORE)
4540 
4541 #########################################
4542 #
4543 # Sets
4544 #
4545 #########################################
4546 
4547 
4548 def SetSort(s):
4549  """ Create a set sort over element sort s"""
4550  return ArraySort(s, BoolSort())
4551 
4552 def EmptySet(s):
4553  """Create the empty set
4554  >>> EmptySet(IntSort())
4555  K(Int, False)
4556  """
4557  ctx = s.ctx
4558  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4559 
4560 def FullSet(s):
4561  """Create the full set
4562  >>> FullSet(IntSort())
4563  K(Int, True)
4564  """
4565  ctx = s.ctx
4566  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4567 
4568 def SetUnion(*args):
4569  """ Take the union of sets
4570  >>> a = Const('a', SetSort(IntSort()))
4571  >>> b = Const('b', SetSort(IntSort()))
4572  >>> SetUnion(a, b)
4573  union(a, b)
4574  """
4575  args = _get_args(args)
4576  ctx = _ctx_from_ast_arg_list(args)
4577  _args, sz = _to_ast_array(args)
4578  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4579 
4580 def SetIntersect(*args):
4581  """ Take the union of sets
4582  >>> a = Const('a', SetSort(IntSort()))
4583  >>> b = Const('b', SetSort(IntSort()))
4584  >>> SetIntersect(a, b)
4585  intersection(a, b)
4586  """
4587  args = _get_args(args)
4588  ctx = _ctx_from_ast_arg_list(args)
4589  _args, sz = _to_ast_array(args)
4590  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4591 
4592 def SetAdd(s, e):
4593  """ Add element e to set s
4594  >>> a = Const('a', SetSort(IntSort()))
4595  >>> SetAdd(a, 1)
4596  Store(a, 1, True)
4597  """
4598  ctx = _ctx_from_ast_arg_list([s,e])
4599  e = _py2expr(e, ctx)
4600  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4601 
4602 def SetDel(s, e):
4603  """ Remove element e to set s
4604  >>> a = Const('a', SetSort(IntSort()))
4605  >>> SetDel(a, 1)
4606  Store(a, 1, False)
4607  """
4608  ctx = _ctx_from_ast_arg_list([s,e])
4609  e = _py2expr(e, ctx)
4610  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4611 
4612 def SetComplement(s):
4613  """ The complement of set s
4614  >>> a = Const('a', SetSort(IntSort()))
4615  >>> SetComplement(a)
4616  complement(a)
4617  """
4618  ctx = s.ctx
4619  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4620 
4621 def SetDifference(a, b):
4622  """ The set difference of a and b
4623  >>> a = Const('a', SetSort(IntSort()))
4624  >>> b = Const('b', SetSort(IntSort()))
4625  >>> SetDifference(a, b)
4626  setminus(a, b)
4627  """
4628  ctx = _ctx_from_ast_arg_list([a, b])
4629  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4630 
4631 def IsMember(e, s):
4632  """ Check if e is a member of set s
4633  >>> a = Const('a', SetSort(IntSort()))
4634  >>> IsMember(1, a)
4635  a[1]
4636  """
4637  ctx = _ctx_from_ast_arg_list([s,e])
4638  e = _py2expr(e, ctx)
4639  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4640 
4641 def IsSubset(a, b):
4642  """ Check if a is a subset of b
4643  >>> a = Const('a', SetSort(IntSort()))
4644  >>> b = Const('b', SetSort(IntSort()))
4645  >>> IsSubset(a, b)
4646  subset(a, b)
4647  """
4648  ctx = _ctx_from_ast_arg_list([a, b])
4649  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4650 
4651 
4652 #########################################
4653 #
4654 # Datatypes
4655 #
4656 #########################################
4657 
4658 def _valid_accessor(acc):
4659  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4660  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4661 
4662 class Datatype:
4663  """Helper class for declaring Z3 datatypes.
4664 
4665  >>> List = Datatype('List')
4666  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4667  >>> List.declare('nil')
4668  >>> List = List.create()
4669  >>> # List is now a Z3 declaration
4670  >>> List.nil
4671  nil
4672  >>> List.cons(10, List.nil)
4673  cons(10, nil)
4674  >>> List.cons(10, List.nil).sort()
4675  List
4676  >>> cons = List.cons
4677  >>> nil = List.nil
4678  >>> car = List.car
4679  >>> cdr = List.cdr
4680  >>> n = cons(1, cons(0, nil))
4681  >>> n
4682  cons(1, cons(0, nil))
4683  >>> simplify(cdr(n))
4684  cons(0, nil)
4685  >>> simplify(car(n))
4686  1
4687  """
4688  def __init__(self, name, ctx=None):
4689  self.ctx = _get_ctx(ctx)
4690  self.name = name
4691  self.constructors = []
4692 
4693  def __deepcopy__(self, memo={}):
4694  r = Datatype(self.name, self.ctx)
4695  r.constructors = copy.deepcopy(self.constructors)
4696  return r
4697 
4698  def declare_core(self, name, rec_name, *args):
4699  if z3_debug():
4700  _z3_assert(isinstance(name, str), "String expected")
4701  _z3_assert(isinstance(rec_name, str), "String expected")
4702  _z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)")
4703  self.constructors.append((name, rec_name, args))
4704 
4705  def declare(self, name, *args):
4706  """Declare constructor named `name` with the given accessors `args`.
4707  Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared.
4708 
4709  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4710  declares the constructor named `cons` that builds a new List using an integer and a List.
4711  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4712  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4713  the actual datatype in Z3.
4714 
4715  >>> List = Datatype('List')
4716  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4717  >>> List.declare('nil')
4718  >>> List = List.create()
4719  """
4720  if z3_debug():
4721  _z3_assert(isinstance(name, str), "String expected")
4722  _z3_assert(name != "", "Constructor name cannot be empty")
4723  return self.declare_core(name, "is-" + name, *args)
4724 
4725  def __repr__(self):
4726  return "Datatype(%s, %s)" % (self.name, self.constructors)
4727 
4728  def create(self):
4729  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4730 
4731  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4732 
4733  >>> List = Datatype('List')
4734  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4735  >>> List.declare('nil')
4736  >>> List = List.create()
4737  >>> List.nil
4738  nil
4739  >>> List.cons(10, List.nil)
4740  cons(10, nil)
4741  """
4742  return CreateDatatypes([self])[0]
4743 
4744 class ScopedConstructor:
4745  """Auxiliary object used to create Z3 datatypes."""
4746  def __init__(self, c, ctx):
4747  self.c = c
4748  self.ctx = ctx
4749  def __del__(self):
4750  if self.ctx.ref() is not None:
4751  Z3_del_constructor(self.ctx.ref(), self.c)
4752 
4753 class ScopedConstructorList:
4754  """Auxiliary object used to create Z3 datatypes."""
4755  def __init__(self, c, ctx):
4756  self.c = c
4757  self.ctx = ctx
4758  def __del__(self):
4759  if self.ctx.ref() is not None:
4760  Z3_del_constructor_list(self.ctx.ref(), self.c)
4761 
4762 def CreateDatatypes(*ds):
4763  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4764 
4765  In the following example we define a Tree-List using two mutually recursive datatypes.
4766 
4767  >>> TreeList = Datatype('TreeList')
4768  >>> Tree = Datatype('Tree')
4769  >>> # Tree has two constructors: leaf and node
4770  >>> Tree.declare('leaf', ('val', IntSort()))
4771  >>> # a node contains a list of trees
4772  >>> Tree.declare('node', ('children', TreeList))
4773  >>> TreeList.declare('nil')
4774  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4775  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4776  >>> Tree.val(Tree.leaf(10))
4777  val(leaf(10))
4778  >>> simplify(Tree.val(Tree.leaf(10)))
4779  10
4780  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4781  >>> n1
4782  node(cons(leaf(10), cons(leaf(20), nil)))
4783  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4784  >>> simplify(n2 == n1)
4785  False
4786  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4787  True
4788  """
4789  ds = _get_args(ds)
4790  if z3_debug():
4791  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4792  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4793  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4794  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4795  ctx = ds[0].ctx
4796  num = len(ds)
4797  names = (Symbol * num)()
4798  out = (Sort * num)()
4799  clists = (ConstructorList * num)()
4800  to_delete = []
4801  for i in range(num):
4802  d = ds[i]
4803  names[i] = to_symbol(d.name, ctx)
4804  num_cs = len(d.constructors)
4805  cs = (Constructor * num_cs)()
4806  for j in range(num_cs):
4807  c = d.constructors[j]
4808  cname = to_symbol(c[0], ctx)
4809  rname = to_symbol(c[1], ctx)
4810  fs = c[2]
4811  num_fs = len(fs)
4812  fnames = (Symbol * num_fs)()
4813  sorts = (Sort * num_fs)()
4814  refs = (ctypes.c_uint * num_fs)()
4815  for k in range(num_fs):
4816  fname = fs[k][0]
4817  ftype = fs[k][1]
4818  fnames[k] = to_symbol(fname, ctx)
4819  if isinstance(ftype, Datatype):
4820  if z3_debug():
4821  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4822  sorts[k] = None
4823  refs[k] = ds.index(ftype)
4824  else:
4825  if z3_debug():
4826  _z3_assert(is_sort(ftype), "Z3 sort expected")
4827  sorts[k] = ftype.ast
4828  refs[k] = 0
4829  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4830  to_delete.append(ScopedConstructor(cs[j], ctx))
4831  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4832  to_delete.append(ScopedConstructorList(clists[i], ctx))
4833  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4834  result = []
4835  ## Create a field for every constructor, recognizer and accessor
4836  for i in range(num):
4837  dref = DatatypeSortRef(out[i], ctx)
4838  num_cs = dref.num_constructors()
4839  for j in range(num_cs):
4840  cref = dref.constructor(j)
4841  cref_name = cref.name()
4842  cref_arity = cref.arity()
4843  if cref.arity() == 0:
4844  cref = cref()
4845  setattr(dref, cref_name, cref)
4846  rref = dref.recognizer(j)
4847  setattr(dref, "is_" + cref_name, rref)
4848  for k in range(cref_arity):
4849  aref = dref.accessor(j, k)
4850  setattr(dref, aref.name(), aref)
4851  result.append(dref)
4852  return tuple(result)
4853 
4854 class DatatypeSortRef(SortRef):
4855  """Datatype sorts."""
4856  def num_constructors(self):
4857  """Return the number of constructors in the given Z3 datatype.
4858 
4859  >>> List = Datatype('List')
4860  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4861  >>> List.declare('nil')
4862  >>> List = List.create()
4863  >>> # List is now a Z3 declaration
4864  >>> List.num_constructors()
4865  2
4866  """
4867  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4868 
4869  def constructor(self, idx):
4870  """Return a constructor of the datatype `self`.
4871 
4872  >>> List = Datatype('List')
4873  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4874  >>> List.declare('nil')
4875  >>> List = List.create()
4876  >>> # List is now a Z3 declaration
4877  >>> List.num_constructors()
4878  2
4879  >>> List.constructor(0)
4880  cons
4881  >>> List.constructor(1)
4882  nil
4883  """
4884  if z3_debug():
4885  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4886  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4887 
4888  def recognizer(self, idx):
4889  """In Z3, each constructor has an associated recognizer predicate.
4890 
4891  If the constructor is named `name`, then the recognizer `is_name`.
4892 
4893  >>> List = Datatype('List')
4894  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4895  >>> List.declare('nil')
4896  >>> List = List.create()
4897  >>> # List is now a Z3 declaration
4898  >>> List.num_constructors()
4899  2
4900  >>> List.recognizer(0)
4901  is(cons)
4902  >>> List.recognizer(1)
4903  is(nil)
4904  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4905  False
4906  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4907  True
4908  >>> l = Const('l', List)
4909  >>> simplify(List.is_cons(l))
4910  is(cons, l)
4911  """
4912  if z3_debug():
4913  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4914  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4915 
4916  def accessor(self, i, j):
4917  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4918 
4919  >>> List = Datatype('List')
4920  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4921  >>> List.declare('nil')
4922  >>> List = List.create()
4923  >>> List.num_constructors()
4924  2
4925  >>> List.constructor(0)
4926  cons
4927  >>> num_accs = List.constructor(0).arity()
4928  >>> num_accs
4929  2
4930  >>> List.accessor(0, 0)
4931  car
4932  >>> List.accessor(0, 1)
4933  cdr
4934  >>> List.constructor(1)
4935  nil
4936  >>> num_accs = List.constructor(1).arity()
4937  >>> num_accs
4938  0
4939  """
4940  if z3_debug():
4941  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4942  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4943  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4944 
4945 class DatatypeRef(ExprRef):
4946  """Datatype expressions."""
4947  def sort(self):
4948  """Return the datatype sort of the datatype expression `self`."""
4949  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4950 
4951 def TupleSort(name, sorts, ctx = None):
4952  """Create a named tuple sort base on a set of underlying sorts
4953  Example:
4954  >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
4955  """
4956  tuple = Datatype(name, ctx)
4957  projects = [ ('project%d' % i, sorts[i]) for i in range(len(sorts)) ]
4958  tuple.declare(name, *projects)
4959  tuple = tuple.create()
4960  return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
4961 
4962 def DisjointSum(name, sorts, ctx=None):
4963  """Create a named tagged union sort base on a set of underlying sorts
4964  Example:
4965  >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
4966  """
4967  sum = Datatype(name, ctx)
4968  for i in range(len(sorts)):
4969  sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
4970  sum = sum.create()
4971  return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
4972 
4973 
4974 def EnumSort(name, values, ctx=None):
4975  """Return a new enumeration sort named `name` containing the given values.
4976 
4977  The result is a pair (sort, list of constants).
4978  Example:
4979  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4980  """
4981  if z3_debug():
4982  _z3_assert(isinstance(name, str), "Name must be a string")
4983  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4984  _z3_assert(len(values) > 0, "At least one value expected")
4985  ctx = _get_ctx(ctx)
4986  num = len(values)
4987  _val_names = (Symbol * num)()
4988  for i in range(num):
4989  _val_names[i] = to_symbol(values[i])
4990  _values = (FuncDecl * num)()
4991  _testers = (FuncDecl * num)()
4992  name = to_symbol(name)
4993  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4994  V = []
4995  for i in range(num):
4996  V.append(FuncDeclRef(_values[i], ctx))
4997  V = [a() for a in V]
4998  return S, V
4999 
5000 #########################################
5001 #
5002 # Parameter Sets
5003 #
5004 #########################################
5005 
5006 class ParamsRef:
5007  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5008 
5009  Consider using the function `args2params` to create instances of this object.
5010  """
5011  def __init__(self, ctx=None, params=None):
5012  self.ctx = _get_ctx(ctx)
5013  if params is None:
5014  self.params = Z3_mk_params(self.ctx.ref())
5015  else:
5016  self.params = params
5017  Z3_params_inc_ref(self.ctx.ref(), self.params)
5018 
5019  def __deepcopy__(self, memo={}):
5020  return ParamsRef(self.ctx, self.params)
5021 
5022  def __del__(self):
5023  if self.ctx.ref() is not None:
5024  Z3_params_dec_ref(self.ctx.ref(), self.params)
5025 
5026  def set(self, name, val):
5027  """Set parameter name with value val."""
5028  if z3_debug():
5029  _z3_assert(isinstance(name, str), "parameter name must be a string")
5030  name_sym = to_symbol(name, self.ctx)
5031  if isinstance(val, bool):
5032  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5033  elif _is_int(val):
5034  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5035  elif isinstance(val, float):
5036  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5037  elif isinstance(val, str):
5038  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5039  else:
5040  if z3_debug():
5041  _z3_assert(False, "invalid parameter value")
5042 
5043  def __repr__(self):
5044  return Z3_params_to_string(self.ctx.ref(), self.params)
5045 
5046  def validate(self, ds):
5047  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5048  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5049 
5050 def args2params(arguments, keywords, ctx=None):
5051  """Convert python arguments into a Z3_params object.
5052  A ':' is added to the keywords, and '_' is replaced with '-'
5053 
5054  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5055  (params model true relevancy 2 elim_and true)
5056  """
5057  if z3_debug():
5058  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5059  prev = None
5060  r = ParamsRef(ctx)
5061  for a in arguments:
5062  if prev is None:
5063  prev = a
5064  else:
5065  r.set(prev, a)
5066  prev = None
5067  for k in keywords:
5068  v = keywords[k]
5069  r.set(k, v)
5070  return r
5071 
5072 class ParamDescrsRef:
5073  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5074  """
5075  def __init__(self, descr, ctx=None):
5076  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5077  self.ctx = _get_ctx(ctx)
5078  self.descr = descr
5079  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5080 
5081  def __deepcopy__(self, memo={}):
5082  return ParamsDescrsRef(self.descr, self.ctx)
5083 
5084  def __del__(self):
5085  if self.ctx.ref() is not None:
5086  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5087 
5088  def size(self):
5089  """Return the size of in the parameter description `self`.
5090  """
5091  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5092 
5093  def __len__(self):
5094  """Return the size of in the parameter description `self`.
5095  """
5096  return self.size()
5097 
5098  def get_name(self, i):
5099  """Return the i-th parameter name in the parameter description `self`.
5100  """
5101  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5102 
5103  def get_kind(self, n):
5104  """Return the kind of the parameter named `n`.
5105  """
5106  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5107 
5108  def get_documentation(self, n):
5109  """Return the documentation string of the parameter named `n`.
5110  """
5111  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5112 
5113  def __getitem__(self, arg):
5114  if _is_int(arg):
5115  return self.get_name(arg)
5116  else:
5117  return self.get_kind(arg)
5118 
5119  def __repr__(self):
5120  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5121 
5122 #########################################
5123 #
5124 # Goals
5125 #
5126 #########################################
5127 
5128 class Goal(Z3PPObject):
5129  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5130 
5131  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5132  A goal has a solution if one of its subgoals has a solution.
5133  A goal is unsatisfiable if all subgoals are unsatisfiable.
5134  """
5135 
5136  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5137  if z3_debug():
5138  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
5139  self.ctx = _get_ctx(ctx)
5140  self.goal = goal
5141  if self.goal is None:
5142  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5143  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5144 
5145  def __deepcopy__(self, memo={}):
5146  return Goal(False, False, False, self.ctx, self.goal)
5147 
5148  def __del__(self):
5149  if self.goal is not None and self.ctx.ref() is not None:
5150  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5151 
5152  def depth(self):
5153  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
5154 
5155  >>> x, y = Ints('x y')
5156  >>> g = Goal()
5157  >>> g.add(x == 0, y >= x + 1)
5158  >>> g.depth()
5159  0
5160  >>> r = Then('simplify', 'solve-eqs')(g)
5161  >>> # r has 1 subgoal
5162  >>> len(r)
5163  1
5164  >>> r[0].depth()
5165  2
5166  """
5167  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5168 
5169  def inconsistent(self):
5170  """Return `True` if `self` contains the `False` constraints.
5171 
5172  >>> x, y = Ints('x y')
5173  >>> g = Goal()
5174  >>> g.inconsistent()
5175  False
5176  >>> g.add(x == 0, x == 1)
5177  >>> g
5178  [x == 0, x == 1]
5179  >>> g.inconsistent()
5180  False
5181  >>> g2 = Tactic('propagate-values')(g)[0]
5182  >>> g2.inconsistent()
5183  True
5184  """
5185  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5186 
5187  def prec(self):
5188  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5189 
5190  >>> g = Goal()
5191  >>> g.prec() == Z3_GOAL_PRECISE
5192  True
5193  >>> x, y = Ints('x y')
5194  >>> g.add(x == y + 1)
5195  >>> g.prec() == Z3_GOAL_PRECISE
5196  True
5197  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5198  >>> g2 = t(g)[0]
5199  >>> g2
5200  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5201  >>> g2.prec() == Z3_GOAL_PRECISE
5202  False
5203  >>> g2.prec() == Z3_GOAL_UNDER
5204  True
5205  """
5206  return Z3_goal_precision(self.ctx.ref(), self.goal)
5207 
5208  def precision(self):
5209  """Alias for `prec()`.
5210 
5211  >>> g = Goal()
5212  >>> g.precision() == Z3_GOAL_PRECISE
5213  True
5214  """
5215  return self.prec()
5216 
5217  def size(self):
5218  """Return the number of constraints in the goal `self`.
5219 
5220  >>> g = Goal()
5221  >>> g.size()
5222  0
5223  >>> x, y = Ints('x y')
5224  >>> g.add(x == 0, y > x)
5225  >>> g.size()
5226  2
5227  """
5228  return int(Z3_goal_size(self.ctx.ref(), self.goal))
5229 
5230  def __len__(self):
5231  """Return the number of constraints in the goal `self`.
5232 
5233  >>> g = Goal()
5234  >>> len(g)
5235  0
5236  >>> x, y = Ints('x y')
5237  >>> g.add(x == 0, y > x)
5238  >>> len(g)
5239  2
5240  """
5241  return self.size()
5242 
5243  def get(self, i):
5244  """Return a constraint in the goal `self`.
5245 
5246  >>> g = Goal()
5247  >>> x, y = Ints('x y')
5248  >>> g.add(x == 0, y > x)
5249  >>> g.get(0)
5250  x == 0
5251  >>> g.get(1)
5252  y > x
5253  """
5254  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5255 
5256  def __getitem__(self, arg):
5257  """Return a constraint in the goal `self`.
5258 
5259  >>> g = Goal()
5260  >>> x, y = Ints('x y')
5261  >>> g.add(x == 0, y > x)
5262  >>> g[0]
5263  x == 0
5264  >>> g[1]
5265  y > x
5266  """
5267  if arg >= len(self):
5268  raise IndexError
5269  return self.get(arg)
5270 
5271  def assert_exprs(self, *args):
5272  """Assert constraints into the goal.
5273 
5274  >>> x = Int('x')
5275  >>> g = Goal()
5276  >>> g.assert_exprs(x > 0, x < 2)
5277  >>> g
5278  [x > 0, x < 2]
5279  """
5280  args = _get_args(args)
5281  s = BoolSort(self.ctx)
5282  for arg in args:
5283  arg = s.cast(arg)
5284  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5285 
5286  def append(self, *args):
5287  """Add constraints.
5288 
5289  >>> x = Int('x')
5290  >>> g = Goal()
5291  >>> g.append(x > 0, x < 2)
5292  >>> g
5293  [x > 0, x < 2]
5294  """
5295  self.assert_exprs(*args)
5296 
5297  def insert(self, *args):
5298  """Add constraints.
5299 
5300  >>> x = Int('x')
5301  >>> g = Goal()
5302  >>> g.insert(x > 0, x < 2)
5303  >>> g
5304  [x > 0, x < 2]
5305  """
5306  self.assert_exprs(*args)
5307 
5308  def add(self, *args):
5309  """Add constraints.
5310 
5311  >>> x = Int('x')
5312  >>> g = Goal()
5313  >>> g.add(x > 0, x < 2)
5314  >>> g
5315  [x > 0, x < 2]
5316  """
5317  self.assert_exprs(*args)
5318 
5319  def convert_model(self, model):
5320  """Retrieve model from a satisfiable goal
5321  >>> a, b = Ints('a b')
5322  >>> g = Goal()
5323  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5324  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5325  >>> r = t(g)
5326  >>> r[0]
5327  [Or(b == 0, b == 1), Not(0 <= b)]
5328  >>> r[1]
5329  [Or(b == 0, b == 1), Not(1 <= b)]
5330  >>> # Remark: the subgoal r[0] is unsatisfiable
5331  >>> # Creating a solver for solving the second subgoal
5332  >>> s = Solver()
5333  >>> s.add(r[1])
5334  >>> s.check()
5335  sat
5336  >>> s.model()
5337  [b = 0]
5338  >>> # Model s.model() does not assign a value to `a`
5339  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5340  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5341  >>> r[1].convert_model(s.model())
5342  [b = 0, a = 1]
5343  """
5344  if z3_debug():
5345  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5346  return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5347 
5348  def __repr__(self):
5349  return obj_to_string(self)
5350 
5351  def sexpr(self):
5352  """Return a textual representation of the s-expression representing the goal."""
5353  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5354 
5355  def dimacs(self):
5356  """Return a textual representation of the goal in DIMACS format."""
5357  return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
5358 
5359  def translate(self, target):
5360  """Copy goal `self` to context `target`.
5361 
5362  >>> x = Int('x')
5363  >>> g = Goal()
5364  >>> g.add(x > 10)
5365  >>> g
5366  [x > 10]
5367  >>> c2 = Context()
5368  >>> g2 = g.translate(c2)
5369  >>> g2
5370  [x > 10]
5371  >>> g.ctx == main_ctx()
5372  True
5373  >>> g2.ctx == c2
5374  True
5375  >>> g2.ctx == main_ctx()
5376  False
5377  """
5378  if z3_debug():
5379  _z3_assert(isinstance(target, Context), "target must be a context")
5380  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5381 
5382  def __copy__(self):
5383  return self.translate(self.ctx)
5384 
5385  def __deepcopy__(self, memo={}):
5386  return self.translate(self.ctx)
5387 
5388  def simplify(self, *arguments, **keywords):
5389  """Return a new simplified goal.
5390 
5391  This method is essentially invoking the simplify tactic.
5392 
5393  >>> g = Goal()
5394  >>> x = Int('x')
5395  >>> g.add(x + 1 >= 2)
5396  >>> g
5397  [x + 1 >= 2]
5398  >>> g2 = g.simplify()
5399  >>> g2
5400  [x >= 1]
5401  >>> # g was not modified
5402  >>> g
5403  [x + 1 >= 2]
5404  """
5405  t = Tactic('simplify')
5406  return t.apply(self, *arguments, **keywords)[0]
5407 
5408  def as_expr(self):
5409  """Return goal `self` as a single Z3 expression.
5410 
5411  >>> x = Int('x')
5412  >>> g = Goal()
5413  >>> g.as_expr()
5414  True
5415  >>> g.add(x > 1)
5416  >>> g.as_expr()
5417  x > 1
5418  >>> g.add(x < 10)
5419  >>> g.as_expr()
5420  And(x > 1, x < 10)
5421  """
5422  sz = len(self)
5423  if sz == 0:
5424  return BoolVal(True, self.ctx)
5425  elif sz == 1:
5426  return self.get(0)
5427  else:
5428  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5429 
5430 #########################################
5431 #
5432 # AST Vector
5433 #
5434 #########################################
5435 class AstVector(Z3PPObject):
5436  """A collection (vector) of ASTs."""
5437 
5438  def __init__(self, v=None, ctx=None):
5439  self.vector = None
5440  if v is None:
5441  self.ctx = _get_ctx(ctx)
5442  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5443  else:
5444  self.vector = v
5445  assert ctx is not None
5446  self.ctx = ctx
5447  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5448 
5449  def __deepcopy__(self, memo={}):
5450  return AstVector(self.vector, self.ctx)
5451 
5452  def __del__(self):
5453  if self.vector is not None and self.ctx.ref() is not None:
5454  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5455 
5456  def __len__(self):
5457  """Return the size of the vector `self`.
5458 
5459  >>> A = AstVector()
5460  >>> len(A)
5461  0
5462  >>> A.push(Int('x'))
5463  >>> A.push(Int('x'))
5464  >>> len(A)
5465  2
5466  """
5467  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5468 
5469  def __getitem__(self, i):
5470  """Return the AST at position `i`.
5471 
5472  >>> A = AstVector()
5473  >>> A.push(Int('x') + 1)
5474  >>> A.push(Int('y'))
5475  >>> A[0]
5476  x + 1
5477  >>> A[1]
5478  y
5479  """
5480 
5481  if isinstance(i, int):
5482  if i < 0:
5483  i += self.__len__()
5484 
5485  if i >= self.__len__():
5486  raise IndexError
5487  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5488 
5489  elif isinstance(i, slice):
5490  return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5491 
5492 
5493  def __setitem__(self, i, v):
5494  """Update AST at position `i`.
5495 
5496  >>> A = AstVector()
5497  >>> A.push(Int('x') + 1)
5498  >>> A.push(Int('y'))
5499  >>> A[0]
5500  x + 1
5501  >>> A[0] = Int('x')
5502  >>> A[0]
5503  x
5504  """
5505  if i >= self.__len__():
5506  raise IndexError
5507  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5508 
5509  def push(self, v):
5510  """Add `v` in the end of the vector.
5511 
5512  >>> A = AstVector()
5513  >>> len(A)
5514  0
5515  >>> A.push(Int('x'))
5516  >>> len(A)
5517  1
5518  """
5519  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5520 
5521  def resize(self, sz):
5522  """Resize the vector to `sz` elements.
5523 
5524  >>> A = AstVector()
5525  >>> A.resize(10)
5526  >>> len(A)
5527  10
5528  >>> for i in range(10): A[i] = Int('x')
5529  >>> A[5]
5530  x
5531  """
5532  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5533 
5534  def __contains__(self, item):
5535  """Return `True` if the vector contains `item`.
5536 
5537  >>> x = Int('x')
5538  >>> A = AstVector()
5539  >>> x in A
5540  False
5541  >>> A.push(x)
5542  >>> x in A
5543  True
5544  >>> (x+1) in A
5545  False
5546  >>> A.push(x+1)
5547  >>> (x+1) in A
5548  True
5549  >>> A
5550  [x, x + 1]
5551  """
5552  for elem in self:
5553  if elem.eq(item):
5554  return True
5555  return False
5556 
5557  def translate(self, other_ctx):
5558  """Copy vector `self` to context `other_ctx`.
5559 
5560  >>> x = Int('x')
5561  >>> A = AstVector()
5562  >>> A.push(x)
5563  >>> c2 = Context()
5564  >>> B = A.translate(c2)
5565  >>> B
5566  [x]
5567  """
5568  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5569 
5570  def __copy__(self):
5571  return self.translate(self.ctx)
5572 
5573  def __deepcopy__(self, memo={}):
5574  return self.translate(self.ctx)
5575 
5576  def __repr__(self):
5577  return obj_to_string(self)
5578 
5579  def sexpr(self):
5580  """Return a textual representation of the s-expression representing the vector."""
5581  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5582 
5583 #########################################
5584 #
5585 # AST Map
5586 #
5587 #########################################
5588 class AstMap:
5589  """A mapping from ASTs to ASTs."""
5590 
5591  def __init__(self, m=None, ctx=None):
5592  self.map = None
5593  if m is None:
5594  self.ctx = _get_ctx(ctx)
5595  self.map = Z3_mk_ast_map(self.ctx.ref())
5596  else:
5597  self.map = m
5598  assert ctx is not None
5599  self.ctx = ctx
5600  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5601 
5602  def __deepcopy__(self, memo={}):
5603  return AstMap(self.map, self.ctx)
5604 
5605  def __del__(self):
5606  if self.map is not None and self.ctx.ref() is not None:
5607  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5608 
5609  def __len__(self):
5610  """Return the size of the map.
5611 
5612  >>> M = AstMap()
5613  >>> len(M)
5614  0
5615  >>> x = Int('x')
5616  >>> M[x] = IntVal(1)
5617  >>> len(M)
5618  1
5619  """
5620  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5621 
5622  def __contains__(self, key):
5623  """Return `True` if the map contains key `key`.
5624 
5625  >>> M = AstMap()
5626  >>> x = Int('x')
5627  >>> M[x] = x + 1
5628  >>> x in M
5629  True
5630  >>> x+1 in M
5631  False
5632  """
5633  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5634 
5635  def __getitem__(self, key):
5636  """Retrieve the value associated with key `key`.
5637 
5638  >>> M = AstMap()
5639  >>> x = Int('x')
5640  >>> M[x] = x + 1
5641  >>> M[x]
5642  x + 1
5643  """
5644  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5645 
5646  def __setitem__(self, k, v):
5647  """Add/Update key `k` with value `v`.
5648 
5649  >>> M = AstMap()
5650  >>> x = Int('x')
5651  >>> M[x] = x + 1
5652  >>> len(M)
5653  1
5654  >>> M[x]
5655  x + 1
5656  >>> M[x] = IntVal(1)
5657  >>> M[x]
5658  1
5659  """
5660  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5661 
5662  def __repr__(self):
5663  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5664 
5665  def erase(self, k):
5666  """Remove the entry associated with key `k`.
5667 
5668  >>> M = AstMap()
5669  >>> x = Int('x')
5670  >>> M[x] = x + 1
5671  >>> len(M)
5672  1
5673  >>> M.erase(x)
5674  >>> len(M)
5675  0
5676  """
5677  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5678 
5679  def reset(self):
5680  """Remove all entries from the map.
5681 
5682  >>> M = AstMap()
5683  >>> x = Int('x')
5684  >>> M[x] = x + 1
5685  >>> M[x+x] = IntVal(1)
5686  >>> len(M)
5687  2
5688  >>> M.reset()
5689  >>> len(M)
5690  0
5691  """
5692  Z3_ast_map_reset(self.ctx.ref(), self.map)
5693 
5694  def keys(self):
5695  """Return an AstVector containing all keys in the map.
5696 
5697  >>> M = AstMap()
5698  >>> x = Int('x')
5699  >>> M[x] = x + 1
5700  >>> M[x+x] = IntVal(1)
5701  >>> M.keys()
5702  [x, x + x]
5703  """
5704  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5705 
5706 #########################################
5707 #
5708 # Model
5709 #
5710 #########################################
5711 
5712 class FuncEntry:
5713  """Store the value of the interpretation of a function in a particular point."""
5714 
5715  def __init__(self, entry, ctx):
5716  self.entry = entry
5717  self.ctx = ctx
5718  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5719 
5720  def __deepcopy__(self, memo={}):
5721  return FuncEntry(self.entry, self.ctx)
5722 
5723  def __del__(self):
5724  if self.ctx.ref() is not None:
5725  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5726 
5727  def num_args(self):
5728  """Return the number of arguments in the given entry.
5729 
5730  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5731  >>> s = Solver()
5732  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5733  >>> s.check()
5734  sat
5735  >>> m = s.model()
5736  >>> f_i = m[f]
5737  >>> f_i.num_entries()
5738  1
5739  >>> e = f_i.entry(0)
5740  >>> e.num_args()
5741  2
5742  """
5743  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5744 
5745  def arg_value(self, idx):
5746  """Return the value of argument `idx`.
5747 
5748  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5749  >>> s = Solver()
5750  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5751  >>> s.check()
5752  sat
5753  >>> m = s.model()
5754  >>> f_i = m[f]
5755  >>> f_i.num_entries()
5756  1
5757  >>> e = f_i.entry(0)
5758  >>> e
5759  [1, 2, 20]
5760  >>> e.num_args()
5761  2
5762  >>> e.arg_value(0)
5763  1
5764  >>> e.arg_value(1)
5765  2
5766  >>> try:
5767  ... e.arg_value(2)
5768  ... except IndexError:
5769  ... print("index error")
5770  index error
5771  """
5772  if idx >= self.num_args():
5773  raise IndexError
5774  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5775 
5776  def value(self):
5777  """Return the value of the function at point `self`.
5778 
5779  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5780  >>> s = Solver()
5781  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5782  >>> s.check()
5783  sat
5784  >>> m = s.model()
5785  >>> f_i = m[f]
5786  >>> f_i.num_entries()
5787  1
5788  >>> e = f_i.entry(0)
5789  >>> e
5790  [1, 2, 20]
5791  >>> e.num_args()
5792  2
5793  >>> e.value()
5794  20
5795  """
5796  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5797 
5798  def as_list(self):
5799  """Return entry `self` as a Python list.
5800  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5801  >>> s = Solver()
5802  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5803  >>> s.check()
5804  sat
5805  >>> m = s.model()
5806  >>> f_i = m[f]
5807  >>> f_i.num_entries()
5808  1
5809  >>> e = f_i.entry(0)
5810  >>> e.as_list()
5811  [1, 2, 20]
5812  """
5813  args = [ self.arg_value(i) for i in range(self.num_args())]
5814  args.append(self.value())
5815  return args
5816 
5817  def __repr__(self):
5818  return repr(self.as_list())
5819 
5820 class FuncInterp(Z3PPObject):
5821  """Stores the interpretation of a function in a Z3 model."""
5822 
5823  def __init__(self, f, ctx):
5824  self.f = f
5825  self.ctx = ctx
5826  if self.f is not None:
5827  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5828 
5829  def __deepcopy__(self, memo={}):
5830  return FuncInterp(self.f, self.ctx)
5831 
5832  def __del__(self):
5833  if self.f is not None and self.ctx.ref() is not None:
5834  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5835 
5836  def else_value(self):
5837  """
5838  Return the `else` value for a function interpretation.
5839  Return None if Z3 did not specify the `else` value for
5840  this object.
5841 
5842  >>> f = Function('f', IntSort(), IntSort())
5843  >>> s = Solver()
5844  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5845  >>> s.check()
5846  sat
5847  >>> m = s.model()
5848  >>> m[f]
5849  [2 -> 0, else -> 1]
5850  >>> m[f].else_value()
5851  1
5852  """
5853  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5854  if r:
5855  return _to_expr_ref(r, self.ctx)
5856  else:
5857  return None
5858 
5859  def num_entries(self):
5860  """Return the number of entries/points in the function interpretation `self`.
5861 
5862  >>> f = Function('f', IntSort(), IntSort())
5863  >>> s = Solver()
5864  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5865  >>> s.check()
5866  sat
5867  >>> m = s.model()
5868  >>> m[f]
5869  [2 -> 0, else -> 1]
5870  >>> m[f].num_entries()
5871  1
5872  """
5873  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5874 
5875  def arity(self):
5876  """Return the number of arguments for each entry in the function interpretation `self`.
5877 
5878  >>> f = Function('f', IntSort(), IntSort())
5879  >>> s = Solver()
5880  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5881  >>> s.check()
5882  sat
5883  >>> m = s.model()
5884  >>> m[f].arity()
5885  1
5886  """
5887  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5888 
5889  def entry(self, idx):
5890  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5891 
5892  >>> f = Function('f', IntSort(), IntSort())
5893  >>> s = Solver()
5894  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5895  >>> s.check()
5896  sat
5897  >>> m = s.model()
5898  >>> m[f]
5899  [2 -> 0, else -> 1]
5900  >>> m[f].num_entries()
5901  1
5902  >>> m[f].entry(0)
5903  [2, 0]
5904  """
5905  if idx >= self.num_entries():
5906  raise IndexError
5907  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5908 
5909  def translate(self, other_ctx):
5910  """Copy model 'self' to context 'other_ctx'.
5911  """
5912  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5913 
5914  def __copy__(self):
5915  return self.translate(self.ctx)
5916 
5917  def __deepcopy__(self, memo={}):
5918  return self.translate(self.ctx)
5919 
5920  def as_list(self):
5921  """Return the function interpretation as a Python list.
5922  >>> f = Function('f', IntSort(), IntSort())
5923  >>> s = Solver()
5924  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5925  >>> s.check()
5926  sat
5927  >>> m = s.model()
5928  >>> m[f]
5929  [2 -> 0, else -> 1]
5930  >>> m[f].as_list()
5931  [[2, 0], 1]
5932  """
5933  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5934  r.append(self.else_value())
5935  return r
5936 
5937  def __repr__(self):
5938  return obj_to_string(self)
5939 
5940 class ModelRef(Z3PPObject):
5941  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5942 
5943  def __init__(self, m, ctx):
5944  assert ctx is not None
5945  self.model = m
5946  self.ctx = ctx
5947  Z3_model_inc_ref(self.ctx.ref(), self.model)
5948 
5949  def __del__(self):
5950  if self.ctx.ref() is not None:
5951  Z3_model_dec_ref(self.ctx.ref(), self.model)
5952 
5953  def __repr__(self):
5954  return obj_to_string(self)
5955 
5956  def sexpr(self):
5957  """Return a textual representation of the s-expression representing the model."""
5958  return Z3_model_to_string(self.ctx.ref(), self.model)
5959 
5960  def eval(self, t, model_completion=False):
5961  """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`.
5962 
5963  >>> x = Int('x')
5964  >>> s = Solver()
5965  >>> s.add(x > 0, x < 2)
5966  >>> s.check()
5967  sat
5968  >>> m = s.model()
5969  >>> m.eval(x + 1)
5970  2
5971  >>> m.eval(x == 1)
5972  True
5973  >>> y = Int('y')
5974  >>> m.eval(y + x)
5975  1 + y
5976  >>> m.eval(y)
5977  y
5978  >>> m.eval(y, model_completion=True)
5979  0
5980  >>> # Now, m contains an interpretation for y
5981  >>> m.eval(y + x)
5982  1
5983  """
5984  r = (Ast * 1)()
5985  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5986  return _to_expr_ref(r[0], self.ctx)
5987  raise Z3Exception("failed to evaluate expression in the model")
5988 
5989  def evaluate(self, t, model_completion=False):
5990  """Alias for `eval`.
5991 
5992  >>> x = Int('x')
5993  >>> s = Solver()
5994  >>> s.add(x > 0, x < 2)
5995  >>> s.check()
5996  sat
5997  >>> m = s.model()
5998  >>> m.evaluate(x + 1)
5999  2
6000  >>> m.evaluate(x == 1)
6001  True
6002  >>> y = Int('y')
6003  >>> m.evaluate(y + x)
6004  1 + y
6005  >>> m.evaluate(y)
6006  y
6007  >>> m.evaluate(y, model_completion=True)
6008  0
6009  >>> # Now, m contains an interpretation for y
6010  >>> m.evaluate(y + x)
6011  1
6012  """
6013  return self.eval(t, model_completion)
6014 
6015  def __len__(self):
6016  """Return the number of constant and function declarations in the model `self`.
6017 
6018  >>> f = Function('f', IntSort(), IntSort())
6019  >>> x = Int('x')
6020  >>> s = Solver()
6021  >>> s.add(x > 0, f(x) != x)
6022  >>> s.check()
6023  sat
6024  >>> m = s.model()
6025  >>> len(m)
6026  2
6027  """
6028  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6029 
6030  def get_interp(self, decl):
6031  """Return the interpretation for a given declaration or constant.
6032 
6033  >>> f = Function('f', IntSort(), IntSort())
6034  >>> x = Int('x')
6035  >>> s = Solver()
6036  >>> s.add(x > 0, x < 2, f(x) == 0)
6037  >>> s.check()
6038  sat
6039  >>> m = s.model()
6040  >>> m[x]
6041  1
6042  >>> m[f]
6043  [else -> 0]
6044  """
6045  if z3_debug():
6046  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6047  if is_const(decl):
6048  decl = decl.decl()
6049  try:
6050  if decl.arity() == 0:
6051  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6052  if _r.value is None:
6053  return None
6054  r = _to_expr_ref(_r, self.ctx)
6055  if is_as_array(r):
6056  return self.get_interp(get_as_array_func(r))
6057  else:
6058  return r
6059  else:
6060  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6061  except Z3Exception:
6062  return None
6063 
6064  def num_sorts(self):
6065  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6066 
6067  >>> A = DeclareSort('A')
6068  >>> a, b = Consts('a b', A)
6069  >>> s = Solver()
6070  >>> s.add(a != b)
6071  >>> s.check()
6072  sat
6073  >>> m = s.model()
6074  >>> m.num_sorts()
6075  1
6076  """
6077  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6078 
6079  def get_sort(self, idx):
6080  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6081 
6082  >>> A = DeclareSort('A')
6083  >>> B = DeclareSort('B')
6084  >>> a1, a2 = Consts('a1 a2', A)
6085  >>> b1, b2 = Consts('b1 b2', B)
6086  >>> s = Solver()
6087  >>> s.add(a1 != a2, b1 != b2)
6088  >>> s.check()
6089  sat
6090  >>> m = s.model()
6091  >>> m.num_sorts()
6092  2
6093  >>> m.get_sort(0)
6094  A
6095  >>> m.get_sort(1)
6096  B
6097  """
6098  if idx >= self.num_sorts():
6099  raise IndexError
6100  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6101 
6102  def sorts(self):
6103  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6104 
6105  >>> A = DeclareSort('A')
6106  >>> B = DeclareSort('B')
6107  >>> a1, a2 = Consts('a1 a2', A)
6108  >>> b1, b2 = Consts('b1 b2', B)
6109  >>> s = Solver()
6110  >>> s.add(a1 != a2, b1 != b2)
6111  >>> s.check()
6112  sat
6113  >>> m = s.model()
6114  >>> m.sorts()
6115  [A, B]
6116  """
6117  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
6118 
6119  def get_universe(self, s):
6120  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6121 
6122  >>> A = DeclareSort('A')
6123  >>> a, b = Consts('a b', A)
6124  >>> s = Solver()
6125  >>> s.add(a != b)
6126  >>> s.check()
6127  sat
6128  >>> m = s.model()
6129  >>> m.get_universe(A)
6130  [A!val!0, A!val!1]
6131  """
6132  if z3_debug():
6133  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6134  try:
6135  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6136  except Z3Exception:
6137  return None
6138 
6139  def __getitem__(self, idx):
6140  """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned.
6141 
6142  The elements can be retrieved using position or the actual declaration.
6143 
6144  >>> f = Function('f', IntSort(), IntSort())
6145  >>> x = Int('x')
6146  >>> s = Solver()
6147  >>> s.add(x > 0, x < 2, f(x) == 0)
6148  >>> s.check()
6149  sat
6150  >>> m = s.model()
6151  >>> len(m)
6152  2
6153  >>> m[0]
6154  x
6155  >>> m[1]
6156  f
6157  >>> m[x]
6158  1
6159  >>> m[f]
6160  [else -> 0]
6161  >>> for d in m: print("%s -> %s" % (d, m[d]))
6162  x -> 1
6163  f -> [else -> 0]
6164  """
6165  if _is_int(idx):
6166  if idx >= len(self):
6167  raise IndexError
6168  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6169  if (idx < num_consts):
6170  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6171  else:
6172  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6173  if isinstance(idx, FuncDeclRef):
6174  return self.get_interp(idx)
6175  if is_const(idx):
6176  return self.get_interp(idx.decl())
6177  if isinstance(idx, SortRef):
6178  return self.get_universe(idx)
6179  if z3_debug():
6180  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6181  return None
6182 
6183  def decls(self):
6184  """Return a list with all symbols that have an interpretation in the model `self`.
6185  >>> f = Function('f', IntSort(), IntSort())
6186  >>> x = Int('x')
6187  >>> s = Solver()
6188  >>> s.add(x > 0, x < 2, f(x) == 0)
6189  >>> s.check()
6190  sat
6191  >>> m = s.model()
6192  >>> m.decls()
6193  [x, f]
6194  """
6195  r = []
6196  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6197  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6198  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6199  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6200  return r
6201 
6202  def translate(self, target):
6203  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6204  """
6205  if z3_debug():
6206  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6207  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6208  return Model(model, target)
6209 
6210  def __copy__(self):
6211  return self.translate(self.ctx)
6212 
6213  def __deepcopy__(self, memo={}):
6214  return self.translate(self.ctx)
6215 
6216 def Model(ctx = None):
6217  ctx = _get_ctx(ctx)
6218  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6219 
6220 def is_as_array(n):
6221  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6222  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6223 
6224 def get_as_array_func(n):
6225  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6226  if z3_debug():
6227  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6228  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6229 
6230 #########################################
6231 #
6232 # Statistics
6233 #
6234 #########################################
6235 class Statistics:
6236  """Statistics for `Solver.check()`."""
6237 
6238  def __init__(self, stats, ctx):
6239  self.stats = stats
6240  self.ctx = ctx
6241  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6242 
6243  def __deepcopy__(self, memo={}):
6244  return Statistics(self.stats, self.ctx)
6245 
6246  def __del__(self):
6247  if self.ctx.ref() is not None:
6248  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6249 
6250  def __repr__(self):
6251  if in_html_mode():
6252  out = io.StringIO()
6253  even = True
6254  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6255  for k, v in self:
6256  if even:
6257  out.write(u('<tr style="background-color:#CFCFCF">'))
6258  even = False
6259  else:
6260  out.write(u('<tr>'))
6261  even = True
6262  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
6263  out.write(u('</table>'))
6264  return out.getvalue()
6265  else:
6266  return Z3_stats_to_string(self.ctx.ref(), self.stats)
6267 
6268  def __len__(self):
6269  """Return the number of statistical counters.
6270 
6271  >>> x = Int('x')
6272  >>> s = Then('simplify', 'nlsat').solver()
6273  >>> s.add(x > 0)
6274  >>> s.check()
6275  sat
6276  >>> st = s.statistics()
6277  >>> len(st)
6278  6
6279  """
6280  return int(Z3_stats_size(self.ctx.ref(), self.stats))
6281 
6282  def __getitem__(self, idx):
6283  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6284 
6285  >>> x = Int('x')
6286  >>> s = Then('simplify', 'nlsat').solver()
6287  >>> s.add(x > 0)
6288  >>> s.check()
6289  sat
6290  >>> st = s.statistics()
6291  >>> len(st)
6292  6
6293  >>> st[0]
6294  ('nlsat propagations', 2)
6295  >>> st[1]
6296  ('nlsat stages', 2)
6297  """
6298  if idx >= len(self):
6299  raise IndexError
6300  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6301  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6302  else:
6303  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6304  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6305 
6306  def keys(self):
6307  """Return the list of statistical counters.
6308 
6309  >>> x = Int('x')
6310  >>> s = Then('simplify', 'nlsat').solver()
6311  >>> s.add(x > 0)
6312  >>> s.check()
6313  sat
6314  >>> st = s.statistics()
6315  """
6316  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6317 
6318  def get_key_value(self, key):
6319  """Return the value of a particular statistical counter.
6320 
6321  >>> x = Int('x')
6322  >>> s = Then('simplify', 'nlsat').solver()
6323  >>> s.add(x > 0)
6324  >>> s.check()
6325  sat
6326  >>> st = s.statistics()
6327  >>> st.get_key_value('nlsat propagations')
6328  2
6329  """
6330  for idx in range(len(self)):
6331  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6332  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6333  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6334  else:
6335  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6336  raise Z3Exception("unknown key")
6337 
6338  def __getattr__(self, name):
6339  """Access the value of statistical using attributes.
6340 
6341  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6342  we should use '_' (e.g., 'nlsat_propagations').
6343 
6344  >>> x = Int('x')
6345  >>> s = Then('simplify', 'nlsat').solver()
6346  >>> s.add(x > 0)
6347  >>> s.check()
6348  sat
6349  >>> st = s.statistics()
6350  >>> st.nlsat_propagations
6351  2
6352  >>> st.nlsat_stages
6353  2
6354  """
6355  key = name.replace('_', ' ')
6356  try:
6357  return self.get_key_value(key)
6358  except Z3Exception:
6359  raise AttributeError
6360 
6361 #########################################
6362 #
6363 # Solver
6364 #
6365 #########################################
6366 class CheckSatResult:
6367  """Represents the result of a satisfiability check: sat, unsat, unknown.
6368 
6369  >>> s = Solver()
6370  >>> s.check()
6371  sat
6372  >>> r = s.check()
6373  >>> isinstance(r, CheckSatResult)
6374  True
6375  """
6376 
6377  def __init__(self, r):
6378  self.r = r
6379 
6380  def __deepcopy__(self, memo={}):
6381  return CheckSatResult(self.r)
6382 
6383  def __eq__(self, other):
6384  return isinstance(other, CheckSatResult) and self.r == other.r
6385 
6386  def __ne__(self, other):
6387  return not self.__eq__(other)
6388 
6389  def __repr__(self):
6390  if in_html_mode():
6391  if self.r == Z3_L_TRUE:
6392  return "<b>sat</b>"
6393  elif self.r == Z3_L_FALSE:
6394  return "<b>unsat</b>"
6395  else:
6396  return "<b>unknown</b>"
6397  else:
6398  if self.r == Z3_L_TRUE:
6399  return "sat"
6400  elif self.r == Z3_L_FALSE:
6401  return "unsat"
6402  else:
6403  return "unknown"
6404 
6405 sat = CheckSatResult(Z3_L_TRUE)
6406 unsat = CheckSatResult(Z3_L_FALSE)
6407 unknown = CheckSatResult(Z3_L_UNDEF)
6408 
6409 class Solver(Z3PPObject):
6410  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6411 
6412  def __init__(self, solver=None, ctx=None):
6413  assert solver is None or ctx is not None
6414  self.ctx = _get_ctx(ctx)
6415  self.backtrack_level = 4000000000
6416  self.solver = None
6417  if solver is None:
6418  self.solver = Z3_mk_solver(self.ctx.ref())
6419  else:
6420  self.solver = solver
6421  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6422 
6423  def __del__(self):
6424  if self.solver is not None and self.ctx.ref() is not None:
6425  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6426 
6427  def set(self, *args, **keys):
6428  """Set a configuration option. The method `help()` return a string containing all available options.
6429 
6430  >>> s = Solver()
6431  >>> # The option MBQI can be set using three different approaches.
6432  >>> s.set(mbqi=True)
6433  >>> s.set('MBQI', True)
6434  >>> s.set(':mbqi', True)
6435  """
6436  p = args2params(args, keys, self.ctx)
6437  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6438 
6439  def push(self):
6440  """Create a backtracking point.
6441 
6442  >>> x = Int('x')
6443  >>> s = Solver()
6444  >>> s.add(x > 0)
6445  >>> s
6446  [x > 0]
6447  >>> s.push()
6448  >>> s.add(x < 1)
6449  >>> s
6450  [x > 0, x < 1]
6451  >>> s.check()
6452  unsat
6453  >>> s.pop()
6454  >>> s.check()
6455  sat
6456  >>> s
6457  [x > 0]
6458  """
6459  Z3_solver_push(self.ctx.ref(), self.solver)
6460 
6461  def pop(self, num=1):
6462  """Backtrack \c num backtracking points.
6463 
6464  >>> x = Int('x')
6465  >>> s = Solver()
6466  >>> s.add(x > 0)
6467  >>> s
6468  [x > 0]
6469  >>> s.push()
6470  >>> s.add(x < 1)
6471  >>> s
6472  [x > 0, x < 1]
6473  >>> s.check()
6474  unsat
6475  >>> s.pop()
6476  >>> s.check()
6477  sat
6478  >>> s
6479  [x > 0]
6480  """
6481  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6482 
6483  def num_scopes(self):
6484  """Return the current number of backtracking points.
6485 
6486  >>> s = Solver()
6487  >>> s.num_scopes()
6488  0L
6489  >>> s.push()
6490  >>> s.num_scopes()
6491  1L
6492  >>> s.push()
6493  >>> s.num_scopes()
6494  2L
6495  >>> s.pop()
6496  >>> s.num_scopes()
6497  1L
6498  """
6499  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6500 
6501  def reset(self):
6502  """Remove all asserted constraints and backtracking points created using `push()`.
6503 
6504  >>> x = Int('x')
6505  >>> s = Solver()
6506  >>> s.add(x > 0)
6507  >>> s
6508  [x > 0]
6509  >>> s.reset()
6510  >>> s
6511  []
6512  """
6513  Z3_solver_reset(self.ctx.ref(), self.solver)
6514 
6515  def assert_exprs(self, *args):
6516  """Assert constraints into the solver.
6517 
6518  >>> x = Int('x')
6519  >>> s = Solver()
6520  >>> s.assert_exprs(x > 0, x < 2)
6521  >>> s
6522  [x > 0, x < 2]
6523  """
6524  args = _get_args(args)
6525  s = BoolSort(self.ctx)
6526  for arg in args:
6527  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6528  for f in arg:
6529  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6530  else:
6531  arg = s.cast(arg)
6532  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6533 
6534  def add(self, *args):
6535  """Assert constraints into the solver.
6536 
6537  >>> x = Int('x')
6538  >>> s = Solver()
6539  >>> s.add(x > 0, x < 2)
6540  >>> s
6541  [x > 0, x < 2]
6542  """
6543  self.assert_exprs(*args)
6544 
6545  def __iadd__(self, fml):
6546  self.add(fml)
6547  return self
6548 
6549  def append(self, *args):
6550  """Assert constraints into the solver.
6551 
6552  >>> x = Int('x')
6553  >>> s = Solver()
6554  >>> s.append(x > 0, x < 2)
6555  >>> s
6556  [x > 0, x < 2]
6557  """
6558  self.assert_exprs(*args)
6559 
6560  def insert(self, *args):
6561  """Assert constraints into the solver.
6562 
6563  >>> x = Int('x')
6564  >>> s = Solver()
6565  >>> s.insert(x > 0, x < 2)
6566  >>> s
6567  [x > 0, x < 2]
6568  """
6569  self.assert_exprs(*args)
6570 
6571  def assert_and_track(self, a, p):
6572  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6573 
6574  If `p` is a string, it will be automatically converted into a Boolean constant.
6575 
6576  >>> x = Int('x')
6577  >>> p3 = Bool('p3')
6578  >>> s = Solver()
6579  >>> s.set(unsat_core=True)
6580  >>> s.assert_and_track(x > 0, 'p1')
6581  >>> s.assert_and_track(x != 1, 'p2')
6582  >>> s.assert_and_track(x < 0, p3)
6583  >>> print(s.check())
6584  unsat
6585  >>> c = s.unsat_core()
6586  >>> len(c)
6587  2
6588  >>> Bool('p1') in c
6589  True
6590  >>> Bool('p2') in c
6591  False
6592  >>> p3 in c
6593  True
6594  """
6595  if isinstance(p, str):
6596  p = Bool(p, self.ctx)
6597  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6598  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6599  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6600 
6601  def check(self, *assumptions):
6602  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6603 
6604  >>> x = Int('x')
6605  >>> s = Solver()
6606  >>> s.check()
6607  sat
6608  >>> s.add(x > 0, x < 2)
6609  >>> s.check()
6610  sat
6611  >>> s.model().eval(x)
6612  1
6613  >>> s.add(x < 1)
6614  >>> s.check()
6615  unsat
6616  >>> s.reset()
6617  >>> s.add(2**x == 4)
6618  >>> s.check()
6619  unknown
6620  """
6621  assumptions = _get_args(assumptions)
6622  num = len(assumptions)
6623  _assumptions = (Ast * num)()
6624  for i in range(num):
6625  _assumptions[i] = assumptions[i].as_ast()
6626  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6627  return CheckSatResult(r)
6628 
6629  def model(self):
6630  """Return a model for the last `check()`.
6631 
6632  This function raises an exception if
6633  a model is not available (e.g., last `check()` returned unsat).
6634 
6635  >>> s = Solver()
6636  >>> a = Int('a')
6637  >>> s.add(a + 2 == 0)
6638  >>> s.check()
6639  sat
6640  >>> s.model()
6641  [a = -2]
6642  """
6643  try:
6644  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6645  except Z3Exception:
6646  raise Z3Exception("model is not available")
6647 
6648  def unsat_core(self):
6649  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6650 
6651  These are the assumptions Z3 used in the unsatisfiability proof.
6652  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6653  They may be also used to "retract" assumptions. Note that, assumptions are not really
6654  "soft constraints", but they can be used to implement them.
6655 
6656  >>> p1, p2, p3 = Bools('p1 p2 p3')
6657  >>> x, y = Ints('x y')
6658  >>> s = Solver()
6659  >>> s.add(Implies(p1, x > 0))
6660  >>> s.add(Implies(p2, y > x))
6661  >>> s.add(Implies(p2, y < 1))
6662  >>> s.add(Implies(p3, y > -3))
6663  >>> s.check(p1, p2, p3)
6664  unsat
6665  >>> core = s.unsat_core()
6666  >>> len(core)
6667  2
6668  >>> p1 in core
6669  True
6670  >>> p2 in core
6671  True
6672  >>> p3 in core
6673  False
6674  >>> # "Retracting" p2
6675  >>> s.check(p1, p3)
6676  sat
6677  """
6678  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6679 
6680  def consequences(self, assumptions, variables):
6681  """Determine fixed values for the variables based on the solver state and assumptions.
6682  >>> s = Solver()
6683  >>> a, b, c, d = Bools('a b c d')
6684  >>> s.add(Implies(a,b), Implies(b, c))
6685  >>> s.consequences([a],[b,c,d])
6686  (sat, [Implies(a, b), Implies(a, c)])
6687  >>> s.consequences([Not(c),d],[a,b,c,d])
6688  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6689  """
6690  if isinstance(assumptions, list):
6691  _asms = AstVector(None, self.ctx)
6692  for a in assumptions:
6693  _asms.push(a)
6694  assumptions = _asms
6695  if isinstance(variables, list):
6696  _vars = AstVector(None, self.ctx)
6697  for a in variables:
6698  _vars.push(a)
6699  variables = _vars
6700  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6701  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6702  consequences = AstVector(None, self.ctx)
6703  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6704  sz = len(consequences)
6705  consequences = [ consequences[i] for i in range(sz) ]
6706  return CheckSatResult(r), consequences
6707 
6708  def from_file(self, filename):
6709  """Parse assertions from a file"""
6710  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6711 
6712  def from_string(self, s):
6713  """Parse assertions from a string"""
6714  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6715 
6716  def cube(self, vars = None):
6717  """Get set of cubes
6718  The method takes an optional set of variables that restrict which
6719  variables may be used as a starting point for cubing.
6720  If vars is not None, then the first case split is based on a variable in
6721  this set.
6722  """
6723  self.cube_vs = AstVector(None, self.ctx)
6724  if vars is not None:
6725  for v in vars:
6726  self.cube_vs.push(v)
6727  while True:
6728  lvl = self.backtrack_level
6729  self.backtrack_level = 4000000000
6730  r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
6731  if (len(r) == 1 and is_false(r[0])):
6732  return
6733  yield r
6734  if (len(r) == 0):
6735  return
6736 
6737  def cube_vars(self):
6738  """Access the set of variables that were touched by the most recently generated cube.
6739  This set of variables can be used as a starting point for additional cubes.
6740  The idea is that variables that appear in clauses that are reduced by the most recent
6741  cube are likely more useful to cube on."""
6742  return self.cube_vs
6743 
6744  def proof(self):
6745  """Return a proof for the last `check()`. Proof construction must be enabled."""
6746  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6747 
6748  def assertions(self):
6749  """Return an AST vector containing all added constraints.
6750 
6751  >>> s = Solver()
6752  >>> s.assertions()
6753  []
6754  >>> a = Int('a')
6755  >>> s.add(a > 0)
6756  >>> s.add(a < 10)
6757  >>> s.assertions()
6758  [a > 0, a < 10]
6759  """
6760  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6761 
6762  def units(self):
6763  """Return an AST vector containing all currently inferred units.
6764  """
6765  return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
6766 
6767  def non_units(self):
6768  """Return an AST vector containing all atomic formulas in solver state that are not units.
6769  """
6770  return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
6771 
6772  def trail_levels(self):
6773  """Return trail and decision levels of the solver state after a check() call.
6774  """
6775  trail = self.trail()
6776  levels = (ctypes.c_uint * len(trail))()
6777  Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
6778  return trail, levels
6779 
6780  def trail(self):
6781  """Return trail of the solver state after a check() call.
6782  """
6783  return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
6784 
6785  def statistics(self):
6786  """Return statistics for the last `check()`.
6787 
6788  >>> s = SimpleSolver()
6789  >>> x = Int('x')
6790  >>> s.add(x > 0)
6791  >>> s.check()
6792  sat
6793  >>> st = s.statistics()
6794  >>> st.get_key_value('final checks')
6795  1
6796  >>> len(st) > 0
6797  True
6798  >>> st[0] != 0
6799  True
6800  """
6801  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6802 
6803  def reason_unknown(self):
6804  """Return a string describing why the last `check()` returned `unknown`.
6805 
6806  >>> x = Int('x')
6807  >>> s = SimpleSolver()
6808  >>> s.add(2**x == 4)
6809  >>> s.check()
6810  unknown
6811  >>> s.reason_unknown()
6812  '(incomplete (theory arithmetic))'
6813  """
6814  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6815 
6816  def help(self):
6817  """Display a string describing all available options."""
6818  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6819 
6820  def param_descrs(self):
6821  """Return the parameter description set."""
6822  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6823 
6824  def __repr__(self):
6825  """Return a formatted string with all added constraints."""
6826  return obj_to_string(self)
6827 
6828  def translate(self, target):
6829  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6830 
6831  >>> c1 = Context()
6832  >>> c2 = Context()
6833  >>> s1 = Solver(ctx=c1)
6834  >>> s2 = s1.translate(c2)
6835  """
6836  if z3_debug():
6837  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6838  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6839  return Solver(solver, target)
6840 
6841  def __copy__(self):
6842  return self.translate(self.ctx)
6843 
6844  def __deepcopy__(self, memo={}):
6845  return self.translate(self.ctx)
6846 
6847  def sexpr(self):
6848  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6849 
6850  >>> x = Int('x')
6851  >>> s = Solver()
6852  >>> s.add(x > 0)
6853  >>> s.add(x < 2)
6854  >>> r = s.sexpr()
6855  """
6856  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6857 
6858  def dimacs(self):
6859  """Return a textual representation of the solver in DIMACS format."""
6860  return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver)
6861 
6862  def to_smt2(self):
6863  """return SMTLIB2 formatted benchmark for solver's assertions"""
6864  es = self.assertions()
6865  sz = len(es)
6866  sz1 = sz
6867  if sz1 > 0:
6868  sz1 -= 1
6869  v = (Ast * sz1)()
6870  for i in range(sz1):
6871  v[i] = es[i].as_ast()
6872  if sz > 0:
6873  e = es[sz1].as_ast()
6874  else:
6875  e = BoolVal(True, self.ctx).as_ast()
6876  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6877 
6878 def SolverFor(logic, ctx=None):
6879  """Create a solver customized for the given logic.
6880 
6881  The parameter `logic` is a string. It should be contains
6882  the name of a SMT-LIB logic.
6883  See http://www.smtlib.org/ for the name of all available logics.
6884 
6885  >>> s = SolverFor("QF_LIA")
6886  >>> x = Int('x')
6887  >>> s.add(x > 0)
6888  >>> s.add(x < 2)
6889  >>> s.check()
6890  sat
6891  >>> s.model()
6892  [x = 1]
6893  """
6894  ctx = _get_ctx(ctx)
6895  logic = to_symbol(logic)
6896  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6897 
6898 def SimpleSolver(ctx=None):
6899  """Return a simple general purpose solver with limited amount of preprocessing.
6900 
6901  >>> s = SimpleSolver()
6902  >>> x = Int('x')
6903  >>> s.add(x > 0)
6904  >>> s.check()
6905  sat
6906  """
6907  ctx = _get_ctx(ctx)
6908  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6909 
6910 #########################################
6911 #
6912 # Fixedpoint
6913 #
6914 #########################################
6915 
6917  """Fixedpoint API provides methods for solving with recursive predicates"""
6918 
6919  def __init__(self, fixedpoint=None, ctx=None):
6920  assert fixedpoint is None or ctx is not None
6921  self.ctx = _get_ctx(ctx)
6922  self.fixedpoint = None
6923  if fixedpoint is None:
6924  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6925  else:
6926  self.fixedpoint = fixedpoint
6927  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6928  self.vars = []
6929 
6930  def __deepcopy__(self, memo={}):
6931  return FixedPoint(self.fixedpoint, self.ctx)
6932 
6933  def __del__(self):
6934  if self.fixedpoint is not None and self.ctx.ref() is not None:
6935  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6936 
6937  def set(self, *args, **keys):
6938  """Set a configuration option. The method `help()` return a string containing all available options.
6939  """
6940  p = args2params(args, keys, self.ctx)
6941  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6942 
6943  def help(self):
6944  """Display a string describing all available options."""
6945  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6946 
6947  def param_descrs(self):
6948  """Return the parameter description set."""
6949  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6950 
6951  def assert_exprs(self, *args):
6952  """Assert constraints as background axioms for the fixedpoint solver."""
6953  args = _get_args(args)
6954  s = BoolSort(self.ctx)
6955  for arg in args:
6956  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6957  for f in arg:
6958  f = self.abstract(f)
6959  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6960  else:
6961  arg = s.cast(arg)
6962  arg = self.abstract(arg)
6963  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6964 
6965  def add(self, *args):
6966  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6967  self.assert_exprs(*args)
6968 
6969  def __iadd__(self, fml):
6970  self.add(fml)
6971  return self
6972 
6973  def append(self, *args):
6974  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6975  self.assert_exprs(*args)
6976 
6977  def insert(self, *args):
6978  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6979  self.assert_exprs(*args)
6980 
6981  def add_rule(self, head, body = None, name = None):
6982  """Assert rules defining recursive predicates to the fixedpoint solver.
6983  >>> a = Bool('a')
6984  >>> b = Bool('b')
6985  >>> s = Fixedpoint()
6986  >>> s.register_relation(a.decl())
6987  >>> s.register_relation(b.decl())
6988  >>> s.fact(a)
6989  >>> s.rule(b, a)
6990  >>> s.query(b)
6991  sat
6992  """
6993  if name is None:
6994  name = ""
6995  name = to_symbol(name, self.ctx)
6996  if body is None:
6997  head = self.abstract(head)
6998  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6999  else:
7000  body = _get_args(body)
7001  f = self.abstract(Implies(And(body, self.ctx),head))
7002  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7003 
7004  def rule(self, head, body = None, name = None):
7005  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7006  self.add_rule(head, body, name)
7007 
7008  def fact(self, head, name = None):
7009  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7010  self.add_rule(head, None, name)
7011 
7012  def query(self, *query):
7013  """Query the fixedpoint engine whether formula is derivable.
7014  You can also pass an tuple or list of recursive predicates.
7015  """
7016  query = _get_args(query)
7017  sz = len(query)
7018  if sz >= 1 and isinstance(query[0], FuncDeclRef):
7019  _decls = (FuncDecl * sz)()
7020  i = 0
7021  for q in query:
7022  _decls[i] = q.ast
7023  i = i + 1
7024  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7025  else:
7026  if sz == 1:
7027  query = query[0]
7028  else:
7029  query = And(query, self.ctx)
7030  query = self.abstract(query, False)
7031  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7032  return CheckSatResult(r)
7033 
7034  def query_from_lvl (self, lvl, *query):
7035  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7036  """
7037  query = _get_args(query)
7038  sz = len(query)
7039  if sz >= 1 and isinstance(query[0], FuncDecl):
7040  _z3_assert (False, "unsupported")
7041  else:
7042  if sz == 1:
7043  query = query[0]
7044  else:
7045  query = And(query)
7046  query = self.abstract(query, False)
7047  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7048  return CheckSatResult(r)
7049 
7050  def update_rule(self, head, body, name):
7051  """update rule"""
7052  if name is None:
7053  name = ""
7054  name = to_symbol(name, self.ctx)
7055  body = _get_args(body)
7056  f = self.abstract(Implies(And(body, self.ctx),head))
7057  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7058 
7059  def get_answer(self):
7060  """Retrieve answer from last query call."""
7061  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7062  return _to_expr_ref(r, self.ctx)
7063 
7065  """Retrieve a ground cex from last query call."""
7066  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7067  return _to_expr_ref(r, self.ctx)
7068 
7070  """retrieve rules along the counterexample trace"""
7071  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7072 
7074  """retrieve rule names along the counterexample trace"""
7075  # this is a hack as I don't know how to return a list of symbols from C++;
7076  # obtain names as a single string separated by semicolons
7077  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7078  # split into individual names
7079  return names.split (';')
7080 
7081  def get_num_levels(self, predicate):
7082  """Retrieve number of levels used for predicate in PDR engine"""
7083  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7084 
7085  def get_cover_delta(self, level, predicate):
7086  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
7087  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7088  return _to_expr_ref(r, self.ctx)
7089 
7090  def add_cover(self, level, predicate, property):
7091  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
7092  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7093 
7094  def register_relation(self, *relations):
7095  """Register relation as recursive"""
7096  relations = _get_args(relations)
7097  for f in relations:
7098  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7099 
7100  def set_predicate_representation(self, f, *representations):
7101  """Control how relation is represented"""
7102  representations = _get_args(representations)
7103  representations = [to_symbol(s) for s in representations]
7104  sz = len(representations)
7105  args = (Symbol * sz)()
7106  for i in range(sz):
7107  args[i] = representations[i]
7108  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7109 
7110  def parse_string(self, s):
7111  """Parse rules and queries from a string"""
7112  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7113 
7114  def parse_file(self, f):
7115  """Parse rules and queries from a file"""
7116  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7117 
7118  def get_rules(self):
7119  """retrieve rules that have been added to fixedpoint context"""
7120  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7121 
7122  def get_assertions(self):
7123  """retrieve assertions that have been added to fixedpoint context"""
7124  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7125 
7126  def __repr__(self):
7127  """Return a formatted string with all added rules and constraints."""
7128  return self.sexpr()
7129 
7130  def sexpr(self):
7131  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7132  """
7133  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7134 
7135  def to_string(self, queries):
7136  """Return a formatted string (in Lisp-like format) with all added constraints.
7137  We say the string is in s-expression format.
7138  Include also queries.
7139  """
7140  args, len = _to_ast_array(queries)
7141  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7142 
7143  def statistics(self):
7144  """Return statistics for the last `query()`.
7145  """
7146  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7147 
7148  def reason_unknown(self):
7149  """Return a string describing why the last `query()` returned `unknown`.
7150  """
7151  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7152 
7153  def declare_var(self, *vars):
7154  """Add variable or several variables.
7155  The added variable or variables will be bound in the rules
7156  and queries
7157  """
7158  vars = _get_args(vars)
7159  for v in vars:
7160  self.vars += [v]
7161 
7162  def abstract(self, fml, is_forall=True):
7163  if self.vars == []:
7164  return fml
7165  if is_forall:
7166  return ForAll(self.vars, fml)
7167  else:
7168  return Exists(self.vars, fml)
7169 
7170 
7171 #########################################
7172 #
7173 # Finite domains
7174 #
7175 #########################################
7176 
7178  """Finite domain sort."""
7179 
7180  def size(self):
7181  """Return the size of the finite domain sort"""
7182  r = (ctypes.c_ulonglong * 1)()
7183  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7184  return r[0]
7185  else:
7186  raise Z3Exception("Failed to retrieve finite domain sort size")
7187 
7188 def FiniteDomainSort(name, sz, ctx=None):
7189  """Create a named finite domain sort of a given size sz"""
7190  if not isinstance(name, Symbol):
7191  name = to_symbol(name)
7192  ctx = _get_ctx(ctx)
7193  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7194 
7196  """Return True if `s` is a Z3 finite-domain sort.
7197 
7198  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7199  True
7200  >>> is_finite_domain_sort(IntSort())
7201  False
7202  """
7203  return isinstance(s, FiniteDomainSortRef)
7204 
7205 
7207  """Finite-domain expressions."""
7208 
7209  def sort(self):
7210  """Return the sort of the finite-domain expression `self`."""
7211  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7212 
7213  def as_string(self):
7214  """Return a Z3 floating point expression as a Python string."""
7215  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7216 
7218  """Return `True` if `a` is a Z3 finite-domain expression.
7219 
7220  >>> s = FiniteDomainSort('S', 100)
7221  >>> b = Const('b', s)
7222  >>> is_finite_domain(b)
7223  True
7224  >>> is_finite_domain(Int('x'))
7225  False
7226  """
7227  return isinstance(a, FiniteDomainRef)
7228 
7229 
7231  """Integer values."""
7232 
7233  def as_long(self):
7234  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7235 
7236  >>> s = FiniteDomainSort('S', 100)
7237  >>> v = FiniteDomainVal(3, s)
7238  >>> v
7239  3
7240  >>> v.as_long() + 1
7241  4
7242  """
7243  return int(self.as_string())
7244 
7245  def as_string(self):
7246  """Return a Z3 finite-domain numeral as a Python string.
7247 
7248  >>> s = FiniteDomainSort('S', 100)
7249  >>> v = FiniteDomainVal(42, s)
7250  >>> v.as_string()
7251  '42'
7252  """
7253  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
7254 
7255 
7256 def FiniteDomainVal(val, sort, ctx=None):
7257  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7258 
7259  >>> s = FiniteDomainSort('S', 256)
7260  >>> FiniteDomainVal(255, s)
7261  255
7262  >>> FiniteDomainVal('100', s)
7263  100
7264  """
7265  if z3_debug():
7266  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
7267  ctx = sort.ctx
7268  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7269 
7271  """Return `True` if `a` is a Z3 finite-domain value.
7272 
7273  >>> s = FiniteDomainSort('S', 100)
7274  >>> b = Const('b', s)
7275  >>> is_finite_domain_value(b)
7276  False
7277  >>> b = FiniteDomainVal(10, s)
7278  >>> b
7279  10
7280  >>> is_finite_domain_value(b)
7281  True
7282  """
7283  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7284 
7285 
7286 #########################################
7287 #
7288 # Optimize
7289 #
7290 #########################################
7291 
7293  def __init__(self, opt, value, is_max):
7294  self._opt = opt
7295  self._value = value
7296  self._is_max = is_max
7297 
7298  def lower(self):
7299  opt = self._opt
7300  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7301 
7302  def upper(self):
7303  opt = self._opt
7304  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7305 
7306  def lower_values(self):
7307  opt = self._opt
7308  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7309 
7310  def upper_values(self):
7311  opt = self._opt
7312  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7313 
7314  def value(self):
7315  if self._is_max:
7316  return self.upper()
7317  else:
7318  return self.lower()
7319 
7320  def __str__(self):
7321  return "%s:%s" % (self._value, self._is_max)
7322 
7323 
7325  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7326 
7327  def __init__(self, ctx=None):
7328  self.ctx = _get_ctx(ctx)
7329  self.optimize = Z3_mk_optimize(self.ctx.ref())
7330  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7331 
7332  def __deepcopy__(self, memo={}):
7333  return Optimize(self.optimize, self.ctx)
7334 
7335  def __del__(self):
7336  if self.optimize is not None and self.ctx.ref() is not None:
7337  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7338 
7339  def set(self, *args, **keys):
7340  """Set a configuration option. The method `help()` return a string containing all available options.
7341  """
7342  p = args2params(args, keys, self.ctx)
7343  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7344 
7345  def help(self):
7346  """Display a string describing all available options."""
7347  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7348 
7349  def param_descrs(self):
7350  """Return the parameter description set."""
7351  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7352 
7353  def assert_exprs(self, *args):
7354  """Assert constraints as background axioms for the optimize solver."""
7355  args = _get_args(args)
7356  s = BoolSort(self.ctx)
7357  for arg in args:
7358  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7359  for f in arg:
7360  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7361  else:
7362  arg = s.cast(arg)
7363  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7364 
7365  def add(self, *args):
7366  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7367  self.assert_exprs(*args)
7368 
7369  def __iadd__(self, fml):
7370  self.add(fml)
7371  return self
7372 
7373  def assert_and_track(self, a, p):
7374  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7375 
7376  If `p` is a string, it will be automatically converted into a Boolean constant.
7377 
7378  >>> x = Int('x')
7379  >>> p3 = Bool('p3')
7380  >>> s = Optimize()
7381  >>> s.assert_and_track(x > 0, 'p1')
7382  >>> s.assert_and_track(x != 1, 'p2')
7383  >>> s.assert_and_track(x < 0, p3)
7384  >>> print(s.check())
7385  unsat
7386  >>> c = s.unsat_core()
7387  >>> len(c)
7388  2
7389  >>> Bool('p1') in c
7390  True
7391  >>> Bool('p2') in c
7392  False
7393  >>> p3 in c
7394  True
7395  """
7396  if isinstance(p, str):
7397  p = Bool(p, self.ctx)
7398  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7399  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7400  Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7401 
7402  def add_soft(self, arg, weight = "1", id = None):
7403  """Add soft constraint with optional weight and optional identifier.
7404  If no weight is supplied, then the penalty for violating the soft constraint
7405  is 1.
7406  Soft constraints are grouped by identifiers. Soft constraints that are
7407  added without identifiers are grouped by default.
7408  """
7409  if _is_int(weight):
7410  weight = "%d" % weight
7411  elif isinstance(weight, float):
7412  weight = "%f" % weight
7413  if not isinstance(weight, str):
7414  raise Z3Exception("weight should be a string or an integer")
7415  if id is None:
7416  id = ""
7417  id = to_symbol(id, self.ctx)
7418  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7419  return OptimizeObjective(self, v, False)
7420 
7421  def maximize(self, arg):
7422  """Add objective function to maximize."""
7423  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7424 
7425  def minimize(self, arg):
7426  """Add objective function to minimize."""
7427  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7428 
7429  def push(self):
7430  """create a backtracking point for added rules, facts and assertions"""
7431  Z3_optimize_push(self.ctx.ref(), self.optimize)
7432 
7433  def pop(self):
7434  """restore to previously created backtracking point"""
7435  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7436 
7437  def check(self, *assumptions):
7438  """Check satisfiability while optimizing objective functions."""
7439  assumptions = _get_args(assumptions)
7440  num = len(assumptions)
7441  _assumptions = (Ast * num)()
7442  for i in range(num):
7443  _assumptions[i] = assumptions[i].as_ast()
7444  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7445 
7446  def reason_unknown(self):
7447  """Return a string that describes why the last `check()` returned `unknown`."""
7448  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7449 
7450  def model(self):
7451  """Return a model for the last check()."""
7452  try:
7453  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7454  except Z3Exception:
7455  raise Z3Exception("model is not available")
7456 
7457  def unsat_core(self):
7458  return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7459 
7460  def lower(self, obj):
7461  if not isinstance(obj, OptimizeObjective):
7462  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7463  return obj.lower()
7464 
7465  def upper(self, obj):
7466  if not isinstance(obj, OptimizeObjective):
7467  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7468  return obj.upper()
7469 
7470  def lower_values(self, obj):
7471  if not isinstance(obj, OptimizeObjective):
7472  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7473  return obj.lower_values()
7474 
7475  def upper_values(self, obj):
7476  if not isinstance(obj, OptimizeObjective):
7477  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7478  return obj.upper_values()
7479 
7480  def from_file(self, filename):
7481  """Parse assertions and objectives from a file"""
7482  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7483 
7484  def from_string(self, s):
7485  """Parse assertions and objectives from a string"""
7486  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7487 
7488  def assertions(self):
7489  """Return an AST vector containing all added constraints."""
7490  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7491 
7492  def objectives(self):
7493  """returns set of objective functions"""
7494  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7495 
7496  def __repr__(self):
7497  """Return a formatted string with all added rules and constraints."""
7498  return self.sexpr()
7499 
7500  def sexpr(self):
7501  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7502  """
7503  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7504 
7505  def statistics(self):
7506  """Return statistics for the last check`.
7507  """
7508  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7509 
7510 
7511 
7512 
7513 #########################################
7514 #
7515 # ApplyResult
7516 #
7517 #########################################
7519  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7520 
7521  def __init__(self, result, ctx):
7522  self.result = result
7523  self.ctx = ctx
7524  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7525 
7526  def __deepcopy__(self, memo={}):
7527  return ApplyResult(self.result, self.ctx)
7528 
7529  def __del__(self):
7530  if self.ctx.ref() is not None:
7531  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7532 
7533  def __len__(self):
7534  """Return the number of subgoals in `self`.
7535 
7536  >>> a, b = Ints('a b')
7537  >>> g = Goal()
7538  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7539  >>> t = Tactic('split-clause')
7540  >>> r = t(g)
7541  >>> len(r)
7542  2
7543  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7544  >>> len(t(g))
7545  4
7546  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7547  >>> len(t(g))
7548  1
7549  """
7550  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7551 
7552  def __getitem__(self, idx):
7553  """Return one of the subgoals stored in ApplyResult object `self`.
7554 
7555  >>> a, b = Ints('a b')
7556  >>> g = Goal()
7557  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7558  >>> t = Tactic('split-clause')
7559  >>> r = t(g)
7560  >>> r[0]
7561  [a == 0, Or(b == 0, b == 1), a > b]
7562  >>> r[1]
7563  [a == 1, Or(b == 0, b == 1), a > b]
7564  """
7565  if idx >= len(self):
7566  raise IndexError
7567  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7568 
7569  def __repr__(self):
7570  return obj_to_string(self)
7571 
7572  def sexpr(self):
7573  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7574  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7575 
7576 
7577  def as_expr(self):
7578  """Return a Z3 expression consisting of all subgoals.
7579 
7580  >>> x = Int('x')
7581  >>> g = Goal()
7582  >>> g.add(x > 1)
7583  >>> g.add(Or(x == 2, x == 3))
7584  >>> r = Tactic('simplify')(g)
7585  >>> r
7586  [[Not(x <= 1), Or(x == 2, x == 3)]]
7587  >>> r.as_expr()
7588  And(Not(x <= 1), Or(x == 2, x == 3))
7589  >>> r = Tactic('split-clause')(g)
7590  >>> r
7591  [[x > 1, x == 2], [x > 1, x == 3]]
7592  >>> r.as_expr()
7593  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7594  """
7595  sz = len(self)
7596  if sz == 0:
7597  return BoolVal(False, self.ctx)
7598  elif sz == 1:
7599  return self[0].as_expr()
7600  else:
7601  return Or([ self[i].as_expr() for i in range(len(self)) ])
7602 
7603 #########################################
7604 #
7605 # Tactics
7606 #
7607 #########################################
7608 class Tactic:
7609  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7610 
7611  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7612  """
7613  def __init__(self, tactic, ctx=None):
7614  self.ctx = _get_ctx(ctx)
7615  self.tactic = None
7616  if isinstance(tactic, TacticObj):
7617  self.tactic = tactic
7618  else:
7619  if z3_debug():
7620  _z3_assert(isinstance(tactic, str), "tactic name expected")
7621  try:
7622  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7623  except Z3Exception:
7624  raise Z3Exception("unknown tactic '%s'" % tactic)
7625  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7626 
7627  def __deepcopy__(self, memo={}):
7628  return Tactic(self.tactic, self.ctx)
7629 
7630  def __del__(self):
7631  if self.tactic is not None and self.ctx.ref() is not None:
7632  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7633 
7634  def solver(self):
7635  """Create a solver using the tactic `self`.
7636 
7637  The solver supports the methods `push()` and `pop()`, but it
7638  will always solve each `check()` from scratch.
7639 
7640  >>> t = Then('simplify', 'nlsat')
7641  >>> s = t.solver()
7642  >>> x = Real('x')
7643  >>> s.add(x**2 == 2, x > 0)
7644  >>> s.check()
7645  sat
7646  >>> s.model()
7647  [x = 1.4142135623?]
7648  """
7649  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7650 
7651  def apply(self, goal, *arguments, **keywords):
7652  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7653 
7654  >>> x, y = Ints('x y')
7655  >>> t = Tactic('solve-eqs')
7656  >>> t.apply(And(x == 0, y >= x + 1))
7657  [[y >= 1]]
7658  """
7659  if z3_debug():
7660  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7661  goal = _to_goal(goal)
7662  if len(arguments) > 0 or len(keywords) > 0:
7663  p = args2params(arguments, keywords, self.ctx)
7664  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7665  else:
7666  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7667 
7668  def __call__(self, goal, *arguments, **keywords):
7669  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7670 
7671  >>> x, y = Ints('x y')
7672  >>> t = Tactic('solve-eqs')
7673  >>> t(And(x == 0, y >= x + 1))
7674  [[y >= 1]]
7675  """
7676  return self.apply(goal, *arguments, **keywords)
7677 
7678  def help(self):
7679  """Display a string containing a description of the available options for the `self` tactic."""
7680  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7681 
7682  def param_descrs(self):
7683  """Return the parameter description set."""
7684  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7685 
7686 def _to_goal(a):
7687  if isinstance(a, BoolRef):
7688  goal = Goal(ctx = a.ctx)
7689  goal.add(a)
7690  return goal
7691  else:
7692  return a
7693 
7694 def _to_tactic(t, ctx=None):
7695  if isinstance(t, Tactic):
7696  return t
7697  else:
7698  return Tactic(t, ctx)
7699 
7700 def _and_then(t1, t2, ctx=None):
7701  t1 = _to_tactic(t1, ctx)
7702  t2 = _to_tactic(t2, ctx)
7703  if z3_debug():
7704  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7705  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7706 
7707 def _or_else(t1, t2, ctx=None):
7708  t1 = _to_tactic(t1, ctx)
7709  t2 = _to_tactic(t2, ctx)
7710  if z3_debug():
7711  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7712  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7713 
7714 def AndThen(*ts, **ks):
7715  """Return a tactic that applies the tactics in `*ts` in sequence.
7716 
7717  >>> x, y = Ints('x y')
7718  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7719  >>> t(And(x == 0, y > x + 1))
7720  [[Not(y <= 1)]]
7721  >>> t(And(x == 0, y > x + 1)).as_expr()
7722  Not(y <= 1)
7723  """
7724  if z3_debug():
7725  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7726  ctx = ks.get('ctx', None)
7727  num = len(ts)
7728  r = ts[0]
7729  for i in range(num - 1):
7730  r = _and_then(r, ts[i+1], ctx)
7731  return r
7732 
7733 def Then(*ts, **ks):
7734  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7735 
7736  >>> x, y = Ints('x y')
7737  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7738  >>> t(And(x == 0, y > x + 1))
7739  [[Not(y <= 1)]]
7740  >>> t(And(x == 0, y > x + 1)).as_expr()
7741  Not(y <= 1)
7742  """
7743  return AndThen(*ts, **ks)
7744 
7745 def OrElse(*ts, **ks):
7746  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7747 
7748  >>> x = Int('x')
7749  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7750  >>> # Tactic split-clause fails if there is no clause in the given goal.
7751  >>> t(x == 0)
7752  [[x == 0]]
7753  >>> t(Or(x == 0, x == 1))
7754  [[x == 0], [x == 1]]
7755  """
7756  if z3_debug():
7757  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7758  ctx = ks.get('ctx', None)
7759  num = len(ts)
7760  r = ts[0]
7761  for i in range(num - 1):
7762  r = _or_else(r, ts[i+1], ctx)
7763  return r
7764 
7765 def ParOr(*ts, **ks):
7766  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7767 
7768  >>> x = Int('x')
7769  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7770  >>> t(x + 1 == 2)
7771  [[x == 1]]
7772  """
7773  if z3_debug():
7774  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7775  ctx = _get_ctx(ks.get('ctx', None))
7776  ts = [ _to_tactic(t, ctx) for t in ts ]
7777  sz = len(ts)
7778  _args = (TacticObj * sz)()
7779  for i in range(sz):
7780  _args[i] = ts[i].tactic
7781  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7782 
7783 def ParThen(t1, t2, ctx=None):
7784  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7785 
7786  >>> x, y = Ints('x y')
7787  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7788  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7789  [[x == 1, y == 2], [x == 2, y == 3]]
7790  """
7791  t1 = _to_tactic(t1, ctx)
7792  t2 = _to_tactic(t2, ctx)
7793  if z3_debug():
7794  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7795  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7796 
7797 def ParAndThen(t1, t2, ctx=None):
7798  """Alias for ParThen(t1, t2, ctx)."""
7799  return ParThen(t1, t2, ctx)
7800 
7801 def With(t, *args, **keys):
7802  """Return a tactic that applies tactic `t` using the given configuration options.
7803 
7804  >>> x, y = Ints('x y')
7805  >>> t = With(Tactic('simplify'), som=True)
7806  >>> t((x + 1)*(y + 2) == 0)
7807  [[2*x + y + x*y == -2]]
7808  """
7809  ctx = keys.pop('ctx', None)
7810  t = _to_tactic(t, ctx)
7811  p = args2params(args, keys, t.ctx)
7812  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7813 
7814 def WithParams(t, p):
7815  """Return a tactic that applies tactic `t` using the given configuration options.
7816 
7817  >>> x, y = Ints('x y')
7818  >>> p = ParamsRef()
7819  >>> p.set("som", True)
7820  >>> t = WithParams(Tactic('simplify'), p)
7821  >>> t((x + 1)*(y + 2) == 0)
7822  [[2*x + y + x*y == -2]]
7823  """
7824  t = _to_tactic(t, None)
7825  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7826 
7827 def Repeat(t, max=4294967295, ctx=None):
7828  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7829 
7830  >>> x, y = Ints('x y')
7831  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7832  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7833  >>> r = t(c)
7834  >>> for subgoal in r: print(subgoal)
7835  [x == 0, y == 0, x > y]
7836  [x == 0, y == 1, x > y]
7837  [x == 1, y == 0, x > y]
7838  [x == 1, y == 1, x > y]
7839  >>> t = Then(t, Tactic('propagate-values'))
7840  >>> t(c)
7841  [[x == 1, y == 0]]
7842  """
7843  t = _to_tactic(t, ctx)
7844  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7845 
7846 def TryFor(t, ms, ctx=None):
7847  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7848 
7849  If `t` does not terminate in `ms` milliseconds, then it fails.
7850  """
7851  t = _to_tactic(t, ctx)
7852  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7853 
7854 def tactics(ctx=None):
7855  """Return a list of all available tactics in Z3.
7856 
7857  >>> l = tactics()
7858  >>> l.count('simplify') == 1
7859  True
7860  """
7861  ctx = _get_ctx(ctx)
7862  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7863 
7864 def tactic_description(name, ctx=None):
7865  """Return a short description for the tactic named `name`.
7866 
7867  >>> d = tactic_description('simplify')
7868  """
7869  ctx = _get_ctx(ctx)
7870  return Z3_tactic_get_descr(ctx.ref(), name)
7871 
7873  """Display a (tabular) description of all available tactics in Z3."""
7874  if in_html_mode():
7875  even = True
7876  print('<table border="1" cellpadding="2" cellspacing="0">')
7877  for t in tactics():
7878  if even:
7879  print('<tr style="background-color:#CFCFCF">')
7880  even = False
7881  else:
7882  print('<tr>')
7883  even = True
7884  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7885  print('</table>')
7886  else:
7887  for t in tactics():
7888  print('%s : %s' % (t, tactic_description(t)))
7889 
7890 class Probe:
7891  """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used."""
7892  def __init__(self, probe, ctx=None):
7893  self.ctx = _get_ctx(ctx)
7894  self.probe = None
7895  if isinstance(probe, ProbeObj):
7896  self.probe = probe
7897  elif isinstance(probe, float):
7898  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7899  elif _is_int(probe):
7900  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7901  elif isinstance(probe, bool):
7902  if probe:
7903  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7904  else:
7905  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7906  else:
7907  if z3_debug():
7908  _z3_assert(isinstance(probe, str), "probe name expected")
7909  try:
7910  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7911  except Z3Exception:
7912  raise Z3Exception("unknown probe '%s'" % probe)
7913  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7914 
7915  def __deepcopy__(self, memo={}):
7916  return Probe(self.probe, self.ctx)
7917 
7918  def __del__(self):
7919  if self.probe is not None and self.ctx.ref() is not None:
7920  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7921 
7922  def __lt__(self, other):
7923  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7924 
7925  >>> p = Probe('size') < 10
7926  >>> x = Int('x')
7927  >>> g = Goal()
7928  >>> g.add(x > 0)
7929  >>> g.add(x < 10)
7930  >>> p(g)
7931  1.0
7932  """
7933  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7934 
7935  def __gt__(self, other):
7936  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7937 
7938  >>> p = Probe('size') > 10
7939  >>> x = Int('x')
7940  >>> g = Goal()
7941  >>> g.add(x > 0)
7942  >>> g.add(x < 10)
7943  >>> p(g)
7944  0.0
7945  """
7946  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7947 
7948  def __le__(self, other):
7949  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7950 
7951  >>> p = Probe('size') <= 2
7952  >>> x = Int('x')
7953  >>> g = Goal()
7954  >>> g.add(x > 0)
7955  >>> g.add(x < 10)
7956  >>> p(g)
7957  1.0
7958  """
7959  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7960 
7961  def __ge__(self, other):
7962  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7963 
7964  >>> p = Probe('size') >= 2
7965  >>> x = Int('x')
7966  >>> g = Goal()
7967  >>> g.add(x > 0)
7968  >>> g.add(x < 10)
7969  >>> p(g)
7970  1.0
7971  """
7972  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7973 
7974  def __eq__(self, other):
7975  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7976 
7977  >>> p = Probe('size') == 2
7978  >>> x = Int('x')
7979  >>> g = Goal()
7980  >>> g.add(x > 0)
7981  >>> g.add(x < 10)
7982  >>> p(g)
7983  1.0
7984  """
7985  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7986 
7987  def __ne__(self, other):
7988  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7989 
7990  >>> p = Probe('size') != 2
7991  >>> x = Int('x')
7992  >>> g = Goal()
7993  >>> g.add(x > 0)
7994  >>> g.add(x < 10)
7995  >>> p(g)
7996  0.0
7997  """
7998  p = self.__eq__(other)
7999  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8000 
8001  def __call__(self, goal):
8002  """Evaluate the probe `self` in the given goal.
8003 
8004  >>> p = Probe('size')
8005  >>> x = Int('x')
8006  >>> g = Goal()
8007  >>> g.add(x > 0)
8008  >>> g.add(x < 10)
8009  >>> p(g)
8010  2.0
8011  >>> g.add(x < 20)
8012  >>> p(g)
8013  3.0
8014  >>> p = Probe('num-consts')
8015  >>> p(g)
8016  1.0
8017  >>> p = Probe('is-propositional')
8018  >>> p(g)
8019  0.0
8020  >>> p = Probe('is-qflia')
8021  >>> p(g)
8022  1.0
8023  """
8024  if z3_debug():
8025  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
8026  goal = _to_goal(goal)
8027  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8028 
8029 def is_probe(p):
8030  """Return `True` if `p` is a Z3 probe.
8031 
8032  >>> is_probe(Int('x'))
8033  False
8034  >>> is_probe(Probe('memory'))
8035  True
8036  """
8037  return isinstance(p, Probe)
8038 
8039 def _to_probe(p, ctx=None):
8040  if is_probe(p):
8041  return p
8042  else:
8043  return Probe(p, ctx)
8044 
8045 def probes(ctx=None):
8046  """Return a list of all available probes in Z3.
8047 
8048  >>> l = probes()
8049  >>> l.count('memory') == 1
8050  True
8051  """
8052  ctx = _get_ctx(ctx)
8053  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
8054 
8055 def probe_description(name, ctx=None):
8056  """Return a short description for the probe named `name`.
8057 
8058  >>> d = probe_description('memory')
8059  """
8060  ctx = _get_ctx(ctx)
8061  return Z3_probe_get_descr(ctx.ref(), name)
8062 
8064  """Display a (tabular) description of all available probes in Z3."""
8065  if in_html_mode():
8066  even = True
8067  print('<table border="1" cellpadding="2" cellspacing="0">')
8068  for p in probes():
8069  if even:
8070  print('<tr style="background-color:#CFCFCF">')
8071  even = False
8072  else:
8073  print('<tr>')
8074  even = True
8075  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
8076  print('</table>')
8077  else:
8078  for p in probes():
8079  print('%s : %s' % (p, probe_description(p)))
8080 
8081 def _probe_nary(f, args, ctx):
8082  if z3_debug():
8083  _z3_assert(len(args) > 0, "At least one argument expected")
8084  num = len(args)
8085  r = _to_probe(args[0], ctx)
8086  for i in range(num - 1):
8087  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
8088  return r
8089 
8090 def _probe_and(args, ctx):
8091  return _probe_nary(Z3_probe_and, args, ctx)
8092 
8093 def _probe_or(args, ctx):
8094  return _probe_nary(Z3_probe_or, args, ctx)
8095 
8096 def FailIf(p, ctx=None):
8097  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8098 
8099  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
8100 
8101  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8102  >>> x, y = Ints('x y')
8103  >>> g = Goal()
8104  >>> g.add(x > 0)
8105  >>> g.add(y > 0)
8106  >>> t(g)
8107  [[x > 0, y > 0]]
8108  >>> g.add(x == y + 1)
8109  >>> t(g)
8110  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8111  """
8112  p = _to_probe(p, ctx)
8113  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8114 
8115 def When(p, t, ctx=None):
8116  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8117 
8118  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8119  >>> x, y = Ints('x y')
8120  >>> g = Goal()
8121  >>> g.add(x > 0)
8122  >>> g.add(y > 0)
8123  >>> t(g)
8124  [[x > 0, y > 0]]
8125  >>> g.add(x == y + 1)
8126  >>> t(g)
8127  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8128  """
8129  p = _to_probe(p, ctx)
8130  t = _to_tactic(t, ctx)
8131  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8132 
8133 def Cond(p, t1, t2, ctx=None):
8134  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8135 
8136  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8137  """
8138  p = _to_probe(p, ctx)
8139  t1 = _to_tactic(t1, ctx)
8140  t2 = _to_tactic(t2, ctx)
8141  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8142 
8143 #########################################
8144 #
8145 # Utils
8146 #
8147 #########################################
8148 
8149 def simplify(a, *arguments, **keywords):
8150  """Simplify the expression `a` using the given options.
8151 
8152  This function has many options. Use `help_simplify` to obtain the complete list.
8153 
8154  >>> x = Int('x')
8155  >>> y = Int('y')
8156  >>> simplify(x + 1 + y + x + 1)
8157  2 + 2*x + y
8158  >>> simplify((x + 1)*(y + 1), som=True)
8159  1 + x + y + x*y
8160  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8161  And(Not(x == y), Not(x == 1), Not(y == 1))
8162  >>> simplify(And(x == 0, y == 1), elim_and=True)
8163  Not(Or(Not(x == 0), Not(y == 1)))
8164  """
8165  if z3_debug():
8166  _z3_assert(is_expr(a), "Z3 expression expected")
8167  if len(arguments) > 0 or len(keywords) > 0:
8168  p = args2params(arguments, keywords, a.ctx)
8169  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8170  else:
8171  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8172 
8174  """Return a string describing all options available for Z3 `simplify` procedure."""
8175  print(Z3_simplify_get_help(main_ctx().ref()))
8176 
8178  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8180 
8181 def substitute(t, *m):
8182  """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
8183 
8184  >>> x = Int('x')
8185  >>> y = Int('y')
8186  >>> substitute(x + 1, (x, y + 1))
8187  y + 1 + 1
8188  >>> f = Function('f', IntSort(), IntSort())
8189  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8190  1 + 1
8191  """
8192  if isinstance(m, tuple):
8193  m1 = _get_args(m)
8194  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8195  m = m1
8196  if z3_debug():
8197  _z3_assert(is_expr(t), "Z3 expression expected")
8198  _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
8199  num = len(m)
8200  _from = (Ast * num)()
8201  _to = (Ast * num)()
8202  for i in range(num):
8203  _from[i] = m[i][0].as_ast()
8204  _to[i] = m[i][1].as_ast()
8205  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8206 
8207 def substitute_vars(t, *m):
8208  """Substitute the free variables in t with the expression in m.
8209 
8210  >>> v0 = Var(0, IntSort())
8211  >>> v1 = Var(1, IntSort())
8212  >>> x = Int('x')
8213  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8214  >>> # replace v0 with x+1 and v1 with x
8215  >>> substitute_vars(f(v0, v1), x + 1, x)
8216  f(x + 1, x)
8217  """
8218  if z3_debug():
8219  _z3_assert(is_expr(t), "Z3 expression expected")
8220  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8221  num = len(m)
8222  _to = (Ast * num)()
8223  for i in range(num):
8224  _to[i] = m[i].as_ast()
8225  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8226 
8227 def Sum(*args):
8228  """Create the sum of the Z3 expressions.
8229 
8230  >>> a, b, c = Ints('a b c')
8231  >>> Sum(a, b, c)
8232  a + b + c
8233  >>> Sum([a, b, c])
8234  a + b + c
8235  >>> A = IntVector('a', 5)
8236  >>> Sum(A)
8237  a__0 + a__1 + a__2 + a__3 + a__4
8238  """
8239  args = _get_args(args)
8240  if len(args) == 0:
8241  return 0
8242  ctx = _ctx_from_ast_arg_list(args)
8243  if ctx is None:
8244  return _reduce(lambda a, b: a + b, args, 0)
8245  args = _coerce_expr_list(args, ctx)
8246  if is_bv(args[0]):
8247  return _reduce(lambda a, b: a + b, args, 0)
8248  else:
8249  _args, sz = _to_ast_array(args)
8250  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8251 
8252 
8253 def Product(*args):
8254  """Create the product of the Z3 expressions.
8255 
8256  >>> a, b, c = Ints('a b c')
8257  >>> Product(a, b, c)
8258  a*b*c
8259  >>> Product([a, b, c])
8260  a*b*c
8261  >>> A = IntVector('a', 5)
8262  >>> Product(A)
8263  a__0*a__1*a__2*a__3*a__4
8264  """
8265  args = _get_args(args)
8266  if len(args) == 0:
8267  return 1
8268  ctx = _ctx_from_ast_arg_list(args)
8269  if ctx is None:
8270  return _reduce(lambda a, b: a * b, args, 1)
8271  args = _coerce_expr_list(args, ctx)
8272  if is_bv(args[0]):
8273  return _reduce(lambda a, b: a * b, args, 1)
8274  else:
8275  _args, sz = _to_ast_array(args)
8276  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8277 
8278 def AtMost(*args):
8279  """Create an at-most Pseudo-Boolean k constraint.
8280 
8281  >>> a, b, c = Bools('a b c')
8282  >>> f = AtMost(a, b, c, 2)
8283  """
8284  args = _get_args(args)
8285  if z3_debug():
8286  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8287  ctx = _ctx_from_ast_arg_list(args)
8288  if z3_debug():
8289  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8290  args1 = _coerce_expr_list(args[:-1], ctx)
8291  k = args[-1]
8292  _args, sz = _to_ast_array(args1)
8293  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8294 
8295 def AtLeast(*args):
8296  """Create an at-most Pseudo-Boolean k constraint.
8297 
8298  >>> a, b, c = Bools('a b c')
8299  >>> f = AtLeast(a, b, c, 2)
8300  """
8301  args = _get_args(args)
8302  if z3_debug():
8303  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8304  ctx = _ctx_from_ast_arg_list(args)
8305  if z3_debug():
8306  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8307  args1 = _coerce_expr_list(args[:-1], ctx)
8308  k = args[-1]
8309  _args, sz = _to_ast_array(args1)
8310  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8311 
8312 
8313 def _pb_args_coeffs(args, default_ctx = None):
8314  args = _get_args_ast_list(args)
8315  if len(args) == 0:
8316  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8317  args, coeffs = zip(*args)
8318  if z3_debug():
8319  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8320  ctx = _ctx_from_ast_arg_list(args)
8321  if z3_debug():
8322  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8323  args = _coerce_expr_list(args, ctx)
8324  _args, sz = _to_ast_array(args)
8325  _coeffs = (ctypes.c_int * len(coeffs))()
8326  for i in range(len(coeffs)):
8327  _z3_check_cint_overflow(coeffs[i], "coefficient")
8328  _coeffs[i] = coeffs[i]
8329  return ctx, sz, _args, _coeffs
8330 
8331 def PbLe(args, k):
8332  """Create a Pseudo-Boolean inequality k constraint.
8333 
8334  >>> a, b, c = Bools('a b c')
8335  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8336  """
8337  _z3_check_cint_overflow(k, "k")
8338  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8339  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8340 
8341 def PbGe(args, k):
8342  """Create a Pseudo-Boolean inequality k constraint.
8343 
8344  >>> a, b, c = Bools('a b c')
8345  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8346  """
8347  _z3_check_cint_overflow(k, "k")
8348  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8349  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8350 
8351 def PbEq(args, k, ctx = None):
8352  """Create a Pseudo-Boolean inequality k constraint.
8353 
8354  >>> a, b, c = Bools('a b c')
8355  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8356  """
8357  _z3_check_cint_overflow(k, "k")
8358  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8359  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8360 
8361 
8362 def solve(*args, **keywords):
8363  """Solve the constraints `*args`.
8364 
8365  This is a simple function for creating demonstrations. It creates a solver,
8366  configure it using the options in `keywords`, adds the constraints
8367  in `args`, and invokes check.
8368 
8369  >>> a = Int('a')
8370  >>> solve(a > 0, a < 2)
8371  [a = 1]
8372  """
8373  s = Solver()
8374  s.set(**keywords)
8375  s.add(*args)
8376  if keywords.get('show', False):
8377  print(s)
8378  r = s.check()
8379  if r == unsat:
8380  print("no solution")
8381  elif r == unknown:
8382  print("failed to solve")
8383  try:
8384  print(s.model())
8385  except Z3Exception:
8386  return
8387  else:
8388  print(s.model())
8389 
8390 def solve_using(s, *args, **keywords):
8391  """Solve the constraints `*args` using solver `s`.
8392 
8393  This is a simple function for creating demonstrations. It is similar to `solve`,
8394  but it uses the given solver `s`.
8395  It configures solver `s` using the options in `keywords`, adds the constraints
8396  in `args`, and invokes check.
8397  """
8398  if z3_debug():
8399  _z3_assert(isinstance(s, Solver), "Solver object expected")
8400  s.set(**keywords)
8401  s.add(*args)
8402  if keywords.get('show', False):
8403  print("Problem:")
8404  print(s)
8405  r = s.check()
8406  if r == unsat:
8407  print("no solution")
8408  elif r == unknown:
8409  print("failed to solve")
8410  try:
8411  print(s.model())
8412  except Z3Exception:
8413  return
8414  else:
8415  if keywords.get('show', False):
8416  print("Solution:")
8417  print(s.model())
8418 
8419 def prove(claim, **keywords):
8420  """Try to prove the given claim.
8421 
8422  This is a simple function for creating demonstrations. It tries to prove
8423  `claim` by showing the negation is unsatisfiable.
8424 
8425  >>> p, q = Bools('p q')
8426  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8427  proved
8428  """
8429  if z3_debug():
8430  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8431  s = Solver()
8432  s.set(**keywords)
8433  s.add(Not(claim))
8434  if keywords.get('show', False):
8435  print(s)
8436  r = s.check()
8437  if r == unsat:
8438  print("proved")
8439  elif r == unknown:
8440  print("failed to prove")
8441  print(s.model())
8442  else:
8443  print("counterexample")
8444  print(s.model())
8445 
8446 def _solve_html(*args, **keywords):
8447  """Version of function `solve` used in RiSE4Fun."""
8448  s = Solver()
8449  s.set(**keywords)
8450  s.add(*args)
8451  if keywords.get('show', False):
8452  print("<b>Problem:</b>")
8453  print(s)
8454  r = s.check()
8455  if r == unsat:
8456  print("<b>no solution</b>")
8457  elif r == unknown:
8458  print("<b>failed to solve</b>")
8459  try:
8460  print(s.model())
8461  except Z3Exception:
8462  return
8463  else:
8464  if keywords.get('show', False):
8465  print("<b>Solution:</b>")
8466  print(s.model())
8467 
8468 def _solve_using_html(s, *args, **keywords):
8469  """Version of function `solve_using` used in RiSE4Fun."""
8470  if z3_debug():
8471  _z3_assert(isinstance(s, Solver), "Solver object expected")
8472  s.set(**keywords)
8473  s.add(*args)
8474  if keywords.get('show', False):
8475  print("<b>Problem:</b>")
8476  print(s)
8477  r = s.check()
8478  if r == unsat:
8479  print("<b>no solution</b>")
8480  elif r == unknown:
8481  print("<b>failed to solve</b>")
8482  try:
8483  print(s.model())
8484  except Z3Exception:
8485  return
8486  else:
8487  if keywords.get('show', False):
8488  print("<b>Solution:</b>")
8489  print(s.model())
8490 
8491 def _prove_html(claim, **keywords):
8492  """Version of function `prove` used in RiSE4Fun."""
8493  if z3_debug():
8494  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8495  s = Solver()
8496  s.set(**keywords)
8497  s.add(Not(claim))
8498  if keywords.get('show', False):
8499  print(s)
8500  r = s.check()
8501  if r == unsat:
8502  print("<b>proved</b>")
8503  elif r == unknown:
8504  print("<b>failed to prove</b>")
8505  print(s.model())
8506  else:
8507  print("<b>counterexample</b>")
8508  print(s.model())
8509 
8510 def _dict2sarray(sorts, ctx):
8511  sz = len(sorts)
8512  _names = (Symbol * sz)()
8513  _sorts = (Sort * sz) ()
8514  i = 0
8515  for k in sorts:
8516  v = sorts[k]
8517  if z3_debug():
8518  _z3_assert(isinstance(k, str), "String expected")
8519  _z3_assert(is_sort(v), "Z3 sort expected")
8520  _names[i] = to_symbol(k, ctx)
8521  _sorts[i] = v.ast
8522  i = i + 1
8523  return sz, _names, _sorts
8524 
8525 def _dict2darray(decls, ctx):
8526  sz = len(decls)
8527  _names = (Symbol * sz)()
8528  _decls = (FuncDecl * sz) ()
8529  i = 0
8530  for k in decls:
8531  v = decls[k]
8532  if z3_debug():
8533  _z3_assert(isinstance(k, str), "String expected")
8534  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8535  _names[i] = to_symbol(k, ctx)
8536  if is_const(v):
8537  _decls[i] = v.decl().ast
8538  else:
8539  _decls[i] = v.ast
8540  i = i + 1
8541  return sz, _names, _decls
8542 
8543 
8544 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8545  """Parse a string in SMT 2.0 format using the given sorts and decls.
8546 
8547  The arguments sorts and decls are Python dictionaries used to initialize
8548  the symbol table used for the SMT 2.0 parser.
8549 
8550  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8551  [x > 0, x < 10]
8552  >>> x, y = Ints('x y')
8553  >>> f = Function('f', IntSort(), IntSort())
8554  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8555  [x + f(y) > 0]
8556  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8557  [a > 0]
8558  """
8559  ctx = _get_ctx(ctx)
8560  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8561  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8562  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8563 
8564 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8565  """Parse a file in SMT 2.0 format using the given sorts and decls.
8566 
8567  This function is similar to parse_smt2_string().
8568  """
8569  ctx = _get_ctx(ctx)
8570  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8571  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8572  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8573 
8574 
8575 #########################################
8576 #
8577 # Floating-Point Arithmetic
8578 #
8579 #########################################
8580 
8581 
8582 # Global default rounding mode
8583 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8584 _dflt_fpsort_ebits = 11
8585 _dflt_fpsort_sbits = 53
8586 
8587 def get_default_rounding_mode(ctx=None):
8588  """Retrieves the global default rounding mode."""
8589  global _dflt_rounding_mode
8590  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8591  return RTZ(ctx)
8592  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8593  return RTN(ctx)
8594  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8595  return RTP(ctx)
8596  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8597  return RNE(ctx)
8598  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8599  return RNA(ctx)
8600 
8601 def set_default_rounding_mode(rm, ctx=None):
8602  global _dflt_rounding_mode
8603  if is_fprm_value(rm):
8604  _dflt_rounding_mode = rm.decl().kind()
8605  else:
8606  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8607  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8608  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8609  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8610  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8611  "illegal rounding mode")
8612  _dflt_rounding_mode = rm
8613 
8614 def get_default_fp_sort(ctx=None):
8615  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8616 
8617 def set_default_fp_sort(ebits, sbits, ctx=None):
8618  global _dflt_fpsort_ebits
8619  global _dflt_fpsort_sbits
8620  _dflt_fpsort_ebits = ebits
8621  _dflt_fpsort_sbits = sbits
8622 
8623 def _dflt_rm(ctx=None):
8624  return get_default_rounding_mode(ctx)
8625 
8626 def _dflt_fps(ctx=None):
8627  return get_default_fp_sort(ctx)
8628 
8629 def _coerce_fp_expr_list(alist, ctx):
8630  first_fp_sort = None
8631  for a in alist:
8632  if is_fp(a):
8633  if first_fp_sort is None:
8634  first_fp_sort = a.sort()
8635  elif first_fp_sort == a.sort():
8636  pass # OK, same as before
8637  else:
8638  # we saw at least 2 different float sorts; something will
8639  # throw a sort mismatch later, for now assume None.
8640  first_fp_sort = None
8641  break
8642 
8643  r = []
8644  for i in range(len(alist)):
8645  a = alist[i]
8646  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8647  r.append(FPVal(a, None, first_fp_sort, ctx))
8648  else:
8649  r.append(a)
8650  return _coerce_expr_list(r, ctx)
8651 
8652 
8653 ### FP Sorts
8654 
8655 class FPSortRef(SortRef):
8656  """Floating-point sort."""
8657 
8658  def ebits(self):
8659  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8660  >>> b = FPSort(8, 24)
8661  >>> b.ebits()
8662  8
8663  """
8664  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8665 
8666  def sbits(self):
8667  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8668  >>> b = FPSort(8, 24)
8669  >>> b.sbits()
8670  24
8671  """
8672  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8673 
8674  def cast(self, val):
8675  """Try to cast `val` as a floating-point expression.
8676  >>> b = FPSort(8, 24)
8677  >>> b.cast(1.0)
8678  1
8679  >>> b.cast(1.0).sexpr()
8680  '(fp #b0 #x7f #b00000000000000000000000)'
8681  """
8682  if is_expr(val):
8683  if z3_debug():
8684  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8685  return val
8686  else:
8687  return FPVal(val, None, self, self.ctx)
8688 
8689 
8690 def Float16(ctx=None):
8691  """Floating-point 16-bit (half) sort."""
8692  ctx = _get_ctx(ctx)
8693  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8694 
8695 def FloatHalf(ctx=None):
8696  """Floating-point 16-bit (half) sort."""
8697  ctx = _get_ctx(ctx)
8698  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8699 
8700 def Float32(ctx=None):
8701  """Floating-point 32-bit (single) sort."""
8702  ctx = _get_ctx(ctx)
8703  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8704 
8705 def FloatSingle(ctx=None):
8706  """Floating-point 32-bit (single) sort."""
8707  ctx = _get_ctx(ctx)
8708  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8709 
8710 def Float64(ctx=None):
8711  """Floating-point 64-bit (double) sort."""
8712  ctx = _get_ctx(ctx)
8713  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8714 
8715 def FloatDouble(ctx=None):
8716  """Floating-point 64-bit (double) sort."""
8717  ctx = _get_ctx(ctx)
8718  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8719 
8720 def Float128(ctx=None):
8721  """Floating-point 128-bit (quadruple) sort."""
8722  ctx = _get_ctx(ctx)
8723  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8724 
8725 def FloatQuadruple(ctx=None):
8726  """Floating-point 128-bit (quadruple) sort."""
8727  ctx = _get_ctx(ctx)
8728  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8729 
8730 class FPRMSortRef(SortRef):
8731  """"Floating-point rounding mode sort."""
8732 
8733 
8734 def is_fp_sort(s):
8735  """Return True if `s` is a Z3 floating-point sort.
8736 
8737  >>> is_fp_sort(FPSort(8, 24))
8738  True
8739  >>> is_fp_sort(IntSort())
8740  False
8741  """
8742  return isinstance(s, FPSortRef)
8743 
8744 def is_fprm_sort(s):
8745  """Return True if `s` is a Z3 floating-point rounding mode sort.
8746 
8747  >>> is_fprm_sort(FPSort(8, 24))
8748  False
8749  >>> is_fprm_sort(RNE().sort())
8750  True
8751  """
8752  return isinstance(s, FPRMSortRef)
8753 
8754 ### FP Expressions
8755 
8756 class FPRef(ExprRef):
8757  """Floating-point expressions."""
8758 
8759  def sort(self):
8760  """Return the sort of the floating-point expression `self`.
8761 
8762  >>> x = FP('1.0', FPSort(8, 24))
8763  >>> x.sort()
8764  FPSort(8, 24)
8765  >>> x.sort() == FPSort(8, 24)
8766  True
8767  """
8768  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8769 
8770  def ebits(self):
8771  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8772  >>> b = FPSort(8, 24)
8773  >>> b.ebits()
8774  8
8775  """
8776  return self.sort().ebits();
8777 
8778  def sbits(self):
8779  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8780  >>> b = FPSort(8, 24)
8781  >>> b.sbits()
8782  24
8783  """
8784  return self.sort().sbits();
8785 
8786  def as_string(self):
8787  """Return a Z3 floating point expression as a Python string."""
8788  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8789 
8790  def __le__(self, other):
8791  return fpLEQ(self, other, self.ctx)
8792 
8793  def __lt__(self, other):
8794  return fpLT(self, other, self.ctx)
8795 
8796  def __ge__(self, other):
8797  return fpGEQ(self, other, self.ctx)
8798 
8799  def __gt__(self, other):
8800  return fpGT(self, other, self.ctx)
8801 
8802  def __add__(self, other):
8803  """Create the Z3 expression `self + other`.
8804 
8805  >>> x = FP('x', FPSort(8, 24))
8806  >>> y = FP('y', FPSort(8, 24))
8807  >>> x + y
8808  x + y
8809  >>> (x + y).sort()
8810  FPSort(8, 24)
8811  """
8812  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8813  return fpAdd(_dflt_rm(), a, b, self.ctx)
8814 
8815  def __radd__(self, other):
8816  """Create the Z3 expression `other + self`.
8817 
8818  >>> x = FP('x', FPSort(8, 24))
8819  >>> 10 + x
8820  1.25*(2**3) + x
8821  """
8822  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8823  return fpAdd(_dflt_rm(), a, b, self.ctx)
8824 
8825  def __sub__(self, other):
8826  """Create the Z3 expression `self - other`.
8827 
8828  >>> x = FP('x', FPSort(8, 24))
8829  >>> y = FP('y', FPSort(8, 24))
8830  >>> x - y
8831  x - y
8832  >>> (x - y).sort()
8833  FPSort(8, 24)
8834  """
8835  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8836  return fpSub(_dflt_rm(), a, b, self.ctx)
8837 
8838  def __rsub__(self, other):
8839  """Create the Z3 expression `other - self`.
8840 
8841  >>> x = FP('x', FPSort(8, 24))
8842  >>> 10 - x
8843  1.25*(2**3) - x
8844  """
8845  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8846  return fpSub(_dflt_rm(), a, b, self.ctx)
8847 
8848  def __mul__(self, other):
8849  """Create the Z3 expression `self * other`.
8850 
8851  >>> x = FP('x', FPSort(8, 24))
8852  >>> y = FP('y', FPSort(8, 24))
8853  >>> x * y
8854  x * y
8855  >>> (x * y).sort()
8856  FPSort(8, 24)
8857  >>> 10 * y
8858  1.25*(2**3) * y
8859  """
8860  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8861  return fpMul(_dflt_rm(), a, b, self.ctx)
8862 
8863  def __rmul__(self, other):
8864  """Create the Z3 expression `other * self`.
8865 
8866  >>> x = FP('x', FPSort(8, 24))
8867  >>> y = FP('y', FPSort(8, 24))
8868  >>> x * y
8869  x * y
8870  >>> x * 10
8871  x * 1.25*(2**3)
8872  """
8873  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8874  return fpMul(_dflt_rm(), a, b, self.ctx)
8875 
8876  def __pos__(self):
8877  """Create the Z3 expression `+self`."""
8878  return self
8879 
8880  def __neg__(self):
8881  """Create the Z3 expression `-self`.
8882 
8883  >>> x = FP('x', Float32())
8884  >>> -x
8885  -x
8886  """
8887  return fpNeg(self)
8888 
8889  def __div__(self, other):
8890  """Create the Z3 expression `self / other`.
8891 
8892  >>> x = FP('x', FPSort(8, 24))
8893  >>> y = FP('y', FPSort(8, 24))
8894  >>> x / y
8895  x / y
8896  >>> (x / y).sort()
8897  FPSort(8, 24)
8898  >>> 10 / y
8899  1.25*(2**3) / y
8900  """
8901  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8902  return fpDiv(_dflt_rm(), a, b, self.ctx)
8903 
8904  def __rdiv__(self, other):
8905  """Create the Z3 expression `other / self`.
8906 
8907  >>> x = FP('x', FPSort(8, 24))
8908  >>> y = FP('y', FPSort(8, 24))
8909  >>> x / y
8910  x / y
8911  >>> x / 10
8912  x / 1.25*(2**3)
8913  """
8914  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8915  return fpDiv(_dflt_rm(), a, b, self.ctx)
8916 
8917  if not sys.version < '3':
8918  def __truediv__(self, other):
8919  """Create the Z3 expression division `self / other`."""
8920  return self.__div__(other)
8921 
8922  def __rtruediv__(self, other):
8923  """Create the Z3 expression division `other / self`."""
8924  return self.__rdiv__(other)
8925 
8926  def __mod__(self, other):
8927  """Create the Z3 expression mod `self % other`."""
8928  return fpRem(self, other)
8929 
8930  def __rmod__(self, other):
8931  """Create the Z3 expression mod `other % self`."""
8932  return fpRem(other, self)
8933 
8934 class FPRMRef(ExprRef):
8935  """Floating-point rounding mode expressions"""
8936 
8937  def as_string(self):
8938  """Return a Z3 floating point expression as a Python string."""
8939  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8940 
8941 
8942 def RoundNearestTiesToEven(ctx=None):
8943  ctx = _get_ctx(ctx)
8944  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8945 
8946 def RNE (ctx=None):
8947  ctx = _get_ctx(ctx)
8948  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8949 
8950 def RoundNearestTiesToAway(ctx=None):
8951  ctx = _get_ctx(ctx)
8952  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8953 
8954 def RNA (ctx=None):
8955  ctx = _get_ctx(ctx)
8956  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8957 
8958 def RoundTowardPositive(ctx=None):
8959  ctx = _get_ctx(ctx)
8960  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8961 
8962 def RTP(ctx=None):
8963  ctx = _get_ctx(ctx)
8964  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8965 
8966 def RoundTowardNegative(ctx=None):
8967  ctx = _get_ctx(ctx)
8968  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8969 
8970 def RTN(ctx=None):
8971  ctx = _get_ctx(ctx)
8972  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8973 
8974 def RoundTowardZero(ctx=None):
8975  ctx = _get_ctx(ctx)
8976  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8977 
8978 def RTZ(ctx=None):
8979  ctx = _get_ctx(ctx)
8980  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8981 
8982 def is_fprm(a):
8983  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8984 
8985  >>> rm = RNE()
8986  >>> is_fprm(rm)
8987  True
8988  >>> rm = 1.0
8989  >>> is_fprm(rm)
8990  False
8991  """
8992  return isinstance(a, FPRMRef)
8993 
8994 def is_fprm_value(a):
8995  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8996  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8997 
8998 ### FP Numerals
8999 
9000 class FPNumRef(FPRef):
9001  """The sign of the numeral.
9002 
9003  >>> x = FPVal(+1.0, FPSort(8, 24))
9004  >>> x.sign()
9005  False
9006  >>> x = FPVal(-1.0, FPSort(8, 24))
9007  >>> x.sign()
9008  True
9009  """
9010  def sign(self):
9011  l = (ctypes.c_int)()
9012  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
9013  raise Z3Exception("error retrieving the sign of a numeral.")
9014  return l.value != 0
9015 
9016  """The sign of a floating-point numeral as a bit-vector expression.
9017 
9018  Remark: NaN's are invalid arguments.
9019  """
9020  def sign_as_bv(self):
9021  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9022 
9023  """The significand of the numeral.
9024 
9025  >>> x = FPVal(2.5, FPSort(8, 24))
9026  >>> x.significand()
9027  1.25
9028  """
9029  def significand(self):
9030  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
9031 
9032  """The significand of the numeral as a long.
9033 
9034  >>> x = FPVal(2.5, FPSort(8, 24))
9035  >>> x.significand_as_long()
9036  1.25
9037  """
9038  def significand_as_long(self):
9039  ptr = (ctypes.c_ulonglong * 1)()
9040  if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
9041  raise Z3Exception("error retrieving the significand of a numeral.")
9042  return ptr[0]
9043 
9044  """The significand of the numeral as a bit-vector expression.
9045 
9046  Remark: NaN are invalid arguments.
9047  """
9048  def significand_as_bv(self):
9049  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9050 
9051  """The exponent of the numeral.
9052 
9053  >>> x = FPVal(2.5, FPSort(8, 24))
9054  >>> x.exponent()
9055  1
9056  """
9057  def exponent(self, biased=True):
9058  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
9059 
9060  """The exponent of the numeral as a long.
9061 
9062  >>> x = FPVal(2.5, FPSort(8, 24))
9063  >>> x.exponent_as_long()
9064  1
9065  """
9066  def exponent_as_long(self, biased=True):
9067  ptr = (ctypes.c_longlong * 1)()
9068  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
9069  raise Z3Exception("error retrieving the exponent of a numeral.")
9070  return ptr[0]
9071 
9072  """The exponent of the numeral as a bit-vector expression.
9073 
9074  Remark: NaNs are invalid arguments.
9075  """
9076  def exponent_as_bv(self, biased=True):
9077  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
9078 
9079  """Indicates whether the numeral is a NaN."""
9080  def isNaN(self):
9081  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
9082 
9083  """Indicates whether the numeral is +oo or -oo."""
9084  def isInf(self):
9085  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
9086 
9087  """Indicates whether the numeral is +zero or -zero."""
9088  def isZero(self):
9089  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
9090 
9091  """Indicates whether the numeral is normal."""
9092  def isNormal(self):
9093  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
9094 
9095  """Indicates whether the numeral is subnormal."""
9096  def isSubnormal(self):
9097  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
9098 
9099  """Indicates whether the numeral is positive."""
9100  def isPositive(self):
9101  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
9102 
9103  """Indicates whether the numeral is negative."""
9104  def isNegative(self):
9105  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
9106 
9107  """
9108  The string representation of the numeral.
9109 
9110  >>> x = FPVal(20, FPSort(8, 24))
9111  >>> x.as_string()
9112  1.25*(2**4)
9113  """
9114  def as_string(self):
9115  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
9116  return ("FPVal(%s, %s)" % (s, self.sort()))
9117 
9118 def is_fp(a):
9119  """Return `True` if `a` is a Z3 floating-point expression.
9120 
9121  >>> b = FP('b', FPSort(8, 24))
9122  >>> is_fp(b)
9123  True
9124  >>> is_fp(b + 1.0)
9125  True
9126  >>> is_fp(Int('x'))
9127  False
9128  """
9129  return isinstance(a, FPRef)
9130 
9131 def is_fp_value(a):
9132  """Return `True` if `a` is a Z3 floating-point numeral value.
9133 
9134  >>> b = FP('b', FPSort(8, 24))
9135  >>> is_fp_value(b)
9136  False
9137  >>> b = FPVal(1.0, FPSort(8, 24))
9138  >>> b
9139  1
9140  >>> is_fp_value(b)
9141  True
9142  """
9143  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9144 
9145 def FPSort(ebits, sbits, ctx=None):
9146  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9147 
9148  >>> Single = FPSort(8, 24)
9149  >>> Double = FPSort(11, 53)
9150  >>> Single
9151  FPSort(8, 24)
9152  >>> x = Const('x', Single)
9153  >>> eq(x, FP('x', FPSort(8, 24)))
9154  True
9155  """
9156  ctx = _get_ctx(ctx)
9157  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9158 
9159 def _to_float_str(val, exp=0):
9160  if isinstance(val, float):
9161  if math.isnan(val):
9162  res = "NaN"
9163  elif val == 0.0:
9164  sone = math.copysign(1.0, val)
9165  if sone < 0.0:
9166  return "-0.0"
9167  else:
9168  return "+0.0"
9169  elif val == float("+inf"):
9170  res = "+oo"
9171  elif val == float("-inf"):
9172  res = "-oo"
9173  else:
9174  v = val.as_integer_ratio()
9175  num = v[0]
9176  den = v[1]
9177  rvs = str(num) + '/' + str(den)
9178  res = rvs + 'p' + _to_int_str(exp)
9179  elif isinstance(val, bool):
9180  if val:
9181  res = "1.0"
9182  else:
9183  res = "0.0"
9184  elif _is_int(val):
9185  res = str(val)
9186  elif isinstance(val, str):
9187  inx = val.find('*(2**')
9188  if inx == -1:
9189  res = val
9190  elif val[-1] == ')':
9191  res = val[0:inx]
9192  exp = str(int(val[inx+5:-1]) + int(exp))
9193  else:
9194  _z3_assert(False, "String does not have floating-point numeral form.")
9195  elif z3_debug():
9196  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9197  if exp == 0:
9198  return res
9199  else:
9200  return res + 'p' + exp
9201 
9202 
9203 def fpNaN(s):
9204  """Create a Z3 floating-point NaN term.
9205 
9206  >>> s = FPSort(8, 24)
9207  >>> set_fpa_pretty(True)
9208  >>> fpNaN(s)
9209  NaN
9210  >>> pb = get_fpa_pretty()
9211  >>> set_fpa_pretty(False)
9212  >>> fpNaN(s)
9213  fpNaN(FPSort(8, 24))
9214  >>> set_fpa_pretty(pb)
9215  """
9216  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9217  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9218 
9219 def fpPlusInfinity(s):
9220  """Create a Z3 floating-point +oo term.
9221 
9222  >>> s = FPSort(8, 24)
9223  >>> pb = get_fpa_pretty()
9224  >>> set_fpa_pretty(True)
9225  >>> fpPlusInfinity(s)
9226  +oo
9227  >>> set_fpa_pretty(False)
9228  >>> fpPlusInfinity(s)
9229  fpPlusInfinity(FPSort(8, 24))
9230  >>> set_fpa_pretty(pb)
9231  """
9232  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9233  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9234 
9235 def fpMinusInfinity(s):
9236  """Create a Z3 floating-point -oo term."""
9237  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9238  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9239 
9240 def fpInfinity(s, negative):
9241  """Create a Z3 floating-point +oo or -oo term."""
9242  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9243  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9244  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9245 
9246 def fpPlusZero(s):
9247  """Create a Z3 floating-point +0.0 term."""
9248  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9249  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9250 
9251 def fpMinusZero(s):
9252  """Create a Z3 floating-point -0.0 term."""
9253  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9254  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9255 
9256 def fpZero(s, negative):
9257  """Create a Z3 floating-point +0.0 or -0.0 term."""
9258  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9259  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9260  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9261 
9262 def FPVal(sig, exp=None, fps=None, ctx=None):
9263  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9264 
9265  >>> v = FPVal(20.0, FPSort(8, 24))
9266  >>> v
9267  1.25*(2**4)
9268  >>> print("0x%.8x" % v.exponent_as_long(False))
9269  0x00000004
9270  >>> v = FPVal(2.25, FPSort(8, 24))
9271  >>> v
9272  1.125*(2**1)
9273  >>> v = FPVal(-2.25, FPSort(8, 24))
9274  >>> v
9275  -1.125*(2**1)
9276  >>> FPVal(-0.0, FPSort(8, 24))
9277  -0.0
9278  >>> FPVal(0.0, FPSort(8, 24))
9279  +0.0
9280  >>> FPVal(+0.0, FPSort(8, 24))
9281  +0.0
9282  """
9283  ctx = _get_ctx(ctx)
9284  if is_fp_sort(exp):
9285  fps = exp
9286  exp = None
9287  elif fps is None:
9288  fps = _dflt_fps(ctx)
9289  _z3_assert(is_fp_sort(fps), "sort mismatch")
9290  if exp is None:
9291  exp = 0
9292  val = _to_float_str(sig)
9293  if val == "NaN" or val == "nan":
9294  return fpNaN(fps)
9295  elif val == "-0.0":
9296  return fpMinusZero(fps)
9297  elif val == "0.0" or val == "+0.0":
9298  return fpPlusZero(fps)
9299  elif val == "+oo" or val == "+inf" or val == "+Inf":
9300  return fpPlusInfinity(fps)
9301  elif val == "-oo" or val == "-inf" or val == "-Inf":
9302  return fpMinusInfinity(fps)
9303  else:
9304  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9305 
9306 def FP(name, fpsort, ctx=None):
9307  """Return a floating-point constant named `name`.
9308  `fpsort` is the floating-point sort.
9309  If `ctx=None`, then the global context is used.
9310 
9311  >>> x = FP('x', FPSort(8, 24))
9312  >>> is_fp(x)
9313  True
9314  >>> x.ebits()
9315  8
9316  >>> x.sort()
9317  FPSort(8, 24)
9318  >>> word = FPSort(8, 24)
9319  >>> x2 = FP('x', word)
9320  >>> eq(x, x2)
9321  True
9322  """
9323  if isinstance(fpsort, FPSortRef) and ctx is None:
9324  ctx = fpsort.ctx
9325  else:
9326  ctx = _get_ctx(ctx)
9327  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9328 
9329 def FPs(names, fpsort, ctx=None):
9330  """Return an array of floating-point constants.
9331 
9332  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9333  >>> x.sort()
9334  FPSort(8, 24)
9335  >>> x.sbits()
9336  24
9337  >>> x.ebits()
9338  8
9339  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9340  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9341  """
9342  ctx = _get_ctx(ctx)
9343  if isinstance(names, str):
9344  names = names.split(" ")
9345  return [FP(name, fpsort, ctx) for name in names]
9346 
9347 def fpAbs(a, ctx=None):
9348  """Create a Z3 floating-point absolute value expression.
9349 
9350  >>> s = FPSort(8, 24)
9351  >>> rm = RNE()
9352  >>> x = FPVal(1.0, s)
9353  >>> fpAbs(x)
9354  fpAbs(1)
9355  >>> y = FPVal(-20.0, s)
9356  >>> y
9357  -1.25*(2**4)
9358  >>> fpAbs(y)
9359  fpAbs(-1.25*(2**4))
9360  >>> fpAbs(-1.25*(2**4))
9361  fpAbs(-1.25*(2**4))
9362  >>> fpAbs(x).sort()
9363  FPSort(8, 24)
9364  """
9365  ctx = _get_ctx(ctx)
9366  [a] = _coerce_fp_expr_list([a], ctx)
9367  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9368 
9369 def fpNeg(a, ctx=None):
9370  """Create a Z3 floating-point addition expression.
9371 
9372  >>> s = FPSort(8, 24)
9373  >>> rm = RNE()
9374  >>> x = FP('x', s)
9375  >>> fpNeg(x)
9376  -x
9377  >>> fpNeg(x).sort()
9378  FPSort(8, 24)
9379  """
9380  ctx = _get_ctx(ctx)
9381  [a] = _coerce_fp_expr_list([a], ctx)
9382  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9383 
9384 def _mk_fp_unary(f, rm, a, ctx):
9385  ctx = _get_ctx(ctx)
9386  [a] = _coerce_fp_expr_list([a], ctx)
9387  if z3_debug():
9388  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9389  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9390  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9391 
9392 def _mk_fp_unary_norm(f, a, ctx):
9393  ctx = _get_ctx(ctx)
9394  [a] = _coerce_fp_expr_list([a], ctx)
9395  if z3_debug():
9396  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9397  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
9398 
9399 def _mk_fp_unary_pred(f, a, ctx):
9400  ctx = _get_ctx(ctx)
9401  [a] = _coerce_fp_expr_list([a], ctx)
9402  if z3_debug():
9403  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9404  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9405 
9406 def _mk_fp_bin(f, rm, a, b, ctx):
9407  ctx = _get_ctx(ctx)
9408  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9409  if z3_debug():
9410  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9411  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9412  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9413 
9414 def _mk_fp_bin_norm(f, a, b, ctx):
9415  ctx = _get_ctx(ctx)
9416  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9417  if z3_debug():
9418  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9419  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9420 
9421 def _mk_fp_bin_pred(f, a, b, ctx):
9422  ctx = _get_ctx(ctx)
9423  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9424  if z3_debug():
9425  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9426  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9427 
9428 def _mk_fp_tern(f, rm, a, b, c, ctx):
9429  ctx = _get_ctx(ctx)
9430  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9431  if z3_debug():
9432  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9433  _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression")
9434  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9435 
9436 def fpAdd(rm, a, b, ctx=None):
9437  """Create a Z3 floating-point addition expression.
9438 
9439  >>> s = FPSort(8, 24)
9440  >>> rm = RNE()
9441  >>> x = FP('x', s)
9442  >>> y = FP('y', s)
9443  >>> fpAdd(rm, x, y)
9444  fpAdd(RNE(), x, y)
9445  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9446  x + y
9447  >>> fpAdd(rm, x, y).sort()
9448  FPSort(8, 24)
9449  """
9450  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9451 
9452 def fpSub(rm, a, b, ctx=None):
9453  """Create a Z3 floating-point subtraction expression.
9454 
9455  >>> s = FPSort(8, 24)
9456  >>> rm = RNE()
9457  >>> x = FP('x', s)
9458  >>> y = FP('y', s)
9459  >>> fpSub(rm, x, y)
9460  fpSub(RNE(), x, y)
9461  >>> fpSub(rm, x, y).sort()
9462  FPSort(8, 24)
9463  """
9464  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9465 
9466 def fpMul(rm, a, b, ctx=None):
9467  """Create a Z3 floating-point multiplication expression.
9468 
9469  >>> s = FPSort(8, 24)
9470  >>> rm = RNE()
9471  >>> x = FP('x', s)
9472  >>> y = FP('y', s)
9473  >>> fpMul(rm, x, y)
9474  fpMul(RNE(), x, y)
9475  >>> fpMul(rm, x, y).sort()
9476  FPSort(8, 24)
9477  """
9478  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9479 
9480 def fpDiv(rm, a, b, ctx=None):
9481  """Create a Z3 floating-point division expression.
9482 
9483  >>> s = FPSort(8, 24)
9484  >>> rm = RNE()
9485  >>> x = FP('x', s)
9486  >>> y = FP('y', s)
9487  >>> fpDiv(rm, x, y)
9488  fpDiv(RNE(), x, y)
9489  >>> fpDiv(rm, x, y).sort()
9490  FPSort(8, 24)
9491  """
9492  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9493 
9494 def fpRem(a, b, ctx=None):
9495  """Create a Z3 floating-point remainder expression.
9496 
9497  >>> s = FPSort(8, 24)
9498  >>> x = FP('x', s)
9499  >>> y = FP('y', s)
9500  >>> fpRem(x, y)
9501  fpRem(x, y)
9502  >>> fpRem(x, y).sort()
9503  FPSort(8, 24)
9504  """
9505  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9506 
9507 def fpMin(a, b, ctx=None):
9508  """Create a Z3 floating-point minimum expression.
9509 
9510  >>> s = FPSort(8, 24)
9511  >>> rm = RNE()
9512  >>> x = FP('x', s)
9513  >>> y = FP('y', s)
9514  >>> fpMin(x, y)
9515  fpMin(x, y)
9516  >>> fpMin(x, y).sort()
9517  FPSort(8, 24)
9518  """
9519  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9520 
9521 def fpMax(a, b, ctx=None):
9522  """Create a Z3 floating-point maximum expression.
9523 
9524  >>> s = FPSort(8, 24)
9525  >>> rm = RNE()
9526  >>> x = FP('x', s)
9527  >>> y = FP('y', s)
9528  >>> fpMax(x, y)
9529  fpMax(x, y)
9530  >>> fpMax(x, y).sort()
9531  FPSort(8, 24)
9532  """
9533  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9534 
9535 def fpFMA(rm, a, b, c, ctx=None):
9536  """Create a Z3 floating-point fused multiply-add expression.
9537  """
9538  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9539 
9540 def fpSqrt(rm, a, ctx=None):
9541  """Create a Z3 floating-point square root expression.
9542  """
9543  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9544 
9545 def fpRoundToIntegral(rm, a, ctx=None):
9546  """Create a Z3 floating-point roundToIntegral expression.
9547  """
9548  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9549 
9550 def fpIsNaN(a, ctx=None):
9551  """Create a Z3 floating-point isNaN expression.
9552 
9553  >>> s = FPSort(8, 24)
9554  >>> x = FP('x', s)
9555  >>> y = FP('y', s)
9556  >>> fpIsNaN(x)
9557  fpIsNaN(x)
9558  """
9559  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
9560 
9561 def fpIsInf(a, ctx=None):
9562  """Create a Z3 floating-point isInfinite expression.
9563 
9564  >>> s = FPSort(8, 24)
9565  >>> x = FP('x', s)
9566  >>> fpIsInf(x)
9567  fpIsInf(x)
9568  """
9569  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
9570 
9571 def fpIsZero(a, ctx=None):
9572  """Create a Z3 floating-point isZero expression.
9573  """
9574  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
9575 
9576 def fpIsNormal(a, ctx=None):
9577  """Create a Z3 floating-point isNormal expression.
9578  """
9579  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
9580 
9581 def fpIsSubnormal(a, ctx=None):
9582  """Create a Z3 floating-point isSubnormal expression.
9583  """
9584  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
9585 
9586 def fpIsNegative(a, ctx=None):
9587  """Create a Z3 floating-point isNegative expression.
9588  """
9589  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9590 
9591 def fpIsPositive(a, ctx=None):
9592  """Create a Z3 floating-point isPositive expression.
9593  """
9594  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9595  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9596 
9597 def _check_fp_args(a, b):
9598  if z3_debug():
9599  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9600 
9601 def fpLT(a, b, ctx=None):
9602  """Create the Z3 floating-point expression `other < self`.
9603 
9604  >>> x, y = FPs('x y', FPSort(8, 24))
9605  >>> fpLT(x, y)
9606  x < y
9607  >>> (x < y).sexpr()
9608  '(fp.lt x y)'
9609  """
9610  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9611 
9612 def fpLEQ(a, b, ctx=None):
9613  """Create the Z3 floating-point expression `other <= self`.
9614 
9615  >>> x, y = FPs('x y', FPSort(8, 24))
9616  >>> fpLEQ(x, y)
9617  x <= y
9618  >>> (x <= y).sexpr()
9619  '(fp.leq x y)'
9620  """
9621  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9622 
9623 def fpGT(a, b, ctx=None):
9624  """Create the Z3 floating-point expression `other > self`.
9625 
9626  >>> x, y = FPs('x y', FPSort(8, 24))
9627  >>> fpGT(x, y)
9628  x > y
9629  >>> (x > y).sexpr()
9630  '(fp.gt x y)'
9631  """
9632  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9633 
9634 def fpGEQ(a, b, ctx=None):
9635  """Create the Z3 floating-point expression `other >= self`.
9636 
9637  >>> x, y = FPs('x y', FPSort(8, 24))
9638  >>> fpGEQ(x, y)
9639  x >= y
9640  >>> (x >= y).sexpr()
9641  '(fp.geq x y)'
9642  """
9643  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9644 
9645 def fpEQ(a, b, ctx=None):
9646  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9647 
9648  >>> x, y = FPs('x y', FPSort(8, 24))
9649  >>> fpEQ(x, y)
9650  fpEQ(x, y)
9651  >>> fpEQ(x, y).sexpr()
9652  '(fp.eq x y)'
9653  """
9654  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9655 
9656 def fpNEQ(a, b, ctx=None):
9657  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9658 
9659  >>> x, y = FPs('x y', FPSort(8, 24))
9660  >>> fpNEQ(x, y)
9661  Not(fpEQ(x, y))
9662  >>> (x != y).sexpr()
9663  '(distinct x y)'
9664  """
9665  return Not(fpEQ(a, b, ctx))
9666 
9667 def fpFP(sgn, exp, sig, ctx=None):
9668  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9669 
9670  >>> s = FPSort(8, 24)
9671  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9672  >>> print(x)
9673  fpFP(1, 127, 4194304)
9674  >>> xv = FPVal(-1.5, s)
9675  >>> print(xv)
9676  -1.5
9677  >>> slvr = Solver()
9678  >>> slvr.add(fpEQ(x, xv))
9679  >>> slvr.check()
9680  sat
9681  >>> xv = FPVal(+1.5, s)
9682  >>> print(xv)
9683  1.5
9684  >>> slvr = Solver()
9685  >>> slvr.add(fpEQ(x, xv))
9686  >>> slvr.check()
9687  unsat
9688  """
9689  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9690  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9691  ctx = _get_ctx(ctx)
9692  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9693  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9694 
9695 def fpToFP(a1, a2=None, a3=None, ctx=None):
9696  """Create a Z3 floating-point conversion expression from other term sorts
9697  to floating-point.
9698 
9699  From a bit-vector term in IEEE 754-2008 format:
9700  >>> x = FPVal(1.0, Float32())
9701  >>> x_bv = fpToIEEEBV(x)
9702  >>> simplify(fpToFP(x_bv, Float32()))
9703  1
9704 
9705  From a floating-point term with different precision:
9706  >>> x = FPVal(1.0, Float32())
9707  >>> x_db = fpToFP(RNE(), x, Float64())
9708  >>> x_db.sort()
9709  FPSort(11, 53)
9710 
9711  From a real term:
9712  >>> x_r = RealVal(1.5)
9713  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9714  1.5
9715 
9716  From a signed bit-vector term:
9717  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9718  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9719  -1.25*(2**2)
9720  """
9721  ctx = _get_ctx(ctx)
9722  if is_bv(a1) and is_fp_sort(a2):
9723  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9724  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9725  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9726  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9727  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9728  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9729  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9730  else:
9731  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9732 
9733 def fpBVToFP(v, sort, ctx=None):
9734  """Create a Z3 floating-point conversion expression that represents the
9735  conversion from a bit-vector term to a floating-point term.
9736 
9737  >>> x_bv = BitVecVal(0x3F800000, 32)
9738  >>> x_fp = fpBVToFP(x_bv, Float32())
9739  >>> x_fp
9740  fpToFP(1065353216)
9741  >>> simplify(x_fp)
9742  1
9743  """
9744  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9745  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9746  ctx = _get_ctx(ctx)
9747  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9748 
9749 def fpFPToFP(rm, v, sort, ctx=None):
9750  """Create a Z3 floating-point conversion expression that represents the
9751  conversion from a floating-point term to a floating-point term of different precision.
9752 
9753  >>> x_sgl = FPVal(1.0, Float32())
9754  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9755  >>> x_dbl
9756  fpToFP(RNE(), 1)
9757  >>> simplify(x_dbl)
9758  1
9759  >>> x_dbl.sort()
9760  FPSort(11, 53)
9761  """
9762  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9763  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9764  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9765  ctx = _get_ctx(ctx)
9766  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9767 
9768 def fpRealToFP(rm, v, sort, ctx=None):
9769  """Create a Z3 floating-point conversion expression that represents the
9770  conversion from a real term to a floating-point term.
9771 
9772  >>> x_r = RealVal(1.5)
9773  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9774  >>> x_fp
9775  fpToFP(RNE(), 3/2)
9776  >>> simplify(x_fp)
9777  1.5
9778  """
9779  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9780  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9781  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9782  ctx = _get_ctx(ctx)
9783  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9784 
9785 def fpSignedToFP(rm, v, sort, ctx=None):
9786  """Create a Z3 floating-point conversion expression that represents the
9787  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9788 
9789  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9790  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9791  >>> x_fp
9792  fpToFP(RNE(), 4294967291)
9793  >>> simplify(x_fp)
9794  -1.25*(2**2)
9795  """
9796  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9797  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9798  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9799  ctx = _get_ctx(ctx)
9800  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9801 
9802 def fpUnsignedToFP(rm, v, sort, ctx=None):
9803  """Create a Z3 floating-point conversion expression that represents the
9804  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9805 
9806  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9807  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9808  >>> x_fp
9809  fpToFPUnsigned(RNE(), 4294967291)
9810  >>> simplify(x_fp)
9811  1*(2**32)
9812  """
9813  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9814  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9815  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9816  ctx = _get_ctx(ctx)
9817  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9818 
9819 def fpToFPUnsigned(rm, x, s, ctx=None):
9820  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9821  if z3_debug():
9822  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9823  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9824  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9825  ctx = _get_ctx(ctx)
9826  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9827 
9828 def fpToSBV(rm, x, s, ctx=None):
9829  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9830 
9831  >>> x = FP('x', FPSort(8, 24))
9832  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9833  >>> print(is_fp(x))
9834  True
9835  >>> print(is_bv(y))
9836  True
9837  >>> print(is_fp(y))
9838  False
9839  >>> print(is_bv(x))
9840  False
9841  """
9842  if z3_debug():
9843  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9844  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9845  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9846  ctx = _get_ctx(ctx)
9847  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9848 
9849 def fpToUBV(rm, x, s, ctx=None):
9850  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9851 
9852  >>> x = FP('x', FPSort(8, 24))
9853  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9854  >>> print(is_fp(x))
9855  True
9856  >>> print(is_bv(y))
9857  True
9858  >>> print(is_fp(y))
9859  False
9860  >>> print(is_bv(x))
9861  False
9862  """
9863  if z3_debug():
9864  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9865  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9866  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9867  ctx = _get_ctx(ctx)
9868  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9869 
9870 def fpToReal(x, ctx=None):
9871  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9872 
9873  >>> x = FP('x', FPSort(8, 24))
9874  >>> y = fpToReal(x)
9875  >>> print(is_fp(x))
9876  True
9877  >>> print(is_real(y))
9878  True
9879  >>> print(is_fp(y))
9880  False
9881  >>> print(is_real(x))
9882  False
9883  """
9884  if z3_debug():
9885  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9886  ctx = _get_ctx(ctx)
9887  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9888 
9889 def fpToIEEEBV(x, ctx=None):
9890  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9891 
9892  The size of the resulting bit-vector is automatically determined.
9893 
9894  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9895  knows only one NaN and it will always produce the same bit-vector representation of
9896  that NaN.
9897 
9898  >>> x = FP('x', FPSort(8, 24))
9899  >>> y = fpToIEEEBV(x)
9900  >>> print(is_fp(x))
9901  True
9902  >>> print(is_bv(y))
9903  True
9904  >>> print(is_fp(y))
9905  False
9906  >>> print(is_bv(x))
9907  False
9908  """
9909  if z3_debug():
9910  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9911  ctx = _get_ctx(ctx)
9912  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9913 
9914 
9915 
9916 #########################################
9917 #
9918 # Strings, Sequences and Regular expressions
9919 #
9920 #########################################
9921 
9922 class SeqSortRef(SortRef):
9923  """Sequence sort."""
9924 
9925  def is_string(self):
9926  """Determine if sort is a string
9927  >>> s = StringSort()
9928  >>> s.is_string()
9929  True
9930  >>> s = SeqSort(IntSort())
9931  >>> s.is_string()
9932  False
9933  """
9934  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9935 
9936  def basis(self):
9937  return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
9938 
9939 
9940 def StringSort(ctx=None):
9941  """Create a string sort
9942  >>> s = StringSort()
9943  >>> print(s)
9944  String
9945  """
9946  ctx = _get_ctx(ctx)
9947  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9948 
9949 
9950 def SeqSort(s):
9951  """Create a sequence sort over elements provided in the argument
9952  >>> s = SeqSort(IntSort())
9953  >>> s == Unit(IntVal(1)).sort()
9954  True
9955  """
9956  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9957 
9958 class SeqRef(ExprRef):
9959  """Sequence expression."""
9960 
9961  def sort(self):
9962  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9963 
9964  def __add__(self, other):
9965  return Concat(self, other)
9966 
9967  def __radd__(self, other):
9968  return Concat(other, self)
9969 
9970  def __getitem__(self, i):
9971  if _is_int(i):
9972  i = IntVal(i, self.ctx)
9973  return SeqRef(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9974 
9975  def at(self, i):
9976  if _is_int(i):
9977  i = IntVal(i, self.ctx)
9978  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9979 
9980  def is_string(self):
9981  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9982 
9983  def is_string_value(self):
9984  return Z3_is_string(self.ctx_ref(), self.as_ast())
9985 
9986  def as_string(self):
9987  """Return a string representation of sequence expression."""
9988  if self.is_string_value():
9989  return Z3_get_string(self.ctx_ref(), self.as_ast())
9990  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9991 
9992 
9993 def _coerce_seq(s, ctx=None):
9994  if isinstance(s, str):
9995  ctx = _get_ctx(ctx)
9996  s = StringVal(s, ctx)
9997  if not is_expr(s):
9998  raise Z3Exception("Non-expression passed as a sequence")
9999  if not is_seq(s):
10000  raise Z3Exception("Non-sequence passed as a sequence")
10001  return s
10002 
10003 def _get_ctx2(a, b, ctx=None):
10004  if is_expr(a):
10005  return a.ctx
10006  if is_expr(b):
10007  return b.ctx
10008  if ctx is None:
10009  ctx = main_ctx()
10010  return ctx
10011 
10012 def is_seq(a):
10013  """Return `True` if `a` is a Z3 sequence expression.
10014  >>> print (is_seq(Unit(IntVal(0))))
10015  True
10016  >>> print (is_seq(StringVal("abc")))
10017  True
10018  """
10019  return isinstance(a, SeqRef)
10020 
10021 def is_string(a):
10022  """Return `True` if `a` is a Z3 string expression.
10023  >>> print (is_string(StringVal("ab")))
10024  True
10025  """
10026  return isinstance(a, SeqRef) and a.is_string()
10027 
10028 def is_string_value(a):
10029  """return 'True' if 'a' is a Z3 string constant expression.
10030  >>> print (is_string_value(StringVal("a")))
10031  True
10032  >>> print (is_string_value(StringVal("a") + StringVal("b")))
10033  False
10034  """
10035  return isinstance(a, SeqRef) and a.is_string_value()
10036 
10037 
10038 def StringVal(s, ctx=None):
10039  """create a string expression"""
10040  ctx = _get_ctx(ctx)
10041  return SeqRef(Z3_mk_lstring(ctx.ref(), len(s), s), ctx)
10042 
10043 def String(name, ctx=None):
10044  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10045 
10046  >>> x = String('x')
10047  """
10048  ctx = _get_ctx(ctx)
10049  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10050 
10051 def SubString(s, offset, length):
10052  """Extract substring or subsequence starting at offset"""
10053  return Extract(s, offset, length)
10054 
10055 def SubSeq(s, offset, length):
10056  """Extract substring or subsequence starting at offset"""
10057  return Extract(s, offset, length)
10058 
10059 def Strings(names, ctx=None):
10060  """Return a tuple of String constants. """
10061  ctx = _get_ctx(ctx)
10062  if isinstance(names, str):
10063  names = names.split(" ")
10064  return [String(name, ctx) for name in names]
10065 
10066 def Empty(s):
10067  """Create the empty sequence of the given sort
10068  >>> e = Empty(StringSort())
10069  >>> e2 = StringVal("")
10070  >>> print(e.eq(e2))
10071  True
10072  >>> e3 = Empty(SeqSort(IntSort()))
10073  >>> print(e3)
10074  Empty(Seq(Int))
10075  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10076  >>> print(e4)
10077  Empty(ReSort(Seq(Int)))
10078  """
10079  if isinstance(s, SeqSortRef):
10080  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10081  if isinstance(s, ReSortRef):
10082  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10083  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10084 
10085 def Full(s):
10086  """Create the regular expression that accepts the universal language
10087  >>> e = Full(ReSort(SeqSort(IntSort())))
10088  >>> print(e)
10089  Full(ReSort(Seq(Int)))
10090  >>> e1 = Full(ReSort(StringSort()))
10091  >>> print(e1)
10092  Full(ReSort(String))
10093  """
10094  if isinstance(s, ReSortRef):
10095  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10096  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10097 
10098 
10099 def Unit(a):
10100  """Create a singleton sequence"""
10101  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10102 
10103 def PrefixOf(a, b):
10104  """Check if 'a' is a prefix of 'b'
10105  >>> s1 = PrefixOf("ab", "abc")
10106  >>> simplify(s1)
10107  True
10108  >>> s2 = PrefixOf("bc", "abc")
10109  >>> simplify(s2)
10110  False
10111  """
10112  ctx = _get_ctx2(a, b)
10113  a = _coerce_seq(a, ctx)
10114  b = _coerce_seq(b, ctx)
10115  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10116 
10117 def SuffixOf(a, b):
10118  """Check if 'a' is a suffix of 'b'
10119  >>> s1 = SuffixOf("ab", "abc")
10120  >>> simplify(s1)
10121  False
10122  >>> s2 = SuffixOf("bc", "abc")
10123  >>> simplify(s2)
10124  True
10125  """
10126  ctx = _get_ctx2(a, b)
10127  a = _coerce_seq(a, ctx)
10128  b = _coerce_seq(b, ctx)
10129  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10130 
10131 def Contains(a, b):
10132  """Check if 'a' contains 'b'
10133  >>> s1 = Contains("abc", "ab")
10134  >>> simplify(s1)
10135  True
10136  >>> s2 = Contains("abc", "bc")
10137  >>> simplify(s2)
10138  True
10139  >>> x, y, z = Strings('x y z')
10140  >>> s3 = Contains(Concat(x,y,z), y)
10141  >>> simplify(s3)
10142  True
10143  """
10144  ctx = _get_ctx2(a, b)
10145  a = _coerce_seq(a, ctx)
10146  b = _coerce_seq(b, ctx)
10147  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10148 
10149 
10150 def Replace(s, src, dst):
10151  """Replace the first occurrence of 'src' by 'dst' in 's'
10152  >>> r = Replace("aaa", "a", "b")
10153  >>> simplify(r)
10154  "baa"
10155  """
10156  ctx = _get_ctx2(dst, s)
10157  if ctx is None and is_expr(src):
10158  ctx = src.ctx
10159  src = _coerce_seq(src, ctx)
10160  dst = _coerce_seq(dst, ctx)
10161  s = _coerce_seq(s, ctx)
10162  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10163 
10164 def IndexOf(s, substr):
10165  return IndexOf(s, substr, IntVal(0))
10166 
10167 def IndexOf(s, substr, offset):
10168  """Retrieve the index of substring within a string starting at a specified offset.
10169  >>> simplify(IndexOf("abcabc", "bc", 0))
10170  1
10171  >>> simplify(IndexOf("abcabc", "bc", 2))
10172  4
10173  """
10174  ctx = None
10175  if is_expr(offset):
10176  ctx = offset.ctx
10177  ctx = _get_ctx2(s, substr, ctx)
10178  s = _coerce_seq(s, ctx)
10179  substr = _coerce_seq(substr, ctx)
10180  if _is_int(offset):
10181  offset = IntVal(offset, ctx)
10182  return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10183 
10184 def LastIndexOf(s, substr):
10185  """Retrieve the last index of substring within a string"""
10186  ctx = None
10187  ctx = _get_ctx2(s, substr, ctx)
10188  s = _coerce_seq(s, ctx)
10189  substr = _coerce_seq(substr, ctx)
10190  return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10191 
10192 
10193 def Length(s):
10194  """Obtain the length of a sequence 's'
10195  >>> l = Length(StringVal("abc"))
10196  >>> simplify(l)
10197  3
10198  """
10199  s = _coerce_seq(s)
10200  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10201 
10202 def StrToInt(s):
10203  """Convert string expression to integer
10204  >>> a = StrToInt("1")
10205  >>> simplify(1 == a)
10206  True
10207  >>> b = StrToInt("2")
10208  >>> simplify(1 == b)
10209  False
10210  >>> c = StrToInt(IntToStr(2))
10211  >>> simplify(1 == c)
10212  False
10213  """
10214  s = _coerce_seq(s)
10215  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10216 
10217 
10218 def IntToStr(s):
10219  """Convert integer expression to string"""
10220  if not is_expr(s):
10221  s = _py2expr(s)
10222  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10223 
10224 
10225 def Re(s, ctx=None):
10226  """The regular expression that accepts sequence 's'
10227  >>> s1 = Re("ab")
10228  >>> s2 = Re(StringVal("ab"))
10229  >>> s3 = Re(Unit(BoolVal(True)))
10230  """
10231  s = _coerce_seq(s, ctx)
10232  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10233 
10234 
10235 
10236 
10237 ## Regular expressions
10238 
10239 class ReSortRef(SortRef):
10240  """Regular expression sort."""
10241 
10242  def basis(self):
10243  return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10244 
10245 def ReSort(s):
10246  if is_ast(s):
10247  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10248  if s is None or isinstance(s, Context):
10249  ctx = _get_ctx(s)
10250  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10251  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10252 
10253 
10254 class ReRef(ExprRef):
10255  """Regular expressions."""
10256 
10257  def __add__(self, other):
10258  return Union(self, other)
10259 
10260 def is_re(s):
10261  return isinstance(s, ReRef)
10262 
10263 
10264 def InRe(s, re):
10265  """Create regular expression membership test
10266  >>> re = Union(Re("a"),Re("b"))
10267  >>> print (simplify(InRe("a", re)))
10268  True
10269  >>> print (simplify(InRe("b", re)))
10270  True
10271  >>> print (simplify(InRe("c", re)))
10272  False
10273  """
10274  s = _coerce_seq(s, re.ctx)
10275  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10276 
10277 def Union(*args):
10278  """Create union of regular expressions.
10279  >>> re = Union(Re("a"), Re("b"), Re("c"))
10280  >>> print (simplify(InRe("d", re)))
10281  False
10282  """
10283  args = _get_args(args)
10284  sz = len(args)
10285  if z3_debug():
10286  _z3_assert(sz > 0, "At least one argument expected.")
10287  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10288  if sz == 1:
10289  return args[0]
10290  ctx = args[0].ctx
10291  v = (Ast * sz)()
10292  for i in range(sz):
10293  v[i] = args[i].as_ast()
10294  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10295 
10296 def Intersect(*args):
10297  """Create intersection of regular expressions.
10298  >>> re = Intersect(Re("a"), Re("b"), Re("c"))
10299  """
10300  args = _get_args(args)
10301  sz = len(args)
10302  if z3_debug():
10303  _z3_assert(sz > 0, "At least one argument expected.")
10304  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10305  if sz == 1:
10306  return args[0]
10307  ctx = args[0].ctx
10308  v = (Ast * sz)()
10309  for i in range(sz):
10310  v[i] = args[i].as_ast()
10311  return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
10312 
10313 def Plus(re):
10314  """Create the regular expression accepting one or more repetitions of argument.
10315  >>> re = Plus(Re("a"))
10316  >>> print(simplify(InRe("aa", re)))
10317  True
10318  >>> print(simplify(InRe("ab", re)))
10319  False
10320  >>> print(simplify(InRe("", re)))
10321  False
10322  """
10323  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10324 
10325 def Option(re):
10326  """Create the regular expression that optionally accepts the argument.
10327  >>> re = Option(Re("a"))
10328  >>> print(simplify(InRe("a", re)))
10329  True
10330  >>> print(simplify(InRe("", re)))
10331  True
10332  >>> print(simplify(InRe("aa", re)))
10333  False
10334  """
10335  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10336 
10337 def Complement(re):
10338  """Create the complement regular expression."""
10339  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10340 
10341 def Star(re):
10342  """Create the regular expression accepting zero or more repetitions of argument.
10343  >>> re = Star(Re("a"))
10344  >>> print(simplify(InRe("aa", re)))
10345  True
10346  >>> print(simplify(InRe("ab", re)))
10347  False
10348  >>> print(simplify(InRe("", re)))
10349  True
10350  """
10351  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10352 
10353 def Loop(re, lo, hi=0):
10354  """Create the regular expression accepting between a lower and upper bound repetitions
10355  >>> re = Loop(Re("a"), 1, 3)
10356  >>> print(simplify(InRe("aa", re)))
10357  True
10358  >>> print(simplify(InRe("aaaa", re)))
10359  False
10360  >>> print(simplify(InRe("", re)))
10361  False
10362  """
10363  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
10364 
10365 def Range(lo, hi, ctx = None):
10366  """Create the range regular expression over two sequences of length 1
10367  >>> range = Range("a","z")
10368  >>> print(simplify(InRe("b", range)))
10369  True
10370  >>> print(simplify(InRe("bb", range)))
10371  False
10372  """
10373  lo = _coerce_seq(lo, ctx)
10374  hi = _coerce_seq(hi, ctx)
10375  return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
10376 
10377 # Special Relations
10378 
10379 def PartialOrder(a, index):
10380  return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx);
10381 
10382 def LinearOrder(a, index):
10383  return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10384 
10385 def TreeOrder(a, index):
10386  return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx);
10387 
10388 def PiecewiseLinearOrder(a, index):
10389  return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10390 
10391 def TransitiveClosure(f):
10392  """Given a binary relation R, such that the two arguments have the same sort
10393  create the transitive closure relation R+.
10394  The transitive closure R+ is a new relation.
10395  """
10396  return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
10397 
def Not
Definition: z3py.py:1641
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 is_var
Definition: z3py.py:1170
def is_string_value
Definition: z3py.py:10028
def convert_model
Definition: z3py.py:5319
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:9802
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.
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 is_ast
Definition: z3py.py:402
def depth
Definition: z3py.py:5152
def RealSort
Definition: z3py.py:2906
def objectives
Definition: z3py.py:7492
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.
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 UGE
Definition: z3py.py:3902
def BV2Int
Definition: z3py.py:3693
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.
Regular expressions.
Definition: z3py.py:10239
def fpEQ
Definition: z3py.py:9645
def Update
Definition: z3py.py:4396
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 sexpr
Definition: z3py.py:335
Fixedpoint.
Definition: z3py.py:6916
def solve_using
Definition: z3py.py:8390
def Lambda
Definition: z3py.py:2064
def __le__
Definition: z3py.py:7948
def upper
Definition: z3py.py:7465
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 Re
Definition: z3py.py:10225
def ref
Definition: z3py.py:198
def FiniteDomainVal
Definition: z3py.py:7256
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:1803
def is_lt
Definition: z3py.py:2661
def __str__
Definition: z3py.py:310
def With
Definition: z3py.py:7801
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def DisjointSum
Definition: z3py.py:4962
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_cover
Definition: z3py.py:7090
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
def __eq__
Definition: z3py.py:7974
def SetDel
Definition: z3py.py:4602
def BoolVal
Definition: z3py.py:1540
Function Declarations.
Definition: z3py.py:651
def FP
Definition: z3py.py:9306
def is_is_int
Definition: z3py.py:2694
def TupleSort
Definition: z3py.py:4951
def is_implies
Definition: z3py.py:1481
def Unit
Definition: z3py.py:10099
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:7526
Booleans.
Definition: z3py.py:1360
def help
Definition: z3py.py:6816
def fpMax
Definition: z3py.py:9521
def IntSort
Definition: z3py.py:2890
def to_string
Definition: z3py.py:7135
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 sort
Definition: z3py.py:879
def LShR
Definition: z3py.py:3996
def BoolSort
Definition: z3py.py:1523
def is_map
Definition: z3py.py:4311
def fpToFP
Definition: z3py.py:9695
def is_ge
Definition: z3py.py:2672
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 __hash__
Definition: z3py.py:919
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.
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3358
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 Array
Definition: z3py.py:4383
def SetSort
Sets.
Definition: z3py.py:4548
def Real
Definition: z3py.py:3041
def statistics
Definition: z3py.py:7143
def FreshConst
Definition: z3py.py:1316
def SolverFor
Definition: z3py.py:6878
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 declare
Definition: z3py.py:4705
def is_distinct
Definition: z3py.py:1512
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def BitVecSort
Definition: z3py.py:3723
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
def SignExt
Definition: z3py.py:4057
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def __ne__
Definition: z3py.py:571
def get_rules
Definition: z3py.py:7118
def Int2BV
Definition: z3py.py:3715
def is_int_value
Definition: z3py.py:2522
def fpMul
Definition: z3py.py:9466
def RealVarVector
Definition: z3py.py:1343
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 is_fp
Definition: z3py.py:9118
def get_answer
Definition: z3py.py:7059
def is_arith
Definition: z3py.py:2460
def is_fprm_sort
Definition: z3py.py:8744
def is_algebraic_value
Definition: z3py.py:2566
def Option
Definition: z3py.py:10325
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:3173
def is_finite_domain_value
Definition: z3py.py:7270
def ULE
Definition: z3py.py:3868
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
def unsat_core
Definition: z3py.py:7457
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
def Implies
Definition: z3py.py:1611
def get_assertions
Definition: z3py.py:7122
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def Cbrt
Definition: z3py.py:3155
def URem
Definition: z3py.py:3956
def ArraySort
Definition: z3py.py:4351
def UDiv
Definition: z3py.py:3936
def When
Definition: z3py.py:8115
def RotateLeft
Definition: z3py.py:4027
def BitVecVal
Definition: z3py.py:3737
def set_option
Definition: z3py.py:267
Arithmetic.
Definition: z3py.py:2090
FP Expressions.
Definition: z3py.py:8756
def __call__
Definition: z3py.py:8001
def is_real
Definition: z3py.py:2203
def StrToInt
Definition: z3py.py:10202
def SetUnion
Definition: z3py.py:4568
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.
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 disable_trace
Definition: z3py.py:72
def And
Definition: z3py.py:1672
def __del__
Definition: z3py.py:303
def SeqSort
Definition: z3py.py:9950
def __del__
Definition: z3py.py:193
def RNE
Definition: z3py.py:8946
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 OrElse
Definition: z3py.py:7745
ASTs base class.
Definition: z3py.py:291
def fpGEQ
Definition: z3py.py:9634
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def __bool__
Definition: z3py.py:325
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
def sort
Definition: z3py.py:2179
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.
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 help
Definition: z3py.py:7678
def If
Definition: z3py.py:1238
def __del__
Definition: z3py.py:7630
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 IntToStr
Definition: z3py.py:10218
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
def subsort
Definition: z3py.py:525
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 K
Definition: z3py.py:4481
def RealVector
Definition: z3py.py:3067
def lower_values
Definition: z3py.py:7470
def __repr__
Definition: z3py.py:7126
def __init__
Definition: z3py.py:7892
def ToReal
Definition: z3py.py:3093
def check
Definition: z3py.py:6601
def StringVal
Definition: z3py.py:10038
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:5050
def SetComplement
Definition: z3py.py:4612
def is_arith_sort
Definition: z3py.py:2161
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 is_seq
Definition: z3py.py:10012
def __hash__
Definition: z3py.py:319
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 __eq__
Definition: z3py.py:902
def get_id
Definition: z3py.py:348
def apply
Definition: z3py.py:7651
def fpRem
Definition: z3py.py:9494
def ZeroExt
Definition: z3py.py:4086
def sexpr
Definition: z3py.py:7500
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 Full
Definition: z3py.py:10085
def is_eq
Definition: z3py.py:1503
def IsMember
Definition: z3py.py:4631
def is_true
Definition: z3py.py:1429
def is_bv
Definition: z3py.py:3666
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:9262
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def get_rule_names_along_trace
Definition: z3py.py:7073
def __init__
Definition: z3py.py:6919
def __eq__
Definition: z3py.py:558
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
def is_mod
Definition: z3py.py:2639
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
def fpToFPUnsigned
Definition: z3py.py:9819
def FreshBool
Definition: z3py.py:1598
def Ints
Definition: z3py.py:3005
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.
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
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:2044
def is_probe
Definition: z3py.py:8029
def fpMin
Definition: z3py.py:9507
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:2027
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def Concat
Definition: z3py.py:3796
def Int
Definition: z3py.py:2993
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 Sum
Definition: z3py.py:8227
Statistics.
Definition: z3py.py:6235
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:7613
def numerator
Definition: z3py.py:2760
def String
Definition: z3py.py:10043
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
def push
Definition: z3py.py:7429
def is_rational_value
Definition: z3py.py:2545
def __ge__
Definition: z3py.py:7961
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 from_file
Definition: z3py.py:7480
def domain
Definition: z3py.py:4239
def is_finite_domain_sort
Definition: z3py.py:7195
def __del__
Definition: z3py.py:7335
def Product
Definition: z3py.py:8253
def DeclareSort
Definition: z3py.py:627
def Replace
Definition: z3py.py:10150
Arrays.
Definition: z3py.py:4206
Patterns.
Definition: z3py.py:1741
def simplify_param_descrs
Definition: z3py.py:8177
def __nonzero__
Definition: z3py.py:322
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 RecFunction
Definition: z3py.py:814
def statistics
Definition: z3py.py:7505
def __repr__
Definition: z3py.py:313
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 AndThen
Definition: z3py.py:7714
def RealVar
Definition: z3py.py:1333
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 sort
Definition: z3py.py:1396
def Repeat
Definition: z3py.py:7827
def as_ast
Definition: z3py.py:873
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 is_quantifier
Definition: z3py.py:1980
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 is_div
Definition: z3py.py:2612
def UGT
Definition: z3py.py:3919
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def Union
Definition: z3py.py:10277
def Q
Definition: z3py.py:2981
def Xor
Definition: z3py.py:1626
def abstract
Definition: z3py.py:7162
def assert_exprs
Definition: z3py.py:7353
def set_predicate_representation
Definition: z3py.py:7100
def ParThen
Definition: z3py.py:7783
def Distinct
Definition: z3py.py:1260
def param_descrs
Definition: z3py.py:7349
def num_args
Definition: z3py.py:959
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs...
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:9561
def is_not
Definition: z3py.py:1492
def params
Definition: z3py.py:941
def Select
Definition: z3py.py:4444
def use_pp
Definition: z3py.py:293
def prec
Definition: z3py.py:5187
def SetDifference
Definition: z3py.py:4621
def is_le
Definition: z3py.py:2650
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 Strings
Definition: z3py.py:10059
def is_pattern
Definition: z3py.py:1751
def fpLT
Definition: z3py.py:9601
def Function
Definition: z3py.py:789
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def fpIsNaN
Definition: z3py.py:9550
def SetAdd
Definition: z3py.py:4592
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def get_version
Definition: z3py.py:83
def eq
Definition: z3py.py:356
def IsInt
Definition: z3py.py:3127
def ToInt
Definition: z3py.py:3110
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 __call__
Definition: z3py.py:745
def ReSort
Definition: z3py.py:10245
def is_false
Definition: z3py.py:1446
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...
def z3_error_handler
Definition: z3py.py:158
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 is_expr
Definition: z3py.py:1105
def PbLe
Definition: z3py.py:8331
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. ...
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:9452
def fpSignedToFP
Definition: z3py.py:9785
def FullSet
Definition: z3py.py:4560
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...
Strings, Sequences and Regular expressions.
Definition: z3py.py:9922
def __init__
Definition: z3py.py:298
def param_descrs
Definition: z3py.py:7682
def Then
Definition: z3py.py:7733
def MultiPattern
Definition: z3py.py:1768
def is_add
Definition: z3py.py:2579
def Loop
Definition: z3py.py:10353
def probe_description
Definition: z3py.py:8055
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def solve
Definition: z3py.py:8362
def Float32
Definition: z3py.py:8700
def IntVector
Definition: z3py.py:3017
def __eq__
Definition: z3py.py:316
def AtLeast
Definition: z3py.py:8295
def __del__
Definition: z3py.py:7918
def parse_string
Definition: z3py.py:7110
def add_rule
Definition: z3py.py:6981
def InRe
Definition: z3py.py:10264
def FreshReal
Definition: z3py.py:3080
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
def __lt__
Definition: z3py.py:7922
def num_sorts
Definition: z3py.py:6064
def enable_trace
Definition: z3py.py:69
def Consts
Definition: z3py.py:1302
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
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:9329
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:8351
def is_int
Definition: z3py.py:2480
def main_ctx
Definition: z3py.py:213
def else_value
Definition: z3py.py:5836
def fpFPToFP
Definition: z3py.py:9749
def fpBVToFP
Definition: z3py.py:9733
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 __call__
Definition: z3py.py:7668
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def substitute
Definition: z3py.py:8181
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a string of a numeric constant term.
def is_const
Definition: z3py.py:1152
def __copy__
Definition: z3py.py:389
def Range
Definition: z3py.py:10365
def is_mul
Definition: z3py.py:2590
def is_sub
Definition: z3py.py:2601
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 update_rule
Definition: z3py.py:7050
def is_idiv
Definition: z3py.py:2628
def __ne__
Definition: z3py.py:7987
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def get_map_func
Definition: z3py.py:4334
def register_relation
Definition: z3py.py:7094
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 Const
Definition: z3py.py:1291
def get_rules_along_trace
Definition: z3py.py:7069
def Contains
Definition: z3py.py:10131
def Ext
Definition: z3py.py:4502
def is_fp_value
Definition: z3py.py:9131
def EnumSort
Definition: z3py.py:4974
def Cond
Definition: z3py.py:8133
def __iadd__
Definition: z3py.py:6969
def __deepcopy__
Definition: z3py.py:7915
def fpToSBV
Definition: z3py.py:9828
def is_select
Definition: z3py.py:4518
def __iadd__
Definition: z3py.py:7369
def CreateDatatypes
Definition: z3py.py:4762
def Reals
Definition: z3py.py:3053
def Map
Definition: z3py.py:4459
def get_id
Definition: z3py.py:876
def range
Definition: z3py.py:4248
def probes
Definition: z3py.py:8045
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
def is_store
Definition: z3py.py:4530
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 is_int
Definition: z3py.py:2189
def __deepcopy__
Definition: z3py.py:7332
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 FailIf
Definition: z3py.py:8096
def is_bool
Definition: z3py.py:1412
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 RotateRight
Definition: z3py.py:4042
def __deepcopy__
Definition: z3py.py:6930
def Bools
Definition: z3py.py:1569
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 model
Definition: z3py.py:7450
def fpRealToFP
Definition: z3py.py:9768
def is_bv_sort
Definition: z3py.py:3205
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def __deepcopy__
Definition: z3py.py:7627
def reset_params
Definition: z3py.py:262
def is_and
Definition: z3py.py:1459
def Default
Definition: z3py.py:4417
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def help_simplify
Definition: z3py.py:8173
def solver
Definition: z3py.py:7634
def is_func_decl
Definition: z3py.py:777
def as_func_decl
Definition: z3py.py:664
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. ...
def __getitem__
Definition: z3py.py:7552
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 help
Definition: z3py.py:7345
def __repr__
Definition: z3py.py:7496
def as_signed_long
Definition: z3py.py:3641
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 open_log
Definition: z3py.py:103
def Star
Definition: z3py.py:10341
def ParOr
Definition: z3py.py:7765
def is_app_of
Definition: z3py.py:1226
def Float64
Definition: z3py.py:8710
def __deepcopy__
Definition: z3py.py:307
def Bool
Definition: z3py.py:1558
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 Var
Definition: z3py.py:1321
def __rmul__
Definition: z3py.py:1399
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.
def substitute_vars
Definition: z3py.py:8207
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 is_gt
Definition: z3py.py:2683
def as_ast
Definition: z3py.py:344
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def fpGT
Definition: z3py.py:9623
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
def sort_kind
Definition: z3py.py:891
def param_descrs
Definition: z3py.py:6947
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def z3_debug
Definition: z3py.py:58
def from_string
Definition: z3py.py:7484
def get_ground_sat_answer
Definition: z3py.py:7064
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.
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.
def is_to_int
Definition: z3py.py:2719
def FiniteDomainSort
Definition: z3py.py:7188
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.
def create
Definition: z3py.py:4728
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
def append_log
Definition: z3py.py:107
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 get_full_version
Definition: z3py.py:91
def __mul__
Definition: z3py.py:1402
def get_var_index
Definition: z3py.py:1194
def reason_unknown
Definition: z3py.py:7446
def fpToIEEEBV
Definition: z3py.py:9889
def EmptySet
Definition: z3py.py:4552
def is_K
Definition: z3py.py:4299
def PrefixOf
Definition: z3py.py:10103
def fpAbs
Definition: z3py.py:9347
def get_num_levels
Definition: z3py.py:7081
def minimize
Definition: z3py.py:7425
FP Numerals.
Definition: z3py.py:9000
def IsSubset
Definition: z3py.py:4641
FP Sorts.
Definition: z3py.py:8655
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 Store
Definition: z3py.py:4428
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:8978
def simplify
Utils.
Definition: z3py.py:8149
def __init__
Definition: z3py.py:174
Expressions.
Definition: z3py.py:863
def is_fp_sort
Definition: z3py.py:8734
def push
Definition: z3py.py:6439
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def fpFP
Definition: z3py.py:9667
def is_const_array
Definition: z3py.py:4287
def is_string
Definition: z3py.py:10021
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def name
Definition: z3py.py:548
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
def Extract
Definition: z3py.py:3841
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
def is_real
Definition: z3py.py:2498
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 is_bv_value
Definition: z3py.py:3679
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 interrupt
Definition: z3py.py:202
def upper_values
Definition: z3py.py:7475
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:2948
def translate
Definition: z3py.py:373
def parse_smt2_string
Definition: z3py.py:8544
def as_ast
Definition: z3py.py:503
def fpToReal
Definition: z3py.py:9870
def BitVec
Definition: z3py.py:3753
def get_cover_delta
Definition: z3py.py:7085
def Intersect
Definition: z3py.py:10296
def fpToUBV
Definition: z3py.py:9849
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 ParAndThen
Definition: z3py.py:7797
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
def is_sort
Definition: z3py.py:586
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def fpNEQ
Definition: z3py.py:9656
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 ctx_ref
Definition: z3py.py:352
def arg
Definition: z3py.py:975
def is_array
Definition: z3py.py:4274
def SuffixOf
Definition: z3py.py:10117
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 get_param
Definition: z3py.py:272
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 WithParams
Definition: z3py.py:7814
def decl
Definition: z3py.py:944
def Plus
Definition: z3py.py:10313
def assert_and_track
Definition: z3py.py:7373
def set_param
Definition: z3py.py:239
def fpNaN
Definition: z3py.py:9203
def prove
Definition: z3py.py:8419
def __hash__
Definition: z3py.py:582
def Length
Definition: z3py.py:10193
def ULT
Definition: z3py.py:3885
def is_finite_domain
Definition: z3py.py:7217
def fpNeg
Definition: z3py.py:9369
def query_from_lvl
Definition: z3py.py:7034
def fpPlusInfinity
Definition: z3py.py:9219
def FreshInt
Definition: z3py.py:3028
def fpAdd
Definition: z3py.py:9436
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 PbGe
Definition: z3py.py:8341
def is_to_real
Definition: z3py.py:2705
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 TryFor
Definition: z3py.py:7846
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 to_symbol
Definition: z3py.py:111
def parse_file
Definition: z3py.py:7114
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
def IndexOf
Definition: z3py.py:10164
def get_version_string
Definition: z3py.py:75
def SimpleSolver
Definition: z3py.py:6898
def add_soft
Definition: z3py.py:7402
def RepeatBitVec
Definition: z3py.py:4113
def sort
Definition: z3py.py:8759
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
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 __ne__
Definition: z3py.py:923
def tactic_description
Definition: z3py.py:7864
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def describe_tactics
Definition: z3py.py:7872
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 lower
Definition: z3py.py:7460
def eq
Definition: z3py.py:422
def check
Definition: z3py.py:7437
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:9145
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.
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
def children
Definition: z3py.py:996
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 maximize
Definition: z3py.py:7421
def __init__
Definition: z3py.py:7327
def BitVecs
Definition: z3py.py:3776
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:3143
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
def declare_var
Definition: z3py.py:7153
def get_id
Definition: z3py.py:506
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def kind
Definition: z3py.py:509
def reason_unknown
Definition: z3py.py:7148
def tactics
Definition: z3py.py:7854
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.
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:2966
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 assert_exprs
Definition: z3py.py:6951
def describe_probes
Definition: z3py.py:8063
def is_fprm
Definition: z3py.py:8982
def assertions
Definition: z3py.py:7488
def num_entries
Definition: z3py.py:5859
def BoolVector
Definition: z3py.py:1584
def Or
Definition: z3py.py:1705
def assertions
Definition: z3py.py:6748
def cast
Definition: z3py.py:533
def AtMost
Definition: z3py.py:8278
def IntVal
Definition: z3py.py:2937
def RecAddDefinition
Definition: z3py.py:831
def is_or
Definition: z3py.py:1470
def SetIntersect
Definition: z3py.py:4580
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def fpLEQ
Definition: z3py.py:9612
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.
def StringSort
Definition: z3py.py:9940
def fpDiv
Definition: z3py.py:9480
def Empty
Definition: z3py.py:10066
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 hash
Definition: z3py.py:392
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def __gt__
Definition: z3py.py:7935
def is_default
Definition: z3py.py:4326
def is_app
Definition: z3py.py:1127
def SRem
Definition: z3py.py:3976
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.