Z3
z3py.py
Go to the documentation of this file.
1 
2 
3 
10 
11 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
12 
13 Several online tutorials for Z3Py are available at:
14 http://rise4fun.com/Z3Py/tutorial/guide
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
17 
18 Small example:
19 
20 >>> x = Int('x')
21 >>> y = Int('y')
22 >>> s = Solver()
23 >>> s.add(x > 0)
24 >>> s.add(x < 2)
25 >>> s.add(y == x + 1)
26 >>> s.check()
27 sat
28 >>> m = s.model()
29 >>> m[x]
30 1
31 >>> m[y]
32 2
33 
34 Z3 exceptions:
35 
36 >>> try:
37 ... x = BitVec('x', 32)
38 ... y = Bool('y')
39 ... # the expression x + y is type incorrect
40 ... n = x + y
41 ... except Z3Exception as ex:
42 ... print("failed: %s" % ex)
43 failed: sort mismatch
44 """
45 from . import z3core
46 from .z3core import *
47 from .z3types import *
48 from .z3consts import *
49 from .z3printer import *
50 from fractions import Fraction
51 import sys
52 import io
53 import math
54 import copy
55 
56 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 get_ctx(ctx):
240  return _get_ctx(ctx)
241 
242 def set_param(*args, **kws):
243  """Set Z3 global (or module) parameters.
244 
245  >>> set_param(precision=10)
246  """
247  if z3_debug():
248  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
249  new_kws = {}
250  for k in kws:
251  v = kws[k]
252  if not set_pp_option(k, v):
253  new_kws[k] = v
254  for key in new_kws:
255  value = new_kws[key]
256  Z3_global_param_set(str(key).upper(), _to_param_value(value))
257  prev = None
258  for a in args:
259  if prev is None:
260  prev = a
261  else:
262  Z3_global_param_set(str(prev), _to_param_value(a))
263  prev = None
264 
266  """Reset all global (or module) parameters.
267  """
269 
270 def set_option(*args, **kws):
271  """Alias for 'set_param' for backward compatibility.
272  """
273  return set_param(*args, **kws)
274 
275 def get_param(name):
276  """Return the value of a Z3 global (or module) parameter
277 
278  >>> get_param('nlsat.reorder')
279  'true'
280  """
281  ptr = (ctypes.c_char_p * 1)()
282  if Z3_global_param_get(str(name), ptr):
283  r = z3core._to_pystr(ptr[0])
284  return r
285  raise Z3Exception("failed to retrieve value for '%s'" % name)
286 
287 
292 
293 # Mark objects that use pretty printer
295  """Superclass for all Z3 objects that have support for pretty printing."""
296  def use_pp(self):
297  return True
298 
299  def _repr_html_(self):
300  in_html = in_html_mode()
301  set_html_mode(True)
302  res = repr(self)
303  set_html_mode(in_html)
304  return res
305 
306 
308  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
309  def __init__(self, ast, ctx=None):
310  self.ast = ast
311  self.ctx = _get_ctx(ctx)
312  Z3_inc_ref(self.ctx.ref(), self.as_ast())
313 
314  def __del__(self):
315  if self.ctx.ref() is not None and self.ast is not None:
316  Z3_dec_ref(self.ctx.ref(), self.as_ast())
317  self.ast = None
318 
319  def __deepcopy__(self, memo={}):
320  return _to_ast_ref(self.ast, self.ctx)
321 
322  def __str__(self):
323  return obj_to_string(self)
324 
325  def __repr__(self):
326  return obj_to_string(self)
327 
328  def __eq__(self, other):
329  return self.eq(other)
330 
331  def __hash__(self):
332  return self.hash()
333 
334  def __nonzero__(self):
335  return self.__bool__()
336 
337  def __bool__(self):
338  if is_true(self):
339  return True
340  elif is_false(self):
341  return False
342  elif is_eq(self) and self.num_args() == 2:
343  return self.arg(0).eq(self.arg(1))
344  else:
345  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
346 
347  def sexpr(self):
348  """Return a string representing the AST node in s-expression notation.
349 
350  >>> x = Int('x')
351  >>> ((x + 1)*x).sexpr()
352  '(* (+ x 1) x)'
353  """
354  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
355 
356  def as_ast(self):
357  """Return a pointer to the corresponding C Z3_ast object."""
358  return self.ast
359 
360  def get_id(self):
361  """Return unique identifier for object. It can be used for hash-tables and maps."""
362  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
363 
364  def ctx_ref(self):
365  """Return a reference to the C context where this AST node is stored."""
366  return self.ctx.ref()
367 
368  def eq(self, other):
369  """Return `True` if `self` and `other` are structurally identical.
370 
371  >>> x = Int('x')
372  >>> n1 = x + 1
373  >>> n2 = 1 + x
374  >>> n1.eq(n2)
375  False
376  >>> n1 = simplify(n1)
377  >>> n2 = simplify(n2)
378  >>> n1.eq(n2)
379  True
380  """
381  if z3_debug():
382  _z3_assert(is_ast(other), "Z3 AST expected")
383  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
384 
385  def translate(self, target):
386  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
387 
388  >>> c1 = Context()
389  >>> c2 = Context()
390  >>> x = Int('x', c1)
391  >>> y = Int('y', c2)
392  >>> # Nodes in different contexts can't be mixed.
393  >>> # However, we can translate nodes from one context to another.
394  >>> x.translate(c2) + y
395  x + y
396  """
397  if z3_debug():
398  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
399  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
400 
401  def __copy__(self):
402  return self.translate(self.ctx)
403 
404  def hash(self):
405  """Return a hashcode for the `self`.
406 
407  >>> n1 = simplify(Int('x') + 1)
408  >>> n2 = simplify(2 + Int('x') - 1)
409  >>> n1.hash() == n2.hash()
410  True
411  """
412  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
413 
414 def is_ast(a):
415  """Return `True` if `a` is an AST node.
416 
417  >>> is_ast(10)
418  False
419  >>> is_ast(IntVal(10))
420  True
421  >>> is_ast(Int('x'))
422  True
423  >>> is_ast(BoolSort())
424  True
425  >>> is_ast(Function('f', IntSort(), IntSort()))
426  True
427  >>> is_ast("x")
428  False
429  >>> is_ast(Solver())
430  False
431  """
432  return isinstance(a, AstRef)
433 
434 def eq(a, b):
435  """Return `True` if `a` and `b` are structurally identical AST nodes.
436 
437  >>> x = Int('x')
438  >>> y = Int('y')
439  >>> eq(x, y)
440  False
441  >>> eq(x + 1, x + 1)
442  True
443  >>> eq(x + 1, 1 + x)
444  False
445  >>> eq(simplify(x + 1), simplify(1 + x))
446  True
447  """
448  if z3_debug():
449  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
450  return a.eq(b)
451 
452 def _ast_kind(ctx, a):
453  if is_ast(a):
454  a = a.as_ast()
455  return Z3_get_ast_kind(ctx.ref(), a)
456 
457 def _ctx_from_ast_arg_list(args, default_ctx=None):
458  ctx = None
459  for a in args:
460  if is_ast(a) or is_probe(a):
461  if ctx is None:
462  ctx = a.ctx
463  else:
464  if z3_debug():
465  _z3_assert(ctx == a.ctx, "Context mismatch")
466  if ctx is None:
467  ctx = default_ctx
468  return ctx
469 
470 def _ctx_from_ast_args(*args):
471  return _ctx_from_ast_arg_list(args)
472 
473 def _to_func_decl_array(args):
474  sz = len(args)
475  _args = (FuncDecl * sz)()
476  for i in range(sz):
477  _args[i] = args[i].as_func_decl()
478  return _args, sz
479 
480 def _to_ast_array(args):
481  sz = len(args)
482  _args = (Ast * sz)()
483  for i in range(sz):
484  _args[i] = args[i].as_ast()
485  return _args, sz
486 
487 def _to_ref_array(ref, args):
488  sz = len(args)
489  _args = (ref * sz)()
490  for i in range(sz):
491  _args[i] = args[i].as_ast()
492  return _args, sz
493 
494 def _to_ast_ref(a, ctx):
495  k = _ast_kind(ctx, a)
496  if k == Z3_SORT_AST:
497  return _to_sort_ref(a, ctx)
498  elif k == Z3_FUNC_DECL_AST:
499  return _to_func_decl_ref(a, ctx)
500  else:
501  return _to_expr_ref(a, ctx)
502 
503 
504 
509 
510 def _sort_kind(ctx, s):
511  return Z3_get_sort_kind(ctx.ref(), s)
512 
514  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
515  def as_ast(self):
516  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
517 
518  def get_id(self):
519  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
520 
521  def kind(self):
522  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
523 
524  >>> b = BoolSort()
525  >>> b.kind() == Z3_BOOL_SORT
526  True
527  >>> b.kind() == Z3_INT_SORT
528  False
529  >>> A = ArraySort(IntSort(), IntSort())
530  >>> A.kind() == Z3_ARRAY_SORT
531  True
532  >>> A.kind() == Z3_INT_SORT
533  False
534  """
535  return _sort_kind(self.ctx, self.ast)
536 
537  def subsort(self, other):
538  """Return `True` if `self` is a subsort of `other`.
539 
540  >>> IntSort().subsort(RealSort())
541  True
542  """
543  return False
544 
545  def cast(self, val):
546  """Try to cast `val` as an element of sort `self`.
547 
548  This method is used in Z3Py to convert Python objects such as integers,
549  floats, longs and strings into Z3 expressions.
550 
551  >>> x = Int('x')
552  >>> RealSort().cast(x)
553  ToReal(x)
554  """
555  if z3_debug():
556  _z3_assert(is_expr(val), "Z3 expression expected")
557  _z3_assert(self.eq(val.sort()), "Sort mismatch")
558  return val
559 
560  def name(self):
561  """Return the name (string) of sort `self`.
562 
563  >>> BoolSort().name()
564  'Bool'
565  >>> ArraySort(IntSort(), IntSort()).name()
566  'Array'
567  """
568  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
569 
570  def __eq__(self, other):
571  """Return `True` if `self` and `other` are the same Z3 sort.
572 
573  >>> p = Bool('p')
574  >>> p.sort() == BoolSort()
575  True
576  >>> p.sort() == IntSort()
577  False
578  """
579  if other is None:
580  return False
581  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
582 
583  def __ne__(self, other):
584  """Return `True` if `self` and `other` are not the same Z3 sort.
585 
586  >>> p = Bool('p')
587  >>> p.sort() != BoolSort()
588  False
589  >>> p.sort() != IntSort()
590  True
591  """
592  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
593 
594  def __hash__(self):
595  """ Hash code. """
596  return AstRef.__hash__(self)
597 
598 def is_sort(s):
599  """Return `True` if `s` is a Z3 sort.
600 
601  >>> is_sort(IntSort())
602  True
603  >>> is_sort(Int('x'))
604  False
605  >>> is_expr(Int('x'))
606  True
607  """
608  return isinstance(s, SortRef)
609 
610 def _to_sort_ref(s, ctx):
611  if z3_debug():
612  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
613  k = _sort_kind(ctx, s)
614  if k == Z3_BOOL_SORT:
615  return BoolSortRef(s, ctx)
616  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
617  return ArithSortRef(s, ctx)
618  elif k == Z3_BV_SORT:
619  return BitVecSortRef(s, ctx)
620  elif k == Z3_ARRAY_SORT:
621  return ArraySortRef(s, ctx)
622  elif k == Z3_DATATYPE_SORT:
623  return DatatypeSortRef(s, ctx)
624  elif k == Z3_FINITE_DOMAIN_SORT:
625  return FiniteDomainSortRef(s, ctx)
626  elif k == Z3_FLOATING_POINT_SORT:
627  return FPSortRef(s, ctx)
628  elif k == Z3_ROUNDING_MODE_SORT:
629  return FPRMSortRef(s, ctx)
630  elif k == Z3_RE_SORT:
631  return ReSortRef(s, ctx)
632  elif k == Z3_SEQ_SORT:
633  return SeqSortRef(s, ctx)
634  return SortRef(s, ctx)
635 
636 def _sort(ctx, a):
637  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
638 
639 def DeclareSort(name, ctx=None):
640  """Create a new uninterpreted sort named `name`.
641 
642  If `ctx=None`, then the new sort is declared in the global Z3Py context.
643 
644  >>> A = DeclareSort('A')
645  >>> a = Const('a', A)
646  >>> b = Const('b', A)
647  >>> a.sort() == A
648  True
649  >>> b.sort() == A
650  True
651  >>> a == b
652  a == b
653  """
654  ctx = _get_ctx(ctx)
655  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
656 
657 
662 
664  """Function declaration. Every constant and function have an associated declaration.
665 
666  The declaration assigns a name, a sort (i.e., type), and for function
667  the sort (i.e., type) of each of its arguments. Note that, in Z3,
668  a constant is a function with 0 arguments.
669  """
670  def as_ast(self):
671  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
672 
673  def get_id(self):
674  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
675 
676  def as_func_decl(self):
677  return self.ast
678 
679  def name(self):
680  """Return the name of the function declaration `self`.
681 
682  >>> f = Function('f', IntSort(), IntSort())
683  >>> f.name()
684  'f'
685  >>> isinstance(f.name(), str)
686  True
687  """
688  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
689 
690  def arity(self):
691  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
692 
693  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
694  >>> f.arity()
695  2
696  """
697  return int(Z3_get_arity(self.ctx_ref(), self.ast))
698 
699  def domain(self, i):
700  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
701 
702  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
703  >>> f.domain(0)
704  Int
705  >>> f.domain(1)
706  Real
707  """
708  if z3_debug():
709  _z3_assert(i < self.arity(), "Index out of bounds")
710  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
711 
712  def range(self):
713  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
714 
715  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
716  >>> f.range()
717  Bool
718  """
719  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
720 
721  def kind(self):
722  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
723 
724  >>> x = Int('x')
725  >>> d = (x + 1).decl()
726  >>> d.kind() == Z3_OP_ADD
727  True
728  >>> d.kind() == Z3_OP_MUL
729  False
730  """
731  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
732 
733  def params(self):
734  ctx = self.ctx
735  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
736  result = [ None for i in range(n) ]
737  for i in range(n):
738  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
739  if k == Z3_PARAMETER_INT:
740  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
741  elif k == Z3_PARAMETER_DOUBLE:
742  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
743  elif k == Z3_PARAMETER_RATIONAL:
744  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
745  elif k == Z3_PARAMETER_SYMBOL:
746  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
747  elif k == Z3_PARAMETER_SORT:
748  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
749  elif k == Z3_PARAMETER_AST:
750  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
751  elif k == Z3_PARAMETER_FUNC_DECL:
752  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
753  else:
754  assert(False)
755  return result
756 
757  def __call__(self, *args):
758  """Create a Z3 application expression using the function `self`, and the given arguments.
759 
760  The arguments must be Z3 expressions. This method assumes that
761  the sorts of the elements in `args` match the sorts of the
762  domain. Limited coercion is supported. For example, if
763  args[0] is a Python integer, and the function expects a Z3
764  integer, then the argument is automatically converted into a
765  Z3 integer.
766 
767  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
768  >>> x = Int('x')
769  >>> y = Real('y')
770  >>> f(x, y)
771  f(x, y)
772  >>> f(x, x)
773  f(x, ToReal(x))
774  """
775  args = _get_args(args)
776  num = len(args)
777  if z3_debug():
778  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
779  _args = (Ast * num)()
780  saved = []
781  for i in range(num):
782  # self.domain(i).cast(args[i]) may create a new Z3 expression,
783  # then we must save in 'saved' to prevent it from being garbage collected.
784  tmp = self.domain(i).cast(args[i])
785  saved.append(tmp)
786  _args[i] = tmp.as_ast()
787  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
788 
790  """Return `True` if `a` is a Z3 function declaration.
791 
792  >>> f = Function('f', IntSort(), IntSort())
793  >>> is_func_decl(f)
794  True
795  >>> x = Real('x')
796  >>> is_func_decl(x)
797  False
798  """
799  return isinstance(a, FuncDeclRef)
800 
801 def Function(name, *sig):
802  """Create a new Z3 uninterpreted function with the given sorts.
803 
804  >>> f = Function('f', IntSort(), IntSort())
805  >>> f(f(0))
806  f(f(0))
807  """
808  sig = _get_args(sig)
809  if z3_debug():
810  _z3_assert(len(sig) > 0, "At least two arguments expected")
811  arity = len(sig) - 1
812  rng = sig[arity]
813  if z3_debug():
814  _z3_assert(is_sort(rng), "Z3 sort expected")
815  dom = (Sort * arity)()
816  for i in range(arity):
817  if z3_debug():
818  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
819  dom[i] = sig[i].ast
820  ctx = rng.ctx
821  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
822 
823 def _to_func_decl_ref(a, ctx):
824  return FuncDeclRef(a, ctx)
825 
826 def RecFunction(name, *sig):
827  """Create a new Z3 recursive with the given sorts."""
828  sig = _get_args(sig)
829  if z3_debug():
830  _z3_assert(len(sig) > 0, "At least two arguments expected")
831  arity = len(sig) - 1
832  rng = sig[arity]
833  if z3_debug():
834  _z3_assert(is_sort(rng), "Z3 sort expected")
835  dom = (Sort * arity)()
836  for i in range(arity):
837  if z3_debug():
838  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
839  dom[i] = sig[i].ast
840  ctx = rng.ctx
841  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
842 
843 def RecAddDefinition(f, args, body):
844  """Set the body of a recursive function.
845  Recursive definitions are only unfolded during search.
846  >>> ctx = Context()
847  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
848  >>> n = Int('n', ctx)
849  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
850  >>> simplify(fac(5))
851  fac(5)
852  >>> s = Solver(ctx=ctx)
853  >>> s.add(fac(n) < 3)
854  >>> s.check()
855  sat
856  >>> s.model().eval(fac(5))
857  120
858  """
859  if is_app(args):
860  args = [args]
861  ctx = body.ctx
862  args = _get_args(args)
863  n = len(args)
864  _args = (Ast * n)()
865  for i in range(n):
866  _args[i] = args[i].ast
867  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
868 
869 
874 
876  """Constraints, formulas and terms are expressions in Z3.
877 
878  Expressions are ASTs. Every expression has a sort.
879  There are three main kinds of expressions:
880  function applications, quantifiers and bounded variables.
881  A constant is a function application with 0 arguments.
882  For quantifier free problems, all expressions are
883  function applications.
884  """
885  def as_ast(self):
886  return self.ast
887 
888  def get_id(self):
889  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
890 
891  def sort(self):
892  """Return the sort of expression `self`.
893 
894  >>> x = Int('x')
895  >>> (x + 1).sort()
896  Int
897  >>> y = Real('y')
898  >>> (x + y).sort()
899  Real
900  """
901  return _sort(self.ctx, self.as_ast())
902 
903  def sort_kind(self):
904  """Shorthand for `self.sort().kind()`.
905 
906  >>> a = Array('a', IntSort(), IntSort())
907  >>> a.sort_kind() == Z3_ARRAY_SORT
908  True
909  >>> a.sort_kind() == Z3_INT_SORT
910  False
911  """
912  return self.sort().kind()
913 
914  def __eq__(self, other):
915  """Return a Z3 expression that represents the constraint `self == other`.
916 
917  If `other` is `None`, then this method simply returns `False`.
918 
919  >>> a = Int('a')
920  >>> b = Int('b')
921  >>> a == b
922  a == b
923  >>> a is None
924  False
925  """
926  if other is None:
927  return False
928  a, b = _coerce_exprs(self, other)
929  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
930 
931  def __hash__(self):
932  """ Hash code. """
933  return AstRef.__hash__(self)
934 
935  def __ne__(self, other):
936  """Return a Z3 expression that represents the constraint `self != other`.
937 
938  If `other` is `None`, then this method simply returns `True`.
939 
940  >>> a = Int('a')
941  >>> b = Int('b')
942  >>> a != b
943  a != b
944  >>> a is not None
945  True
946  """
947  if other is None:
948  return True
949  a, b = _coerce_exprs(self, other)
950  _args, sz = _to_ast_array((a, b))
951  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
952 
953  def params(self):
954  return self.decl().params()
955 
956  def decl(self):
957  """Return the Z3 function declaration associated with a Z3 application.
958 
959  >>> f = Function('f', IntSort(), IntSort())
960  >>> a = Int('a')
961  >>> t = f(a)
962  >>> eq(t.decl(), f)
963  True
964  >>> (a + 1).decl()
965  +
966  """
967  if z3_debug():
968  _z3_assert(is_app(self), "Z3 application expected")
969  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
970 
971  def num_args(self):
972  """Return the number of arguments of a Z3 application.
973 
974  >>> a = Int('a')
975  >>> b = Int('b')
976  >>> (a + b).num_args()
977  2
978  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
979  >>> t = f(a, b, 0)
980  >>> t.num_args()
981  3
982  """
983  if z3_debug():
984  _z3_assert(is_app(self), "Z3 application expected")
985  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
986 
987  def arg(self, idx):
988  """Return argument `idx` of the application `self`.
989 
990  This method assumes that `self` is a function application with at least `idx+1` arguments.
991 
992  >>> a = Int('a')
993  >>> b = Int('b')
994  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
995  >>> t = f(a, b, 0)
996  >>> t.arg(0)
997  a
998  >>> t.arg(1)
999  b
1000  >>> t.arg(2)
1001  0
1002  """
1003  if z3_debug():
1004  _z3_assert(is_app(self), "Z3 application expected")
1005  _z3_assert(idx < self.num_args(), "Invalid argument index")
1006  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
1007 
1008  def children(self):
1009  """Return a list containing the children of the given expression
1010 
1011  >>> a = Int('a')
1012  >>> b = Int('b')
1013  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1014  >>> t = f(a, b, 0)
1015  >>> t.children()
1016  [a, b, 0]
1017  """
1018  if is_app(self):
1019  return [self.arg(i) for i in range(self.num_args())]
1020  else:
1021  return []
1022 
1023 def _to_expr_ref(a, ctx):
1024  if isinstance(a, Pattern):
1025  return PatternRef(a, ctx)
1026  ctx_ref = ctx.ref()
1027  k = Z3_get_ast_kind(ctx_ref, a)
1028  if k == Z3_QUANTIFIER_AST:
1029  return QuantifierRef(a, ctx)
1030  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1031  if sk == Z3_BOOL_SORT:
1032  return BoolRef(a, ctx)
1033  if sk == Z3_INT_SORT:
1034  if k == Z3_NUMERAL_AST:
1035  return IntNumRef(a, ctx)
1036  return ArithRef(a, ctx)
1037  if sk == Z3_REAL_SORT:
1038  if k == Z3_NUMERAL_AST:
1039  return RatNumRef(a, ctx)
1040  if _is_algebraic(ctx, a):
1041  return AlgebraicNumRef(a, ctx)
1042  return ArithRef(a, ctx)
1043  if sk == Z3_BV_SORT:
1044  if k == Z3_NUMERAL_AST:
1045  return BitVecNumRef(a, ctx)
1046  else:
1047  return BitVecRef(a, ctx)
1048  if sk == Z3_ARRAY_SORT:
1049  return ArrayRef(a, ctx)
1050  if sk == Z3_DATATYPE_SORT:
1051  return DatatypeRef(a, ctx)
1052  if sk == Z3_FLOATING_POINT_SORT:
1053  if k == Z3_APP_AST and _is_numeral(ctx, a):
1054  return FPNumRef(a, ctx)
1055  else:
1056  return FPRef(a, ctx)
1057  if sk == Z3_FINITE_DOMAIN_SORT:
1058  if k == Z3_NUMERAL_AST:
1059  return FiniteDomainNumRef(a, ctx)
1060  else:
1061  return FiniteDomainRef(a, ctx)
1062  if sk == Z3_ROUNDING_MODE_SORT:
1063  return FPRMRef(a, ctx)
1064  if sk == Z3_SEQ_SORT:
1065  return SeqRef(a, ctx)
1066  if sk == Z3_RE_SORT:
1067  return ReRef(a, ctx)
1068  return ExprRef(a, ctx)
1069 
1070 def _coerce_expr_merge(s, a):
1071  if is_expr(a):
1072  s1 = a.sort()
1073  if s is None:
1074  return s1
1075  if s1.eq(s):
1076  return s
1077  elif s.subsort(s1):
1078  return s1
1079  elif s1.subsort(s):
1080  return s
1081  else:
1082  if z3_debug():
1083  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1084  _z3_assert(False, "sort mismatch")
1085  else:
1086  return s
1087 
1088 def _coerce_exprs(a, b, ctx=None):
1089  if not is_expr(a) and not is_expr(b):
1090  a = _py2expr(a, ctx)
1091  b = _py2expr(b, ctx)
1092  s = None
1093  s = _coerce_expr_merge(s, a)
1094  s = _coerce_expr_merge(s, b)
1095  a = s.cast(a)
1096  b = s.cast(b)
1097  return (a, b)
1098 
1099 
1100 def _reduce(f, l, a):
1101  r = a
1102  for e in l:
1103  r = f(r, e)
1104  return r
1105 
1106 def _coerce_expr_list(alist, ctx=None):
1107  has_expr = False
1108  for a in alist:
1109  if is_expr(a):
1110  has_expr = True
1111  break
1112  if not has_expr:
1113  alist = [ _py2expr(a, ctx) for a in alist ]
1114  s = _reduce(_coerce_expr_merge, alist, None)
1115  return [ s.cast(a) for a in alist ]
1116 
1117 def is_expr(a):
1118  """Return `True` if `a` is a Z3 expression.
1119 
1120  >>> a = Int('a')
1121  >>> is_expr(a)
1122  True
1123  >>> is_expr(a + 1)
1124  True
1125  >>> is_expr(IntSort())
1126  False
1127  >>> is_expr(1)
1128  False
1129  >>> is_expr(IntVal(1))
1130  True
1131  >>> x = Int('x')
1132  >>> is_expr(ForAll(x, x >= 0))
1133  True
1134  >>> is_expr(FPVal(1.0))
1135  True
1136  """
1137  return isinstance(a, ExprRef)
1138 
1139 def is_app(a):
1140  """Return `True` if `a` is a Z3 function application.
1141 
1142  Note that, constants are function applications with 0 arguments.
1143 
1144  >>> a = Int('a')
1145  >>> is_app(a)
1146  True
1147  >>> is_app(a + 1)
1148  True
1149  >>> is_app(IntSort())
1150  False
1151  >>> is_app(1)
1152  False
1153  >>> is_app(IntVal(1))
1154  True
1155  >>> x = Int('x')
1156  >>> is_app(ForAll(x, x >= 0))
1157  False
1158  """
1159  if not isinstance(a, ExprRef):
1160  return False
1161  k = _ast_kind(a.ctx, a)
1162  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1163 
1164 def is_const(a):
1165  """Return `True` if `a` is Z3 constant/variable expression.
1166 
1167  >>> a = Int('a')
1168  >>> is_const(a)
1169  True
1170  >>> is_const(a + 1)
1171  False
1172  >>> is_const(1)
1173  False
1174  >>> is_const(IntVal(1))
1175  True
1176  >>> x = Int('x')
1177  >>> is_const(ForAll(x, x >= 0))
1178  False
1179  """
1180  return is_app(a) and a.num_args() == 0
1181 
1182 def is_var(a):
1183  """Return `True` if `a` is variable.
1184 
1185  Z3 uses de-Bruijn indices for representing bound variables in
1186  quantifiers.
1187 
1188  >>> x = Int('x')
1189  >>> is_var(x)
1190  False
1191  >>> is_const(x)
1192  True
1193  >>> f = Function('f', IntSort(), IntSort())
1194  >>> # Z3 replaces x with bound variables when ForAll is executed.
1195  >>> q = ForAll(x, f(x) == x)
1196  >>> b = q.body()
1197  >>> b
1198  f(Var(0)) == Var(0)
1199  >>> b.arg(1)
1200  Var(0)
1201  >>> is_var(b.arg(1))
1202  True
1203  """
1204  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1205 
1207  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1208 
1209  >>> x = Int('x')
1210  >>> y = Int('y')
1211  >>> is_var(x)
1212  False
1213  >>> is_const(x)
1214  True
1215  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1216  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1217  >>> q = ForAll([x, y], f(x, y) == x + y)
1218  >>> q.body()
1219  f(Var(1), Var(0)) == Var(1) + Var(0)
1220  >>> b = q.body()
1221  >>> b.arg(0)
1222  f(Var(1), Var(0))
1223  >>> v1 = b.arg(0).arg(0)
1224  >>> v2 = b.arg(0).arg(1)
1225  >>> v1
1226  Var(1)
1227  >>> v2
1228  Var(0)
1229  >>> get_var_index(v1)
1230  1
1231  >>> get_var_index(v2)
1232  0
1233  """
1234  if z3_debug():
1235  _z3_assert(is_var(a), "Z3 bound variable expected")
1236  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1237 
1238 def is_app_of(a, k):
1239  """Return `True` if `a` is an application of the given kind `k`.
1240 
1241  >>> x = Int('x')
1242  >>> n = x + 1
1243  >>> is_app_of(n, Z3_OP_ADD)
1244  True
1245  >>> is_app_of(n, Z3_OP_MUL)
1246  False
1247  """
1248  return is_app(a) and a.decl().kind() == k
1249 
1250 def If(a, b, c, ctx=None):
1251  """Create a Z3 if-then-else expression.
1252 
1253  >>> x = Int('x')
1254  >>> y = Int('y')
1255  >>> max = If(x > y, x, y)
1256  >>> max
1257  If(x > y, x, y)
1258  >>> simplify(max)
1259  If(x <= y, y, x)
1260  """
1261  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1262  return Cond(a, b, c, ctx)
1263  else:
1264  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1265  s = BoolSort(ctx)
1266  a = s.cast(a)
1267  b, c = _coerce_exprs(b, c, ctx)
1268  if z3_debug():
1269  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1270  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1271 
1272 def Distinct(*args):
1273  """Create a Z3 distinct expression.
1274 
1275  >>> x = Int('x')
1276  >>> y = Int('y')
1277  >>> Distinct(x, y)
1278  x != y
1279  >>> z = Int('z')
1280  >>> Distinct(x, y, z)
1281  Distinct(x, y, z)
1282  >>> simplify(Distinct(x, y, z))
1283  Distinct(x, y, z)
1284  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1285  And(Not(x == y), Not(x == z), Not(y == z))
1286  """
1287  args = _get_args(args)
1288  ctx = _ctx_from_ast_arg_list(args)
1289  if z3_debug():
1290  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1291  args = _coerce_expr_list(args, ctx)
1292  _args, sz = _to_ast_array(args)
1293  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1294 
1295 def _mk_bin(f, a, b):
1296  args = (Ast * 2)()
1297  if z3_debug():
1298  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1299  args[0] = a.as_ast()
1300  args[1] = b.as_ast()
1301  return f(a.ctx.ref(), 2, args)
1302 
1303 def Const(name, sort):
1304  """Create a constant of the given sort.
1305 
1306  >>> Const('x', IntSort())
1307  x
1308  """
1309  if z3_debug():
1310  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1311  ctx = sort.ctx
1312  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1313 
1314 def Consts(names, sort):
1315  """Create several constants of the given sort.
1316 
1317  `names` is a string containing the names of all constants to be created.
1318  Blank spaces separate the names of different constants.
1319 
1320  >>> x, y, z = Consts('x y z', IntSort())
1321  >>> x + y + z
1322  x + y + z
1323  """
1324  if isinstance(names, str):
1325  names = names.split(" ")
1326  return [Const(name, sort) for name in names]
1327 
1328 def FreshConst(sort, prefix='c'):
1329  """Create a fresh constant of a specified sort"""
1330  ctx = _get_ctx(sort.ctx)
1331  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1332 
1333 def Var(idx, s):
1334  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1335 
1336  >>> Var(0, IntSort())
1337  Var(0)
1338  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1339  False
1340  """
1341  if z3_debug():
1342  _z3_assert(is_sort(s), "Z3 sort expected")
1343  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1344 
1345 def RealVar(idx, ctx=None):
1346  """
1347  Create a real free variable. Free variables are used to create quantified formulas.
1348  They are also used to create polynomials.
1349 
1350  >>> RealVar(0)
1351  Var(0)
1352  """
1353  return Var(idx, RealSort(ctx))
1354 
1355 def RealVarVector(n, ctx=None):
1356  """
1357  Create a list of Real free variables.
1358  The variables have ids: 0, 1, ..., n-1
1359 
1360  >>> x0, x1, x2, x3 = RealVarVector(4)
1361  >>> x2
1362  Var(2)
1363  """
1364  return [ RealVar(i, ctx) for i in range(n) ]
1365 
1366 
1371 
1373  """Boolean sort."""
1374  def cast(self, val):
1375  """Try to cast `val` as a Boolean.
1376 
1377  >>> x = BoolSort().cast(True)
1378  >>> x
1379  True
1380  >>> is_expr(x)
1381  True
1382  >>> is_expr(True)
1383  False
1384  >>> x.sort()
1385  Bool
1386  """
1387  if isinstance(val, bool):
1388  return BoolVal(val, self.ctx)
1389  if z3_debug():
1390  if not is_expr(val):
1391  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1392  if not self.eq(val.sort()):
1393  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1394  return val
1395 
1396  def subsort(self, other):
1397  return isinstance(other, ArithSortRef)
1398 
1399  def is_int(self):
1400  return True
1401 
1402  def is_bool(self):
1403  return True
1404 
1405 
1407  """All Boolean expressions are instances of this class."""
1408  def sort(self):
1409  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1410 
1411  def __rmul__(self, other):
1412  return self * other
1413 
1414  def __mul__(self, other):
1415  """Create the Z3 expression `self * other`.
1416  """
1417  if other == 1:
1418  return self
1419  if other == 0:
1420  return 0
1421  return If(self, other, 0)
1422 
1423 
1424 def is_bool(a):
1425  """Return `True` if `a` is a Z3 Boolean expression.
1426 
1427  >>> p = Bool('p')
1428  >>> is_bool(p)
1429  True
1430  >>> q = Bool('q')
1431  >>> is_bool(And(p, q))
1432  True
1433  >>> x = Real('x')
1434  >>> is_bool(x)
1435  False
1436  >>> is_bool(x == 0)
1437  True
1438  """
1439  return isinstance(a, BoolRef)
1440 
1441 def is_true(a):
1442  """Return `True` if `a` is the Z3 true expression.
1443 
1444  >>> p = Bool('p')
1445  >>> is_true(p)
1446  False
1447  >>> is_true(simplify(p == p))
1448  True
1449  >>> x = Real('x')
1450  >>> is_true(x == 0)
1451  False
1452  >>> # True is a Python Boolean expression
1453  >>> is_true(True)
1454  False
1455  """
1456  return is_app_of(a, Z3_OP_TRUE)
1457 
1458 def is_false(a):
1459  """Return `True` if `a` is the Z3 false expression.
1460 
1461  >>> p = Bool('p')
1462  >>> is_false(p)
1463  False
1464  >>> is_false(False)
1465  False
1466  >>> is_false(BoolVal(False))
1467  True
1468  """
1469  return is_app_of(a, Z3_OP_FALSE)
1470 
1471 def is_and(a):
1472  """Return `True` if `a` is a Z3 and expression.
1473 
1474  >>> p, q = Bools('p q')
1475  >>> is_and(And(p, q))
1476  True
1477  >>> is_and(Or(p, q))
1478  False
1479  """
1480  return is_app_of(a, Z3_OP_AND)
1481 
1482 def is_or(a):
1483  """Return `True` if `a` is a Z3 or expression.
1484 
1485  >>> p, q = Bools('p q')
1486  >>> is_or(Or(p, q))
1487  True
1488  >>> is_or(And(p, q))
1489  False
1490  """
1491  return is_app_of(a, Z3_OP_OR)
1492 
1493 def is_implies(a):
1494  """Return `True` if `a` is a Z3 implication expression.
1495 
1496  >>> p, q = Bools('p q')
1497  >>> is_implies(Implies(p, q))
1498  True
1499  >>> is_implies(And(p, q))
1500  False
1501  """
1502  return is_app_of(a, Z3_OP_IMPLIES)
1503 
1504 def is_not(a):
1505  """Return `True` if `a` is a Z3 not expression.
1506 
1507  >>> p = Bool('p')
1508  >>> is_not(p)
1509  False
1510  >>> is_not(Not(p))
1511  True
1512  """
1513  return is_app_of(a, Z3_OP_NOT)
1514 
1515 def is_eq(a):
1516  """Return `True` if `a` is a Z3 equality expression.
1517 
1518  >>> x, y = Ints('x y')
1519  >>> is_eq(x == y)
1520  True
1521  """
1522  return is_app_of(a, Z3_OP_EQ)
1523 
1525  """Return `True` if `a` is a Z3 distinct expression.
1526 
1527  >>> x, y, z = Ints('x y z')
1528  >>> is_distinct(x == y)
1529  False
1530  >>> is_distinct(Distinct(x, y, z))
1531  True
1532  """
1533  return is_app_of(a, Z3_OP_DISTINCT)
1534 
1535 def BoolSort(ctx=None):
1536  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1537 
1538  >>> BoolSort()
1539  Bool
1540  >>> p = Const('p', BoolSort())
1541  >>> is_bool(p)
1542  True
1543  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1544  >>> r(0, 1)
1545  r(0, 1)
1546  >>> is_bool(r(0, 1))
1547  True
1548  """
1549  ctx = _get_ctx(ctx)
1550  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1551 
1552 def BoolVal(val, ctx=None):
1553  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1554 
1555  >>> BoolVal(True)
1556  True
1557  >>> is_true(BoolVal(True))
1558  True
1559  >>> is_true(True)
1560  False
1561  >>> is_false(BoolVal(False))
1562  True
1563  """
1564  ctx = _get_ctx(ctx)
1565  if val == False:
1566  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1567  else:
1568  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1569 
1570 def Bool(name, ctx=None):
1571  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1572 
1573  >>> p = Bool('p')
1574  >>> q = Bool('q')
1575  >>> And(p, q)
1576  And(p, q)
1577  """
1578  ctx = _get_ctx(ctx)
1579  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1580 
1581 def Bools(names, ctx=None):
1582  """Return a tuple of Boolean constants.
1583 
1584  `names` is a single string containing all names separated by blank spaces.
1585  If `ctx=None`, then the global context is used.
1586 
1587  >>> p, q, r = Bools('p q r')
1588  >>> And(p, Or(q, r))
1589  And(p, Or(q, r))
1590  """
1591  ctx = _get_ctx(ctx)
1592  if isinstance(names, str):
1593  names = names.split(" ")
1594  return [Bool(name, ctx) for name in names]
1595 
1596 def BoolVector(prefix, sz, ctx=None):
1597  """Return a list of Boolean constants of size `sz`.
1598 
1599  The constants are named using the given prefix.
1600  If `ctx=None`, then the global context is used.
1601 
1602  >>> P = BoolVector('p', 3)
1603  >>> P
1604  [p__0, p__1, p__2]
1605  >>> And(P)
1606  And(p__0, p__1, p__2)
1607  """
1608  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1609 
1610 def FreshBool(prefix='b', ctx=None):
1611  """Return a fresh Boolean constant in the given context using the given prefix.
1612 
1613  If `ctx=None`, then the global context is used.
1614 
1615  >>> b1 = FreshBool()
1616  >>> b2 = FreshBool()
1617  >>> eq(b1, b2)
1618  False
1619  """
1620  ctx = _get_ctx(ctx)
1621  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1622 
1623 def Implies(a, b, ctx=None):
1624  """Create a Z3 implies expression.
1625 
1626  >>> p, q = Bools('p q')
1627  >>> Implies(p, q)
1628  Implies(p, q)
1629  >>> simplify(Implies(p, q))
1630  Or(q, Not(p))
1631  """
1632  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1633  s = BoolSort(ctx)
1634  a = s.cast(a)
1635  b = s.cast(b)
1636  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1637 
1638 def Xor(a, b, ctx=None):
1639  """Create a Z3 Xor expression.
1640 
1641  >>> p, q = Bools('p q')
1642  >>> Xor(p, q)
1643  Xor(p, q)
1644  >>> simplify(Xor(p, q))
1645  Not(p) == q
1646  """
1647  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1648  s = BoolSort(ctx)
1649  a = s.cast(a)
1650  b = s.cast(b)
1651  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1652 
1653 def Not(a, ctx=None):
1654  """Create a Z3 not expression or probe.
1655 
1656  >>> p = Bool('p')
1657  >>> Not(Not(p))
1658  Not(Not(p))
1659  >>> simplify(Not(Not(p)))
1660  p
1661  """
1662  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1663  if is_probe(a):
1664  # Not is also used to build probes
1665  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1666  else:
1667  s = BoolSort(ctx)
1668  a = s.cast(a)
1669  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1670 
1671 def mk_not(a):
1672  if is_not(a):
1673  return a.arg(0)
1674  else:
1675  return Not(a)
1676 
1677 def _has_probe(args):
1678  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1679  for arg in args:
1680  if is_probe(arg):
1681  return True
1682  return False
1683 
1684 def And(*args):
1685  """Create a Z3 and-expression or and-probe.
1686 
1687  >>> p, q, r = Bools('p q r')
1688  >>> And(p, q, r)
1689  And(p, q, r)
1690  >>> P = BoolVector('p', 5)
1691  >>> And(P)
1692  And(p__0, p__1, p__2, p__3, p__4)
1693  """
1694  last_arg = None
1695  if len(args) > 0:
1696  last_arg = args[len(args)-1]
1697  if isinstance(last_arg, Context):
1698  ctx = args[len(args)-1]
1699  args = args[:len(args)-1]
1700  elif len(args) == 1 and isinstance(args[0], AstVector):
1701  ctx = args[0].ctx
1702  args = [a for a in args[0]]
1703  else:
1704  ctx = main_ctx()
1705  args = _get_args(args)
1706  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1707  if z3_debug():
1708  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1709  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1710  if _has_probe(args):
1711  return _probe_and(args, ctx)
1712  else:
1713  args = _coerce_expr_list(args, ctx)
1714  _args, sz = _to_ast_array(args)
1715  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1716 
1717 def Or(*args):
1718  """Create a Z3 or-expression or or-probe.
1719 
1720  >>> p, q, r = Bools('p q r')
1721  >>> Or(p, q, r)
1722  Or(p, q, r)
1723  >>> P = BoolVector('p', 5)
1724  >>> Or(P)
1725  Or(p__0, p__1, p__2, p__3, p__4)
1726  """
1727  last_arg = None
1728  if len(args) > 0:
1729  last_arg = args[len(args)-1]
1730  if isinstance(last_arg, Context):
1731  ctx = args[len(args)-1]
1732  args = args[:len(args)-1]
1733  else:
1734  ctx = main_ctx()
1735  args = _get_args(args)
1736  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1737  if z3_debug():
1738  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1739  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1740  if _has_probe(args):
1741  return _probe_or(args, ctx)
1742  else:
1743  args = _coerce_expr_list(args, ctx)
1744  _args, sz = _to_ast_array(args)
1745  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1746 
1747 
1752 
1754  """Patterns are hints for quantifier instantiation.
1755 
1756  """
1757  def as_ast(self):
1758  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1759 
1760  def get_id(self):
1761  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1762 
1763 def is_pattern(a):
1764  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1765 
1766  >>> f = Function('f', IntSort(), IntSort())
1767  >>> x = Int('x')
1768  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1769  >>> q
1770  ForAll(x, f(x) == 0)
1771  >>> q.num_patterns()
1772  1
1773  >>> is_pattern(q.pattern(0))
1774  True
1775  >>> q.pattern(0)
1776  f(Var(0))
1777  """
1778  return isinstance(a, PatternRef)
1779 
1780 def MultiPattern(*args):
1781  """Create a Z3 multi-pattern using the given expressions `*args`
1782 
1783  >>> f = Function('f', IntSort(), IntSort())
1784  >>> g = Function('g', IntSort(), IntSort())
1785  >>> x = Int('x')
1786  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1787  >>> q
1788  ForAll(x, f(x) != g(x))
1789  >>> q.num_patterns()
1790  1
1791  >>> is_pattern(q.pattern(0))
1792  True
1793  >>> q.pattern(0)
1794  MultiPattern(f(Var(0)), g(Var(0)))
1795  """
1796  if z3_debug():
1797  _z3_assert(len(args) > 0, "At least one argument expected")
1798  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1799  ctx = args[0].ctx
1800  args, sz = _to_ast_array(args)
1801  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1802 
1803 def _to_pattern(arg):
1804  if is_pattern(arg):
1805  return arg
1806  else:
1807  return MultiPattern(arg)
1808 
1809 
1814 
1816  """Universally and Existentially quantified formulas."""
1817 
1818  def as_ast(self):
1819  return self.ast
1820 
1821  def get_id(self):
1822  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1823 
1824  def sort(self):
1825  """Return the Boolean sort or sort of Lambda."""
1826  if self.is_lambda():
1827  return _sort(self.ctx, self.as_ast())
1828  return BoolSort(self.ctx)
1829 
1830  def is_forall(self):
1831  """Return `True` if `self` is a universal quantifier.
1832 
1833  >>> f = Function('f', IntSort(), IntSort())
1834  >>> x = Int('x')
1835  >>> q = ForAll(x, f(x) == 0)
1836  >>> q.is_forall()
1837  True
1838  >>> q = Exists(x, f(x) != 0)
1839  >>> q.is_forall()
1840  False
1841  """
1842  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1843 
1844  def is_exists(self):
1845  """Return `True` if `self` is an existential quantifier.
1846 
1847  >>> f = Function('f', IntSort(), IntSort())
1848  >>> x = Int('x')
1849  >>> q = ForAll(x, f(x) == 0)
1850  >>> q.is_exists()
1851  False
1852  >>> q = Exists(x, f(x) != 0)
1853  >>> q.is_exists()
1854  True
1855  """
1856  return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1857 
1858  def is_lambda(self):
1859  """Return `True` if `self` is a lambda expression.
1860 
1861  >>> f = Function('f', IntSort(), IntSort())
1862  >>> x = Int('x')
1863  >>> q = Lambda(x, f(x))
1864  >>> q.is_lambda()
1865  True
1866  >>> q = Exists(x, f(x) != 0)
1867  >>> q.is_lambda()
1868  False
1869  """
1870  return Z3_is_lambda(self.ctx_ref(), self.ast)
1871 
1872  def __getitem__(self, arg):
1873  """Return the Z3 expression `self[arg]`.
1874  """
1875  if z3_debug():
1876  _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
1877  arg = self.sort().domain().cast(arg)
1878  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
1879 
1880 
1881  def weight(self):
1882  """Return the weight annotation of `self`.
1883 
1884  >>> f = Function('f', IntSort(), IntSort())
1885  >>> x = Int('x')
1886  >>> q = ForAll(x, f(x) == 0)
1887  >>> q.weight()
1888  1
1889  >>> q = ForAll(x, f(x) == 0, weight=10)
1890  >>> q.weight()
1891  10
1892  """
1893  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1894 
1895  def num_patterns(self):
1896  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1897 
1898  >>> f = Function('f', IntSort(), IntSort())
1899  >>> g = Function('g', IntSort(), IntSort())
1900  >>> x = Int('x')
1901  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1902  >>> q.num_patterns()
1903  2
1904  """
1905  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1906 
1907  def pattern(self, idx):
1908  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1909 
1910  >>> f = Function('f', IntSort(), IntSort())
1911  >>> g = Function('g', IntSort(), IntSort())
1912  >>> x = Int('x')
1913  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1914  >>> q.num_patterns()
1915  2
1916  >>> q.pattern(0)
1917  f(Var(0))
1918  >>> q.pattern(1)
1919  g(Var(0))
1920  """
1921  if z3_debug():
1922  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1923  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1924 
1925  def num_no_patterns(self):
1926  """Return the number of no-patterns."""
1927  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1928 
1929  def no_pattern(self, idx):
1930  """Return a no-pattern."""
1931  if z3_debug():
1932  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1933  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1934 
1935  def body(self):
1936  """Return the expression being quantified.
1937 
1938  >>> f = Function('f', IntSort(), IntSort())
1939  >>> x = Int('x')
1940  >>> q = ForAll(x, f(x) == 0)
1941  >>> q.body()
1942  f(Var(0)) == 0
1943  """
1944  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1945 
1946  def num_vars(self):
1947  """Return the number of variables bounded by this quantifier.
1948 
1949  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1950  >>> x = Int('x')
1951  >>> y = Int('y')
1952  >>> q = ForAll([x, y], f(x, y) >= x)
1953  >>> q.num_vars()
1954  2
1955  """
1956  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1957 
1958  def var_name(self, idx):
1959  """Return a string representing a name used when displaying the quantifier.
1960 
1961  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1962  >>> x = Int('x')
1963  >>> y = Int('y')
1964  >>> q = ForAll([x, y], f(x, y) >= x)
1965  >>> q.var_name(0)
1966  'x'
1967  >>> q.var_name(1)
1968  'y'
1969  """
1970  if z3_debug():
1971  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1972  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1973 
1974  def var_sort(self, idx):
1975  """Return the sort of a bound variable.
1976 
1977  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1978  >>> x = Int('x')
1979  >>> y = Real('y')
1980  >>> q = ForAll([x, y], f(x, y) >= x)
1981  >>> q.var_sort(0)
1982  Int
1983  >>> q.var_sort(1)
1984  Real
1985  """
1986  if z3_debug():
1987  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1988  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1989 
1990  def children(self):
1991  """Return a list containing a single element self.body()
1992 
1993  >>> f = Function('f', IntSort(), IntSort())
1994  >>> x = Int('x')
1995  >>> q = ForAll(x, f(x) == 0)
1996  >>> q.children()
1997  [f(Var(0)) == 0]
1998  """
1999  return [ self.body() ]
2000 
2002  """Return `True` if `a` is a Z3 quantifier.
2003 
2004  >>> f = Function('f', IntSort(), IntSort())
2005  >>> x = Int('x')
2006  >>> q = ForAll(x, f(x) == 0)
2007  >>> is_quantifier(q)
2008  True
2009  >>> is_quantifier(f(x))
2010  False
2011  """
2012  return isinstance(a, QuantifierRef)
2013 
2014 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2015  if z3_debug():
2016  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2017  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
2018  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2019  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2020  if is_app(vs):
2021  ctx = vs.ctx
2022  vs = [vs]
2023  else:
2024  ctx = vs[0].ctx
2025  if not is_expr(body):
2026  body = BoolVal(body, ctx)
2027  num_vars = len(vs)
2028  if num_vars == 0:
2029  return body
2030  _vs = (Ast * num_vars)()
2031  for i in range(num_vars):
2032 
2033  _vs[i] = vs[i].as_ast()
2034  patterns = [ _to_pattern(p) for p in patterns ]
2035  num_pats = len(patterns)
2036  _pats = (Pattern * num_pats)()
2037  for i in range(num_pats):
2038  _pats[i] = patterns[i].ast
2039  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2040  qid = to_symbol(qid, ctx)
2041  skid = to_symbol(skid, ctx)
2042  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2043  num_vars, _vs,
2044  num_pats, _pats,
2045  num_no_pats, _no_pats,
2046  body.as_ast()), ctx)
2047 
2048 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2049  """Create a Z3 forall formula.
2050 
2051  The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2052 
2053  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2054  >>> x = Int('x')
2055  >>> y = Int('y')
2056  >>> ForAll([x, y], f(x, y) >= x)
2057  ForAll([x, y], f(x, y) >= x)
2058  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2059  ForAll([x, y], f(x, y) >= x)
2060  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2061  ForAll([x, y], f(x, y) >= x)
2062  """
2063  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2064 
2065 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2066  """Create a Z3 exists formula.
2067 
2068  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2069 
2070 
2071  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2072  >>> x = Int('x')
2073  >>> y = Int('y')
2074  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2075  >>> q
2076  Exists([x, y], f(x, y) >= x)
2077  >>> is_quantifier(q)
2078  True
2079  >>> r = Tactic('nnf')(q).as_expr()
2080  >>> is_quantifier(r)
2081  False
2082  """
2083  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2084 
2085 def Lambda(vs, body):
2086  """Create a Z3 lambda expression.
2087 
2088  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2089  >>> mem0 = Array('mem0', IntSort(), IntSort())
2090  >>> lo, hi, e, i = Ints('lo hi e i')
2091  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2092  >>> mem1
2093  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2094  """
2095  ctx = body.ctx
2096  if is_app(vs):
2097  vs = [vs]
2098  num_vars = len(vs)
2099  _vs = (Ast * num_vars)()
2100  for i in range(num_vars):
2101 
2102  _vs[i] = vs[i].as_ast()
2103  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2104 
2105 
2110 
2112  """Real and Integer sorts."""
2113 
2114  def is_real(self):
2115  """Return `True` if `self` is of the sort Real.
2116 
2117  >>> x = Real('x')
2118  >>> x.is_real()
2119  True
2120  >>> (x + 1).is_real()
2121  True
2122  >>> x = Int('x')
2123  >>> x.is_real()
2124  False
2125  """
2126  return self.kind() == Z3_REAL_SORT
2127 
2128  def is_int(self):
2129  """Return `True` if `self` is of the sort Integer.
2130 
2131  >>> x = Int('x')
2132  >>> x.is_int()
2133  True
2134  >>> (x + 1).is_int()
2135  True
2136  >>> x = Real('x')
2137  >>> x.is_int()
2138  False
2139  """
2140  return self.kind() == Z3_INT_SORT
2141 
2142  def subsort(self, other):
2143  """Return `True` if `self` is a subsort of `other`."""
2144  return self.is_int() and is_arith_sort(other) and other.is_real()
2145 
2146  def cast(self, val):
2147  """Try to cast `val` as an Integer or Real.
2148 
2149  >>> IntSort().cast(10)
2150  10
2151  >>> is_int(IntSort().cast(10))
2152  True
2153  >>> is_int(10)
2154  False
2155  >>> RealSort().cast(10)
2156  10
2157  >>> is_real(RealSort().cast(10))
2158  True
2159  """
2160  if is_expr(val):
2161  if z3_debug():
2162  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2163  val_s = val.sort()
2164  if self.eq(val_s):
2165  return val
2166  if val_s.is_int() and self.is_real():
2167  return ToReal(val)
2168  if val_s.is_bool() and self.is_int():
2169  return If(val, 1, 0)
2170  if val_s.is_bool() and self.is_real():
2171  return ToReal(If(val, 1, 0))
2172  if z3_debug():
2173  _z3_assert(False, "Z3 Integer/Real expression expected" )
2174  else:
2175  if self.is_int():
2176  return IntVal(val, self.ctx)
2177  if self.is_real():
2178  return RealVal(val, self.ctx)
2179  if z3_debug():
2180  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2181 
2183  """Return `True` if s is an arithmetical sort (type).
2184 
2185  >>> is_arith_sort(IntSort())
2186  True
2187  >>> is_arith_sort(RealSort())
2188  True
2189  >>> is_arith_sort(BoolSort())
2190  False
2191  >>> n = Int('x') + 1
2192  >>> is_arith_sort(n.sort())
2193  True
2194  """
2195  return isinstance(s, ArithSortRef)
2196 
2198  """Integer and Real expressions."""
2199 
2200  def sort(self):
2201  """Return the sort (type) of the arithmetical expression `self`.
2202 
2203  >>> Int('x').sort()
2204  Int
2205  >>> (Real('x') + 1).sort()
2206  Real
2207  """
2208  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2209 
2210  def is_int(self):
2211  """Return `True` if `self` is an integer expression.
2212 
2213  >>> x = Int('x')
2214  >>> x.is_int()
2215  True
2216  >>> (x + 1).is_int()
2217  True
2218  >>> y = Real('y')
2219  >>> (x + y).is_int()
2220  False
2221  """
2222  return self.sort().is_int()
2223 
2224  def is_real(self):
2225  """Return `True` if `self` is an real expression.
2226 
2227  >>> x = Real('x')
2228  >>> x.is_real()
2229  True
2230  >>> (x + 1).is_real()
2231  True
2232  """
2233  return self.sort().is_real()
2234 
2235  def __add__(self, other):
2236  """Create the Z3 expression `self + other`.
2237 
2238  >>> x = Int('x')
2239  >>> y = Int('y')
2240  >>> x + y
2241  x + y
2242  >>> (x + y).sort()
2243  Int
2244  """
2245  a, b = _coerce_exprs(self, other)
2246  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2247 
2248  def __radd__(self, other):
2249  """Create the Z3 expression `other + self`.
2250 
2251  >>> x = Int('x')
2252  >>> 10 + x
2253  10 + x
2254  """
2255  a, b = _coerce_exprs(self, other)
2256  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2257 
2258  def __mul__(self, other):
2259  """Create the Z3 expression `self * other`.
2260 
2261  >>> x = Real('x')
2262  >>> y = Real('y')
2263  >>> x * y
2264  x*y
2265  >>> (x * y).sort()
2266  Real
2267  """
2268  if isinstance(other, BoolRef):
2269  return If(other, self, 0)
2270  a, b = _coerce_exprs(self, other)
2271  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2272 
2273  def __rmul__(self, other):
2274  """Create the Z3 expression `other * self`.
2275 
2276  >>> x = Real('x')
2277  >>> 10 * x
2278  10*x
2279  """
2280  a, b = _coerce_exprs(self, other)
2281  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2282 
2283  def __sub__(self, other):
2284  """Create the Z3 expression `self - other`.
2285 
2286  >>> x = Int('x')
2287  >>> y = Int('y')
2288  >>> x - y
2289  x - y
2290  >>> (x - y).sort()
2291  Int
2292  """
2293  a, b = _coerce_exprs(self, other)
2294  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2295 
2296  def __rsub__(self, other):
2297  """Create the Z3 expression `other - self`.
2298 
2299  >>> x = Int('x')
2300  >>> 10 - x
2301  10 - x
2302  """
2303  a, b = _coerce_exprs(self, other)
2304  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2305 
2306  def __pow__(self, other):
2307  """Create the Z3 expression `self**other` (** is the power operator).
2308 
2309  >>> x = Real('x')
2310  >>> x**3
2311  x**3
2312  >>> (x**3).sort()
2313  Real
2314  >>> simplify(IntVal(2)**8)
2315  256
2316  """
2317  a, b = _coerce_exprs(self, other)
2318  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2319 
2320  def __rpow__(self, other):
2321  """Create the Z3 expression `other**self` (** is the power operator).
2322 
2323  >>> x = Real('x')
2324  >>> 2**x
2325  2**x
2326  >>> (2**x).sort()
2327  Real
2328  >>> simplify(2**IntVal(8))
2329  256
2330  """
2331  a, b = _coerce_exprs(self, other)
2332  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2333 
2334  def __div__(self, other):
2335  """Create the Z3 expression `other/self`.
2336 
2337  >>> x = Int('x')
2338  >>> y = Int('y')
2339  >>> x/y
2340  x/y
2341  >>> (x/y).sort()
2342  Int
2343  >>> (x/y).sexpr()
2344  '(div x y)'
2345  >>> x = Real('x')
2346  >>> y = Real('y')
2347  >>> x/y
2348  x/y
2349  >>> (x/y).sort()
2350  Real
2351  >>> (x/y).sexpr()
2352  '(/ x y)'
2353  """
2354  a, b = _coerce_exprs(self, other)
2355  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2356 
2357  def __truediv__(self, other):
2358  """Create the Z3 expression `other/self`."""
2359  return self.__div__(other)
2360 
2361  def __rdiv__(self, other):
2362  """Create the Z3 expression `other/self`.
2363 
2364  >>> x = Int('x')
2365  >>> 10/x
2366  10/x
2367  >>> (10/x).sexpr()
2368  '(div 10 x)'
2369  >>> x = Real('x')
2370  >>> 10/x
2371  10/x
2372  >>> (10/x).sexpr()
2373  '(/ 10.0 x)'
2374  """
2375  a, b = _coerce_exprs(self, other)
2376  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2377 
2378  def __rtruediv__(self, other):
2379  """Create the Z3 expression `other/self`."""
2380  return self.__rdiv__(other)
2381 
2382  def __mod__(self, other):
2383  """Create the Z3 expression `other%self`.
2384 
2385  >>> x = Int('x')
2386  >>> y = Int('y')
2387  >>> x % y
2388  x%y
2389  >>> simplify(IntVal(10) % IntVal(3))
2390  1
2391  """
2392  a, b = _coerce_exprs(self, other)
2393  if z3_debug():
2394  _z3_assert(a.is_int(), "Z3 integer expression expected")
2395  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2396 
2397  def __rmod__(self, other):
2398  """Create the Z3 expression `other%self`.
2399 
2400  >>> x = Int('x')
2401  >>> 10 % x
2402  10%x
2403  """
2404  a, b = _coerce_exprs(self, other)
2405  if z3_debug():
2406  _z3_assert(a.is_int(), "Z3 integer expression expected")
2407  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2408 
2409  def __neg__(self):
2410  """Return an expression representing `-self`.
2411 
2412  >>> x = Int('x')
2413  >>> -x
2414  -x
2415  >>> simplify(-(-x))
2416  x
2417  """
2418  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2419 
2420  def __pos__(self):
2421  """Return `self`.
2422 
2423  >>> x = Int('x')
2424  >>> +x
2425  x
2426  """
2427  return self
2428 
2429  def __le__(self, other):
2430  """Create the Z3 expression `other <= self`.
2431 
2432  >>> x, y = Ints('x y')
2433  >>> x <= y
2434  x <= y
2435  >>> y = Real('y')
2436  >>> x <= y
2437  ToReal(x) <= y
2438  """
2439  a, b = _coerce_exprs(self, other)
2440  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2441 
2442  def __lt__(self, other):
2443  """Create the Z3 expression `other < self`.
2444 
2445  >>> x, y = Ints('x y')
2446  >>> x < y
2447  x < y
2448  >>> y = Real('y')
2449  >>> x < y
2450  ToReal(x) < y
2451  """
2452  a, b = _coerce_exprs(self, other)
2453  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2454 
2455  def __gt__(self, other):
2456  """Create the Z3 expression `other > self`.
2457 
2458  >>> x, y = Ints('x y')
2459  >>> x > y
2460  x > y
2461  >>> y = Real('y')
2462  >>> x > y
2463  ToReal(x) > y
2464  """
2465  a, b = _coerce_exprs(self, other)
2466  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2467 
2468  def __ge__(self, other):
2469  """Create the Z3 expression `other >= self`.
2470 
2471  >>> x, y = Ints('x y')
2472  >>> x >= y
2473  x >= y
2474  >>> y = Real('y')
2475  >>> x >= y
2476  ToReal(x) >= y
2477  """
2478  a, b = _coerce_exprs(self, other)
2479  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2480 
2481 def is_arith(a):
2482  """Return `True` if `a` is an arithmetical expression.
2483 
2484  >>> x = Int('x')
2485  >>> is_arith(x)
2486  True
2487  >>> is_arith(x + 1)
2488  True
2489  >>> is_arith(1)
2490  False
2491  >>> is_arith(IntVal(1))
2492  True
2493  >>> y = Real('y')
2494  >>> is_arith(y)
2495  True
2496  >>> is_arith(y + 1)
2497  True
2498  """
2499  return isinstance(a, ArithRef)
2500 
2501 def is_int(a):
2502  """Return `True` if `a` is an integer expression.
2503 
2504  >>> x = Int('x')
2505  >>> is_int(x + 1)
2506  True
2507  >>> is_int(1)
2508  False
2509  >>> is_int(IntVal(1))
2510  True
2511  >>> y = Real('y')
2512  >>> is_int(y)
2513  False
2514  >>> is_int(y + 1)
2515  False
2516  """
2517  return is_arith(a) and a.is_int()
2518 
2519 def is_real(a):
2520  """Return `True` if `a` is a real expression.
2521 
2522  >>> x = Int('x')
2523  >>> is_real(x + 1)
2524  False
2525  >>> y = Real('y')
2526  >>> is_real(y)
2527  True
2528  >>> is_real(y + 1)
2529  True
2530  >>> is_real(1)
2531  False
2532  >>> is_real(RealVal(1))
2533  True
2534  """
2535  return is_arith(a) and a.is_real()
2536 
2537 def _is_numeral(ctx, a):
2538  return Z3_is_numeral_ast(ctx.ref(), a)
2539 
2540 def _is_algebraic(ctx, a):
2541  return Z3_is_algebraic_number(ctx.ref(), a)
2542 
2544  """Return `True` if `a` is an integer value of sort Int.
2545 
2546  >>> is_int_value(IntVal(1))
2547  True
2548  >>> is_int_value(1)
2549  False
2550  >>> is_int_value(Int('x'))
2551  False
2552  >>> n = Int('x') + 1
2553  >>> n
2554  x + 1
2555  >>> n.arg(1)
2556  1
2557  >>> is_int_value(n.arg(1))
2558  True
2559  >>> is_int_value(RealVal("1/3"))
2560  False
2561  >>> is_int_value(RealVal(1))
2562  False
2563  """
2564  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2565 
2567  """Return `True` if `a` is rational value of sort Real.
2568 
2569  >>> is_rational_value(RealVal(1))
2570  True
2571  >>> is_rational_value(RealVal("3/5"))
2572  True
2573  >>> is_rational_value(IntVal(1))
2574  False
2575  >>> is_rational_value(1)
2576  False
2577  >>> n = Real('x') + 1
2578  >>> n.arg(1)
2579  1
2580  >>> is_rational_value(n.arg(1))
2581  True
2582  >>> is_rational_value(Real('x'))
2583  False
2584  """
2585  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2586 
2588  """Return `True` if `a` is an algebraic value of sort Real.
2589 
2590  >>> is_algebraic_value(RealVal("3/5"))
2591  False
2592  >>> n = simplify(Sqrt(2))
2593  >>> n
2594  1.4142135623?
2595  >>> is_algebraic_value(n)
2596  True
2597  """
2598  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2599 
2600 def is_add(a):
2601  """Return `True` if `a` is an expression of the form b + c.
2602 
2603  >>> x, y = Ints('x y')
2604  >>> is_add(x + y)
2605  True
2606  >>> is_add(x - y)
2607  False
2608  """
2609  return is_app_of(a, Z3_OP_ADD)
2610 
2611 def is_mul(a):
2612  """Return `True` if `a` is an expression of the form b * c.
2613 
2614  >>> x, y = Ints('x y')
2615  >>> is_mul(x * y)
2616  True
2617  >>> is_mul(x - y)
2618  False
2619  """
2620  return is_app_of(a, Z3_OP_MUL)
2621 
2622 def is_sub(a):
2623  """Return `True` if `a` is an expression of the form b - c.
2624 
2625  >>> x, y = Ints('x y')
2626  >>> is_sub(x - y)
2627  True
2628  >>> is_sub(x + y)
2629  False
2630  """
2631  return is_app_of(a, Z3_OP_SUB)
2632 
2633 def is_div(a):
2634  """Return `True` if `a` is an expression of the form b / c.
2635 
2636  >>> x, y = Reals('x y')
2637  >>> is_div(x / y)
2638  True
2639  >>> is_div(x + y)
2640  False
2641  >>> x, y = Ints('x y')
2642  >>> is_div(x / y)
2643  False
2644  >>> is_idiv(x / y)
2645  True
2646  """
2647  return is_app_of(a, Z3_OP_DIV)
2648 
2649 def is_idiv(a):
2650  """Return `True` if `a` is an expression of the form b div c.
2651 
2652  >>> x, y = Ints('x y')
2653  >>> is_idiv(x / y)
2654  True
2655  >>> is_idiv(x + y)
2656  False
2657  """
2658  return is_app_of(a, Z3_OP_IDIV)
2659 
2660 def is_mod(a):
2661  """Return `True` if `a` is an expression of the form b % c.
2662 
2663  >>> x, y = Ints('x y')
2664  >>> is_mod(x % y)
2665  True
2666  >>> is_mod(x + y)
2667  False
2668  """
2669  return is_app_of(a, Z3_OP_MOD)
2670 
2671 def is_le(a):
2672  """Return `True` if `a` is an expression of the form b <= c.
2673 
2674  >>> x, y = Ints('x y')
2675  >>> is_le(x <= y)
2676  True
2677  >>> is_le(x < y)
2678  False
2679  """
2680  return is_app_of(a, Z3_OP_LE)
2681 
2682 def is_lt(a):
2683  """Return `True` if `a` is an expression of the form b < c.
2684 
2685  >>> x, y = Ints('x y')
2686  >>> is_lt(x < y)
2687  True
2688  >>> is_lt(x == y)
2689  False
2690  """
2691  return is_app_of(a, Z3_OP_LT)
2692 
2693 def is_ge(a):
2694  """Return `True` if `a` is an expression of the form b >= c.
2695 
2696  >>> x, y = Ints('x y')
2697  >>> is_ge(x >= y)
2698  True
2699  >>> is_ge(x == y)
2700  False
2701  """
2702  return is_app_of(a, Z3_OP_GE)
2703 
2704 def is_gt(a):
2705  """Return `True` if `a` is an expression of the form b > c.
2706 
2707  >>> x, y = Ints('x y')
2708  >>> is_gt(x > y)
2709  True
2710  >>> is_gt(x == y)
2711  False
2712  """
2713  return is_app_of(a, Z3_OP_GT)
2714 
2715 def is_is_int(a):
2716  """Return `True` if `a` is an expression of the form IsInt(b).
2717 
2718  >>> x = Real('x')
2719  >>> is_is_int(IsInt(x))
2720  True
2721  >>> is_is_int(x)
2722  False
2723  """
2724  return is_app_of(a, Z3_OP_IS_INT)
2725 
2726 def is_to_real(a):
2727  """Return `True` if `a` is an expression of the form ToReal(b).
2728 
2729  >>> x = Int('x')
2730  >>> n = ToReal(x)
2731  >>> n
2732  ToReal(x)
2733  >>> is_to_real(n)
2734  True
2735  >>> is_to_real(x)
2736  False
2737  """
2738  return is_app_of(a, Z3_OP_TO_REAL)
2739 
2740 def is_to_int(a):
2741  """Return `True` if `a` is an expression of the form ToInt(b).
2742 
2743  >>> x = Real('x')
2744  >>> n = ToInt(x)
2745  >>> n
2746  ToInt(x)
2747  >>> is_to_int(n)
2748  True
2749  >>> is_to_int(x)
2750  False
2751  """
2752  return is_app_of(a, Z3_OP_TO_INT)
2753 
2755  """Integer values."""
2756 
2757  def as_long(self):
2758  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2759 
2760  >>> v = IntVal(1)
2761  >>> v + 1
2762  1 + 1
2763  >>> v.as_long() + 1
2764  2
2765  """
2766  if z3_debug():
2767  _z3_assert(self.is_int(), "Integer value expected")
2768  return int(self.as_string())
2769 
2770  def as_string(self):
2771  """Return a Z3 integer numeral as a Python string.
2772  >>> v = IntVal(100)
2773  >>> v.as_string()
2774  '100'
2775  """
2776  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2777 
2779  """Rational values."""
2780 
2781  def numerator(self):
2782  """ Return the numerator of a Z3 rational numeral.
2783 
2784  >>> is_rational_value(RealVal("3/5"))
2785  True
2786  >>> n = RealVal("3/5")
2787  >>> n.numerator()
2788  3
2789  >>> is_rational_value(Q(3,5))
2790  True
2791  >>> Q(3,5).numerator()
2792  3
2793  """
2794  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2795 
2796  def denominator(self):
2797  """ Return the denominator of a Z3 rational numeral.
2798 
2799  >>> is_rational_value(Q(3,5))
2800  True
2801  >>> n = Q(3,5)
2802  >>> n.denominator()
2803  5
2804  """
2805  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2806 
2808  """ Return the numerator as a Python long.
2809 
2810  >>> v = RealVal(10000000000)
2811  >>> v
2812  10000000000
2813  >>> v + 1
2814  10000000000 + 1
2815  >>> v.numerator_as_long() + 1 == 10000000001
2816  True
2817  """
2818  return self.numerator().as_long()
2819 
2821  """ Return the denominator as a Python long.
2822 
2823  >>> v = RealVal("1/3")
2824  >>> v
2825  1/3
2826  >>> v.denominator_as_long()
2827  3
2828  """
2829  return self.denominator().as_long()
2830 
2831  def is_int(self):
2832  return False
2833 
2834  def is_real(self):
2835  return True
2836 
2837  def is_int_value(self):
2838  return self.denominator().is_int() and self.denominator_as_long() == 1
2839 
2840  def as_long(self):
2841  _z3_assert(self.is_int_value(), "Expected integer fraction")
2842  return self.numerator_as_long()
2843 
2844  def as_decimal(self, prec):
2845  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2846 
2847  >>> v = RealVal("1/5")
2848  >>> v.as_decimal(3)
2849  '0.2'
2850  >>> v = RealVal("1/3")
2851  >>> v.as_decimal(3)
2852  '0.333?'
2853  """
2854  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2855 
2856  def as_string(self):
2857  """Return a Z3 rational numeral as a Python string.
2858 
2859  >>> v = Q(3,6)
2860  >>> v.as_string()
2861  '1/2'
2862  """
2863  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2864 
2865  def as_fraction(self):
2866  """Return a Z3 rational as a Python Fraction object.
2867 
2868  >>> v = RealVal("1/5")
2869  >>> v.as_fraction()
2870  Fraction(1, 5)
2871  """
2872  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2873 
2875  """Algebraic irrational values."""
2876 
2877  def approx(self, precision=10):
2878  """Return a Z3 rational number that approximates the algebraic number `self`.
2879  The result `r` is such that |r - self| <= 1/10^precision
2880 
2881  >>> x = simplify(Sqrt(2))
2882  >>> x.approx(20)
2883  6838717160008073720548335/4835703278458516698824704
2884  >>> x.approx(5)
2885  2965821/2097152
2886  """
2887  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2888  def as_decimal(self, prec):
2889  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2890 
2891  >>> x = simplify(Sqrt(2))
2892  >>> x.as_decimal(10)
2893  '1.4142135623?'
2894  >>> x.as_decimal(20)
2895  '1.41421356237309504880?'
2896  """
2897  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2898 
2899 def _py2expr(a, ctx=None):
2900  if isinstance(a, bool):
2901  return BoolVal(a, ctx)
2902  if _is_int(a):
2903  return IntVal(a, ctx)
2904  if isinstance(a, float):
2905  return RealVal(a, ctx)
2906  if is_expr(a):
2907  return a
2908  if z3_debug():
2909  _z3_assert(False, "Python bool, int, long or float expected")
2910 
2911 def IntSort(ctx=None):
2912  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2913 
2914  >>> IntSort()
2915  Int
2916  >>> x = Const('x', IntSort())
2917  >>> is_int(x)
2918  True
2919  >>> x.sort() == IntSort()
2920  True
2921  >>> x.sort() == BoolSort()
2922  False
2923  """
2924  ctx = _get_ctx(ctx)
2925  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2926 
2927 def RealSort(ctx=None):
2928  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2929 
2930  >>> RealSort()
2931  Real
2932  >>> x = Const('x', RealSort())
2933  >>> is_real(x)
2934  True
2935  >>> is_int(x)
2936  False
2937  >>> x.sort() == RealSort()
2938  True
2939  """
2940  ctx = _get_ctx(ctx)
2941  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2942 
2943 def _to_int_str(val):
2944  if isinstance(val, float):
2945  return str(int(val))
2946  elif isinstance(val, bool):
2947  if val:
2948  return "1"
2949  else:
2950  return "0"
2951  elif _is_int(val):
2952  return str(val)
2953  elif isinstance(val, str):
2954  return val
2955  if z3_debug():
2956  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2957 
2958 def IntVal(val, ctx=None):
2959  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2960 
2961  >>> IntVal(1)
2962  1
2963  >>> IntVal("100")
2964  100
2965  """
2966  ctx = _get_ctx(ctx)
2967  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2968 
2969 def RealVal(val, ctx=None):
2970  """Return a Z3 real value.
2971 
2972  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2973  If `ctx=None`, then the global context is used.
2974 
2975  >>> RealVal(1)
2976  1
2977  >>> RealVal(1).sort()
2978  Real
2979  >>> RealVal("3/5")
2980  3/5
2981  >>> RealVal("1.5")
2982  3/2
2983  """
2984  ctx = _get_ctx(ctx)
2985  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2986 
2987 def RatVal(a, b, ctx=None):
2988  """Return a Z3 rational a/b.
2989 
2990  If `ctx=None`, then the global context is used.
2991 
2992  >>> RatVal(3,5)
2993  3/5
2994  >>> RatVal(3,5).sort()
2995  Real
2996  """
2997  if z3_debug():
2998  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2999  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3000  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
3001 
3002 def Q(a, b, ctx=None):
3003  """Return a Z3 rational a/b.
3004 
3005  If `ctx=None`, then the global context is used.
3006 
3007  >>> Q(3,5)
3008  3/5
3009  >>> Q(3,5).sort()
3010  Real
3011  """
3012  return simplify(RatVal(a, b))
3013 
3014 def Int(name, ctx=None):
3015  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3016 
3017  >>> x = Int('x')
3018  >>> is_int(x)
3019  True
3020  >>> is_int(x + 1)
3021  True
3022  """
3023  ctx = _get_ctx(ctx)
3024  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3025 
3026 def Ints(names, ctx=None):
3027  """Return a tuple of Integer constants.
3028 
3029  >>> x, y, z = Ints('x y z')
3030  >>> Sum(x, y, z)
3031  x + y + z
3032  """
3033  ctx = _get_ctx(ctx)
3034  if isinstance(names, str):
3035  names = names.split(" ")
3036  return [Int(name, ctx) for name in names]
3037 
3038 def IntVector(prefix, sz, ctx=None):
3039  """Return a list of integer constants of size `sz`.
3040 
3041  >>> X = IntVector('x', 3)
3042  >>> X
3043  [x__0, x__1, x__2]
3044  >>> Sum(X)
3045  x__0 + x__1 + x__2
3046  """
3047  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
3048 
3049 def FreshInt(prefix='x', ctx=None):
3050  """Return a fresh integer constant in the given context using the given prefix.
3051 
3052  >>> x = FreshInt()
3053  >>> y = FreshInt()
3054  >>> eq(x, y)
3055  False
3056  >>> x.sort()
3057  Int
3058  """
3059  ctx = _get_ctx(ctx)
3060  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3061 
3062 def Real(name, ctx=None):
3063  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3064 
3065  >>> x = Real('x')
3066  >>> is_real(x)
3067  True
3068  >>> is_real(x + 1)
3069  True
3070  """
3071  ctx = _get_ctx(ctx)
3072  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3073 
3074 def Reals(names, ctx=None):
3075  """Return a tuple of real constants.
3076 
3077  >>> x, y, z = Reals('x y z')
3078  >>> Sum(x, y, z)
3079  x + y + z
3080  >>> Sum(x, y, z).sort()
3081  Real
3082  """
3083  ctx = _get_ctx(ctx)
3084  if isinstance(names, str):
3085  names = names.split(" ")
3086  return [Real(name, ctx) for name in names]
3087 
3088 def RealVector(prefix, sz, ctx=None):
3089  """Return a list of real constants of size `sz`.
3090 
3091  >>> X = RealVector('x', 3)
3092  >>> X
3093  [x__0, x__1, x__2]
3094  >>> Sum(X)
3095  x__0 + x__1 + x__2
3096  >>> Sum(X).sort()
3097  Real
3098  """
3099  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
3100 
3101 def FreshReal(prefix='b', ctx=None):
3102  """Return a fresh real constant in the given context using the given prefix.
3103 
3104  >>> x = FreshReal()
3105  >>> y = FreshReal()
3106  >>> eq(x, y)
3107  False
3108  >>> x.sort()
3109  Real
3110  """
3111  ctx = _get_ctx(ctx)
3112  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3113 
3114 def ToReal(a):
3115  """ Return the Z3 expression ToReal(a).
3116 
3117  >>> x = Int('x')
3118  >>> x.sort()
3119  Int
3120  >>> n = ToReal(x)
3121  >>> n
3122  ToReal(x)
3123  >>> n.sort()
3124  Real
3125  """
3126  if z3_debug():
3127  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3128  ctx = a.ctx
3129  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3130 
3131 def ToInt(a):
3132  """ Return the Z3 expression ToInt(a).
3133 
3134  >>> x = Real('x')
3135  >>> x.sort()
3136  Real
3137  >>> n = ToInt(x)
3138  >>> n
3139  ToInt(x)
3140  >>> n.sort()
3141  Int
3142  """
3143  if z3_debug():
3144  _z3_assert(a.is_real(), "Z3 real expression expected.")
3145  ctx = a.ctx
3146  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3147 
3148 def IsInt(a):
3149  """ Return the Z3 predicate IsInt(a).
3150 
3151  >>> x = Real('x')
3152  >>> IsInt(x + "1/2")
3153  IsInt(x + 1/2)
3154  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3155  [x = 1/2]
3156  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3157  no solution
3158  """
3159  if z3_debug():
3160  _z3_assert(a.is_real(), "Z3 real expression expected.")
3161  ctx = a.ctx
3162  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3163 
3164 def Sqrt(a, ctx=None):
3165  """ Return a Z3 expression which represents the square root of a.
3166 
3167  >>> x = Real('x')
3168  >>> Sqrt(x)
3169  x**(1/2)
3170  """
3171  if not is_expr(a):
3172  ctx = _get_ctx(ctx)
3173  a = RealVal(a, ctx)
3174  return a ** "1/2"
3175 
3176 def Cbrt(a, ctx=None):
3177  """ Return a Z3 expression which represents the cubic root of a.
3178 
3179  >>> x = Real('x')
3180  >>> Cbrt(x)
3181  x**(1/3)
3182  """
3183  if not is_expr(a):
3184  ctx = _get_ctx(ctx)
3185  a = RealVal(a, ctx)
3186  return a ** "1/3"
3187 
3188 
3193 
3195  """Bit-vector sort."""
3196 
3197  def size(self):
3198  """Return the size (number of bits) of the bit-vector sort `self`.
3199 
3200  >>> b = BitVecSort(32)
3201  >>> b.size()
3202  32
3203  """
3204  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3205 
3206  def subsort(self, other):
3207  return is_bv_sort(other) and self.size() < other.size()
3208 
3209  def cast(self, val):
3210  """Try to cast `val` as a Bit-Vector.
3211 
3212  >>> b = BitVecSort(32)
3213  >>> b.cast(10)
3214  10
3215  >>> b.cast(10).sexpr()
3216  '#x0000000a'
3217  """
3218  if is_expr(val):
3219  if z3_debug():
3220  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3221  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3222  return val
3223  else:
3224  return BitVecVal(val, self)
3225 
3226 def is_bv_sort(s):
3227  """Return True if `s` is a Z3 bit-vector sort.
3228 
3229  >>> is_bv_sort(BitVecSort(32))
3230  True
3231  >>> is_bv_sort(IntSort())
3232  False
3233  """
3234  return isinstance(s, BitVecSortRef)
3235 
3237  """Bit-vector expressions."""
3238 
3239  def sort(self):
3240  """Return the sort of the bit-vector expression `self`.
3241 
3242  >>> x = BitVec('x', 32)
3243  >>> x.sort()
3244  BitVec(32)
3245  >>> x.sort() == BitVecSort(32)
3246  True
3247  """
3248  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3249 
3250  def size(self):
3251  """Return the number of bits of the bit-vector expression `self`.
3252 
3253  >>> x = BitVec('x', 32)
3254  >>> (x + 1).size()
3255  32
3256  >>> Concat(x, x).size()
3257  64
3258  """
3259  return self.sort().size()
3260 
3261  def __add__(self, other):
3262  """Create the Z3 expression `self + other`.
3263 
3264  >>> x = BitVec('x', 32)
3265  >>> y = BitVec('y', 32)
3266  >>> x + y
3267  x + y
3268  >>> (x + y).sort()
3269  BitVec(32)
3270  """
3271  a, b = _coerce_exprs(self, other)
3272  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3273 
3274  def __radd__(self, other):
3275  """Create the Z3 expression `other + self`.
3276 
3277  >>> x = BitVec('x', 32)
3278  >>> 10 + x
3279  10 + x
3280  """
3281  a, b = _coerce_exprs(self, other)
3282  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3283 
3284  def __mul__(self, other):
3285  """Create the Z3 expression `self * other`.
3286 
3287  >>> x = BitVec('x', 32)
3288  >>> y = BitVec('y', 32)
3289  >>> x * y
3290  x*y
3291  >>> (x * y).sort()
3292  BitVec(32)
3293  """
3294  a, b = _coerce_exprs(self, other)
3295  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3296 
3297  def __rmul__(self, other):
3298  """Create the Z3 expression `other * self`.
3299 
3300  >>> x = BitVec('x', 32)
3301  >>> 10 * x
3302  10*x
3303  """
3304  a, b = _coerce_exprs(self, other)
3305  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3306 
3307  def __sub__(self, other):
3308  """Create the Z3 expression `self - other`.
3309 
3310  >>> x = BitVec('x', 32)
3311  >>> y = BitVec('y', 32)
3312  >>> x - y
3313  x - y
3314  >>> (x - y).sort()
3315  BitVec(32)
3316  """
3317  a, b = _coerce_exprs(self, other)
3318  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3319 
3320  def __rsub__(self, other):
3321  """Create the Z3 expression `other - self`.
3322 
3323  >>> x = BitVec('x', 32)
3324  >>> 10 - x
3325  10 - x
3326  """
3327  a, b = _coerce_exprs(self, other)
3328  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3329 
3330  def __or__(self, other):
3331  """Create the Z3 expression bitwise-or `self | other`.
3332 
3333  >>> x = BitVec('x', 32)
3334  >>> y = BitVec('y', 32)
3335  >>> x | y
3336  x | y
3337  >>> (x | y).sort()
3338  BitVec(32)
3339  """
3340  a, b = _coerce_exprs(self, other)
3341  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3342 
3343  def __ror__(self, other):
3344  """Create the Z3 expression bitwise-or `other | self`.
3345 
3346  >>> x = BitVec('x', 32)
3347  >>> 10 | x
3348  10 | x
3349  """
3350  a, b = _coerce_exprs(self, other)
3351  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3352 
3353  def __and__(self, other):
3354  """Create the Z3 expression bitwise-and `self & other`.
3355 
3356  >>> x = BitVec('x', 32)
3357  >>> y = BitVec('y', 32)
3358  >>> x & y
3359  x & y
3360  >>> (x & y).sort()
3361  BitVec(32)
3362  """
3363  a, b = _coerce_exprs(self, other)
3364  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3365 
3366  def __rand__(self, other):
3367  """Create the Z3 expression bitwise-or `other & self`.
3368 
3369  >>> x = BitVec('x', 32)
3370  >>> 10 & x
3371  10 & x
3372  """
3373  a, b = _coerce_exprs(self, other)
3374  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3375 
3376  def __xor__(self, other):
3377  """Create the Z3 expression bitwise-xor `self ^ other`.
3378 
3379  >>> x = BitVec('x', 32)
3380  >>> y = BitVec('y', 32)
3381  >>> x ^ y
3382  x ^ y
3383  >>> (x ^ y).sort()
3384  BitVec(32)
3385  """
3386  a, b = _coerce_exprs(self, other)
3387  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3388 
3389  def __rxor__(self, other):
3390  """Create the Z3 expression bitwise-xor `other ^ self`.
3391 
3392  >>> x = BitVec('x', 32)
3393  >>> 10 ^ x
3394  10 ^ x
3395  """
3396  a, b = _coerce_exprs(self, other)
3397  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3398 
3399  def __pos__(self):
3400  """Return `self`.
3401 
3402  >>> x = BitVec('x', 32)
3403  >>> +x
3404  x
3405  """
3406  return self
3407 
3408  def __neg__(self):
3409  """Return an expression representing `-self`.
3410 
3411  >>> x = BitVec('x', 32)
3412  >>> -x
3413  -x
3414  >>> simplify(-(-x))
3415  x
3416  """
3417  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3418 
3419  def __invert__(self):
3420  """Create the Z3 expression bitwise-not `~self`.
3421 
3422  >>> x = BitVec('x', 32)
3423  >>> ~x
3424  ~x
3425  >>> simplify(~(~x))
3426  x
3427  """
3428  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3429 
3430  def __div__(self, other):
3431  """Create the Z3 expression (signed) division `self / other`.
3432 
3433  Use the function UDiv() for unsigned division.
3434 
3435  >>> x = BitVec('x', 32)
3436  >>> y = BitVec('y', 32)
3437  >>> x / y
3438  x/y
3439  >>> (x / y).sort()
3440  BitVec(32)
3441  >>> (x / y).sexpr()
3442  '(bvsdiv x y)'
3443  >>> UDiv(x, y).sexpr()
3444  '(bvudiv x y)'
3445  """
3446  a, b = _coerce_exprs(self, other)
3447  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3448 
3449  def __truediv__(self, other):
3450  """Create the Z3 expression (signed) division `self / other`."""
3451  return self.__div__(other)
3452 
3453  def __rdiv__(self, other):
3454  """Create the Z3 expression (signed) division `other / self`.
3455 
3456  Use the function UDiv() for unsigned division.
3457 
3458  >>> x = BitVec('x', 32)
3459  >>> 10 / x
3460  10/x
3461  >>> (10 / x).sexpr()
3462  '(bvsdiv #x0000000a x)'
3463  >>> UDiv(10, x).sexpr()
3464  '(bvudiv #x0000000a x)'
3465  """
3466  a, b = _coerce_exprs(self, other)
3467  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3468 
3469  def __rtruediv__(self, other):
3470  """Create the Z3 expression (signed) division `other / self`."""
3471  return self.__rdiv__(other)
3472 
3473  def __mod__(self, other):
3474  """Create the Z3 expression (signed) mod `self % other`.
3475 
3476  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3477 
3478  >>> x = BitVec('x', 32)
3479  >>> y = BitVec('y', 32)
3480  >>> x % y
3481  x%y
3482  >>> (x % y).sort()
3483  BitVec(32)
3484  >>> (x % y).sexpr()
3485  '(bvsmod x y)'
3486  >>> URem(x, y).sexpr()
3487  '(bvurem x y)'
3488  >>> SRem(x, y).sexpr()
3489  '(bvsrem x y)'
3490  """
3491  a, b = _coerce_exprs(self, other)
3492  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3493 
3494  def __rmod__(self, other):
3495  """Create the Z3 expression (signed) mod `other % self`.
3496 
3497  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3498 
3499  >>> x = BitVec('x', 32)
3500  >>> 10 % x
3501  10%x
3502  >>> (10 % x).sexpr()
3503  '(bvsmod #x0000000a x)'
3504  >>> URem(10, x).sexpr()
3505  '(bvurem #x0000000a x)'
3506  >>> SRem(10, x).sexpr()
3507  '(bvsrem #x0000000a x)'
3508  """
3509  a, b = _coerce_exprs(self, other)
3510  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3511 
3512  def __le__(self, other):
3513  """Create the Z3 expression (signed) `other <= self`.
3514 
3515  Use the function ULE() for unsigned less than or equal to.
3516 
3517  >>> x, y = BitVecs('x y', 32)
3518  >>> x <= y
3519  x <= y
3520  >>> (x <= y).sexpr()
3521  '(bvsle x y)'
3522  >>> ULE(x, y).sexpr()
3523  '(bvule x y)'
3524  """
3525  a, b = _coerce_exprs(self, other)
3526  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3527 
3528  def __lt__(self, other):
3529  """Create the Z3 expression (signed) `other < self`.
3530 
3531  Use the function ULT() for unsigned less than.
3532 
3533  >>> x, y = BitVecs('x y', 32)
3534  >>> x < y
3535  x < y
3536  >>> (x < y).sexpr()
3537  '(bvslt x y)'
3538  >>> ULT(x, y).sexpr()
3539  '(bvult x y)'
3540  """
3541  a, b = _coerce_exprs(self, other)
3542  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3543 
3544  def __gt__(self, other):
3545  """Create the Z3 expression (signed) `other > self`.
3546 
3547  Use the function UGT() for unsigned greater than.
3548 
3549  >>> x, y = BitVecs('x y', 32)
3550  >>> x > y
3551  x > y
3552  >>> (x > y).sexpr()
3553  '(bvsgt x y)'
3554  >>> UGT(x, y).sexpr()
3555  '(bvugt x y)'
3556  """
3557  a, b = _coerce_exprs(self, other)
3558  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3559 
3560  def __ge__(self, other):
3561  """Create the Z3 expression (signed) `other >= self`.
3562 
3563  Use the function UGE() for unsigned greater than or equal to.
3564 
3565  >>> x, y = BitVecs('x y', 32)
3566  >>> x >= y
3567  x >= y
3568  >>> (x >= y).sexpr()
3569  '(bvsge x y)'
3570  >>> UGE(x, y).sexpr()
3571  '(bvuge x y)'
3572  """
3573  a, b = _coerce_exprs(self, other)
3574  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3575 
3576  def __rshift__(self, other):
3577  """Create the Z3 expression (arithmetical) right shift `self >> other`
3578 
3579  Use the function LShR() for the right logical shift
3580 
3581  >>> x, y = BitVecs('x y', 32)
3582  >>> x >> y
3583  x >> y
3584  >>> (x >> y).sexpr()
3585  '(bvashr x y)'
3586  >>> LShR(x, y).sexpr()
3587  '(bvlshr x y)'
3588  >>> BitVecVal(4, 3)
3589  4
3590  >>> BitVecVal(4, 3).as_signed_long()
3591  -4
3592  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3593  -2
3594  >>> simplify(BitVecVal(4, 3) >> 1)
3595  6
3596  >>> simplify(LShR(BitVecVal(4, 3), 1))
3597  2
3598  >>> simplify(BitVecVal(2, 3) >> 1)
3599  1
3600  >>> simplify(LShR(BitVecVal(2, 3), 1))
3601  1
3602  """
3603  a, b = _coerce_exprs(self, other)
3604  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3605 
3606  def __lshift__(self, other):
3607  """Create the Z3 expression left shift `self << other`
3608 
3609  >>> x, y = BitVecs('x y', 32)
3610  >>> x << y
3611  x << y
3612  >>> (x << y).sexpr()
3613  '(bvshl x y)'
3614  >>> simplify(BitVecVal(2, 3) << 1)
3615  4
3616  """
3617  a, b = _coerce_exprs(self, other)
3618  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3619 
3620  def __rrshift__(self, other):
3621  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3622 
3623  Use the function LShR() for the right logical shift
3624 
3625  >>> x = BitVec('x', 32)
3626  >>> 10 >> x
3627  10 >> x
3628  >>> (10 >> x).sexpr()
3629  '(bvashr #x0000000a x)'
3630  """
3631  a, b = _coerce_exprs(self, other)
3632  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3633 
3634  def __rlshift__(self, other):
3635  """Create the Z3 expression left shift `other << self`.
3636 
3637  Use the function LShR() for the right logical shift
3638 
3639  >>> x = BitVec('x', 32)
3640  >>> 10 << x
3641  10 << x
3642  >>> (10 << x).sexpr()
3643  '(bvshl #x0000000a x)'
3644  """
3645  a, b = _coerce_exprs(self, other)
3646  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3647 
3649  """Bit-vector values."""
3650 
3651  def as_long(self):
3652  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3653 
3654  >>> v = BitVecVal(0xbadc0de, 32)
3655  >>> v
3656  195936478
3657  >>> print("0x%.8x" % v.as_long())
3658  0x0badc0de
3659  """
3660  return int(self.as_string())
3661 
3662  def as_signed_long(self):
3663  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3664 
3665  >>> BitVecVal(4, 3).as_signed_long()
3666  -4
3667  >>> BitVecVal(7, 3).as_signed_long()
3668  -1
3669  >>> BitVecVal(3, 3).as_signed_long()
3670  3
3671  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3672  -1
3673  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3674  -1
3675  """
3676  sz = self.size()
3677  val = self.as_long()
3678  if val >= 2**(sz - 1):
3679  val = val - 2**sz
3680  if val < -2**(sz - 1):
3681  val = val + 2**sz
3682  return int(val)
3683 
3684  def as_string(self):
3685  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3686 
3687 def is_bv(a):
3688  """Return `True` if `a` is a Z3 bit-vector expression.
3689 
3690  >>> b = BitVec('b', 32)
3691  >>> is_bv(b)
3692  True
3693  >>> is_bv(b + 10)
3694  True
3695  >>> is_bv(Int('x'))
3696  False
3697  """
3698  return isinstance(a, BitVecRef)
3699 
3701  """Return `True` if `a` is a Z3 bit-vector numeral value.
3702 
3703  >>> b = BitVec('b', 32)
3704  >>> is_bv_value(b)
3705  False
3706  >>> b = BitVecVal(10, 32)
3707  >>> b
3708  10
3709  >>> is_bv_value(b)
3710  True
3711  """
3712  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3713 
3714 def BV2Int(a, is_signed=False):
3715  """Return the Z3 expression BV2Int(a).
3716 
3717  >>> b = BitVec('b', 3)
3718  >>> BV2Int(b).sort()
3719  Int
3720  >>> x = Int('x')
3721  >>> x > BV2Int(b)
3722  x > BV2Int(b)
3723  >>> x > BV2Int(b, is_signed=False)
3724  x > BV2Int(b)
3725  >>> x > BV2Int(b, is_signed=True)
3726  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3727  >>> solve(x > BV2Int(b), b == 1, x < 3)
3728  [x = 2, b = 1]
3729  """
3730  if z3_debug():
3731  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3732  ctx = a.ctx
3733 
3734  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3735 
3736 def Int2BV(a, num_bits):
3737  """Return the z3 expression Int2BV(a, num_bits).
3738  It is a bit-vector of width num_bits and represents the
3739  modulo of a by 2^num_bits
3740  """
3741  ctx = a.ctx
3742  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3743 
3744 def BitVecSort(sz, ctx=None):
3745  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3746 
3747  >>> Byte = BitVecSort(8)
3748  >>> Word = BitVecSort(16)
3749  >>> Byte
3750  BitVec(8)
3751  >>> x = Const('x', Byte)
3752  >>> eq(x, BitVec('x', 8))
3753  True
3754  """
3755  ctx = _get_ctx(ctx)
3756  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3757 
3758 def BitVecVal(val, bv, ctx=None):
3759  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3760 
3761  >>> v = BitVecVal(10, 32)
3762  >>> v
3763  10
3764  >>> print("0x%.8x" % v.as_long())
3765  0x0000000a
3766  """
3767  if is_bv_sort(bv):
3768  ctx = bv.ctx
3769  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3770  else:
3771  ctx = _get_ctx(ctx)
3772  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3773 
3774 def BitVec(name, bv, ctx=None):
3775  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3776  If `ctx=None`, then the global context is used.
3777 
3778  >>> x = BitVec('x', 16)
3779  >>> is_bv(x)
3780  True
3781  >>> x.size()
3782  16
3783  >>> x.sort()
3784  BitVec(16)
3785  >>> word = BitVecSort(16)
3786  >>> x2 = BitVec('x', word)
3787  >>> eq(x, x2)
3788  True
3789  """
3790  if isinstance(bv, BitVecSortRef):
3791  ctx = bv.ctx
3792  else:
3793  ctx = _get_ctx(ctx)
3794  bv = BitVecSort(bv, ctx)
3795  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3796 
3797 def BitVecs(names, bv, ctx=None):
3798  """Return a tuple of bit-vector constants of size bv.
3799 
3800  >>> x, y, z = BitVecs('x y z', 16)
3801  >>> x.size()
3802  16
3803  >>> x.sort()
3804  BitVec(16)
3805  >>> Sum(x, y, z)
3806  0 + x + y + z
3807  >>> Product(x, y, z)
3808  1*x*y*z
3809  >>> simplify(Product(x, y, z))
3810  x*y*z
3811  """
3812  ctx = _get_ctx(ctx)
3813  if isinstance(names, str):
3814  names = names.split(" ")
3815  return [BitVec(name, bv, ctx) for name in names]
3816 
3817 def Concat(*args):
3818  """Create a Z3 bit-vector concatenation expression.
3819 
3820  >>> v = BitVecVal(1, 4)
3821  >>> Concat(v, v+1, v)
3822  Concat(Concat(1, 1 + 1), 1)
3823  >>> simplify(Concat(v, v+1, v))
3824  289
3825  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3826  121
3827  """
3828  args = _get_args(args)
3829  sz = len(args)
3830  if z3_debug():
3831  _z3_assert(sz >= 2, "At least two arguments expected.")
3832 
3833  ctx = None
3834  for a in args:
3835  if is_expr(a):
3836  ctx = a.ctx
3837  break
3838  if is_seq(args[0]) or isinstance(args[0], str):
3839  args = [_coerce_seq(s, ctx) for s in args]
3840  if z3_debug():
3841  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3842  v = (Ast * sz)()
3843  for i in range(sz):
3844  v[i] = args[i].as_ast()
3845  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3846 
3847  if is_re(args[0]):
3848  if z3_debug():
3849  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3850  v = (Ast * sz)()
3851  for i in range(sz):
3852  v[i] = args[i].as_ast()
3853  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3854 
3855  if z3_debug():
3856  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3857  r = args[0]
3858  for i in range(sz - 1):
3859  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3860  return r
3861 
3862 def Extract(high, low, a):
3863  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3864 
3865  >>> x = BitVec('x', 8)
3866  >>> Extract(6, 2, x)
3867  Extract(6, 2, x)
3868  >>> Extract(6, 2, x).sort()
3869  BitVec(5)
3870  >>> simplify(Extract(StringVal("abcd"),2,1))
3871  "c"
3872  """
3873  if isinstance(high, str):
3874  high = StringVal(high)
3875  if is_seq(high):
3876  s = high
3877  offset, length = _coerce_exprs(low, a, s.ctx)
3878  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3879  if z3_debug():
3880  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3881  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3882  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3883  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3884 
3885 def _check_bv_args(a, b):
3886  if z3_debug():
3887  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3888 
3889 def ULE(a, b):
3890  """Create the Z3 expression (unsigned) `other <= self`.
3891 
3892  Use the operator <= for signed less than or equal to.
3893 
3894  >>> x, y = BitVecs('x y', 32)
3895  >>> ULE(x, y)
3896  ULE(x, y)
3897  >>> (x <= y).sexpr()
3898  '(bvsle x y)'
3899  >>> ULE(x, y).sexpr()
3900  '(bvule x y)'
3901  """
3902  _check_bv_args(a, b)
3903  a, b = _coerce_exprs(a, b)
3904  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3905 
3906 def ULT(a, b):
3907  """Create the Z3 expression (unsigned) `other < self`.
3908 
3909  Use the operator < for signed less than.
3910 
3911  >>> x, y = BitVecs('x y', 32)
3912  >>> ULT(x, y)
3913  ULT(x, y)
3914  >>> (x < y).sexpr()
3915  '(bvslt x y)'
3916  >>> ULT(x, y).sexpr()
3917  '(bvult x y)'
3918  """
3919  _check_bv_args(a, b)
3920  a, b = _coerce_exprs(a, b)
3921  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3922 
3923 def UGE(a, b):
3924  """Create the Z3 expression (unsigned) `other >= self`.
3925 
3926  Use the operator >= for signed greater than or equal to.
3927 
3928  >>> x, y = BitVecs('x y', 32)
3929  >>> UGE(x, y)
3930  UGE(x, y)
3931  >>> (x >= y).sexpr()
3932  '(bvsge x y)'
3933  >>> UGE(x, y).sexpr()
3934  '(bvuge x y)'
3935  """
3936  _check_bv_args(a, b)
3937  a, b = _coerce_exprs(a, b)
3938  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3939 
3940 def UGT(a, b):
3941  """Create the Z3 expression (unsigned) `other > self`.
3942 
3943  Use the operator > for signed greater than.
3944 
3945  >>> x, y = BitVecs('x y', 32)
3946  >>> UGT(x, y)
3947  UGT(x, y)
3948  >>> (x > y).sexpr()
3949  '(bvsgt x y)'
3950  >>> UGT(x, y).sexpr()
3951  '(bvugt x y)'
3952  """
3953  _check_bv_args(a, b)
3954  a, b = _coerce_exprs(a, b)
3955  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3956 
3957 def UDiv(a, b):
3958  """Create the Z3 expression (unsigned) division `self / other`.
3959 
3960  Use the operator / for signed division.
3961 
3962  >>> x = BitVec('x', 32)
3963  >>> y = BitVec('y', 32)
3964  >>> UDiv(x, y)
3965  UDiv(x, y)
3966  >>> UDiv(x, y).sort()
3967  BitVec(32)
3968  >>> (x / y).sexpr()
3969  '(bvsdiv x y)'
3970  >>> UDiv(x, y).sexpr()
3971  '(bvudiv x y)'
3972  """
3973  _check_bv_args(a, b)
3974  a, b = _coerce_exprs(a, b)
3975  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3976 
3977 def URem(a, b):
3978  """Create the Z3 expression (unsigned) remainder `self % other`.
3979 
3980  Use the operator % for signed modulus, and SRem() for signed remainder.
3981 
3982  >>> x = BitVec('x', 32)
3983  >>> y = BitVec('y', 32)
3984  >>> URem(x, y)
3985  URem(x, y)
3986  >>> URem(x, y).sort()
3987  BitVec(32)
3988  >>> (x % y).sexpr()
3989  '(bvsmod x y)'
3990  >>> URem(x, y).sexpr()
3991  '(bvurem x y)'
3992  """
3993  _check_bv_args(a, b)
3994  a, b = _coerce_exprs(a, b)
3995  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3996 
3997 def SRem(a, b):
3998  """Create the Z3 expression signed remainder.
3999 
4000  Use the operator % for signed modulus, and URem() for unsigned remainder.
4001 
4002  >>> x = BitVec('x', 32)
4003  >>> y = BitVec('y', 32)
4004  >>> SRem(x, y)
4005  SRem(x, y)
4006  >>> SRem(x, y).sort()
4007  BitVec(32)
4008  >>> (x % y).sexpr()
4009  '(bvsmod x y)'
4010  >>> SRem(x, y).sexpr()
4011  '(bvsrem x y)'
4012  """
4013  _check_bv_args(a, b)
4014  a, b = _coerce_exprs(a, b)
4015  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4016 
4017 def LShR(a, b):
4018  """Create the Z3 expression logical right shift.
4019 
4020  Use the operator >> for the arithmetical right shift.
4021 
4022  >>> x, y = BitVecs('x y', 32)
4023  >>> LShR(x, y)
4024  LShR(x, y)
4025  >>> (x >> y).sexpr()
4026  '(bvashr x y)'
4027  >>> LShR(x, y).sexpr()
4028  '(bvlshr x y)'
4029  >>> BitVecVal(4, 3)
4030  4
4031  >>> BitVecVal(4, 3).as_signed_long()
4032  -4
4033  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4034  -2
4035  >>> simplify(BitVecVal(4, 3) >> 1)
4036  6
4037  >>> simplify(LShR(BitVecVal(4, 3), 1))
4038  2
4039  >>> simplify(BitVecVal(2, 3) >> 1)
4040  1
4041  >>> simplify(LShR(BitVecVal(2, 3), 1))
4042  1
4043  """
4044  _check_bv_args(a, b)
4045  a, b = _coerce_exprs(a, b)
4046  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4047 
4048 def RotateLeft(a, b):
4049  """Return an expression representing `a` rotated to the left `b` times.
4050 
4051  >>> a, b = BitVecs('a b', 16)
4052  >>> RotateLeft(a, b)
4053  RotateLeft(a, b)
4054  >>> simplify(RotateLeft(a, 0))
4055  a
4056  >>> simplify(RotateLeft(a, 16))
4057  a
4058  """
4059  _check_bv_args(a, b)
4060  a, b = _coerce_exprs(a, b)
4061  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4062 
4063 def RotateRight(a, b):
4064  """Return an expression representing `a` rotated to the right `b` times.
4065 
4066  >>> a, b = BitVecs('a b', 16)
4067  >>> RotateRight(a, b)
4068  RotateRight(a, b)
4069  >>> simplify(RotateRight(a, 0))
4070  a
4071  >>> simplify(RotateRight(a, 16))
4072  a
4073  """
4074  _check_bv_args(a, b)
4075  a, b = _coerce_exprs(a, b)
4076  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4077 
4078 def SignExt(n, a):
4079  """Return a bit-vector expression with `n` extra sign-bits.
4080 
4081  >>> x = BitVec('x', 16)
4082  >>> n = SignExt(8, x)
4083  >>> n.size()
4084  24
4085  >>> n
4086  SignExt(8, x)
4087  >>> n.sort()
4088  BitVec(24)
4089  >>> v0 = BitVecVal(2, 2)
4090  >>> v0
4091  2
4092  >>> v0.size()
4093  2
4094  >>> v = simplify(SignExt(6, v0))
4095  >>> v
4096  254
4097  >>> v.size()
4098  8
4099  >>> print("%.x" % v.as_long())
4100  fe
4101  """
4102  if z3_debug():
4103  _z3_assert(_is_int(n), "First argument must be an integer")
4104  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4105  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4106 
4107 def ZeroExt(n, a):
4108  """Return a bit-vector expression with `n` extra zero-bits.
4109 
4110  >>> x = BitVec('x', 16)
4111  >>> n = ZeroExt(8, x)
4112  >>> n.size()
4113  24
4114  >>> n
4115  ZeroExt(8, x)
4116  >>> n.sort()
4117  BitVec(24)
4118  >>> v0 = BitVecVal(2, 2)
4119  >>> v0
4120  2
4121  >>> v0.size()
4122  2
4123  >>> v = simplify(ZeroExt(6, v0))
4124  >>> v
4125  2
4126  >>> v.size()
4127  8
4128  """
4129  if z3_debug():
4130  _z3_assert(_is_int(n), "First argument must be an integer")
4131  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4132  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4133 
4134 def RepeatBitVec(n, a):
4135  """Return an expression representing `n` copies of `a`.
4136 
4137  >>> x = BitVec('x', 8)
4138  >>> n = RepeatBitVec(4, x)
4139  >>> n
4140  RepeatBitVec(4, x)
4141  >>> n.size()
4142  32
4143  >>> v0 = BitVecVal(10, 4)
4144  >>> print("%.x" % v0.as_long())
4145  a
4146  >>> v = simplify(RepeatBitVec(4, v0))
4147  >>> v.size()
4148  16
4149  >>> print("%.x" % v.as_long())
4150  aaaa
4151  """
4152  if z3_debug():
4153  _z3_assert(_is_int(n), "First argument must be an integer")
4154  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4155  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4156 
4157 def BVRedAnd(a):
4158  """Return the reduction-and expression of `a`."""
4159  if z3_debug():
4160  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4161  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4162 
4163 def BVRedOr(a):
4164  """Return the reduction-or expression of `a`."""
4165  if z3_debug():
4166  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4167  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4168 
4169 def BVAddNoOverflow(a, b, signed):
4170  """A predicate the determines that bit-vector addition does not overflow"""
4171  _check_bv_args(a, b)
4172  a, b = _coerce_exprs(a, b)
4173  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4174 
4176  """A predicate the determines that signed bit-vector addition does not underflow"""
4177  _check_bv_args(a, b)
4178  a, b = _coerce_exprs(a, b)
4179  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4180 
4182  """A predicate the determines that bit-vector subtraction does not overflow"""
4183  _check_bv_args(a, b)
4184  a, b = _coerce_exprs(a, b)
4185  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4186 
4187 
4188 def BVSubNoUnderflow(a, b, signed):
4189  """A predicate the determines that bit-vector subtraction does not underflow"""
4190  _check_bv_args(a, b)
4191  a, b = _coerce_exprs(a, b)
4192  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4193 
4195  """A predicate the determines that bit-vector signed division does not overflow"""
4196  _check_bv_args(a, b)
4197  a, b = _coerce_exprs(a, b)
4198  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4199 
4201  """A predicate the determines that bit-vector unary negation does not overflow"""
4202  if z3_debug():
4203  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4204  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4205 
4206 def BVMulNoOverflow(a, b, signed):
4207  """A predicate the determines that bit-vector multiplication does not overflow"""
4208  _check_bv_args(a, b)
4209  a, b = _coerce_exprs(a, b)
4210  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4211 
4212 
4214  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4215  _check_bv_args(a, b)
4216  a, b = _coerce_exprs(a, b)
4217  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4218 
4219 
4220 
4221 
4226 
4228  """Array sorts."""
4229 
4230  def domain(self):
4231  """Return the domain of the array sort `self`.
4232 
4233  >>> A = ArraySort(IntSort(), BoolSort())
4234  >>> A.domain()
4235  Int
4236  """
4237  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4238 
4239  def range(self):
4240  """Return the range of the array sort `self`.
4241 
4242  >>> A = ArraySort(IntSort(), BoolSort())
4243  >>> A.range()
4244  Bool
4245  """
4246  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4247 
4249  """Array expressions. """
4250 
4251  def sort(self):
4252  """Return the array sort of the array expression `self`.
4253 
4254  >>> a = Array('a', IntSort(), BoolSort())
4255  >>> a.sort()
4256  Array(Int, Bool)
4257  """
4258  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4259 
4260  def domain(self):
4261  """Shorthand for `self.sort().domain()`.
4262 
4263  >>> a = Array('a', IntSort(), BoolSort())
4264  >>> a.domain()
4265  Int
4266  """
4267  return self.sort().domain()
4268 
4269  def range(self):
4270  """Shorthand for `self.sort().range()`.
4271 
4272  >>> a = Array('a', IntSort(), BoolSort())
4273  >>> a.range()
4274  Bool
4275  """
4276  return self.sort().range()
4277 
4278  def __getitem__(self, arg):
4279  """Return the Z3 expression `self[arg]`.
4280 
4281  >>> a = Array('a', IntSort(), BoolSort())
4282  >>> i = Int('i')
4283  >>> a[i]
4284  a[i]
4285  >>> a[i].sexpr()
4286  '(select a i)'
4287  """
4288  arg = self.domain().cast(arg)
4289  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4290 
4291  def default(self):
4292  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4293 
4295  return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4296 
4297 
4298 def is_array(a):
4299  """Return `True` if `a` is a Z3 array expression.
4300 
4301  >>> a = Array('a', IntSort(), IntSort())
4302  >>> is_array(a)
4303  True
4304  >>> is_array(Store(a, 0, 1))
4305  True
4306  >>> is_array(a[0])
4307  False
4308  """
4309  return isinstance(a, ArrayRef)
4310 
4312  """Return `True` if `a` is a Z3 constant array.
4313 
4314  >>> a = K(IntSort(), 10)
4315  >>> is_const_array(a)
4316  True
4317  >>> a = Array('a', IntSort(), IntSort())
4318  >>> is_const_array(a)
4319  False
4320  """
4321  return is_app_of(a, Z3_OP_CONST_ARRAY)
4322 
4323 def is_K(a):
4324  """Return `True` if `a` is a Z3 constant array.
4325 
4326  >>> a = K(IntSort(), 10)
4327  >>> is_K(a)
4328  True
4329  >>> a = Array('a', IntSort(), IntSort())
4330  >>> is_K(a)
4331  False
4332  """
4333  return is_app_of(a, Z3_OP_CONST_ARRAY)
4334 
4335 def is_map(a):
4336  """Return `True` if `a` is a Z3 map array expression.
4337 
4338  >>> f = Function('f', IntSort(), IntSort())
4339  >>> b = Array('b', IntSort(), IntSort())
4340  >>> a = Map(f, b)
4341  >>> a
4342  Map(f, b)
4343  >>> is_map(a)
4344  True
4345  >>> is_map(b)
4346  False
4347  """
4348  return is_app_of(a, Z3_OP_ARRAY_MAP)
4349 
4350 def is_default(a):
4351  """Return `True` if `a` is a Z3 default array expression.
4352  >>> d = Default(K(IntSort(), 10))
4353  >>> is_default(d)
4354  True
4355  """
4356  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4357 
4359  """Return the function declaration associated with a Z3 map array expression.
4360 
4361  >>> f = Function('f', IntSort(), IntSort())
4362  >>> b = Array('b', IntSort(), IntSort())
4363  >>> a = Map(f, b)
4364  >>> eq(f, get_map_func(a))
4365  True
4366  >>> get_map_func(a)
4367  f
4368  >>> get_map_func(a)(0)
4369  f(0)
4370  """
4371  if z3_debug():
4372  _z3_assert(is_map(a), "Z3 array map expression expected.")
4373  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4374 
4375 def ArraySort(*sig):
4376  """Return the Z3 array sort with the given domain and range sorts.
4377 
4378  >>> A = ArraySort(IntSort(), BoolSort())
4379  >>> A
4380  Array(Int, Bool)
4381  >>> A.domain()
4382  Int
4383  >>> A.range()
4384  Bool
4385  >>> AA = ArraySort(IntSort(), A)
4386  >>> AA
4387  Array(Int, Array(Int, Bool))
4388  """
4389  sig = _get_args(sig)
4390  if z3_debug():
4391  _z3_assert(len(sig) > 1, "At least two arguments expected")
4392  arity = len(sig) - 1
4393  r = sig[arity]
4394  d = sig[0]
4395  if z3_debug():
4396  for s in sig:
4397  _z3_assert(is_sort(s), "Z3 sort expected")
4398  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4399  ctx = d.ctx
4400  if len(sig) == 2:
4401  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4402  dom = (Sort * arity)()
4403  for i in range(arity):
4404  dom[i] = sig[i].ast
4405  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4406 
4407 def Array(name, dom, rng):
4408  """Return an array constant named `name` with the given domain and range sorts.
4409 
4410  >>> a = Array('a', IntSort(), IntSort())
4411  >>> a.sort()
4412  Array(Int, Int)
4413  >>> a[0]
4414  a[0]
4415  """
4416  s = ArraySort(dom, rng)
4417  ctx = s.ctx
4418  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4419 
4420 def Update(a, i, v):
4421  """Return a Z3 store array expression.
4422 
4423  >>> a = Array('a', IntSort(), IntSort())
4424  >>> i, v = Ints('i v')
4425  >>> s = Update(a, i, v)
4426  >>> s.sort()
4427  Array(Int, Int)
4428  >>> prove(s[i] == v)
4429  proved
4430  >>> j = Int('j')
4431  >>> prove(Implies(i != j, s[j] == a[j]))
4432  proved
4433  """
4434  if z3_debug():
4435  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4436  i = a.domain().cast(i)
4437  v = a.range().cast(v)
4438  ctx = a.ctx
4439  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4440 
4441 def Default(a):
4442  """ Return a default value for array expression.
4443  >>> b = K(IntSort(), 1)
4444  >>> prove(Default(b) == 1)
4445  proved
4446  """
4447  if z3_debug():
4448  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4449  return a.default()
4450 
4451 
4452 def Store(a, i, v):
4453  """Return a Z3 store array expression.
4454 
4455  >>> a = Array('a', IntSort(), IntSort())
4456  >>> i, v = Ints('i v')
4457  >>> s = Store(a, i, v)
4458  >>> s.sort()
4459  Array(Int, Int)
4460  >>> prove(s[i] == v)
4461  proved
4462  >>> j = Int('j')
4463  >>> prove(Implies(i != j, s[j] == a[j]))
4464  proved
4465  """
4466  return Update(a, i, v)
4467 
4468 def Select(a, i):
4469  """Return a Z3 select array expression.
4470 
4471  >>> a = Array('a', IntSort(), IntSort())
4472  >>> i = Int('i')
4473  >>> Select(a, i)
4474  a[i]
4475  >>> eq(Select(a, i), a[i])
4476  True
4477  """
4478  if z3_debug():
4479  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4480  return a[i]
4481 
4482 
4483 def Map(f, *args):
4484  """Return a Z3 map array expression.
4485 
4486  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4487  >>> a1 = Array('a1', IntSort(), IntSort())
4488  >>> a2 = Array('a2', IntSort(), IntSort())
4489  >>> b = Map(f, a1, a2)
4490  >>> b
4491  Map(f, a1, a2)
4492  >>> prove(b[0] == f(a1[0], a2[0]))
4493  proved
4494  """
4495  args = _get_args(args)
4496  if z3_debug():
4497  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4498  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4499  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4500  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4501  _args, sz = _to_ast_array(args)
4502  ctx = f.ctx
4503  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4504 
4505 def K(dom, v):
4506  """Return a Z3 constant array expression.
4507 
4508  >>> a = K(IntSort(), 10)
4509  >>> a
4510  K(Int, 10)
4511  >>> a.sort()
4512  Array(Int, Int)
4513  >>> i = Int('i')
4514  >>> a[i]
4515  K(Int, 10)[i]
4516  >>> simplify(a[i])
4517  10
4518  """
4519  if z3_debug():
4520  _z3_assert(is_sort(dom), "Z3 sort expected")
4521  ctx = dom.ctx
4522  if not is_expr(v):
4523  v = _py2expr(v, ctx)
4524  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4525 
4526 def Ext(a, b):
4527  """Return extensionality index for one-dimensional arrays.
4528  >> a, b = Consts('a b', SetSort(IntSort()))
4529  >> Ext(a, b)
4530  Ext(a, b)
4531  """
4532  ctx = a.ctx
4533  if z3_debug():
4534  _z3_assert(is_array_sort(a) and is_array(b), "arguments must be arrays")
4535  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4536 
4537 def SetHasSize(a, k):
4538  ctx = a.ctx
4539  k = _py2expr(k, ctx)
4540  return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4541 
4542 def is_select(a):
4543  """Return `True` if `a` is a Z3 array select application.
4544 
4545  >>> a = Array('a', IntSort(), IntSort())
4546  >>> is_select(a)
4547  False
4548  >>> i = Int('i')
4549  >>> is_select(a[i])
4550  True
4551  """
4552  return is_app_of(a, Z3_OP_SELECT)
4553 
4554 def is_store(a):
4555  """Return `True` if `a` is a Z3 array store application.
4556 
4557  >>> a = Array('a', IntSort(), IntSort())
4558  >>> is_store(a)
4559  False
4560  >>> is_store(Store(a, 0, 1))
4561  True
4562  """
4563  return is_app_of(a, Z3_OP_STORE)
4564 
4565 
4570 
4571 
4572 def SetSort(s):
4573  """ Create a set sort over element sort s"""
4574  return ArraySort(s, BoolSort())
4575 
4576 def EmptySet(s):
4577  """Create the empty set
4578  >>> EmptySet(IntSort())
4579  K(Int, False)
4580  """
4581  ctx = s.ctx
4582  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4583 
4584 def FullSet(s):
4585  """Create the full set
4586  >>> FullSet(IntSort())
4587  K(Int, True)
4588  """
4589  ctx = s.ctx
4590  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4591 
4592 def SetUnion(*args):
4593  """ Take the union of sets
4594  >>> a = Const('a', SetSort(IntSort()))
4595  >>> b = Const('b', SetSort(IntSort()))
4596  >>> SetUnion(a, b)
4597  union(a, b)
4598  """
4599  args = _get_args(args)
4600  ctx = _ctx_from_ast_arg_list(args)
4601  _args, sz = _to_ast_array(args)
4602  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4603 
4604 def SetIntersect(*args):
4605  """ Take the union of sets
4606  >>> a = Const('a', SetSort(IntSort()))
4607  >>> b = Const('b', SetSort(IntSort()))
4608  >>> SetIntersect(a, b)
4609  intersection(a, b)
4610  """
4611  args = _get_args(args)
4612  ctx = _ctx_from_ast_arg_list(args)
4613  _args, sz = _to_ast_array(args)
4614  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4615 
4616 def SetAdd(s, e):
4617  """ Add element e to set s
4618  >>> a = Const('a', SetSort(IntSort()))
4619  >>> SetAdd(a, 1)
4620  Store(a, 1, True)
4621  """
4622  ctx = _ctx_from_ast_arg_list([s,e])
4623  e = _py2expr(e, ctx)
4624  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4625 
4626 def SetDel(s, e):
4627  """ Remove element e to set s
4628  >>> a = Const('a', SetSort(IntSort()))
4629  >>> SetDel(a, 1)
4630  Store(a, 1, False)
4631  """
4632  ctx = _ctx_from_ast_arg_list([s,e])
4633  e = _py2expr(e, ctx)
4634  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4635 
4637  """ The complement of set s
4638  >>> a = Const('a', SetSort(IntSort()))
4639  >>> SetComplement(a)
4640  complement(a)
4641  """
4642  ctx = s.ctx
4643  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4644 
4645 def SetDifference(a, b):
4646  """ The set difference of a and b
4647  >>> a = Const('a', SetSort(IntSort()))
4648  >>> b = Const('b', SetSort(IntSort()))
4649  >>> SetDifference(a, b)
4650  setminus(a, b)
4651  """
4652  ctx = _ctx_from_ast_arg_list([a, b])
4653  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4654 
4655 def IsMember(e, s):
4656  """ Check if e is a member of set s
4657  >>> a = Const('a', SetSort(IntSort()))
4658  >>> IsMember(1, a)
4659  a[1]
4660  """
4661  ctx = _ctx_from_ast_arg_list([s,e])
4662  e = _py2expr(e, ctx)
4663  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4664 
4665 def IsSubset(a, b):
4666  """ Check if a is a subset of b
4667  >>> a = Const('a', SetSort(IntSort()))
4668  >>> b = Const('b', SetSort(IntSort()))
4669  >>> IsSubset(a, b)
4670  subset(a, b)
4671  """
4672  ctx = _ctx_from_ast_arg_list([a, b])
4673  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4674 
4675 
4676 
4681 
4682 def _valid_accessor(acc):
4683  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4684  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4685 
4686 class Datatype:
4687  """Helper class for declaring Z3 datatypes.
4688 
4689  >>> List = Datatype('List')
4690  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4691  >>> List.declare('nil')
4692  >>> List = List.create()
4693  >>> # List is now a Z3 declaration
4694  >>> List.nil
4695  nil
4696  >>> List.cons(10, List.nil)
4697  cons(10, nil)
4698  >>> List.cons(10, List.nil).sort()
4699  List
4700  >>> cons = List.cons
4701  >>> nil = List.nil
4702  >>> car = List.car
4703  >>> cdr = List.cdr
4704  >>> n = cons(1, cons(0, nil))
4705  >>> n
4706  cons(1, cons(0, nil))
4707  >>> simplify(cdr(n))
4708  cons(0, nil)
4709  >>> simplify(car(n))
4710  1
4711  """
4712  def __init__(self, name, ctx=None):
4713  self.ctx = _get_ctx(ctx)
4714  self.name = name
4715  self.constructors = []
4716 
4717  def __deepcopy__(self, memo={}):
4718  r = Datatype(self.name, self.ctx)
4719  r.constructors = copy.deepcopy(self.constructors)
4720  return r
4721 
4722  def declare_core(self, name, rec_name, *args):
4723  if z3_debug():
4724  _z3_assert(isinstance(name, str), "String expected")
4725  _z3_assert(isinstance(rec_name, str), "String expected")
4726  _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)")
4727  self.constructors.append((name, rec_name, args))
4728 
4729  def declare(self, name, *args):
4730  """Declare constructor named `name` with the given accessors `args`.
4731  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.
4732 
4733  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4734  declares the constructor named `cons` that builds a new List using an integer and a List.
4735  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4736  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4737  the actual datatype in Z3.
4738 
4739  >>> List = Datatype('List')
4740  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4741  >>> List.declare('nil')
4742  >>> List = List.create()
4743  """
4744  if z3_debug():
4745  _z3_assert(isinstance(name, str), "String expected")
4746  _z3_assert(name != "", "Constructor name cannot be empty")
4747  return self.declare_core(name, "is-" + name, *args)
4748 
4749  def __repr__(self):
4750  return "Datatype(%s, %s)" % (self.name, self.constructors)
4751 
4752  def create(self):
4753  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4754 
4755  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4756 
4757  >>> List = Datatype('List')
4758  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4759  >>> List.declare('nil')
4760  >>> List = List.create()
4761  >>> List.nil
4762  nil
4763  >>> List.cons(10, List.nil)
4764  cons(10, nil)
4765  """
4766  return CreateDatatypes([self])[0]
4767 
4769  """Auxiliary object used to create Z3 datatypes."""
4770  def __init__(self, c, ctx):
4771  self.c = c
4772  self.ctx = ctx
4773  def __del__(self):
4774  if self.ctx.ref() is not None:
4775  Z3_del_constructor(self.ctx.ref(), self.c)
4776 
4778  """Auxiliary object used to create Z3 datatypes."""
4779  def __init__(self, c, ctx):
4780  self.c = c
4781  self.ctx = ctx
4782  def __del__(self):
4783  if self.ctx.ref() is not None:
4784  Z3_del_constructor_list(self.ctx.ref(), self.c)
4785 
4787  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4788 
4789  In the following example we define a Tree-List using two mutually recursive datatypes.
4790 
4791  >>> TreeList = Datatype('TreeList')
4792  >>> Tree = Datatype('Tree')
4793  >>> # Tree has two constructors: leaf and node
4794  >>> Tree.declare('leaf', ('val', IntSort()))
4795  >>> # a node contains a list of trees
4796  >>> Tree.declare('node', ('children', TreeList))
4797  >>> TreeList.declare('nil')
4798  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4799  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4800  >>> Tree.val(Tree.leaf(10))
4801  val(leaf(10))
4802  >>> simplify(Tree.val(Tree.leaf(10)))
4803  10
4804  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4805  >>> n1
4806  node(cons(leaf(10), cons(leaf(20), nil)))
4807  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4808  >>> simplify(n2 == n1)
4809  False
4810  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4811  True
4812  """
4813  ds = _get_args(ds)
4814  if z3_debug():
4815  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4816  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4817  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4818  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4819  ctx = ds[0].ctx
4820  num = len(ds)
4821  names = (Symbol * num)()
4822  out = (Sort * num)()
4823  clists = (ConstructorList * num)()
4824  to_delete = []
4825  for i in range(num):
4826  d = ds[i]
4827  names[i] = to_symbol(d.name, ctx)
4828  num_cs = len(d.constructors)
4829  cs = (Constructor * num_cs)()
4830  for j in range(num_cs):
4831  c = d.constructors[j]
4832  cname = to_symbol(c[0], ctx)
4833  rname = to_symbol(c[1], ctx)
4834  fs = c[2]
4835  num_fs = len(fs)
4836  fnames = (Symbol * num_fs)()
4837  sorts = (Sort * num_fs)()
4838  refs = (ctypes.c_uint * num_fs)()
4839  for k in range(num_fs):
4840  fname = fs[k][0]
4841  ftype = fs[k][1]
4842  fnames[k] = to_symbol(fname, ctx)
4843  if isinstance(ftype, Datatype):
4844  if z3_debug():
4845  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4846  sorts[k] = None
4847  refs[k] = ds.index(ftype)
4848  else:
4849  if z3_debug():
4850  _z3_assert(is_sort(ftype), "Z3 sort expected")
4851  sorts[k] = ftype.ast
4852  refs[k] = 0
4853  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4854  to_delete.append(ScopedConstructor(cs[j], ctx))
4855  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4856  to_delete.append(ScopedConstructorList(clists[i], ctx))
4857  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4858  result = []
4859 
4860  for i in range(num):
4861  dref = DatatypeSortRef(out[i], ctx)
4862  num_cs = dref.num_constructors()
4863  for j in range(num_cs):
4864  cref = dref.constructor(j)
4865  cref_name = cref.name()
4866  cref_arity = cref.arity()
4867  if cref.arity() == 0:
4868  cref = cref()
4869  setattr(dref, cref_name, cref)
4870  rref = dref.recognizer(j)
4871  setattr(dref, "is_" + cref_name, rref)
4872  for k in range(cref_arity):
4873  aref = dref.accessor(j, k)
4874  setattr(dref, aref.name(), aref)
4875  result.append(dref)
4876  return tuple(result)
4877 
4879  """Datatype sorts."""
4880  def num_constructors(self):
4881  """Return the number of constructors in the given Z3 datatype.
4882 
4883  >>> List = Datatype('List')
4884  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4885  >>> List.declare('nil')
4886  >>> List = List.create()
4887  >>> # List is now a Z3 declaration
4888  >>> List.num_constructors()
4889  2
4890  """
4891  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4892 
4893  def constructor(self, idx):
4894  """Return a constructor of the datatype `self`.
4895 
4896  >>> List = Datatype('List')
4897  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4898  >>> List.declare('nil')
4899  >>> List = List.create()
4900  >>> # List is now a Z3 declaration
4901  >>> List.num_constructors()
4902  2
4903  >>> List.constructor(0)
4904  cons
4905  >>> List.constructor(1)
4906  nil
4907  """
4908  if z3_debug():
4909  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4910  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4911 
4912  def recognizer(self, idx):
4913  """In Z3, each constructor has an associated recognizer predicate.
4914 
4915  If the constructor is named `name`, then the recognizer `is_name`.
4916 
4917  >>> List = Datatype('List')
4918  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4919  >>> List.declare('nil')
4920  >>> List = List.create()
4921  >>> # List is now a Z3 declaration
4922  >>> List.num_constructors()
4923  2
4924  >>> List.recognizer(0)
4925  is(cons)
4926  >>> List.recognizer(1)
4927  is(nil)
4928  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4929  False
4930  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4931  True
4932  >>> l = Const('l', List)
4933  >>> simplify(List.is_cons(l))
4934  is(cons, l)
4935  """
4936  if z3_debug():
4937  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4938  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4939 
4940  def accessor(self, i, j):
4941  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4942 
4943  >>> List = Datatype('List')
4944  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4945  >>> List.declare('nil')
4946  >>> List = List.create()
4947  >>> List.num_constructors()
4948  2
4949  >>> List.constructor(0)
4950  cons
4951  >>> num_accs = List.constructor(0).arity()
4952  >>> num_accs
4953  2
4954  >>> List.accessor(0, 0)
4955  car
4956  >>> List.accessor(0, 1)
4957  cdr
4958  >>> List.constructor(1)
4959  nil
4960  >>> num_accs = List.constructor(1).arity()
4961  >>> num_accs
4962  0
4963  """
4964  if z3_debug():
4965  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4966  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4967  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4968 
4970  """Datatype expressions."""
4971  def sort(self):
4972  """Return the datatype sort of the datatype expression `self`."""
4973  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4974 
4975 def TupleSort(name, sorts, ctx = None):
4976  """Create a named tuple sort base on a set of underlying sorts
4977  Example:
4978  >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
4979  """
4980  tuple = Datatype(name, ctx)
4981  projects = [ ('project%d' % i, sorts[i]) for i in range(len(sorts)) ]
4982  tuple.declare(name, *projects)
4983  tuple = tuple.create()
4984  return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
4985 
4986 def DisjointSum(name, sorts, ctx=None):
4987  """Create a named tagged union sort base on a set of underlying sorts
4988  Example:
4989  >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
4990  """
4991  sum = Datatype(name, ctx)
4992  for i in range(len(sorts)):
4993  sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
4994  sum = sum.create()
4995  return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
4996 
4997 
4998 def EnumSort(name, values, ctx=None):
4999  """Return a new enumeration sort named `name` containing the given values.
5000 
5001  The result is a pair (sort, list of constants).
5002  Example:
5003  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5004  """
5005  if z3_debug():
5006  _z3_assert(isinstance(name, str), "Name must be a string")
5007  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5008  _z3_assert(len(values) > 0, "At least one value expected")
5009  ctx = _get_ctx(ctx)
5010  num = len(values)
5011  _val_names = (Symbol * num)()
5012  for i in range(num):
5013  _val_names[i] = to_symbol(values[i])
5014  _values = (FuncDecl * num)()
5015  _testers = (FuncDecl * num)()
5016  name = to_symbol(name)
5017  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5018  V = []
5019  for i in range(num):
5020  V.append(FuncDeclRef(_values[i], ctx))
5021  V = [a() for a in V]
5022  return S, V
5023 
5024 
5029 
5031  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5032 
5033  Consider using the function `args2params` to create instances of this object.
5034  """
5035  def __init__(self, ctx=None, params=None):
5036  self.ctx = _get_ctx(ctx)
5037  if params is None:
5038  self.params = Z3_mk_params(self.ctx.ref())
5039  else:
5040  self.params = params
5041  Z3_params_inc_ref(self.ctx.ref(), self.params)
5042 
5043  def __deepcopy__(self, memo={}):
5044  return ParamsRef(self.ctx, self.params)
5045 
5046  def __del__(self):
5047  if self.ctx.ref() is not None:
5048  Z3_params_dec_ref(self.ctx.ref(), self.params)
5049 
5050  def set(self, name, val):
5051  """Set parameter name with value val."""
5052  if z3_debug():
5053  _z3_assert(isinstance(name, str), "parameter name must be a string")
5054  name_sym = to_symbol(name, self.ctx)
5055  if isinstance(val, bool):
5056  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5057  elif _is_int(val):
5058  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5059  elif isinstance(val, float):
5060  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5061  elif isinstance(val, str):
5062  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5063  else:
5064  if z3_debug():
5065  _z3_assert(False, "invalid parameter value")
5066 
5067  def __repr__(self):
5068  return Z3_params_to_string(self.ctx.ref(), self.params)
5069 
5070  def validate(self, ds):
5071  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5072  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5073 
5074 def args2params(arguments, keywords, ctx=None):
5075  """Convert python arguments into a Z3_params object.
5076  A ':' is added to the keywords, and '_' is replaced with '-'
5077 
5078  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5079  (params model true relevancy 2 elim_and true)
5080  """
5081  if z3_debug():
5082  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5083  prev = None
5084  r = ParamsRef(ctx)
5085  for a in arguments:
5086  if prev is None:
5087  prev = a
5088  else:
5089  r.set(prev, a)
5090  prev = None
5091  for k in keywords:
5092  v = keywords[k]
5093  r.set(k, v)
5094  return r
5095 
5097  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5098  """
5099  def __init__(self, descr, ctx=None):
5100  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5101  self.ctx = _get_ctx(ctx)
5102  self.descr = descr
5103  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5104 
5105  def __deepcopy__(self, memo={}):
5106  return ParamsDescrsRef(self.descr, self.ctx)
5107 
5108  def __del__(self):
5109  if self.ctx.ref() is not None:
5110  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5111 
5112  def size(self):
5113  """Return the size of in the parameter description `self`.
5114  """
5115  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5116 
5117  def __len__(self):
5118  """Return the size of in the parameter description `self`.
5119  """
5120  return self.size()
5121 
5122  def get_name(self, i):
5123  """Return the i-th parameter name in the parameter description `self`.
5124  """
5125  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5126 
5127  def get_kind(self, n):
5128  """Return the kind of the parameter named `n`.
5129  """
5130  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5131 
5132  def get_documentation(self, n):
5133  """Return the documentation string of the parameter named `n`.
5134  """
5135  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5136 
5137  def __getitem__(self, arg):
5138  if _is_int(arg):
5139  return self.get_name(arg)
5140  else:
5141  return self.get_kind(arg)
5142 
5143  def __repr__(self):
5144  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5145 
5146 
5151 
5153  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5154 
5155  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5156  A goal has a solution if one of its subgoals has a solution.
5157  A goal is unsatisfiable if all subgoals are unsatisfiable.
5158  """
5159 
5160  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5161  if z3_debug():
5162  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
5163  self.ctx = _get_ctx(ctx)
5164  self.goal = goal
5165  if self.goal is None:
5166  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5167  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5168 
5169  def __deepcopy__(self, memo={}):
5170  return Goal(False, False, False, self.ctx, self.goal)
5171 
5172  def __del__(self):
5173  if self.goal is not None and self.ctx.ref() is not None:
5174  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5175 
5176  def depth(self):
5177  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
5178 
5179  >>> x, y = Ints('x y')
5180  >>> g = Goal()
5181  >>> g.add(x == 0, y >= x + 1)
5182  >>> g.depth()
5183  0
5184  >>> r = Then('simplify', 'solve-eqs')(g)
5185  >>> # r has 1 subgoal
5186  >>> len(r)
5187  1
5188  >>> r[0].depth()
5189  2
5190  """
5191  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5192 
5193  def inconsistent(self):
5194  """Return `True` if `self` contains the `False` constraints.
5195 
5196  >>> x, y = Ints('x y')
5197  >>> g = Goal()
5198  >>> g.inconsistent()
5199  False
5200  >>> g.add(x == 0, x == 1)
5201  >>> g
5202  [x == 0, x == 1]
5203  >>> g.inconsistent()
5204  False
5205  >>> g2 = Tactic('propagate-values')(g)[0]
5206  >>> g2.inconsistent()
5207  True
5208  """
5209  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5210 
5211  def prec(self):
5212  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5213 
5214  >>> g = Goal()
5215  >>> g.prec() == Z3_GOAL_PRECISE
5216  True
5217  >>> x, y = Ints('x y')
5218  >>> g.add(x == y + 1)
5219  >>> g.prec() == Z3_GOAL_PRECISE
5220  True
5221  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5222  >>> g2 = t(g)[0]
5223  >>> g2
5224  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5225  >>> g2.prec() == Z3_GOAL_PRECISE
5226  False
5227  >>> g2.prec() == Z3_GOAL_UNDER
5228  True
5229  """
5230  return Z3_goal_precision(self.ctx.ref(), self.goal)
5231 
5232  def precision(self):
5233  """Alias for `prec()`.
5234 
5235  >>> g = Goal()
5236  >>> g.precision() == Z3_GOAL_PRECISE
5237  True
5238  """
5239  return self.prec()
5240 
5241  def size(self):
5242  """Return the number of constraints in the goal `self`.
5243 
5244  >>> g = Goal()
5245  >>> g.size()
5246  0
5247  >>> x, y = Ints('x y')
5248  >>> g.add(x == 0, y > x)
5249  >>> g.size()
5250  2
5251  """
5252  return int(Z3_goal_size(self.ctx.ref(), self.goal))
5253 
5254  def __len__(self):
5255  """Return the number of constraints in the goal `self`.
5256 
5257  >>> g = Goal()
5258  >>> len(g)
5259  0
5260  >>> x, y = Ints('x y')
5261  >>> g.add(x == 0, y > x)
5262  >>> len(g)
5263  2
5264  """
5265  return self.size()
5266 
5267  def get(self, i):
5268  """Return a constraint in the goal `self`.
5269 
5270  >>> g = Goal()
5271  >>> x, y = Ints('x y')
5272  >>> g.add(x == 0, y > x)
5273  >>> g.get(0)
5274  x == 0
5275  >>> g.get(1)
5276  y > x
5277  """
5278  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5279 
5280  def __getitem__(self, arg):
5281  """Return a constraint in the goal `self`.
5282 
5283  >>> g = Goal()
5284  >>> x, y = Ints('x y')
5285  >>> g.add(x == 0, y > x)
5286  >>> g[0]
5287  x == 0
5288  >>> g[1]
5289  y > x
5290  """
5291  if arg >= len(self):
5292  raise IndexError
5293  return self.get(arg)
5294 
5295  def assert_exprs(self, *args):
5296  """Assert constraints into the goal.
5297 
5298  >>> x = Int('x')
5299  >>> g = Goal()
5300  >>> g.assert_exprs(x > 0, x < 2)
5301  >>> g
5302  [x > 0, x < 2]
5303  """
5304  args = _get_args(args)
5305  s = BoolSort(self.ctx)
5306  for arg in args:
5307  arg = s.cast(arg)
5308  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5309 
5310  def append(self, *args):
5311  """Add constraints.
5312 
5313  >>> x = Int('x')
5314  >>> g = Goal()
5315  >>> g.append(x > 0, x < 2)
5316  >>> g
5317  [x > 0, x < 2]
5318  """
5319  self.assert_exprs(*args)
5320 
5321  def insert(self, *args):
5322  """Add constraints.
5323 
5324  >>> x = Int('x')
5325  >>> g = Goal()
5326  >>> g.insert(x > 0, x < 2)
5327  >>> g
5328  [x > 0, x < 2]
5329  """
5330  self.assert_exprs(*args)
5331 
5332  def add(self, *args):
5333  """Add constraints.
5334 
5335  >>> x = Int('x')
5336  >>> g = Goal()
5337  >>> g.add(x > 0, x < 2)
5338  >>> g
5339  [x > 0, x < 2]
5340  """
5341  self.assert_exprs(*args)
5342 
5343  def convert_model(self, model):
5344  """Retrieve model from a satisfiable goal
5345  >>> a, b = Ints('a b')
5346  >>> g = Goal()
5347  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5348  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5349  >>> r = t(g)
5350  >>> r[0]
5351  [Or(b == 0, b == 1), Not(0 <= b)]
5352  >>> r[1]
5353  [Or(b == 0, b == 1), Not(1 <= b)]
5354  >>> # Remark: the subgoal r[0] is unsatisfiable
5355  >>> # Creating a solver for solving the second subgoal
5356  >>> s = Solver()
5357  >>> s.add(r[1])
5358  >>> s.check()
5359  sat
5360  >>> s.model()
5361  [b = 0]
5362  >>> # Model s.model() does not assign a value to `a`
5363  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5364  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5365  >>> r[1].convert_model(s.model())
5366  [b = 0, a = 1]
5367  """
5368  if z3_debug():
5369  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5370  return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5371 
5372  def __repr__(self):
5373  return obj_to_string(self)
5374 
5375  def sexpr(self):
5376  """Return a textual representation of the s-expression representing the goal."""
5377  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5378 
5379  def dimacs(self):
5380  """Return a textual representation of the goal in DIMACS format."""
5381  return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
5382 
5383  def translate(self, target):
5384  """Copy goal `self` to context `target`.
5385 
5386  >>> x = Int('x')
5387  >>> g = Goal()
5388  >>> g.add(x > 10)
5389  >>> g
5390  [x > 10]
5391  >>> c2 = Context()
5392  >>> g2 = g.translate(c2)
5393  >>> g2
5394  [x > 10]
5395  >>> g.ctx == main_ctx()
5396  True
5397  >>> g2.ctx == c2
5398  True
5399  >>> g2.ctx == main_ctx()
5400  False
5401  """
5402  if z3_debug():
5403  _z3_assert(isinstance(target, Context), "target must be a context")
5404  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5405 
5406  def __copy__(self):
5407  return self.translate(self.ctx)
5408 
5409  def __deepcopy__(self, memo={}):
5410  return self.translate(self.ctx)
5411 
5412  def simplify(self, *arguments, **keywords):
5413  """Return a new simplified goal.
5414 
5415  This method is essentially invoking the simplify tactic.
5416 
5417  >>> g = Goal()
5418  >>> x = Int('x')
5419  >>> g.add(x + 1 >= 2)
5420  >>> g
5421  [x + 1 >= 2]
5422  >>> g2 = g.simplify()
5423  >>> g2
5424  [x >= 1]
5425  >>> # g was not modified
5426  >>> g
5427  [x + 1 >= 2]
5428  """
5429  t = Tactic('simplify')
5430  return t.apply(self, *arguments, **keywords)[0]
5431 
5432  def as_expr(self):
5433  """Return goal `self` as a single Z3 expression.
5434 
5435  >>> x = Int('x')
5436  >>> g = Goal()
5437  >>> g.as_expr()
5438  True
5439  >>> g.add(x > 1)
5440  >>> g.as_expr()
5441  x > 1
5442  >>> g.add(x < 10)
5443  >>> g.as_expr()
5444  And(x > 1, x < 10)
5445  """
5446  sz = len(self)
5447  if sz == 0:
5448  return BoolVal(True, self.ctx)
5449  elif sz == 1:
5450  return self.get(0)
5451  else:
5452  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5453 
5454 
5460  """A collection (vector) of ASTs."""
5461 
5462  def __init__(self, v=None, ctx=None):
5463  self.vector = None
5464  if v is None:
5465  self.ctx = _get_ctx(ctx)
5466  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5467  else:
5468  self.vector = v
5469  assert ctx is not None
5470  self.ctx = ctx
5471  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5472 
5473  def __deepcopy__(self, memo={}):
5474  return AstVector(self.vector, self.ctx)
5475 
5476  def __del__(self):
5477  if self.vector is not None and self.ctx.ref() is not None:
5478  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5479 
5480  def __len__(self):
5481  """Return the size of the vector `self`.
5482 
5483  >>> A = AstVector()
5484  >>> len(A)
5485  0
5486  >>> A.push(Int('x'))
5487  >>> A.push(Int('x'))
5488  >>> len(A)
5489  2
5490  """
5491  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5492 
5493  def __getitem__(self, i):
5494  """Return the 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[1]
5502  y
5503  """
5504 
5505  if isinstance(i, int):
5506  if i < 0:
5507  i += self.__len__()
5508 
5509  if i >= self.__len__():
5510  raise IndexError
5511  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5512 
5513  elif isinstance(i, slice):
5514  return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5515 
5516 
5517  def __setitem__(self, i, v):
5518  """Update AST at position `i`.
5519 
5520  >>> A = AstVector()
5521  >>> A.push(Int('x') + 1)
5522  >>> A.push(Int('y'))
5523  >>> A[0]
5524  x + 1
5525  >>> A[0] = Int('x')
5526  >>> A[0]
5527  x
5528  """
5529  if i >= self.__len__():
5530  raise IndexError
5531  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5532 
5533  def push(self, v):
5534  """Add `v` in the end of the vector.
5535 
5536  >>> A = AstVector()
5537  >>> len(A)
5538  0
5539  >>> A.push(Int('x'))
5540  >>> len(A)
5541  1
5542  """
5543  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5544 
5545  def resize(self, sz):
5546  """Resize the vector to `sz` elements.
5547 
5548  >>> A = AstVector()
5549  >>> A.resize(10)
5550  >>> len(A)
5551  10
5552  >>> for i in range(10): A[i] = Int('x')
5553  >>> A[5]
5554  x
5555  """
5556  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5557 
5558  def __contains__(self, item):
5559  """Return `True` if the vector contains `item`.
5560 
5561  >>> x = Int('x')
5562  >>> A = AstVector()
5563  >>> x in A
5564  False
5565  >>> A.push(x)
5566  >>> x in A
5567  True
5568  >>> (x+1) in A
5569  False
5570  >>> A.push(x+1)
5571  >>> (x+1) in A
5572  True
5573  >>> A
5574  [x, x + 1]
5575  """
5576  for elem in self:
5577  if elem.eq(item):
5578  return True
5579  return False
5580 
5581  def translate(self, other_ctx):
5582  """Copy vector `self` to context `other_ctx`.
5583 
5584  >>> x = Int('x')
5585  >>> A = AstVector()
5586  >>> A.push(x)
5587  >>> c2 = Context()
5588  >>> B = A.translate(c2)
5589  >>> B
5590  [x]
5591  """
5592  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5593 
5594  def __copy__(self):
5595  return self.translate(self.ctx)
5596 
5597  def __deepcopy__(self, memo={}):
5598  return self.translate(self.ctx)
5599 
5600  def __repr__(self):
5601  return obj_to_string(self)
5602 
5603  def sexpr(self):
5604  """Return a textual representation of the s-expression representing the vector."""
5605  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5606 
5607 
5612 class AstMap:
5613  """A mapping from ASTs to ASTs."""
5614 
5615  def __init__(self, m=None, ctx=None):
5616  self.map = None
5617  if m is None:
5618  self.ctx = _get_ctx(ctx)
5619  self.map = Z3_mk_ast_map(self.ctx.ref())
5620  else:
5621  self.map = m
5622  assert ctx is not None
5623  self.ctx = ctx
5624  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5625 
5626  def __deepcopy__(self, memo={}):
5627  return AstMap(self.map, self.ctx)
5628 
5629  def __del__(self):
5630  if self.map is not None and self.ctx.ref() is not None:
5631  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5632 
5633  def __len__(self):
5634  """Return the size of the map.
5635 
5636  >>> M = AstMap()
5637  >>> len(M)
5638  0
5639  >>> x = Int('x')
5640  >>> M[x] = IntVal(1)
5641  >>> len(M)
5642  1
5643  """
5644  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5645 
5646  def __contains__(self, key):
5647  """Return `True` if the map contains key `key`.
5648 
5649  >>> M = AstMap()
5650  >>> x = Int('x')
5651  >>> M[x] = x + 1
5652  >>> x in M
5653  True
5654  >>> x+1 in M
5655  False
5656  """
5657  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5658 
5659  def __getitem__(self, key):
5660  """Retrieve the value associated with key `key`.
5661 
5662  >>> M = AstMap()
5663  >>> x = Int('x')
5664  >>> M[x] = x + 1
5665  >>> M[x]
5666  x + 1
5667  """
5668  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5669 
5670  def __setitem__(self, k, v):
5671  """Add/Update key `k` with value `v`.
5672 
5673  >>> M = AstMap()
5674  >>> x = Int('x')
5675  >>> M[x] = x + 1
5676  >>> len(M)
5677  1
5678  >>> M[x]
5679  x + 1
5680  >>> M[x] = IntVal(1)
5681  >>> M[x]
5682  1
5683  """
5684  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5685 
5686  def __repr__(self):
5687  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5688 
5689  def erase(self, k):
5690  """Remove the entry associated with key `k`.
5691 
5692  >>> M = AstMap()
5693  >>> x = Int('x')
5694  >>> M[x] = x + 1
5695  >>> len(M)
5696  1
5697  >>> M.erase(x)
5698  >>> len(M)
5699  0
5700  """
5701  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5702 
5703  def reset(self):
5704  """Remove all entries from the map.
5705 
5706  >>> M = AstMap()
5707  >>> x = Int('x')
5708  >>> M[x] = x + 1
5709  >>> M[x+x] = IntVal(1)
5710  >>> len(M)
5711  2
5712  >>> M.reset()
5713  >>> len(M)
5714  0
5715  """
5716  Z3_ast_map_reset(self.ctx.ref(), self.map)
5717 
5718  def keys(self):
5719  """Return an AstVector containing all keys in the map.
5720 
5721  >>> M = AstMap()
5722  >>> x = Int('x')
5723  >>> M[x] = x + 1
5724  >>> M[x+x] = IntVal(1)
5725  >>> M.keys()
5726  [x, x + x]
5727  """
5728  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5729 
5730 
5735 
5737  """Store the value of the interpretation of a function in a particular point."""
5738 
5739  def __init__(self, entry, ctx):
5740  self.entry = entry
5741  self.ctx = ctx
5742  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5743 
5744  def __deepcopy__(self, memo={}):
5745  return FuncEntry(self.entry, self.ctx)
5746 
5747  def __del__(self):
5748  if self.ctx.ref() is not None:
5749  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5750 
5751  def num_args(self):
5752  """Return the number of arguments in the given entry.
5753 
5754  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5755  >>> s = Solver()
5756  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5757  >>> s.check()
5758  sat
5759  >>> m = s.model()
5760  >>> f_i = m[f]
5761  >>> f_i.num_entries()
5762  1
5763  >>> e = f_i.entry(0)
5764  >>> e.num_args()
5765  2
5766  """
5767  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5768 
5769  def arg_value(self, idx):
5770  """Return the value of argument `idx`.
5771 
5772  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5773  >>> s = Solver()
5774  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5775  >>> s.check()
5776  sat
5777  >>> m = s.model()
5778  >>> f_i = m[f]
5779  >>> f_i.num_entries()
5780  1
5781  >>> e = f_i.entry(0)
5782  >>> e
5783  [1, 2, 20]
5784  >>> e.num_args()
5785  2
5786  >>> e.arg_value(0)
5787  1
5788  >>> e.arg_value(1)
5789  2
5790  >>> try:
5791  ... e.arg_value(2)
5792  ... except IndexError:
5793  ... print("index error")
5794  index error
5795  """
5796  if idx >= self.num_args():
5797  raise IndexError
5798  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5799 
5800  def value(self):
5801  """Return the value of the function at point `self`.
5802 
5803  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5804  >>> s = Solver()
5805  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5806  >>> s.check()
5807  sat
5808  >>> m = s.model()
5809  >>> f_i = m[f]
5810  >>> f_i.num_entries()
5811  1
5812  >>> e = f_i.entry(0)
5813  >>> e
5814  [1, 2, 20]
5815  >>> e.num_args()
5816  2
5817  >>> e.value()
5818  20
5819  """
5820  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5821 
5822  def as_list(self):
5823  """Return entry `self` as a Python list.
5824  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5825  >>> s = Solver()
5826  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5827  >>> s.check()
5828  sat
5829  >>> m = s.model()
5830  >>> f_i = m[f]
5831  >>> f_i.num_entries()
5832  1
5833  >>> e = f_i.entry(0)
5834  >>> e.as_list()
5835  [1, 2, 20]
5836  """
5837  args = [ self.arg_value(i) for i in range(self.num_args())]
5838  args.append(self.value())
5839  return args
5840 
5841  def __repr__(self):
5842  return repr(self.as_list())
5843 
5845  """Stores the interpretation of a function in a Z3 model."""
5846 
5847  def __init__(self, f, ctx):
5848  self.f = f
5849  self.ctx = ctx
5850  if self.f is not None:
5851  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5852 
5853  def __deepcopy__(self, memo={}):
5854  return FuncInterp(self.f, self.ctx)
5855 
5856  def __del__(self):
5857  if self.f is not None and self.ctx.ref() is not None:
5858  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5859 
5860  def else_value(self):
5861  """
5862  Return the `else` value for a function interpretation.
5863  Return None if Z3 did not specify the `else` value for
5864  this object.
5865 
5866  >>> f = Function('f', IntSort(), IntSort())
5867  >>> s = Solver()
5868  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5869  >>> s.check()
5870  sat
5871  >>> m = s.model()
5872  >>> m[f]
5873  [2 -> 0, else -> 1]
5874  >>> m[f].else_value()
5875  1
5876  """
5877  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5878  if r:
5879  return _to_expr_ref(r, self.ctx)
5880  else:
5881  return None
5882 
5883  def num_entries(self):
5884  """Return the number of entries/points in the function interpretation `self`.
5885 
5886  >>> f = Function('f', IntSort(), IntSort())
5887  >>> s = Solver()
5888  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5889  >>> s.check()
5890  sat
5891  >>> m = s.model()
5892  >>> m[f]
5893  [2 -> 0, else -> 1]
5894  >>> m[f].num_entries()
5895  1
5896  """
5897  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5898 
5899  def arity(self):
5900  """Return the number of arguments for each entry in the function interpretation `self`.
5901 
5902  >>> f = Function('f', IntSort(), IntSort())
5903  >>> s = Solver()
5904  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5905  >>> s.check()
5906  sat
5907  >>> m = s.model()
5908  >>> m[f].arity()
5909  1
5910  """
5911  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5912 
5913  def entry(self, idx):
5914  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5915 
5916  >>> f = Function('f', IntSort(), IntSort())
5917  >>> s = Solver()
5918  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5919  >>> s.check()
5920  sat
5921  >>> m = s.model()
5922  >>> m[f]
5923  [2 -> 0, else -> 1]
5924  >>> m[f].num_entries()
5925  1
5926  >>> m[f].entry(0)
5927  [2, 0]
5928  """
5929  if idx >= self.num_entries():
5930  raise IndexError
5931  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5932 
5933  def translate(self, other_ctx):
5934  """Copy model 'self' to context 'other_ctx'.
5935  """
5936  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5937 
5938  def __copy__(self):
5939  return self.translate(self.ctx)
5940 
5941  def __deepcopy__(self, memo={}):
5942  return self.translate(self.ctx)
5943 
5944  def as_list(self):
5945  """Return the function interpretation as a Python list.
5946  >>> f = Function('f', IntSort(), IntSort())
5947  >>> s = Solver()
5948  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5949  >>> s.check()
5950  sat
5951  >>> m = s.model()
5952  >>> m[f]
5953  [2 -> 0, else -> 1]
5954  >>> m[f].as_list()
5955  [[2, 0], 1]
5956  """
5957  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5958  r.append(self.else_value())
5959  return r
5960 
5961  def __repr__(self):
5962  return obj_to_string(self)
5963 
5965  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5966 
5967  def __init__(self, m, ctx):
5968  assert ctx is not None
5969  self.model = m
5970  self.ctx = ctx
5971  Z3_model_inc_ref(self.ctx.ref(), self.model)
5972 
5973  def __del__(self):
5974  if self.ctx.ref() is not None:
5975  Z3_model_dec_ref(self.ctx.ref(), self.model)
5976 
5977  def __repr__(self):
5978  return obj_to_string(self)
5979 
5980  def sexpr(self):
5981  """Return a textual representation of the s-expression representing the model."""
5982  return Z3_model_to_string(self.ctx.ref(), self.model)
5983 
5984  def eval(self, t, model_completion=False):
5985  """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`.
5986 
5987  >>> x = Int('x')
5988  >>> s = Solver()
5989  >>> s.add(x > 0, x < 2)
5990  >>> s.check()
5991  sat
5992  >>> m = s.model()
5993  >>> m.eval(x + 1)
5994  2
5995  >>> m.eval(x == 1)
5996  True
5997  >>> y = Int('y')
5998  >>> m.eval(y + x)
5999  1 + y
6000  >>> m.eval(y)
6001  y
6002  >>> m.eval(y, model_completion=True)
6003  0
6004  >>> # Now, m contains an interpretation for y
6005  >>> m.eval(y + x)
6006  1
6007  """
6008  r = (Ast * 1)()
6009  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6010  return _to_expr_ref(r[0], self.ctx)
6011  raise Z3Exception("failed to evaluate expression in the model")
6012 
6013  def evaluate(self, t, model_completion=False):
6014  """Alias for `eval`.
6015 
6016  >>> x = Int('x')
6017  >>> s = Solver()
6018  >>> s.add(x > 0, x < 2)
6019  >>> s.check()
6020  sat
6021  >>> m = s.model()
6022  >>> m.evaluate(x + 1)
6023  2
6024  >>> m.evaluate(x == 1)
6025  True
6026  >>> y = Int('y')
6027  >>> m.evaluate(y + x)
6028  1 + y
6029  >>> m.evaluate(y)
6030  y
6031  >>> m.evaluate(y, model_completion=True)
6032  0
6033  >>> # Now, m contains an interpretation for y
6034  >>> m.evaluate(y + x)
6035  1
6036  """
6037  return self.eval(t, model_completion)
6038 
6039  def __len__(self):
6040  """Return the number of constant and function declarations in the model `self`.
6041 
6042  >>> f = Function('f', IntSort(), IntSort())
6043  >>> x = Int('x')
6044  >>> s = Solver()
6045  >>> s.add(x > 0, f(x) != x)
6046  >>> s.check()
6047  sat
6048  >>> m = s.model()
6049  >>> len(m)
6050  2
6051  """
6052  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6053 
6054  def get_interp(self, decl):
6055  """Return the interpretation for a given declaration or constant.
6056 
6057  >>> f = Function('f', IntSort(), IntSort())
6058  >>> x = Int('x')
6059  >>> s = Solver()
6060  >>> s.add(x > 0, x < 2, f(x) == 0)
6061  >>> s.check()
6062  sat
6063  >>> m = s.model()
6064  >>> m[x]
6065  1
6066  >>> m[f]
6067  [else -> 0]
6068  """
6069  if z3_debug():
6070  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6071  if is_const(decl):
6072  decl = decl.decl()
6073  try:
6074  if decl.arity() == 0:
6075  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6076  if _r.value is None:
6077  return None
6078  r = _to_expr_ref(_r, self.ctx)
6079  if is_as_array(r):
6080  return self.get_interp(get_as_array_func(r))
6081  else:
6082  return r
6083  else:
6084  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6085  except Z3Exception:
6086  return None
6087 
6088  def num_sorts(self):
6089  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6090 
6091  >>> A = DeclareSort('A')
6092  >>> a, b = Consts('a b', A)
6093  >>> s = Solver()
6094  >>> s.add(a != b)
6095  >>> s.check()
6096  sat
6097  >>> m = s.model()
6098  >>> m.num_sorts()
6099  1
6100  """
6101  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6102 
6103  def get_sort(self, idx):
6104  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6105 
6106  >>> A = DeclareSort('A')
6107  >>> B = DeclareSort('B')
6108  >>> a1, a2 = Consts('a1 a2', A)
6109  >>> b1, b2 = Consts('b1 b2', B)
6110  >>> s = Solver()
6111  >>> s.add(a1 != a2, b1 != b2)
6112  >>> s.check()
6113  sat
6114  >>> m = s.model()
6115  >>> m.num_sorts()
6116  2
6117  >>> m.get_sort(0)
6118  A
6119  >>> m.get_sort(1)
6120  B
6121  """
6122  if idx >= self.num_sorts():
6123  raise IndexError
6124  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6125 
6126  def sorts(self):
6127  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6128 
6129  >>> A = DeclareSort('A')
6130  >>> B = DeclareSort('B')
6131  >>> a1, a2 = Consts('a1 a2', A)
6132  >>> b1, b2 = Consts('b1 b2', B)
6133  >>> s = Solver()
6134  >>> s.add(a1 != a2, b1 != b2)
6135  >>> s.check()
6136  sat
6137  >>> m = s.model()
6138  >>> m.sorts()
6139  [A, B]
6140  """
6141  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
6142 
6143  def get_universe(self, s):
6144  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6145 
6146  >>> A = DeclareSort('A')
6147  >>> a, b = Consts('a b', A)
6148  >>> s = Solver()
6149  >>> s.add(a != b)
6150  >>> s.check()
6151  sat
6152  >>> m = s.model()
6153  >>> m.get_universe(A)
6154  [A!val!0, A!val!1]
6155  """
6156  if z3_debug():
6157  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6158  try:
6159  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6160  except Z3Exception:
6161  return None
6162 
6163  def __getitem__(self, idx):
6164  """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.
6165 
6166  The elements can be retrieved using position or the actual declaration.
6167 
6168  >>> f = Function('f', IntSort(), IntSort())
6169  >>> x = Int('x')
6170  >>> s = Solver()
6171  >>> s.add(x > 0, x < 2, f(x) == 0)
6172  >>> s.check()
6173  sat
6174  >>> m = s.model()
6175  >>> len(m)
6176  2
6177  >>> m[0]
6178  x
6179  >>> m[1]
6180  f
6181  >>> m[x]
6182  1
6183  >>> m[f]
6184  [else -> 0]
6185  >>> for d in m: print("%s -> %s" % (d, m[d]))
6186  x -> 1
6187  f -> [else -> 0]
6188  """
6189  if _is_int(idx):
6190  if idx >= len(self):
6191  raise IndexError
6192  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6193  if (idx < num_consts):
6194  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6195  else:
6196  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6197  if isinstance(idx, FuncDeclRef):
6198  return self.get_interp(idx)
6199  if is_const(idx):
6200  return self.get_interp(idx.decl())
6201  if isinstance(idx, SortRef):
6202  return self.get_universe(idx)
6203  if z3_debug():
6204  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6205  return None
6206 
6207  def decls(self):
6208  """Return a list with all symbols that have an interpretation in the model `self`.
6209  >>> f = Function('f', IntSort(), IntSort())
6210  >>> x = Int('x')
6211  >>> s = Solver()
6212  >>> s.add(x > 0, x < 2, f(x) == 0)
6213  >>> s.check()
6214  sat
6215  >>> m = s.model()
6216  >>> m.decls()
6217  [x, f]
6218  """
6219  r = []
6220  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6221  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6222  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6223  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6224  return r
6225 
6226  def translate(self, target):
6227  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6228  """
6229  if z3_debug():
6230  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6231  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6232  return Model(model, target)
6233 
6234  def __copy__(self):
6235  return self.translate(self.ctx)
6236 
6237  def __deepcopy__(self, memo={}):
6238  return self.translate(self.ctx)
6239 
6240 def Model(ctx = None):
6241  ctx = _get_ctx(ctx)
6242  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6243 
6245  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6246  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6247 
6249  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6250  if z3_debug():
6251  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6252  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6253 
6254 
6260  """Statistics for `Solver.check()`."""
6261 
6262  def __init__(self, stats, ctx):
6263  self.stats = stats
6264  self.ctx = ctx
6265  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6266 
6267  def __deepcopy__(self, memo={}):
6268  return Statistics(self.stats, self.ctx)
6269 
6270  def __del__(self):
6271  if self.ctx.ref() is not None:
6272  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6273 
6274  def __repr__(self):
6275  if in_html_mode():
6276  out = io.StringIO()
6277  even = True
6278  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6279  for k, v in self:
6280  if even:
6281  out.write(u('<tr style="background-color:#CFCFCF">'))
6282  even = False
6283  else:
6284  out.write(u('<tr>'))
6285  even = True
6286  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
6287  out.write(u('</table>'))
6288  return out.getvalue()
6289  else:
6290  return Z3_stats_to_string(self.ctx.ref(), self.stats)
6291 
6292  def __len__(self):
6293  """Return the number of statistical counters.
6294 
6295  >>> x = Int('x')
6296  >>> s = Then('simplify', 'nlsat').solver()
6297  >>> s.add(x > 0)
6298  >>> s.check()
6299  sat
6300  >>> st = s.statistics()
6301  >>> len(st)
6302  6
6303  """
6304  return int(Z3_stats_size(self.ctx.ref(), self.stats))
6305 
6306  def __getitem__(self, idx):
6307  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
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  >>> len(st)
6316  6
6317  >>> st[0]
6318  ('nlsat propagations', 2)
6319  >>> st[1]
6320  ('nlsat stages', 2)
6321  """
6322  if idx >= len(self):
6323  raise IndexError
6324  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6325  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6326  else:
6327  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6328  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6329 
6330  def keys(self):
6331  """Return the list of statistical counters.
6332 
6333  >>> x = Int('x')
6334  >>> s = Then('simplify', 'nlsat').solver()
6335  >>> s.add(x > 0)
6336  >>> s.check()
6337  sat
6338  >>> st = s.statistics()
6339  """
6340  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6341 
6342  def get_key_value(self, key):
6343  """Return the value of a particular statistical counter.
6344 
6345  >>> x = Int('x')
6346  >>> s = Then('simplify', 'nlsat').solver()
6347  >>> s.add(x > 0)
6348  >>> s.check()
6349  sat
6350  >>> st = s.statistics()
6351  >>> st.get_key_value('nlsat propagations')
6352  2
6353  """
6354  for idx in range(len(self)):
6355  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6356  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6357  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6358  else:
6359  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6360  raise Z3Exception("unknown key")
6361 
6362  def __getattr__(self, name):
6363  """Access the value of statistical using attributes.
6364 
6365  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6366  we should use '_' (e.g., 'nlsat_propagations').
6367 
6368  >>> x = Int('x')
6369  >>> s = Then('simplify', 'nlsat').solver()
6370  >>> s.add(x > 0)
6371  >>> s.check()
6372  sat
6373  >>> st = s.statistics()
6374  >>> st.nlsat_propagations
6375  2
6376  >>> st.nlsat_stages
6377  2
6378  """
6379  key = name.replace('_', ' ')
6380  try:
6381  return self.get_key_value(key)
6382  except Z3Exception:
6383  raise AttributeError
6384 
6385 
6391  """Represents the result of a satisfiability check: sat, unsat, unknown.
6392 
6393  >>> s = Solver()
6394  >>> s.check()
6395  sat
6396  >>> r = s.check()
6397  >>> isinstance(r, CheckSatResult)
6398  True
6399  """
6400 
6401  def __init__(self, r):
6402  self.r = r
6403 
6404  def __deepcopy__(self, memo={}):
6405  return CheckSatResult(self.r)
6406 
6407  def __eq__(self, other):
6408  return isinstance(other, CheckSatResult) and self.r == other.r
6409 
6410  def __ne__(self, other):
6411  return not self.__eq__(other)
6412 
6413  def __repr__(self):
6414  if in_html_mode():
6415  if self.r == Z3_L_TRUE:
6416  return "<b>sat</b>"
6417  elif self.r == Z3_L_FALSE:
6418  return "<b>unsat</b>"
6419  else:
6420  return "<b>unknown</b>"
6421  else:
6422  if self.r == Z3_L_TRUE:
6423  return "sat"
6424  elif self.r == Z3_L_FALSE:
6425  return "unsat"
6426  else:
6427  return "unknown"
6428 
6429  def _repr_html_(self):
6430  in_html = in_html_mode()
6431  set_html_mode(True)
6432  res = repr(self)
6433  set_html_mode(in_html)
6434  return res
6435 
6436 sat = CheckSatResult(Z3_L_TRUE)
6437 unsat = CheckSatResult(Z3_L_FALSE)
6438 unknown = CheckSatResult(Z3_L_UNDEF)
6439 
6441  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6442 
6443  def __init__(self, solver=None, ctx=None):
6444  assert solver is None or ctx is not None
6445  self.ctx = _get_ctx(ctx)
6446  self.backtrack_level = 4000000000
6447  self.solver = None
6448  if solver is None:
6449  self.solver = Z3_mk_solver(self.ctx.ref())
6450  else:
6451  self.solver = solver
6452  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6453 
6454  def __del__(self):
6455  if self.solver is not None and self.ctx.ref() is not None:
6456  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6457 
6458  def set(self, *args, **keys):
6459  """Set a configuration option. The method `help()` return a string containing all available options.
6460 
6461  >>> s = Solver()
6462  >>> # The option MBQI can be set using three different approaches.
6463  >>> s.set(mbqi=True)
6464  >>> s.set('MBQI', True)
6465  >>> s.set(':mbqi', True)
6466  """
6467  p = args2params(args, keys, self.ctx)
6468  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6469 
6470  def push(self):
6471  """Create a backtracking point.
6472 
6473  >>> x = Int('x')
6474  >>> s = Solver()
6475  >>> s.add(x > 0)
6476  >>> s
6477  [x > 0]
6478  >>> s.push()
6479  >>> s.add(x < 1)
6480  >>> s
6481  [x > 0, x < 1]
6482  >>> s.check()
6483  unsat
6484  >>> s.pop()
6485  >>> s.check()
6486  sat
6487  >>> s
6488  [x > 0]
6489  """
6490  Z3_solver_push(self.ctx.ref(), self.solver)
6491 
6492  def pop(self, num=1):
6493  """Backtrack \c num backtracking points.
6494 
6495  >>> x = Int('x')
6496  >>> s = Solver()
6497  >>> s.add(x > 0)
6498  >>> s
6499  [x > 0]
6500  >>> s.push()
6501  >>> s.add(x < 1)
6502  >>> s
6503  [x > 0, x < 1]
6504  >>> s.check()
6505  unsat
6506  >>> s.pop()
6507  >>> s.check()
6508  sat
6509  >>> s
6510  [x > 0]
6511  """
6512  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6513 
6514  def num_scopes(self):
6515  """Return the current number of backtracking points.
6516 
6517  >>> s = Solver()
6518  >>> s.num_scopes()
6519  0L
6520  >>> s.push()
6521  >>> s.num_scopes()
6522  1L
6523  >>> s.push()
6524  >>> s.num_scopes()
6525  2L
6526  >>> s.pop()
6527  >>> s.num_scopes()
6528  1L
6529  """
6530  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6531 
6532  def reset(self):
6533  """Remove all asserted constraints and backtracking points created using `push()`.
6534 
6535  >>> x = Int('x')
6536  >>> s = Solver()
6537  >>> s.add(x > 0)
6538  >>> s
6539  [x > 0]
6540  >>> s.reset()
6541  >>> s
6542  []
6543  """
6544  Z3_solver_reset(self.ctx.ref(), self.solver)
6545 
6546  def assert_exprs(self, *args):
6547  """Assert constraints into the solver.
6548 
6549  >>> x = Int('x')
6550  >>> s = Solver()
6551  >>> s.assert_exprs(x > 0, x < 2)
6552  >>> s
6553  [x > 0, x < 2]
6554  """
6555  args = _get_args(args)
6556  s = BoolSort(self.ctx)
6557  for arg in args:
6558  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6559  for f in arg:
6560  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6561  else:
6562  arg = s.cast(arg)
6563  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6564 
6565  def add(self, *args):
6566  """Assert constraints into the solver.
6567 
6568  >>> x = Int('x')
6569  >>> s = Solver()
6570  >>> s.add(x > 0, x < 2)
6571  >>> s
6572  [x > 0, x < 2]
6573  """
6574  self.assert_exprs(*args)
6575 
6576  def __iadd__(self, fml):
6577  self.add(fml)
6578  return self
6579 
6580  def append(self, *args):
6581  """Assert constraints into the solver.
6582 
6583  >>> x = Int('x')
6584  >>> s = Solver()
6585  >>> s.append(x > 0, x < 2)
6586  >>> s
6587  [x > 0, x < 2]
6588  """
6589  self.assert_exprs(*args)
6590 
6591  def insert(self, *args):
6592  """Assert constraints into the solver.
6593 
6594  >>> x = Int('x')
6595  >>> s = Solver()
6596  >>> s.insert(x > 0, x < 2)
6597  >>> s
6598  [x > 0, x < 2]
6599  """
6600  self.assert_exprs(*args)
6601 
6602  def assert_and_track(self, a, p):
6603  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6604 
6605  If `p` is a string, it will be automatically converted into a Boolean constant.
6606 
6607  >>> x = Int('x')
6608  >>> p3 = Bool('p3')
6609  >>> s = Solver()
6610  >>> s.set(unsat_core=True)
6611  >>> s.assert_and_track(x > 0, 'p1')
6612  >>> s.assert_and_track(x != 1, 'p2')
6613  >>> s.assert_and_track(x < 0, p3)
6614  >>> print(s.check())
6615  unsat
6616  >>> c = s.unsat_core()
6617  >>> len(c)
6618  2
6619  >>> Bool('p1') in c
6620  True
6621  >>> Bool('p2') in c
6622  False
6623  >>> p3 in c
6624  True
6625  """
6626  if isinstance(p, str):
6627  p = Bool(p, self.ctx)
6628  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6629  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6630  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6631 
6632  def check(self, *assumptions):
6633  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6634 
6635  >>> x = Int('x')
6636  >>> s = Solver()
6637  >>> s.check()
6638  sat
6639  >>> s.add(x > 0, x < 2)
6640  >>> s.check()
6641  sat
6642  >>> s.model().eval(x)
6643  1
6644  >>> s.add(x < 1)
6645  >>> s.check()
6646  unsat
6647  >>> s.reset()
6648  >>> s.add(2**x == 4)
6649  >>> s.check()
6650  unknown
6651  """
6652  assumptions = _get_args(assumptions)
6653  num = len(assumptions)
6654  _assumptions = (Ast * num)()
6655  for i in range(num):
6656  _assumptions[i] = assumptions[i].as_ast()
6657  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6658  return CheckSatResult(r)
6659 
6660  def model(self):
6661  """Return a model for the last `check()`.
6662 
6663  This function raises an exception if
6664  a model is not available (e.g., last `check()` returned unsat).
6665 
6666  >>> s = Solver()
6667  >>> a = Int('a')
6668  >>> s.add(a + 2 == 0)
6669  >>> s.check()
6670  sat
6671  >>> s.model()
6672  [a = -2]
6673  """
6674  try:
6675  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6676  except Z3Exception:
6677  raise Z3Exception("model is not available")
6678 
6679  def import_model_converter(self, other):
6680  """Import model converter from other into the current solver"""
6681  Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
6682 
6683  def unsat_core(self):
6684  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6685 
6686  These are the assumptions Z3 used in the unsatisfiability proof.
6687  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6688  They may be also used to "retract" assumptions. Note that, assumptions are not really
6689  "soft constraints", but they can be used to implement them.
6690 
6691  >>> p1, p2, p3 = Bools('p1 p2 p3')
6692  >>> x, y = Ints('x y')
6693  >>> s = Solver()
6694  >>> s.add(Implies(p1, x > 0))
6695  >>> s.add(Implies(p2, y > x))
6696  >>> s.add(Implies(p2, y < 1))
6697  >>> s.add(Implies(p3, y > -3))
6698  >>> s.check(p1, p2, p3)
6699  unsat
6700  >>> core = s.unsat_core()
6701  >>> len(core)
6702  2
6703  >>> p1 in core
6704  True
6705  >>> p2 in core
6706  True
6707  >>> p3 in core
6708  False
6709  >>> # "Retracting" p2
6710  >>> s.check(p1, p3)
6711  sat
6712  """
6713  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6714 
6715  def consequences(self, assumptions, variables):
6716  """Determine fixed values for the variables based on the solver state and assumptions.
6717  >>> s = Solver()
6718  >>> a, b, c, d = Bools('a b c d')
6719  >>> s.add(Implies(a,b), Implies(b, c))
6720  >>> s.consequences([a],[b,c,d])
6721  (sat, [Implies(a, b), Implies(a, c)])
6722  >>> s.consequences([Not(c),d],[a,b,c,d])
6723  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6724  """
6725  if isinstance(assumptions, list):
6726  _asms = AstVector(None, self.ctx)
6727  for a in assumptions:
6728  _asms.push(a)
6729  assumptions = _asms
6730  if isinstance(variables, list):
6731  _vars = AstVector(None, self.ctx)
6732  for a in variables:
6733  _vars.push(a)
6734  variables = _vars
6735  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6736  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6737  consequences = AstVector(None, self.ctx)
6738  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6739  sz = len(consequences)
6740  consequences = [ consequences[i] for i in range(sz) ]
6741  return CheckSatResult(r), consequences
6742 
6743  def from_file(self, filename):
6744  """Parse assertions from a file"""
6745  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6746 
6747  def from_string(self, s):
6748  """Parse assertions from a string"""
6749  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6750 
6751  def cube(self, vars = None):
6752  """Get set of cubes
6753  The method takes an optional set of variables that restrict which
6754  variables may be used as a starting point for cubing.
6755  If vars is not None, then the first case split is based on a variable in
6756  this set.
6757  """
6758  self.cube_vs = AstVector(None, self.ctx)
6759  if vars is not None:
6760  for v in vars:
6761  self.cube_vs.push(v)
6762  while True:
6763  lvl = self.backtrack_level
6764  self.backtrack_level = 4000000000
6765  r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
6766  if (len(r) == 1 and is_false(r[0])):
6767  return
6768  yield r
6769  if (len(r) == 0):
6770  return
6771 
6772  def cube_vars(self):
6773  """Access the set of variables that were touched by the most recently generated cube.
6774  This set of variables can be used as a starting point for additional cubes.
6775  The idea is that variables that appear in clauses that are reduced by the most recent
6776  cube are likely more useful to cube on."""
6777  return self.cube_vs
6778 
6779  def proof(self):
6780  """Return a proof for the last `check()`. Proof construction must be enabled."""
6781  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6782 
6783  def assertions(self):
6784  """Return an AST vector containing all added constraints.
6785 
6786  >>> s = Solver()
6787  >>> s.assertions()
6788  []
6789  >>> a = Int('a')
6790  >>> s.add(a > 0)
6791  >>> s.add(a < 10)
6792  >>> s.assertions()
6793  [a > 0, a < 10]
6794  """
6795  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6796 
6797  def units(self):
6798  """Return an AST vector containing all currently inferred units.
6799  """
6800  return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
6801 
6802  def non_units(self):
6803  """Return an AST vector containing all atomic formulas in solver state that are not units.
6804  """
6805  return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
6806 
6807  def trail_levels(self):
6808  """Return trail and decision levels of the solver state after a check() call.
6809  """
6810  trail = self.trail()
6811  levels = (ctypes.c_uint * len(trail))()
6812  Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
6813  return trail, levels
6814 
6815  def trail(self):
6816  """Return trail of the solver state after a check() call.
6817  """
6818  return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
6819 
6820  def statistics(self):
6821  """Return statistics for the last `check()`.
6822 
6823  >>> s = SimpleSolver()
6824  >>> x = Int('x')
6825  >>> s.add(x > 0)
6826  >>> s.check()
6827  sat
6828  >>> st = s.statistics()
6829  >>> st.get_key_value('final checks')
6830  1
6831  >>> len(st) > 0
6832  True
6833  >>> st[0] != 0
6834  True
6835  """
6836  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6837 
6838  def reason_unknown(self):
6839  """Return a string describing why the last `check()` returned `unknown`.
6840 
6841  >>> x = Int('x')
6842  >>> s = SimpleSolver()
6843  >>> s.add(2**x == 4)
6844  >>> s.check()
6845  unknown
6846  >>> s.reason_unknown()
6847  '(incomplete (theory arithmetic))'
6848  """
6849  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6850 
6851  def help(self):
6852  """Display a string describing all available options."""
6853  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6854 
6855  def param_descrs(self):
6856  """Return the parameter description set."""
6857  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6858 
6859  def __repr__(self):
6860  """Return a formatted string with all added constraints."""
6861  return obj_to_string(self)
6862 
6863  def translate(self, target):
6864  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6865 
6866  >>> c1 = Context()
6867  >>> c2 = Context()
6868  >>> s1 = Solver(ctx=c1)
6869  >>> s2 = s1.translate(c2)
6870  """
6871  if z3_debug():
6872  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6873  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6874  return Solver(solver, target)
6875 
6876  def __copy__(self):
6877  return self.translate(self.ctx)
6878 
6879  def __deepcopy__(self, memo={}):
6880  return self.translate(self.ctx)
6881 
6882  def sexpr(self):
6883  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6884 
6885  >>> x = Int('x')
6886  >>> s = Solver()
6887  >>> s.add(x > 0)
6888  >>> s.add(x < 2)
6889  >>> r = s.sexpr()
6890  """
6891  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6892 
6893  def dimacs(self):
6894  """Return a textual representation of the solver in DIMACS format."""
6895  return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver)
6896 
6897  def to_smt2(self):
6898  """return SMTLIB2 formatted benchmark for solver's assertions"""
6899  es = self.assertions()
6900  sz = len(es)
6901  sz1 = sz
6902  if sz1 > 0:
6903  sz1 -= 1
6904  v = (Ast * sz1)()
6905  for i in range(sz1):
6906  v[i] = es[i].as_ast()
6907  if sz > 0:
6908  e = es[sz1].as_ast()
6909  else:
6910  e = BoolVal(True, self.ctx).as_ast()
6911  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6912 
6913 def SolverFor(logic, ctx=None):
6914  """Create a solver customized for the given logic.
6915 
6916  The parameter `logic` is a string. It should be contains
6917  the name of a SMT-LIB logic.
6918  See http://www.smtlib.org/ for the name of all available logics.
6919 
6920  >>> s = SolverFor("QF_LIA")
6921  >>> x = Int('x')
6922  >>> s.add(x > 0)
6923  >>> s.add(x < 2)
6924  >>> s.check()
6925  sat
6926  >>> s.model()
6927  [x = 1]
6928  """
6929  ctx = _get_ctx(ctx)
6930  logic = to_symbol(logic)
6931  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6932 
6933 def SimpleSolver(ctx=None):
6934  """Return a simple general purpose solver with limited amount of preprocessing.
6935 
6936  >>> s = SimpleSolver()
6937  >>> x = Int('x')
6938  >>> s.add(x > 0)
6939  >>> s.check()
6940  sat
6941  """
6942  ctx = _get_ctx(ctx)
6943  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6944 
6945 
6950 
6952  """Fixedpoint API provides methods for solving with recursive predicates"""
6953 
6954  def __init__(self, fixedpoint=None, ctx=None):
6955  assert fixedpoint is None or ctx is not None
6956  self.ctx = _get_ctx(ctx)
6957  self.fixedpoint = None
6958  if fixedpoint is None:
6959  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6960  else:
6961  self.fixedpoint = fixedpoint
6962  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6963  self.vars = []
6964 
6965  def __deepcopy__(self, memo={}):
6966  return FixedPoint(self.fixedpoint, self.ctx)
6967 
6968  def __del__(self):
6969  if self.fixedpoint is not None and self.ctx.ref() is not None:
6970  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6971 
6972  def set(self, *args, **keys):
6973  """Set a configuration option. The method `help()` return a string containing all available options.
6974  """
6975  p = args2params(args, keys, self.ctx)
6976  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6977 
6978  def help(self):
6979  """Display a string describing all available options."""
6980  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6981 
6982  def param_descrs(self):
6983  """Return the parameter description set."""
6984  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6985 
6986  def assert_exprs(self, *args):
6987  """Assert constraints as background axioms for the fixedpoint solver."""
6988  args = _get_args(args)
6989  s = BoolSort(self.ctx)
6990  for arg in args:
6991  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6992  for f in arg:
6993  f = self.abstract(f)
6994  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6995  else:
6996  arg = s.cast(arg)
6997  arg = self.abstract(arg)
6998  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6999 
7000  def add(self, *args):
7001  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7002  self.assert_exprs(*args)
7003 
7004  def __iadd__(self, fml):
7005  self.add(fml)
7006  return self
7007 
7008  def append(self, *args):
7009  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7010  self.assert_exprs(*args)
7011 
7012  def insert(self, *args):
7013  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7014  self.assert_exprs(*args)
7015 
7016  def add_rule(self, head, body = None, name = None):
7017  """Assert rules defining recursive predicates to the fixedpoint solver.
7018  >>> a = Bool('a')
7019  >>> b = Bool('b')
7020  >>> s = Fixedpoint()
7021  >>> s.register_relation(a.decl())
7022  >>> s.register_relation(b.decl())
7023  >>> s.fact(a)
7024  >>> s.rule(b, a)
7025  >>> s.query(b)
7026  sat
7027  """
7028  if name is None:
7029  name = ""
7030  name = to_symbol(name, self.ctx)
7031  if body is None:
7032  head = self.abstract(head)
7033  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7034  else:
7035  body = _get_args(body)
7036  f = self.abstract(Implies(And(body, self.ctx),head))
7037  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7038 
7039  def rule(self, head, body = None, name = None):
7040  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7041  self.add_rule(head, body, name)
7042 
7043  def fact(self, head, name = None):
7044  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7045  self.add_rule(head, None, name)
7046 
7047  def query(self, *query):
7048  """Query the fixedpoint engine whether formula is derivable.
7049  You can also pass an tuple or list of recursive predicates.
7050  """
7051  query = _get_args(query)
7052  sz = len(query)
7053  if sz >= 1 and isinstance(query[0], FuncDeclRef):
7054  _decls = (FuncDecl * sz)()
7055  i = 0
7056  for q in query:
7057  _decls[i] = q.ast
7058  i = i + 1
7059  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7060  else:
7061  if sz == 1:
7062  query = query[0]
7063  else:
7064  query = And(query, self.ctx)
7065  query = self.abstract(query, False)
7066  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7067  return CheckSatResult(r)
7068 
7069  def query_from_lvl (self, lvl, *query):
7070  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7071  """
7072  query = _get_args(query)
7073  sz = len(query)
7074  if sz >= 1 and isinstance(query[0], FuncDecl):
7075  _z3_assert (False, "unsupported")
7076  else:
7077  if sz == 1:
7078  query = query[0]
7079  else:
7080  query = And(query)
7081  query = self.abstract(query, False)
7082  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7083  return CheckSatResult(r)
7084 
7085  def update_rule(self, head, body, name):
7086  """update rule"""
7087  if name is None:
7088  name = ""
7089  name = to_symbol(name, self.ctx)
7090  body = _get_args(body)
7091  f = self.abstract(Implies(And(body, self.ctx),head))
7092  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7093 
7094  def get_answer(self):
7095  """Retrieve answer from last query call."""
7096  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7097  return _to_expr_ref(r, self.ctx)
7098 
7100  """Retrieve a ground cex from last query call."""
7101  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7102  return _to_expr_ref(r, self.ctx)
7103 
7105  """retrieve rules along the counterexample trace"""
7106  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7107 
7109  """retrieve rule names along the counterexample trace"""
7110  # this is a hack as I don't know how to return a list of symbols from C++;
7111  # obtain names as a single string separated by semicolons
7112  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7113  # split into individual names
7114  return names.split (';')
7115 
7116  def get_num_levels(self, predicate):
7117  """Retrieve number of levels used for predicate in PDR engine"""
7118  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7119 
7120  def get_cover_delta(self, level, predicate):
7121  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
7122  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7123  return _to_expr_ref(r, self.ctx)
7124 
7125  def add_cover(self, level, predicate, property):
7126  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
7127  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7128 
7129  def register_relation(self, *relations):
7130  """Register relation as recursive"""
7131  relations = _get_args(relations)
7132  for f in relations:
7133  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7134 
7135  def set_predicate_representation(self, f, *representations):
7136  """Control how relation is represented"""
7137  representations = _get_args(representations)
7138  representations = [to_symbol(s) for s in representations]
7139  sz = len(representations)
7140  args = (Symbol * sz)()
7141  for i in range(sz):
7142  args[i] = representations[i]
7143  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7144 
7145  def parse_string(self, s):
7146  """Parse rules and queries from a string"""
7147  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7148 
7149  def parse_file(self, f):
7150  """Parse rules and queries from a file"""
7151  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7152 
7153  def get_rules(self):
7154  """retrieve rules that have been added to fixedpoint context"""
7155  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7156 
7157  def get_assertions(self):
7158  """retrieve assertions that have been added to fixedpoint context"""
7159  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7160 
7161  def __repr__(self):
7162  """Return a formatted string with all added rules and constraints."""
7163  return self.sexpr()
7164 
7165  def sexpr(self):
7166  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7167  """
7168  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7169 
7170  def to_string(self, queries):
7171  """Return a formatted string (in Lisp-like format) with all added constraints.
7172  We say the string is in s-expression format.
7173  Include also queries.
7174  """
7175  args, len = _to_ast_array(queries)
7176  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7177 
7178  def statistics(self):
7179  """Return statistics for the last `query()`.
7180  """
7181  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7182 
7183  def reason_unknown(self):
7184  """Return a string describing why the last `query()` returned `unknown`.
7185  """
7186  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7187 
7188  def declare_var(self, *vars):
7189  """Add variable or several variables.
7190  The added variable or variables will be bound in the rules
7191  and queries
7192  """
7193  vars = _get_args(vars)
7194  for v in vars:
7195  self.vars += [v]
7196 
7197  def abstract(self, fml, is_forall=True):
7198  if self.vars == []:
7199  return fml
7200  if is_forall:
7201  return ForAll(self.vars, fml)
7202  else:
7203  return Exists(self.vars, fml)
7204 
7205 
7206 
7211 
7213  """Finite domain sort."""
7214 
7215  def size(self):
7216  """Return the size of the finite domain sort"""
7217  r = (ctypes.c_ulonglong * 1)()
7218  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7219  return r[0]
7220  else:
7221  raise Z3Exception("Failed to retrieve finite domain sort size")
7222 
7223 def FiniteDomainSort(name, sz, ctx=None):
7224  """Create a named finite domain sort of a given size sz"""
7225  if not isinstance(name, Symbol):
7226  name = to_symbol(name)
7227  ctx = _get_ctx(ctx)
7228  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7229 
7231  """Return True if `s` is a Z3 finite-domain sort.
7232 
7233  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7234  True
7235  >>> is_finite_domain_sort(IntSort())
7236  False
7237  """
7238  return isinstance(s, FiniteDomainSortRef)
7239 
7240 
7242  """Finite-domain expressions."""
7243 
7244  def sort(self):
7245  """Return the sort of the finite-domain expression `self`."""
7246  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7247 
7248  def as_string(self):
7249  """Return a Z3 floating point expression as a Python string."""
7250  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7251 
7253  """Return `True` if `a` is a Z3 finite-domain expression.
7254 
7255  >>> s = FiniteDomainSort('S', 100)
7256  >>> b = Const('b', s)
7257  >>> is_finite_domain(b)
7258  True
7259  >>> is_finite_domain(Int('x'))
7260  False
7261  """
7262  return isinstance(a, FiniteDomainRef)
7263 
7264 
7266  """Integer values."""
7267 
7268  def as_long(self):
7269  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7270 
7271  >>> s = FiniteDomainSort('S', 100)
7272  >>> v = FiniteDomainVal(3, s)
7273  >>> v
7274  3
7275  >>> v.as_long() + 1
7276  4
7277  """
7278  return int(self.as_string())
7279 
7280  def as_string(self):
7281  """Return a Z3 finite-domain numeral as a Python string.
7282 
7283  >>> s = FiniteDomainSort('S', 100)
7284  >>> v = FiniteDomainVal(42, s)
7285  >>> v.as_string()
7286  '42'
7287  """
7288  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
7289 
7290 
7291 def FiniteDomainVal(val, sort, ctx=None):
7292  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7293 
7294  >>> s = FiniteDomainSort('S', 256)
7295  >>> FiniteDomainVal(255, s)
7296  255
7297  >>> FiniteDomainVal('100', s)
7298  100
7299  """
7300  if z3_debug():
7301  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
7302  ctx = sort.ctx
7303  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7304 
7306  """Return `True` if `a` is a Z3 finite-domain value.
7307 
7308  >>> s = FiniteDomainSort('S', 100)
7309  >>> b = Const('b', s)
7310  >>> is_finite_domain_value(b)
7311  False
7312  >>> b = FiniteDomainVal(10, s)
7313  >>> b
7314  10
7315  >>> is_finite_domain_value(b)
7316  True
7317  """
7318  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7319 
7320 
7321 
7326 
7328  def __init__(self, opt, value, is_max):
7329  self._opt = opt
7330  self._value = value
7331  self._is_max = is_max
7332 
7333  def lower(self):
7334  opt = self._opt
7335  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7336 
7337  def upper(self):
7338  opt = self._opt
7339  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7340 
7341  def lower_values(self):
7342  opt = self._opt
7343  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7344 
7345  def upper_values(self):
7346  opt = self._opt
7347  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7348 
7349  def value(self):
7350  if self._is_max:
7351  return self.upper()
7352  else:
7353  return self.lower()
7354 
7355  def __str__(self):
7356  return "%s:%s" % (self._value, self._is_max)
7357 
7358 
7360  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7361 
7362  def __init__(self, ctx=None):
7363  self.ctx = _get_ctx(ctx)
7364  self.optimize = Z3_mk_optimize(self.ctx.ref())
7365  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7366 
7367  def __deepcopy__(self, memo={}):
7368  return Optimize(self.optimize, self.ctx)
7369 
7370  def __del__(self):
7371  if self.optimize is not None and self.ctx.ref() is not None:
7372  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7373 
7374  def set(self, *args, **keys):
7375  """Set a configuration option. The method `help()` return a string containing all available options.
7376  """
7377  p = args2params(args, keys, self.ctx)
7378  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7379 
7380  def help(self):
7381  """Display a string describing all available options."""
7382  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7383 
7384  def param_descrs(self):
7385  """Return the parameter description set."""
7386  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7387 
7388  def assert_exprs(self, *args):
7389  """Assert constraints as background axioms for the optimize solver."""
7390  args = _get_args(args)
7391  s = BoolSort(self.ctx)
7392  for arg in args:
7393  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7394  for f in arg:
7395  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7396  else:
7397  arg = s.cast(arg)
7398  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7399 
7400  def add(self, *args):
7401  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7402  self.assert_exprs(*args)
7403 
7404  def __iadd__(self, fml):
7405  self.add(fml)
7406  return self
7407 
7408  def assert_and_track(self, a, p):
7409  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7410 
7411  If `p` is a string, it will be automatically converted into a Boolean constant.
7412 
7413  >>> x = Int('x')
7414  >>> p3 = Bool('p3')
7415  >>> s = Optimize()
7416  >>> s.assert_and_track(x > 0, 'p1')
7417  >>> s.assert_and_track(x != 1, 'p2')
7418  >>> s.assert_and_track(x < 0, p3)
7419  >>> print(s.check())
7420  unsat
7421  >>> c = s.unsat_core()
7422  >>> len(c)
7423  2
7424  >>> Bool('p1') in c
7425  True
7426  >>> Bool('p2') in c
7427  False
7428  >>> p3 in c
7429  True
7430  """
7431  if isinstance(p, str):
7432  p = Bool(p, self.ctx)
7433  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7434  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7435  Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7436 
7437  def add_soft(self, arg, weight = "1", id = None):
7438  """Add soft constraint with optional weight and optional identifier.
7439  If no weight is supplied, then the penalty for violating the soft constraint
7440  is 1.
7441  Soft constraints are grouped by identifiers. Soft constraints that are
7442  added without identifiers are grouped by default.
7443  """
7444  if _is_int(weight):
7445  weight = "%d" % weight
7446  elif isinstance(weight, float):
7447  weight = "%f" % weight
7448  if not isinstance(weight, str):
7449  raise Z3Exception("weight should be a string or an integer")
7450  if id is None:
7451  id = ""
7452  id = to_symbol(id, self.ctx)
7453  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7454  return OptimizeObjective(self, v, False)
7455 
7456  def maximize(self, arg):
7457  """Add objective function to maximize."""
7458  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7459 
7460  def minimize(self, arg):
7461  """Add objective function to minimize."""
7462  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7463 
7464  def push(self):
7465  """create a backtracking point for added rules, facts and assertions"""
7466  Z3_optimize_push(self.ctx.ref(), self.optimize)
7467 
7468  def pop(self):
7469  """restore to previously created backtracking point"""
7470  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7471 
7472  def check(self, *assumptions):
7473  """Check satisfiability while optimizing objective functions."""
7474  assumptions = _get_args(assumptions)
7475  num = len(assumptions)
7476  _assumptions = (Ast * num)()
7477  for i in range(num):
7478  _assumptions[i] = assumptions[i].as_ast()
7479  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7480 
7481  def reason_unknown(self):
7482  """Return a string that describes why the last `check()` returned `unknown`."""
7483  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7484 
7485  def model(self):
7486  """Return a model for the last check()."""
7487  try:
7488  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7489  except Z3Exception:
7490  raise Z3Exception("model is not available")
7491 
7492  def unsat_core(self):
7493  return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7494 
7495  def lower(self, obj):
7496  if not isinstance(obj, OptimizeObjective):
7497  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7498  return obj.lower()
7499 
7500  def upper(self, obj):
7501  if not isinstance(obj, OptimizeObjective):
7502  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7503  return obj.upper()
7504 
7505  def lower_values(self, obj):
7506  if not isinstance(obj, OptimizeObjective):
7507  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7508  return obj.lower_values()
7509 
7510  def upper_values(self, obj):
7511  if not isinstance(obj, OptimizeObjective):
7512  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7513  return obj.upper_values()
7514 
7515  def from_file(self, filename):
7516  """Parse assertions and objectives from a file"""
7517  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7518 
7519  def from_string(self, s):
7520  """Parse assertions and objectives from a string"""
7521  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7522 
7523  def assertions(self):
7524  """Return an AST vector containing all added constraints."""
7525  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7526 
7527  def objectives(self):
7528  """returns set of objective functions"""
7529  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7530 
7531  def __repr__(self):
7532  """Return a formatted string with all added rules and constraints."""
7533  return self.sexpr()
7534 
7535  def sexpr(self):
7536  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7537  """
7538  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7539 
7540  def statistics(self):
7541  """Return statistics for the last check`.
7542  """
7543  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7544 
7545 
7546 
7547 
7548 
7554  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7555 
7556  def __init__(self, result, ctx):
7557  self.result = result
7558  self.ctx = ctx
7559  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7560 
7561  def __deepcopy__(self, memo={}):
7562  return ApplyResult(self.result, self.ctx)
7563 
7564  def __del__(self):
7565  if self.ctx.ref() is not None:
7566  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7567 
7568  def __len__(self):
7569  """Return the number of subgoals in `self`.
7570 
7571  >>> a, b = Ints('a b')
7572  >>> g = Goal()
7573  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7574  >>> t = Tactic('split-clause')
7575  >>> r = t(g)
7576  >>> len(r)
7577  2
7578  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7579  >>> len(t(g))
7580  4
7581  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7582  >>> len(t(g))
7583  1
7584  """
7585  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7586 
7587  def __getitem__(self, idx):
7588  """Return one of the subgoals stored in ApplyResult object `self`.
7589 
7590  >>> a, b = Ints('a b')
7591  >>> g = Goal()
7592  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7593  >>> t = Tactic('split-clause')
7594  >>> r = t(g)
7595  >>> r[0]
7596  [a == 0, Or(b == 0, b == 1), a > b]
7597  >>> r[1]
7598  [a == 1, Or(b == 0, b == 1), a > b]
7599  """
7600  if idx >= len(self):
7601  raise IndexError
7602  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7603 
7604  def __repr__(self):
7605  return obj_to_string(self)
7606 
7607  def sexpr(self):
7608  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7609  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7610 
7611 
7612  def as_expr(self):
7613  """Return a Z3 expression consisting of all subgoals.
7614 
7615  >>> x = Int('x')
7616  >>> g = Goal()
7617  >>> g.add(x > 1)
7618  >>> g.add(Or(x == 2, x == 3))
7619  >>> r = Tactic('simplify')(g)
7620  >>> r
7621  [[Not(x <= 1), Or(x == 2, x == 3)]]
7622  >>> r.as_expr()
7623  And(Not(x <= 1), Or(x == 2, x == 3))
7624  >>> r = Tactic('split-clause')(g)
7625  >>> r
7626  [[x > 1, x == 2], [x > 1, x == 3]]
7627  >>> r.as_expr()
7628  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7629  """
7630  sz = len(self)
7631  if sz == 0:
7632  return BoolVal(False, self.ctx)
7633  elif sz == 1:
7634  return self[0].as_expr()
7635  else:
7636  return Or([ self[i].as_expr() for i in range(len(self)) ])
7637 
7638 
7643 class Tactic:
7644  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7645 
7646  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7647  """
7648  def __init__(self, tactic, ctx=None):
7649  self.ctx = _get_ctx(ctx)
7650  self.tactic = None
7651  if isinstance(tactic, TacticObj):
7652  self.tactic = tactic
7653  else:
7654  if z3_debug():
7655  _z3_assert(isinstance(tactic, str), "tactic name expected")
7656  try:
7657  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7658  except Z3Exception:
7659  raise Z3Exception("unknown tactic '%s'" % tactic)
7660  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7661 
7662  def __deepcopy__(self, memo={}):
7663  return Tactic(self.tactic, self.ctx)
7664 
7665  def __del__(self):
7666  if self.tactic is not None and self.ctx.ref() is not None:
7667  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7668 
7669  def solver(self):
7670  """Create a solver using the tactic `self`.
7671 
7672  The solver supports the methods `push()` and `pop()`, but it
7673  will always solve each `check()` from scratch.
7674 
7675  >>> t = Then('simplify', 'nlsat')
7676  >>> s = t.solver()
7677  >>> x = Real('x')
7678  >>> s.add(x**2 == 2, x > 0)
7679  >>> s.check()
7680  sat
7681  >>> s.model()
7682  [x = 1.4142135623?]
7683  """
7684  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7685 
7686  def apply(self, goal, *arguments, **keywords):
7687  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7688 
7689  >>> x, y = Ints('x y')
7690  >>> t = Tactic('solve-eqs')
7691  >>> t.apply(And(x == 0, y >= x + 1))
7692  [[y >= 1]]
7693  """
7694  if z3_debug():
7695  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7696  goal = _to_goal(goal)
7697  if len(arguments) > 0 or len(keywords) > 0:
7698  p = args2params(arguments, keywords, self.ctx)
7699  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7700  else:
7701  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7702 
7703  def __call__(self, goal, *arguments, **keywords):
7704  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7705 
7706  >>> x, y = Ints('x y')
7707  >>> t = Tactic('solve-eqs')
7708  >>> t(And(x == 0, y >= x + 1))
7709  [[y >= 1]]
7710  """
7711  return self.apply(goal, *arguments, **keywords)
7712 
7713  def help(self):
7714  """Display a string containing a description of the available options for the `self` tactic."""
7715  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7716 
7717  def param_descrs(self):
7718  """Return the parameter description set."""
7719  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7720 
7721 def _to_goal(a):
7722  if isinstance(a, BoolRef):
7723  goal = Goal(ctx = a.ctx)
7724  goal.add(a)
7725  return goal
7726  else:
7727  return a
7728 
7729 def _to_tactic(t, ctx=None):
7730  if isinstance(t, Tactic):
7731  return t
7732  else:
7733  return Tactic(t, ctx)
7734 
7735 def _and_then(t1, t2, ctx=None):
7736  t1 = _to_tactic(t1, ctx)
7737  t2 = _to_tactic(t2, ctx)
7738  if z3_debug():
7739  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7740  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7741 
7742 def _or_else(t1, t2, ctx=None):
7743  t1 = _to_tactic(t1, ctx)
7744  t2 = _to_tactic(t2, ctx)
7745  if z3_debug():
7746  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7747  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7748 
7749 def AndThen(*ts, **ks):
7750  """Return a tactic that applies the tactics in `*ts` in sequence.
7751 
7752  >>> x, y = Ints('x y')
7753  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7754  >>> t(And(x == 0, y > x + 1))
7755  [[Not(y <= 1)]]
7756  >>> t(And(x == 0, y > x + 1)).as_expr()
7757  Not(y <= 1)
7758  """
7759  if z3_debug():
7760  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7761  ctx = ks.get('ctx', None)
7762  num = len(ts)
7763  r = ts[0]
7764  for i in range(num - 1):
7765  r = _and_then(r, ts[i+1], ctx)
7766  return r
7767 
7768 def Then(*ts, **ks):
7769  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7770 
7771  >>> x, y = Ints('x y')
7772  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7773  >>> t(And(x == 0, y > x + 1))
7774  [[Not(y <= 1)]]
7775  >>> t(And(x == 0, y > x + 1)).as_expr()
7776  Not(y <= 1)
7777  """
7778  return AndThen(*ts, **ks)
7779 
7780 def OrElse(*ts, **ks):
7781  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7782 
7783  >>> x = Int('x')
7784  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7785  >>> # Tactic split-clause fails if there is no clause in the given goal.
7786  >>> t(x == 0)
7787  [[x == 0]]
7788  >>> t(Or(x == 0, x == 1))
7789  [[x == 0], [x == 1]]
7790  """
7791  if z3_debug():
7792  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7793  ctx = ks.get('ctx', None)
7794  num = len(ts)
7795  r = ts[0]
7796  for i in range(num - 1):
7797  r = _or_else(r, ts[i+1], ctx)
7798  return r
7799 
7800 def ParOr(*ts, **ks):
7801  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7802 
7803  >>> x = Int('x')
7804  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7805  >>> t(x + 1 == 2)
7806  [[x == 1]]
7807  """
7808  if z3_debug():
7809  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7810  ctx = _get_ctx(ks.get('ctx', None))
7811  ts = [ _to_tactic(t, ctx) for t in ts ]
7812  sz = len(ts)
7813  _args = (TacticObj * sz)()
7814  for i in range(sz):
7815  _args[i] = ts[i].tactic
7816  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7817 
7818 def ParThen(t1, t2, ctx=None):
7819  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7820 
7821  >>> x, y = Ints('x y')
7822  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7823  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7824  [[x == 1, y == 2], [x == 2, y == 3]]
7825  """
7826  t1 = _to_tactic(t1, ctx)
7827  t2 = _to_tactic(t2, ctx)
7828  if z3_debug():
7829  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7830  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7831 
7832 def ParAndThen(t1, t2, ctx=None):
7833  """Alias for ParThen(t1, t2, ctx)."""
7834  return ParThen(t1, t2, ctx)
7835 
7836 def With(t, *args, **keys):
7837  """Return a tactic that applies tactic `t` using the given configuration options.
7838 
7839  >>> x, y = Ints('x y')
7840  >>> t = With(Tactic('simplify'), som=True)
7841  >>> t((x + 1)*(y + 2) == 0)
7842  [[2*x + y + x*y == -2]]
7843  """
7844  ctx = keys.pop('ctx', None)
7845  t = _to_tactic(t, ctx)
7846  p = args2params(args, keys, t.ctx)
7847  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7848 
7849 def WithParams(t, p):
7850  """Return a tactic that applies tactic `t` using the given configuration options.
7851 
7852  >>> x, y = Ints('x y')
7853  >>> p = ParamsRef()
7854  >>> p.set("som", True)
7855  >>> t = WithParams(Tactic('simplify'), p)
7856  >>> t((x + 1)*(y + 2) == 0)
7857  [[2*x + y + x*y == -2]]
7858  """
7859  t = _to_tactic(t, None)
7860  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7861 
7862 def Repeat(t, max=4294967295, ctx=None):
7863  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7864 
7865  >>> x, y = Ints('x y')
7866  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7867  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7868  >>> r = t(c)
7869  >>> for subgoal in r: print(subgoal)
7870  [x == 0, y == 0, x > y]
7871  [x == 0, y == 1, x > y]
7872  [x == 1, y == 0, x > y]
7873  [x == 1, y == 1, x > y]
7874  >>> t = Then(t, Tactic('propagate-values'))
7875  >>> t(c)
7876  [[x == 1, y == 0]]
7877  """
7878  t = _to_tactic(t, ctx)
7879  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7880 
7881 def TryFor(t, ms, ctx=None):
7882  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7883 
7884  If `t` does not terminate in `ms` milliseconds, then it fails.
7885  """
7886  t = _to_tactic(t, ctx)
7887  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7888 
7889 def tactics(ctx=None):
7890  """Return a list of all available tactics in Z3.
7891 
7892  >>> l = tactics()
7893  >>> l.count('simplify') == 1
7894  True
7895  """
7896  ctx = _get_ctx(ctx)
7897  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7898 
7899 def tactic_description(name, ctx=None):
7900  """Return a short description for the tactic named `name`.
7901 
7902  >>> d = tactic_description('simplify')
7903  """
7904  ctx = _get_ctx(ctx)
7905  return Z3_tactic_get_descr(ctx.ref(), name)
7906 
7908  """Display a (tabular) description of all available tactics in Z3."""
7909  if in_html_mode():
7910  even = True
7911  print('<table border="1" cellpadding="2" cellspacing="0">')
7912  for t in tactics():
7913  if even:
7914  print('<tr style="background-color:#CFCFCF">')
7915  even = False
7916  else:
7917  print('<tr>')
7918  even = True
7919  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7920  print('</table>')
7921  else:
7922  for t in tactics():
7923  print('%s : %s' % (t, tactic_description(t)))
7924 
7925 class Probe:
7926  """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."""
7927  def __init__(self, probe, ctx=None):
7928  self.ctx = _get_ctx(ctx)
7929  self.probe = None
7930  if isinstance(probe, ProbeObj):
7931  self.probe = probe
7932  elif isinstance(probe, float):
7933  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7934  elif _is_int(probe):
7935  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7936  elif isinstance(probe, bool):
7937  if probe:
7938  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7939  else:
7940  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7941  else:
7942  if z3_debug():
7943  _z3_assert(isinstance(probe, str), "probe name expected")
7944  try:
7945  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7946  except Z3Exception:
7947  raise Z3Exception("unknown probe '%s'" % probe)
7948  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7949 
7950  def __deepcopy__(self, memo={}):
7951  return Probe(self.probe, self.ctx)
7952 
7953  def __del__(self):
7954  if self.probe is not None and self.ctx.ref() is not None:
7955  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7956 
7957  def __lt__(self, other):
7958  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7959 
7960  >>> p = Probe('size') < 10
7961  >>> x = Int('x')
7962  >>> g = Goal()
7963  >>> g.add(x > 0)
7964  >>> g.add(x < 10)
7965  >>> p(g)
7966  1.0
7967  """
7968  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7969 
7970  def __gt__(self, other):
7971  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7972 
7973  >>> p = Probe('size') > 10
7974  >>> x = Int('x')
7975  >>> g = Goal()
7976  >>> g.add(x > 0)
7977  >>> g.add(x < 10)
7978  >>> p(g)
7979  0.0
7980  """
7981  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7982 
7983  def __le__(self, other):
7984  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7985 
7986  >>> p = Probe('size') <= 2
7987  >>> x = Int('x')
7988  >>> g = Goal()
7989  >>> g.add(x > 0)
7990  >>> g.add(x < 10)
7991  >>> p(g)
7992  1.0
7993  """
7994  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7995 
7996  def __ge__(self, other):
7997  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7998 
7999  >>> p = Probe('size') >= 2
8000  >>> x = Int('x')
8001  >>> g = Goal()
8002  >>> g.add(x > 0)
8003  >>> g.add(x < 10)
8004  >>> p(g)
8005  1.0
8006  """
8007  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8008 
8009  def __eq__(self, other):
8010  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
8011 
8012  >>> p = Probe('size') == 2
8013  >>> x = Int('x')
8014  >>> g = Goal()
8015  >>> g.add(x > 0)
8016  >>> g.add(x < 10)
8017  >>> p(g)
8018  1.0
8019  """
8020  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8021 
8022  def __ne__(self, other):
8023  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
8024 
8025  >>> p = Probe('size') != 2
8026  >>> x = Int('x')
8027  >>> g = Goal()
8028  >>> g.add(x > 0)
8029  >>> g.add(x < 10)
8030  >>> p(g)
8031  0.0
8032  """
8033  p = self.__eq__(other)
8034  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8035 
8036  def __call__(self, goal):
8037  """Evaluate the probe `self` in the given goal.
8038 
8039  >>> p = Probe('size')
8040  >>> x = Int('x')
8041  >>> g = Goal()
8042  >>> g.add(x > 0)
8043  >>> g.add(x < 10)
8044  >>> p(g)
8045  2.0
8046  >>> g.add(x < 20)
8047  >>> p(g)
8048  3.0
8049  >>> p = Probe('num-consts')
8050  >>> p(g)
8051  1.0
8052  >>> p = Probe('is-propositional')
8053  >>> p(g)
8054  0.0
8055  >>> p = Probe('is-qflia')
8056  >>> p(g)
8057  1.0
8058  """
8059  if z3_debug():
8060  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
8061  goal = _to_goal(goal)
8062  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8063 
8064 def is_probe(p):
8065  """Return `True` if `p` is a Z3 probe.
8066 
8067  >>> is_probe(Int('x'))
8068  False
8069  >>> is_probe(Probe('memory'))
8070  True
8071  """
8072  return isinstance(p, Probe)
8073 
8074 def _to_probe(p, ctx=None):
8075  if is_probe(p):
8076  return p
8077  else:
8078  return Probe(p, ctx)
8079 
8080 def probes(ctx=None):
8081  """Return a list of all available probes in Z3.
8082 
8083  >>> l = probes()
8084  >>> l.count('memory') == 1
8085  True
8086  """
8087  ctx = _get_ctx(ctx)
8088  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
8089 
8090 def probe_description(name, ctx=None):
8091  """Return a short description for the probe named `name`.
8092 
8093  >>> d = probe_description('memory')
8094  """
8095  ctx = _get_ctx(ctx)
8096  return Z3_probe_get_descr(ctx.ref(), name)
8097 
8099  """Display a (tabular) description of all available probes in Z3."""
8100  if in_html_mode():
8101  even = True
8102  print('<table border="1" cellpadding="2" cellspacing="0">')
8103  for p in probes():
8104  if even:
8105  print('<tr style="background-color:#CFCFCF">')
8106  even = False
8107  else:
8108  print('<tr>')
8109  even = True
8110  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
8111  print('</table>')
8112  else:
8113  for p in probes():
8114  print('%s : %s' % (p, probe_description(p)))
8115 
8116 def _probe_nary(f, args, ctx):
8117  if z3_debug():
8118  _z3_assert(len(args) > 0, "At least one argument expected")
8119  num = len(args)
8120  r = _to_probe(args[0], ctx)
8121  for i in range(num - 1):
8122  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
8123  return r
8124 
8125 def _probe_and(args, ctx):
8126  return _probe_nary(Z3_probe_and, args, ctx)
8127 
8128 def _probe_or(args, ctx):
8129  return _probe_nary(Z3_probe_or, args, ctx)
8130 
8131 def FailIf(p, ctx=None):
8132  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8133 
8134  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
8135 
8136  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8137  >>> x, y = Ints('x y')
8138  >>> g = Goal()
8139  >>> g.add(x > 0)
8140  >>> g.add(y > 0)
8141  >>> t(g)
8142  [[x > 0, y > 0]]
8143  >>> g.add(x == y + 1)
8144  >>> t(g)
8145  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8146  """
8147  p = _to_probe(p, ctx)
8148  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8149 
8150 def When(p, t, ctx=None):
8151  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8152 
8153  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8154  >>> x, y = Ints('x y')
8155  >>> g = Goal()
8156  >>> g.add(x > 0)
8157  >>> g.add(y > 0)
8158  >>> t(g)
8159  [[x > 0, y > 0]]
8160  >>> g.add(x == y + 1)
8161  >>> t(g)
8162  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8163  """
8164  p = _to_probe(p, ctx)
8165  t = _to_tactic(t, ctx)
8166  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8167 
8168 def Cond(p, t1, t2, ctx=None):
8169  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8170 
8171  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8172  """
8173  p = _to_probe(p, ctx)
8174  t1 = _to_tactic(t1, ctx)
8175  t2 = _to_tactic(t2, ctx)
8176  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8177 
8178 
8183 
8184 def simplify(a, *arguments, **keywords):
8185  """Simplify the expression `a` using the given options.
8186 
8187  This function has many options. Use `help_simplify` to obtain the complete list.
8188 
8189  >>> x = Int('x')
8190  >>> y = Int('y')
8191  >>> simplify(x + 1 + y + x + 1)
8192  2 + 2*x + y
8193  >>> simplify((x + 1)*(y + 1), som=True)
8194  1 + x + y + x*y
8195  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8196  And(Not(x == y), Not(x == 1), Not(y == 1))
8197  >>> simplify(And(x == 0, y == 1), elim_and=True)
8198  Not(Or(Not(x == 0), Not(y == 1)))
8199  """
8200  if z3_debug():
8201  _z3_assert(is_expr(a), "Z3 expression expected")
8202  if len(arguments) > 0 or len(keywords) > 0:
8203  p = args2params(arguments, keywords, a.ctx)
8204  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8205  else:
8206  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8207 
8209  """Return a string describing all options available for Z3 `simplify` procedure."""
8210  print(Z3_simplify_get_help(main_ctx().ref()))
8211 
8213  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8215 
8216 def substitute(t, *m):
8217  """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.
8218 
8219  >>> x = Int('x')
8220  >>> y = Int('y')
8221  >>> substitute(x + 1, (x, y + 1))
8222  y + 1 + 1
8223  >>> f = Function('f', IntSort(), IntSort())
8224  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8225  1 + 1
8226  """
8227  if isinstance(m, tuple):
8228  m1 = _get_args(m)
8229  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8230  m = m1
8231  if z3_debug():
8232  _z3_assert(is_expr(t), "Z3 expression expected")
8233  _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.")
8234  num = len(m)
8235  _from = (Ast * num)()
8236  _to = (Ast * num)()
8237  for i in range(num):
8238  _from[i] = m[i][0].as_ast()
8239  _to[i] = m[i][1].as_ast()
8240  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8241 
8242 def substitute_vars(t, *m):
8243  """Substitute the free variables in t with the expression in m.
8244 
8245  >>> v0 = Var(0, IntSort())
8246  >>> v1 = Var(1, IntSort())
8247  >>> x = Int('x')
8248  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8249  >>> # replace v0 with x+1 and v1 with x
8250  >>> substitute_vars(f(v0, v1), x + 1, x)
8251  f(x + 1, x)
8252  """
8253  if z3_debug():
8254  _z3_assert(is_expr(t), "Z3 expression expected")
8255  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8256  num = len(m)
8257  _to = (Ast * num)()
8258  for i in range(num):
8259  _to[i] = m[i].as_ast()
8260  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8261 
8262 def Sum(*args):
8263  """Create the sum of the Z3 expressions.
8264 
8265  >>> a, b, c = Ints('a b c')
8266  >>> Sum(a, b, c)
8267  a + b + c
8268  >>> Sum([a, b, c])
8269  a + b + c
8270  >>> A = IntVector('a', 5)
8271  >>> Sum(A)
8272  a__0 + a__1 + a__2 + a__3 + a__4
8273  """
8274  args = _get_args(args)
8275  if len(args) == 0:
8276  return 0
8277  ctx = _ctx_from_ast_arg_list(args)
8278  if ctx is None:
8279  return _reduce(lambda a, b: a + b, args, 0)
8280  args = _coerce_expr_list(args, ctx)
8281  if is_bv(args[0]):
8282  return _reduce(lambda a, b: a + b, args, 0)
8283  else:
8284  _args, sz = _to_ast_array(args)
8285  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8286 
8287 
8288 def Product(*args):
8289  """Create the product of the Z3 expressions.
8290 
8291  >>> a, b, c = Ints('a b c')
8292  >>> Product(a, b, c)
8293  a*b*c
8294  >>> Product([a, b, c])
8295  a*b*c
8296  >>> A = IntVector('a', 5)
8297  >>> Product(A)
8298  a__0*a__1*a__2*a__3*a__4
8299  """
8300  args = _get_args(args)
8301  if len(args) == 0:
8302  return 1
8303  ctx = _ctx_from_ast_arg_list(args)
8304  if ctx is None:
8305  return _reduce(lambda a, b: a * b, args, 1)
8306  args = _coerce_expr_list(args, ctx)
8307  if is_bv(args[0]):
8308  return _reduce(lambda a, b: a * b, args, 1)
8309  else:
8310  _args, sz = _to_ast_array(args)
8311  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8312 
8313 def AtMost(*args):
8314  """Create an at-most Pseudo-Boolean k constraint.
8315 
8316  >>> a, b, c = Bools('a b c')
8317  >>> f = AtMost(a, b, c, 2)
8318  """
8319  args = _get_args(args)
8320  if z3_debug():
8321  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8322  ctx = _ctx_from_ast_arg_list(args)
8323  if z3_debug():
8324  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8325  args1 = _coerce_expr_list(args[:-1], ctx)
8326  k = args[-1]
8327  _args, sz = _to_ast_array(args1)
8328  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8329 
8330 def AtLeast(*args):
8331  """Create an at-most Pseudo-Boolean k constraint.
8332 
8333  >>> a, b, c = Bools('a b c')
8334  >>> f = AtLeast(a, b, c, 2)
8335  """
8336  args = _get_args(args)
8337  if z3_debug():
8338  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8339  ctx = _ctx_from_ast_arg_list(args)
8340  if z3_debug():
8341  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8342  args1 = _coerce_expr_list(args[:-1], ctx)
8343  k = args[-1]
8344  _args, sz = _to_ast_array(args1)
8345  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8346 
8347 def _reorder_pb_arg(arg):
8348  a, b = arg
8349  if not _is_int(b) and _is_int(a):
8350  return b, a
8351  return arg
8352 
8353 def _pb_args_coeffs(args, default_ctx = None):
8354  args = _get_args_ast_list(args)
8355  if len(args) == 0:
8356  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8357  args = [_reorder_pb_arg(arg) for arg in args]
8358  args, coeffs = zip(*args)
8359  if z3_debug():
8360  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8361  ctx = _ctx_from_ast_arg_list(args)
8362  if z3_debug():
8363  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8364  args = _coerce_expr_list(args, ctx)
8365  _args, sz = _to_ast_array(args)
8366  _coeffs = (ctypes.c_int * len(coeffs))()
8367  for i in range(len(coeffs)):
8368  _z3_check_cint_overflow(coeffs[i], "coefficient")
8369  _coeffs[i] = coeffs[i]
8370  return ctx, sz, _args, _coeffs
8371 
8372 def PbLe(args, k):
8373  """Create a Pseudo-Boolean inequality k constraint.
8374 
8375  >>> a, b, c = Bools('a b c')
8376  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8377  """
8378  _z3_check_cint_overflow(k, "k")
8379  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8380  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8381 
8382 def PbGe(args, k):
8383  """Create a Pseudo-Boolean inequality k constraint.
8384 
8385  >>> a, b, c = Bools('a b c')
8386  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8387  """
8388  _z3_check_cint_overflow(k, "k")
8389  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8390  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8391 
8392 def PbEq(args, k, ctx = None):
8393  """Create a Pseudo-Boolean inequality k constraint.
8394 
8395  >>> a, b, c = Bools('a b c')
8396  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8397  """
8398  _z3_check_cint_overflow(k, "k")
8399  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8400  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8401 
8402 
8403 def solve(*args, **keywords):
8404  """Solve the constraints `*args`.
8405 
8406  This is a simple function for creating demonstrations. It creates a solver,
8407  configure it using the options in `keywords`, adds the constraints
8408  in `args`, and invokes check.
8409 
8410  >>> a = Int('a')
8411  >>> solve(a > 0, a < 2)
8412  [a = 1]
8413  """
8414  s = Solver()
8415  s.set(**keywords)
8416  s.add(*args)
8417  if keywords.get('show', False):
8418  print(s)
8419  r = s.check()
8420  if r == unsat:
8421  print("no solution")
8422  elif r == unknown:
8423  print("failed to solve")
8424  try:
8425  print(s.model())
8426  except Z3Exception:
8427  return
8428  else:
8429  print(s.model())
8430 
8431 def solve_using(s, *args, **keywords):
8432  """Solve the constraints `*args` using solver `s`.
8433 
8434  This is a simple function for creating demonstrations. It is similar to `solve`,
8435  but it uses the given solver `s`.
8436  It configures solver `s` using the options in `keywords`, adds the constraints
8437  in `args`, and invokes check.
8438  """
8439  if z3_debug():
8440  _z3_assert(isinstance(s, Solver), "Solver object expected")
8441  s.set(**keywords)
8442  s.add(*args)
8443  if keywords.get('show', False):
8444  print("Problem:")
8445  print(s)
8446  r = s.check()
8447  if r == unsat:
8448  print("no solution")
8449  elif r == unknown:
8450  print("failed to solve")
8451  try:
8452  print(s.model())
8453  except Z3Exception:
8454  return
8455  else:
8456  if keywords.get('show', False):
8457  print("Solution:")
8458  print(s.model())
8459 
8460 def prove(claim, **keywords):
8461  """Try to prove the given claim.
8462 
8463  This is a simple function for creating demonstrations. It tries to prove
8464  `claim` by showing the negation is unsatisfiable.
8465 
8466  >>> p, q = Bools('p q')
8467  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8468  proved
8469  """
8470  if z3_debug():
8471  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8472  s = Solver()
8473  s.set(**keywords)
8474  s.add(Not(claim))
8475  if keywords.get('show', False):
8476  print(s)
8477  r = s.check()
8478  if r == unsat:
8479  print("proved")
8480  elif r == unknown:
8481  print("failed to prove")
8482  print(s.model())
8483  else:
8484  print("counterexample")
8485  print(s.model())
8486 
8487 def _solve_html(*args, **keywords):
8488  """Version of function `solve` used in RiSE4Fun."""
8489  s = Solver()
8490  s.set(**keywords)
8491  s.add(*args)
8492  if keywords.get('show', False):
8493  print("<b>Problem:</b>")
8494  print(s)
8495  r = s.check()
8496  if r == unsat:
8497  print("<b>no solution</b>")
8498  elif r == unknown:
8499  print("<b>failed to solve</b>")
8500  try:
8501  print(s.model())
8502  except Z3Exception:
8503  return
8504  else:
8505  if keywords.get('show', False):
8506  print("<b>Solution:</b>")
8507  print(s.model())
8508 
8509 def _solve_using_html(s, *args, **keywords):
8510  """Version of function `solve_using` used in RiSE4Fun."""
8511  if z3_debug():
8512  _z3_assert(isinstance(s, Solver), "Solver object expected")
8513  s.set(**keywords)
8514  s.add(*args)
8515  if keywords.get('show', False):
8516  print("<b>Problem:</b>")
8517  print(s)
8518  r = s.check()
8519  if r == unsat:
8520  print("<b>no solution</b>")
8521  elif r == unknown:
8522  print("<b>failed to solve</b>")
8523  try:
8524  print(s.model())
8525  except Z3Exception:
8526  return
8527  else:
8528  if keywords.get('show', False):
8529  print("<b>Solution:</b>")
8530  print(s.model())
8531 
8532 def _prove_html(claim, **keywords):
8533  """Version of function `prove` used in RiSE4Fun."""
8534  if z3_debug():
8535  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8536  s = Solver()
8537  s.set(**keywords)
8538  s.add(Not(claim))
8539  if keywords.get('show', False):
8540  print(s)
8541  r = s.check()
8542  if r == unsat:
8543  print("<b>proved</b>")
8544  elif r == unknown:
8545  print("<b>failed to prove</b>")
8546  print(s.model())
8547  else:
8548  print("<b>counterexample</b>")
8549  print(s.model())
8550 
8551 def _dict2sarray(sorts, ctx):
8552  sz = len(sorts)
8553  _names = (Symbol * sz)()
8554  _sorts = (Sort * sz) ()
8555  i = 0
8556  for k in sorts:
8557  v = sorts[k]
8558  if z3_debug():
8559  _z3_assert(isinstance(k, str), "String expected")
8560  _z3_assert(is_sort(v), "Z3 sort expected")
8561  _names[i] = to_symbol(k, ctx)
8562  _sorts[i] = v.ast
8563  i = i + 1
8564  return sz, _names, _sorts
8565 
8566 def _dict2darray(decls, ctx):
8567  sz = len(decls)
8568  _names = (Symbol * sz)()
8569  _decls = (FuncDecl * sz) ()
8570  i = 0
8571  for k in decls:
8572  v = decls[k]
8573  if z3_debug():
8574  _z3_assert(isinstance(k, str), "String expected")
8575  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8576  _names[i] = to_symbol(k, ctx)
8577  if is_const(v):
8578  _decls[i] = v.decl().ast
8579  else:
8580  _decls[i] = v.ast
8581  i = i + 1
8582  return sz, _names, _decls
8583 
8584 
8585 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8586  """Parse a string in SMT 2.0 format using the given sorts and decls.
8587 
8588  The arguments sorts and decls are Python dictionaries used to initialize
8589  the symbol table used for the SMT 2.0 parser.
8590 
8591  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8592  [x > 0, x < 10]
8593  >>> x, y = Ints('x y')
8594  >>> f = Function('f', IntSort(), IntSort())
8595  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8596  [x + f(y) > 0]
8597  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8598  [a > 0]
8599  """
8600  ctx = _get_ctx(ctx)
8601  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8602  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8603  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8604 
8605 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8606  """Parse a file in SMT 2.0 format using the given sorts and decls.
8607 
8608  This function is similar to parse_smt2_string().
8609  """
8610  ctx = _get_ctx(ctx)
8611  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8612  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8613  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8614 
8615 
8616 
8621 
8622 
8623 # Global default rounding mode
8624 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8625 _dflt_fpsort_ebits = 11
8626 _dflt_fpsort_sbits = 53
8627 
8629  """Retrieves the global default rounding mode."""
8630  global _dflt_rounding_mode
8631  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8632  return RTZ(ctx)
8633  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8634  return RTN(ctx)
8635  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8636  return RTP(ctx)
8637  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8638  return RNE(ctx)
8639  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8640  return RNA(ctx)
8641 
8642 def set_default_rounding_mode(rm, ctx=None):
8643  global _dflt_rounding_mode
8644  if is_fprm_value(rm):
8645  _dflt_rounding_mode = rm.decl().kind()
8646  else:
8647  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8648  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8649  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8650  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8651  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8652  "illegal rounding mode")
8653  _dflt_rounding_mode = rm
8654 
8655 def get_default_fp_sort(ctx=None):
8656  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8657 
8658 def set_default_fp_sort(ebits, sbits, ctx=None):
8659  global _dflt_fpsort_ebits
8660  global _dflt_fpsort_sbits
8661  _dflt_fpsort_ebits = ebits
8662  _dflt_fpsort_sbits = sbits
8663 
8664 def _dflt_rm(ctx=None):
8665  return get_default_rounding_mode(ctx)
8666 
8667 def _dflt_fps(ctx=None):
8668  return get_default_fp_sort(ctx)
8669 
8670 def _coerce_fp_expr_list(alist, ctx):
8671  first_fp_sort = None
8672  for a in alist:
8673  if is_fp(a):
8674  if first_fp_sort is None:
8675  first_fp_sort = a.sort()
8676  elif first_fp_sort == a.sort():
8677  pass # OK, same as before
8678  else:
8679  # we saw at least 2 different float sorts; something will
8680  # throw a sort mismatch later, for now assume None.
8681  first_fp_sort = None
8682  break
8683 
8684  r = []
8685  for i in range(len(alist)):
8686  a = alist[i]
8687  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8688  r.append(FPVal(a, None, first_fp_sort, ctx))
8689  else:
8690  r.append(a)
8691  return _coerce_expr_list(r, ctx)
8692 
8693 
8694 
8695 
8697  """Floating-point sort."""
8698 
8699  def ebits(self):
8700  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8701  >>> b = FPSort(8, 24)
8702  >>> b.ebits()
8703  8
8704  """
8705  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8706 
8707  def sbits(self):
8708  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8709  >>> b = FPSort(8, 24)
8710  >>> b.sbits()
8711  24
8712  """
8713  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8714 
8715  def cast(self, val):
8716  """Try to cast `val` as a floating-point expression.
8717  >>> b = FPSort(8, 24)
8718  >>> b.cast(1.0)
8719  1
8720  >>> b.cast(1.0).sexpr()
8721  '(fp #b0 #x7f #b00000000000000000000000)'
8722  """
8723  if is_expr(val):
8724  if z3_debug():
8725  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8726  return val
8727  else:
8728  return FPVal(val, None, self, self.ctx)
8729 
8730 
8731 def Float16(ctx=None):
8732  """Floating-point 16-bit (half) sort."""
8733  ctx = _get_ctx(ctx)
8734  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8735 
8736 def FloatHalf(ctx=None):
8737  """Floating-point 16-bit (half) sort."""
8738  ctx = _get_ctx(ctx)
8739  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8740 
8741 def Float32(ctx=None):
8742  """Floating-point 32-bit (single) sort."""
8743  ctx = _get_ctx(ctx)
8744  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8745 
8746 def FloatSingle(ctx=None):
8747  """Floating-point 32-bit (single) sort."""
8748  ctx = _get_ctx(ctx)
8749  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8750 
8751 def Float64(ctx=None):
8752  """Floating-point 64-bit (double) sort."""
8753  ctx = _get_ctx(ctx)
8754  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8755 
8756 def FloatDouble(ctx=None):
8757  """Floating-point 64-bit (double) sort."""
8758  ctx = _get_ctx(ctx)
8759  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8760 
8761 def Float128(ctx=None):
8762  """Floating-point 128-bit (quadruple) sort."""
8763  ctx = _get_ctx(ctx)
8764  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8765 
8766 def FloatQuadruple(ctx=None):
8767  """Floating-point 128-bit (quadruple) sort."""
8768  ctx = _get_ctx(ctx)
8769  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8770 
8772  """"Floating-point rounding mode sort."""
8773 
8774 
8775 def is_fp_sort(s):
8776  """Return True if `s` is a Z3 floating-point sort.
8777 
8778  >>> is_fp_sort(FPSort(8, 24))
8779  True
8780  >>> is_fp_sort(IntSort())
8781  False
8782  """
8783  return isinstance(s, FPSortRef)
8784 
8786  """Return True if `s` is a Z3 floating-point rounding mode sort.
8787 
8788  >>> is_fprm_sort(FPSort(8, 24))
8789  False
8790  >>> is_fprm_sort(RNE().sort())
8791  True
8792  """
8793  return isinstance(s, FPRMSortRef)
8794 
8795 
8796 
8798  """Floating-point expressions."""
8799 
8800  def sort(self):
8801  """Return the sort of the floating-point expression `self`.
8802 
8803  >>> x = FP('1.0', FPSort(8, 24))
8804  >>> x.sort()
8805  FPSort(8, 24)
8806  >>> x.sort() == FPSort(8, 24)
8807  True
8808  """
8809  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8810 
8811  def ebits(self):
8812  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8813  >>> b = FPSort(8, 24)
8814  >>> b.ebits()
8815  8
8816  """
8817  return self.sort().ebits();
8818 
8819  def sbits(self):
8820  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8821  >>> b = FPSort(8, 24)
8822  >>> b.sbits()
8823  24
8824  """
8825  return self.sort().sbits();
8826 
8827  def as_string(self):
8828  """Return a Z3 floating point expression as a Python string."""
8829  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8830 
8831  def __le__(self, other):
8832  return fpLEQ(self, other, self.ctx)
8833 
8834  def __lt__(self, other):
8835  return fpLT(self, other, self.ctx)
8836 
8837  def __ge__(self, other):
8838  return fpGEQ(self, other, self.ctx)
8839 
8840  def __gt__(self, other):
8841  return fpGT(self, other, self.ctx)
8842 
8843  def __add__(self, other):
8844  """Create the Z3 expression `self + other`.
8845 
8846  >>> x = FP('x', FPSort(8, 24))
8847  >>> y = FP('y', FPSort(8, 24))
8848  >>> x + y
8849  x + y
8850  >>> (x + y).sort()
8851  FPSort(8, 24)
8852  """
8853  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8854  return fpAdd(_dflt_rm(), a, b, self.ctx)
8855 
8856  def __radd__(self, other):
8857  """Create the Z3 expression `other + self`.
8858 
8859  >>> x = FP('x', FPSort(8, 24))
8860  >>> 10 + x
8861  1.25*(2**3) + x
8862  """
8863  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8864  return fpAdd(_dflt_rm(), a, b, self.ctx)
8865 
8866  def __sub__(self, other):
8867  """Create the Z3 expression `self - other`.
8868 
8869  >>> x = FP('x', FPSort(8, 24))
8870  >>> y = FP('y', FPSort(8, 24))
8871  >>> x - y
8872  x - y
8873  >>> (x - y).sort()
8874  FPSort(8, 24)
8875  """
8876  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8877  return fpSub(_dflt_rm(), a, b, self.ctx)
8878 
8879  def __rsub__(self, other):
8880  """Create the Z3 expression `other - self`.
8881 
8882  >>> x = FP('x', FPSort(8, 24))
8883  >>> 10 - x
8884  1.25*(2**3) - x
8885  """
8886  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8887  return fpSub(_dflt_rm(), a, b, self.ctx)
8888 
8889  def __mul__(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 fpMul(_dflt_rm(), a, b, self.ctx)
8903 
8904  def __rmul__(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 fpMul(_dflt_rm(), a, b, self.ctx)
8916 
8917  def __pos__(self):
8918  """Create the Z3 expression `+self`."""
8919  return self
8920 
8921  def __neg__(self):
8922  """Create the Z3 expression `-self`.
8923 
8924  >>> x = FP('x', Float32())
8925  >>> -x
8926  -x
8927  """
8928  return fpNeg(self)
8929 
8930  def __div__(self, other):
8931  """Create the Z3 expression `self / other`.
8932 
8933  >>> x = FP('x', FPSort(8, 24))
8934  >>> y = FP('y', FPSort(8, 24))
8935  >>> x / y
8936  x / y
8937  >>> (x / y).sort()
8938  FPSort(8, 24)
8939  >>> 10 / y
8940  1.25*(2**3) / y
8941  """
8942  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8943  return fpDiv(_dflt_rm(), a, b, self.ctx)
8944 
8945  def __rdiv__(self, other):
8946  """Create the Z3 expression `other / self`.
8947 
8948  >>> x = FP('x', FPSort(8, 24))
8949  >>> y = FP('y', FPSort(8, 24))
8950  >>> x / y
8951  x / y
8952  >>> x / 10
8953  x / 1.25*(2**3)
8954  """
8955  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8956  return fpDiv(_dflt_rm(), a, b, self.ctx)
8957 
8958  def __truediv__(self, other):
8959  """Create the Z3 expression division `self / other`."""
8960  return self.__div__(other)
8961 
8962  def __rtruediv__(self, other):
8963  """Create the Z3 expression division `other / self`."""
8964  return self.__rdiv__(other)
8965 
8966  def __mod__(self, other):
8967  """Create the Z3 expression mod `self % other`."""
8968  return fpRem(self, other)
8969 
8970  def __rmod__(self, other):
8971  """Create the Z3 expression mod `other % self`."""
8972  return fpRem(other, self)
8973 
8975  """Floating-point rounding mode expressions"""
8976 
8977  def as_string(self):
8978  """Return a Z3 floating point expression as a Python string."""
8979  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8980 
8981 
8983  ctx = _get_ctx(ctx)
8984  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8985 
8986 def RNE (ctx=None):
8987  ctx = _get_ctx(ctx)
8988  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8989 
8991  ctx = _get_ctx(ctx)
8992  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8993 
8994 def RNA (ctx=None):
8995  ctx = _get_ctx(ctx)
8996  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8997 
8998 def RoundTowardPositive(ctx=None):
8999  ctx = _get_ctx(ctx)
9000  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9001 
9002 def RTP(ctx=None):
9003  ctx = _get_ctx(ctx)
9004  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9005 
9006 def RoundTowardNegative(ctx=None):
9007  ctx = _get_ctx(ctx)
9008  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9009 
9010 def RTN(ctx=None):
9011  ctx = _get_ctx(ctx)
9012  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9013 
9014 def RoundTowardZero(ctx=None):
9015  ctx = _get_ctx(ctx)
9016  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9017 
9018 def RTZ(ctx=None):
9019  ctx = _get_ctx(ctx)
9020  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9021 
9022 def is_fprm(a):
9023  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9024 
9025  >>> rm = RNE()
9026  >>> is_fprm(rm)
9027  True
9028  >>> rm = 1.0
9029  >>> is_fprm(rm)
9030  False
9031  """
9032  return isinstance(a, FPRMRef)
9033 
9035  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9036  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9037 
9038 
9039 
9041  """The sign of the numeral.
9042 
9043  >>> x = FPVal(+1.0, FPSort(8, 24))
9044  >>> x.sign()
9045  False
9046  >>> x = FPVal(-1.0, FPSort(8, 24))
9047  >>> x.sign()
9048  True
9049  """
9050  def sign(self):
9051  l = (ctypes.c_int)()
9052  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
9053  raise Z3Exception("error retrieving the sign of a numeral.")
9054  return l.value != 0
9055 
9056  """The sign of a floating-point numeral as a bit-vector expression.
9057 
9058  Remark: NaN's are invalid arguments.
9059  """
9060  def sign_as_bv(self):
9061  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9062 
9063  """The significand of the numeral.
9064 
9065  >>> x = FPVal(2.5, FPSort(8, 24))
9066  >>> x.significand()
9067  1.25
9068  """
9069  def significand(self):
9070  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
9071 
9072  """The significand of the numeral as a long.
9073 
9074  >>> x = FPVal(2.5, FPSort(8, 24))
9075  >>> x.significand_as_long()
9076  1.25
9077  """
9079  ptr = (ctypes.c_ulonglong * 1)()
9080  if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
9081  raise Z3Exception("error retrieving the significand of a numeral.")
9082  return ptr[0]
9083 
9084  """The significand of the numeral as a bit-vector expression.
9085 
9086  Remark: NaN are invalid arguments.
9087  """
9089  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
9090 
9091  """The exponent of the numeral.
9092 
9093  >>> x = FPVal(2.5, FPSort(8, 24))
9094  >>> x.exponent()
9095  1
9096  """
9097  def exponent(self, biased=True):
9098  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
9099 
9100  """The exponent of the numeral as a long.
9101 
9102  >>> x = FPVal(2.5, FPSort(8, 24))
9103  >>> x.exponent_as_long()
9104  1
9105  """
9106  def exponent_as_long(self, biased=True):
9107  ptr = (ctypes.c_longlong * 1)()
9108  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
9109  raise Z3Exception("error retrieving the exponent of a numeral.")
9110  return ptr[0]
9111 
9112  """The exponent of the numeral as a bit-vector expression.
9113 
9114  Remark: NaNs are invalid arguments.
9115  """
9116  def exponent_as_bv(self, biased=True):
9117  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
9118 
9119  """Indicates whether the numeral is a NaN."""
9120  def isNaN(self):
9121  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
9122 
9123  """Indicates whether the numeral is +oo or -oo."""
9124  def isInf(self):
9125  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
9126 
9127  """Indicates whether the numeral is +zero or -zero."""
9128  def isZero(self):
9129  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
9130 
9131  """Indicates whether the numeral is normal."""
9132  def isNormal(self):
9133  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
9134 
9135  """Indicates whether the numeral is subnormal."""
9136  def isSubnormal(self):
9137  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
9138 
9139  """Indicates whether the numeral is positive."""
9140  def isPositive(self):
9141  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
9142 
9143  """Indicates whether the numeral is negative."""
9144  def isNegative(self):
9145  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
9146 
9147  """
9148  The string representation of the numeral.
9149 
9150  >>> x = FPVal(20, FPSort(8, 24))
9151  >>> x.as_string()
9152  1.25*(2**4)
9153  """
9154  def as_string(self):
9155  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
9156  return ("FPVal(%s, %s)" % (s, self.sort()))
9157 
9158 def is_fp(a):
9159  """Return `True` if `a` is a Z3 floating-point expression.
9160 
9161  >>> b = FP('b', FPSort(8, 24))
9162  >>> is_fp(b)
9163  True
9164  >>> is_fp(b + 1.0)
9165  True
9166  >>> is_fp(Int('x'))
9167  False
9168  """
9169  return isinstance(a, FPRef)
9170 
9172  """Return `True` if `a` is a Z3 floating-point numeral value.
9173 
9174  >>> b = FP('b', FPSort(8, 24))
9175  >>> is_fp_value(b)
9176  False
9177  >>> b = FPVal(1.0, FPSort(8, 24))
9178  >>> b
9179  1
9180  >>> is_fp_value(b)
9181  True
9182  """
9183  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9184 
9185 def FPSort(ebits, sbits, ctx=None):
9186  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9187 
9188  >>> Single = FPSort(8, 24)
9189  >>> Double = FPSort(11, 53)
9190  >>> Single
9191  FPSort(8, 24)
9192  >>> x = Const('x', Single)
9193  >>> eq(x, FP('x', FPSort(8, 24)))
9194  True
9195  """
9196  ctx = _get_ctx(ctx)
9197  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9198 
9199 def _to_float_str(val, exp=0):
9200  if isinstance(val, float):
9201  if math.isnan(val):
9202  res = "NaN"
9203  elif val == 0.0:
9204  sone = math.copysign(1.0, val)
9205  if sone < 0.0:
9206  return "-0.0"
9207  else:
9208  return "+0.0"
9209  elif val == float("+inf"):
9210  res = "+oo"
9211  elif val == float("-inf"):
9212  res = "-oo"
9213  else:
9214  v = val.as_integer_ratio()
9215  num = v[0]
9216  den = v[1]
9217  rvs = str(num) + '/' + str(den)
9218  res = rvs + 'p' + _to_int_str(exp)
9219  elif isinstance(val, bool):
9220  if val:
9221  res = "1.0"
9222  else:
9223  res = "0.0"
9224  elif _is_int(val):
9225  res = str(val)
9226  elif isinstance(val, str):
9227  inx = val.find('*(2**')
9228  if inx == -1:
9229  res = val
9230  elif val[-1] == ')':
9231  res = val[0:inx]
9232  exp = str(int(val[inx+5:-1]) + int(exp))
9233  else:
9234  _z3_assert(False, "String does not have floating-point numeral form.")
9235  elif z3_debug():
9236  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9237  if exp == 0:
9238  return res
9239  else:
9240  return res + 'p' + exp
9241 
9242 
9243 def fpNaN(s):
9244  """Create a Z3 floating-point NaN term.
9245 
9246  >>> s = FPSort(8, 24)
9247  >>> set_fpa_pretty(True)
9248  >>> fpNaN(s)
9249  NaN
9250  >>> pb = get_fpa_pretty()
9251  >>> set_fpa_pretty(False)
9252  >>> fpNaN(s)
9253  fpNaN(FPSort(8, 24))
9254  >>> set_fpa_pretty(pb)
9255  """
9256  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9257  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9258 
9260  """Create a Z3 floating-point +oo term.
9261 
9262  >>> s = FPSort(8, 24)
9263  >>> pb = get_fpa_pretty()
9264  >>> set_fpa_pretty(True)
9265  >>> fpPlusInfinity(s)
9266  +oo
9267  >>> set_fpa_pretty(False)
9268  >>> fpPlusInfinity(s)
9269  fpPlusInfinity(FPSort(8, 24))
9270  >>> set_fpa_pretty(pb)
9271  """
9272  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9273  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9274 
9276  """Create a Z3 floating-point -oo term."""
9277  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9278  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9279 
9280 def fpInfinity(s, negative):
9281  """Create a Z3 floating-point +oo or -oo term."""
9282  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9283  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9284  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9285 
9286 def fpPlusZero(s):
9287  """Create a Z3 floating-point +0.0 term."""
9288  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9289  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9290 
9292  """Create a Z3 floating-point -0.0 term."""
9293  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9294  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9295 
9296 def fpZero(s, negative):
9297  """Create a Z3 floating-point +0.0 or -0.0 term."""
9298  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9299  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9300  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9301 
9302 def FPVal(sig, exp=None, fps=None, ctx=None):
9303  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9304 
9305  >>> v = FPVal(20.0, FPSort(8, 24))
9306  >>> v
9307  1.25*(2**4)
9308  >>> print("0x%.8x" % v.exponent_as_long(False))
9309  0x00000004
9310  >>> v = FPVal(2.25, FPSort(8, 24))
9311  >>> v
9312  1.125*(2**1)
9313  >>> v = FPVal(-2.25, FPSort(8, 24))
9314  >>> v
9315  -1.125*(2**1)
9316  >>> FPVal(-0.0, FPSort(8, 24))
9317  -0.0
9318  >>> FPVal(0.0, FPSort(8, 24))
9319  +0.0
9320  >>> FPVal(+0.0, FPSort(8, 24))
9321  +0.0
9322  """
9323  ctx = _get_ctx(ctx)
9324  if is_fp_sort(exp):
9325  fps = exp
9326  exp = None
9327  elif fps is None:
9328  fps = _dflt_fps(ctx)
9329  _z3_assert(is_fp_sort(fps), "sort mismatch")
9330  if exp is None:
9331  exp = 0
9332  val = _to_float_str(sig)
9333  if val == "NaN" or val == "nan":
9334  return fpNaN(fps)
9335  elif val == "-0.0":
9336  return fpMinusZero(fps)
9337  elif val == "0.0" or val == "+0.0":
9338  return fpPlusZero(fps)
9339  elif val == "+oo" or val == "+inf" or val == "+Inf":
9340  return fpPlusInfinity(fps)
9341  elif val == "-oo" or val == "-inf" or val == "-Inf":
9342  return fpMinusInfinity(fps)
9343  else:
9344  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9345 
9346 def FP(name, fpsort, ctx=None):
9347  """Return a floating-point constant named `name`.
9348  `fpsort` is the floating-point sort.
9349  If `ctx=None`, then the global context is used.
9350 
9351  >>> x = FP('x', FPSort(8, 24))
9352  >>> is_fp(x)
9353  True
9354  >>> x.ebits()
9355  8
9356  >>> x.sort()
9357  FPSort(8, 24)
9358  >>> word = FPSort(8, 24)
9359  >>> x2 = FP('x', word)
9360  >>> eq(x, x2)
9361  True
9362  """
9363  if isinstance(fpsort, FPSortRef) and ctx is None:
9364  ctx = fpsort.ctx
9365  else:
9366  ctx = _get_ctx(ctx)
9367  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9368 
9369 def FPs(names, fpsort, ctx=None):
9370  """Return an array of floating-point constants.
9371 
9372  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9373  >>> x.sort()
9374  FPSort(8, 24)
9375  >>> x.sbits()
9376  24
9377  >>> x.ebits()
9378  8
9379  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9380  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9381  """
9382  ctx = _get_ctx(ctx)
9383  if isinstance(names, str):
9384  names = names.split(" ")
9385  return [FP(name, fpsort, ctx) for name in names]
9386 
9387 def fpAbs(a, ctx=None):
9388  """Create a Z3 floating-point absolute value expression.
9389 
9390  >>> s = FPSort(8, 24)
9391  >>> rm = RNE()
9392  >>> x = FPVal(1.0, s)
9393  >>> fpAbs(x)
9394  fpAbs(1)
9395  >>> y = FPVal(-20.0, s)
9396  >>> y
9397  -1.25*(2**4)
9398  >>> fpAbs(y)
9399  fpAbs(-1.25*(2**4))
9400  >>> fpAbs(-1.25*(2**4))
9401  fpAbs(-1.25*(2**4))
9402  >>> fpAbs(x).sort()
9403  FPSort(8, 24)
9404  """
9405  ctx = _get_ctx(ctx)
9406  [a] = _coerce_fp_expr_list([a], ctx)
9407  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9408 
9409 def fpNeg(a, ctx=None):
9410  """Create a Z3 floating-point addition expression.
9411 
9412  >>> s = FPSort(8, 24)
9413  >>> rm = RNE()
9414  >>> x = FP('x', s)
9415  >>> fpNeg(x)
9416  -x
9417  >>> fpNeg(x).sort()
9418  FPSort(8, 24)
9419  """
9420  ctx = _get_ctx(ctx)
9421  [a] = _coerce_fp_expr_list([a], ctx)
9422  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9423 
9424 def _mk_fp_unary(f, rm, a, ctx):
9425  ctx = _get_ctx(ctx)
9426  [a] = _coerce_fp_expr_list([a], ctx)
9427  if z3_debug():
9428  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9429  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9430  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9431 
9432 def _mk_fp_unary_pred(f, a, ctx):
9433  ctx = _get_ctx(ctx)
9434  [a] = _coerce_fp_expr_list([a], ctx)
9435  if z3_debug():
9436  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9437  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9438 
9439 def _mk_fp_bin(f, rm, a, b, ctx):
9440  ctx = _get_ctx(ctx)
9441  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9442  if z3_debug():
9443  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9444  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9445  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9446 
9447 def _mk_fp_bin_norm(f, a, b, ctx):
9448  ctx = _get_ctx(ctx)
9449  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9450  if z3_debug():
9451  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9452  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9453 
9454 def _mk_fp_bin_pred(f, a, b, ctx):
9455  ctx = _get_ctx(ctx)
9456  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9457  if z3_debug():
9458  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9459  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9460 
9461 def _mk_fp_tern(f, rm, a, b, c, ctx):
9462  ctx = _get_ctx(ctx)
9463  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9464  if z3_debug():
9465  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9466  _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")
9467  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9468 
9469 def fpAdd(rm, a, b, ctx=None):
9470  """Create a Z3 floating-point addition expression.
9471 
9472  >>> s = FPSort(8, 24)
9473  >>> rm = RNE()
9474  >>> x = FP('x', s)
9475  >>> y = FP('y', s)
9476  >>> fpAdd(rm, x, y)
9477  fpAdd(RNE(), x, y)
9478  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9479  x + y
9480  >>> fpAdd(rm, x, y).sort()
9481  FPSort(8, 24)
9482  """
9483  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9484 
9485 def fpSub(rm, a, b, ctx=None):
9486  """Create a Z3 floating-point subtraction expression.
9487 
9488  >>> s = FPSort(8, 24)
9489  >>> rm = RNE()
9490  >>> x = FP('x', s)
9491  >>> y = FP('y', s)
9492  >>> fpSub(rm, x, y)
9493  fpSub(RNE(), x, y)
9494  >>> fpSub(rm, x, y).sort()
9495  FPSort(8, 24)
9496  """
9497  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9498 
9499 def fpMul(rm, a, b, ctx=None):
9500  """Create a Z3 floating-point multiplication expression.
9501 
9502  >>> s = FPSort(8, 24)
9503  >>> rm = RNE()
9504  >>> x = FP('x', s)
9505  >>> y = FP('y', s)
9506  >>> fpMul(rm, x, y)
9507  fpMul(RNE(), x, y)
9508  >>> fpMul(rm, x, y).sort()
9509  FPSort(8, 24)
9510  """
9511  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9512 
9513 def fpDiv(rm, a, b, ctx=None):
9514  """Create a Z3 floating-point division expression.
9515 
9516  >>> s = FPSort(8, 24)
9517  >>> rm = RNE()
9518  >>> x = FP('x', s)
9519  >>> y = FP('y', s)
9520  >>> fpDiv(rm, x, y)
9521  fpDiv(RNE(), x, y)
9522  >>> fpDiv(rm, x, y).sort()
9523  FPSort(8, 24)
9524  """
9525  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9526 
9527 def fpRem(a, b, ctx=None):
9528  """Create a Z3 floating-point remainder expression.
9529 
9530  >>> s = FPSort(8, 24)
9531  >>> x = FP('x', s)
9532  >>> y = FP('y', s)
9533  >>> fpRem(x, y)
9534  fpRem(x, y)
9535  >>> fpRem(x, y).sort()
9536  FPSort(8, 24)
9537  """
9538  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9539 
9540 def fpMin(a, b, ctx=None):
9541  """Create a Z3 floating-point minimum expression.
9542 
9543  >>> s = FPSort(8, 24)
9544  >>> rm = RNE()
9545  >>> x = FP('x', s)
9546  >>> y = FP('y', s)
9547  >>> fpMin(x, y)
9548  fpMin(x, y)
9549  >>> fpMin(x, y).sort()
9550  FPSort(8, 24)
9551  """
9552  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9553 
9554 def fpMax(a, b, ctx=None):
9555  """Create a Z3 floating-point maximum expression.
9556 
9557  >>> s = FPSort(8, 24)
9558  >>> rm = RNE()
9559  >>> x = FP('x', s)
9560  >>> y = FP('y', s)
9561  >>> fpMax(x, y)
9562  fpMax(x, y)
9563  >>> fpMax(x, y).sort()
9564  FPSort(8, 24)
9565  """
9566  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9567 
9568 def fpFMA(rm, a, b, c, ctx=None):
9569  """Create a Z3 floating-point fused multiply-add expression.
9570  """
9571  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9572 
9573 def fpSqrt(rm, a, ctx=None):
9574  """Create a Z3 floating-point square root expression.
9575  """
9576  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9577 
9578 def fpRoundToIntegral(rm, a, ctx=None):
9579  """Create a Z3 floating-point roundToIntegral expression.
9580  """
9581  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9582 
9583 def fpIsNaN(a, ctx=None):
9584  """Create a Z3 floating-point isNaN expression.
9585 
9586  >>> s = FPSort(8, 24)
9587  >>> x = FP('x', s)
9588  >>> y = FP('y', s)
9589  >>> fpIsNaN(x)
9590  fpIsNaN(x)
9591  """
9592  return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
9593 
9594 def fpIsInf(a, ctx=None):
9595  """Create a Z3 floating-point isInfinite expression.
9596 
9597  >>> s = FPSort(8, 24)
9598  >>> x = FP('x', s)
9599  >>> fpIsInf(x)
9600  fpIsInf(x)
9601  """
9602  return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
9603 
9604 def fpIsZero(a, ctx=None):
9605  """Create a Z3 floating-point isZero expression.
9606  """
9607  return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
9608 
9609 def fpIsNormal(a, ctx=None):
9610  """Create a Z3 floating-point isNormal expression.
9611  """
9612  return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
9613 
9614 def fpIsSubnormal(a, ctx=None):
9615  """Create a Z3 floating-point isSubnormal expression.
9616  """
9617  return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
9618 
9619 def fpIsNegative(a, ctx=None):
9620  """Create a Z3 floating-point isNegative expression.
9621  """
9622  return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
9623 
9624 def fpIsPositive(a, ctx=None):
9625  """Create a Z3 floating-point isPositive expression.
9626  """
9627  return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
9628 
9629 def _check_fp_args(a, b):
9630  if z3_debug():
9631  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9632 
9633 def fpLT(a, b, ctx=None):
9634  """Create the Z3 floating-point expression `other < self`.
9635 
9636  >>> x, y = FPs('x y', FPSort(8, 24))
9637  >>> fpLT(x, y)
9638  x < y
9639  >>> (x < y).sexpr()
9640  '(fp.lt x y)'
9641  """
9642  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9643 
9644 def fpLEQ(a, b, ctx=None):
9645  """Create the Z3 floating-point expression `other <= self`.
9646 
9647  >>> x, y = FPs('x y', FPSort(8, 24))
9648  >>> fpLEQ(x, y)
9649  x <= y
9650  >>> (x <= y).sexpr()
9651  '(fp.leq x y)'
9652  """
9653  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9654 
9655 def fpGT(a, b, ctx=None):
9656  """Create the Z3 floating-point expression `other > self`.
9657 
9658  >>> x, y = FPs('x y', FPSort(8, 24))
9659  >>> fpGT(x, y)
9660  x > y
9661  >>> (x > y).sexpr()
9662  '(fp.gt x y)'
9663  """
9664  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9665 
9666 def fpGEQ(a, b, ctx=None):
9667  """Create the Z3 floating-point expression `other >= self`.
9668 
9669  >>> x, y = FPs('x y', FPSort(8, 24))
9670  >>> fpGEQ(x, y)
9671  x >= y
9672  >>> (x >= y).sexpr()
9673  '(fp.geq x y)'
9674  """
9675  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9676 
9677 def fpEQ(a, b, ctx=None):
9678  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9679 
9680  >>> x, y = FPs('x y', FPSort(8, 24))
9681  >>> fpEQ(x, y)
9682  fpEQ(x, y)
9683  >>> fpEQ(x, y).sexpr()
9684  '(fp.eq x y)'
9685  """
9686  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9687 
9688 def fpNEQ(a, b, ctx=None):
9689  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9690 
9691  >>> x, y = FPs('x y', FPSort(8, 24))
9692  >>> fpNEQ(x, y)
9693  Not(fpEQ(x, y))
9694  >>> (x != y).sexpr()
9695  '(distinct x y)'
9696  """
9697  return Not(fpEQ(a, b, ctx))
9698 
9699 def fpFP(sgn, exp, sig, ctx=None):
9700  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9701 
9702  >>> s = FPSort(8, 24)
9703  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9704  >>> print(x)
9705  fpFP(1, 127, 4194304)
9706  >>> xv = FPVal(-1.5, s)
9707  >>> print(xv)
9708  -1.5
9709  >>> slvr = Solver()
9710  >>> slvr.add(fpEQ(x, xv))
9711  >>> slvr.check()
9712  sat
9713  >>> xv = FPVal(+1.5, s)
9714  >>> print(xv)
9715  1.5
9716  >>> slvr = Solver()
9717  >>> slvr.add(fpEQ(x, xv))
9718  >>> slvr.check()
9719  unsat
9720  """
9721  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9722  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9723  ctx = _get_ctx(ctx)
9724  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9725  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9726 
9727 def fpToFP(a1, a2=None, a3=None, ctx=None):
9728  """Create a Z3 floating-point conversion expression from other term sorts
9729  to floating-point.
9730 
9731  From a bit-vector term in IEEE 754-2008 format:
9732  >>> x = FPVal(1.0, Float32())
9733  >>> x_bv = fpToIEEEBV(x)
9734  >>> simplify(fpToFP(x_bv, Float32()))
9735  1
9736 
9737  From a floating-point term with different precision:
9738  >>> x = FPVal(1.0, Float32())
9739  >>> x_db = fpToFP(RNE(), x, Float64())
9740  >>> x_db.sort()
9741  FPSort(11, 53)
9742 
9743  From a real term:
9744  >>> x_r = RealVal(1.5)
9745  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9746  1.5
9747 
9748  From a signed bit-vector term:
9749  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9750  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9751  -1.25*(2**2)
9752  """
9753  ctx = _get_ctx(ctx)
9754  if is_bv(a1) and is_fp_sort(a2):
9755  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9756  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9757  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9758  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9759  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9760  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9761  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9762  else:
9763  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9764 
9765 def fpBVToFP(v, sort, ctx=None):
9766  """Create a Z3 floating-point conversion expression that represents the
9767  conversion from a bit-vector term to a floating-point term.
9768 
9769  >>> x_bv = BitVecVal(0x3F800000, 32)
9770  >>> x_fp = fpBVToFP(x_bv, Float32())
9771  >>> x_fp
9772  fpToFP(1065353216)
9773  >>> simplify(x_fp)
9774  1
9775  """
9776  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9777  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9778  ctx = _get_ctx(ctx)
9779  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9780 
9781 def fpFPToFP(rm, v, sort, ctx=None):
9782  """Create a Z3 floating-point conversion expression that represents the
9783  conversion from a floating-point term to a floating-point term of different precision.
9784 
9785  >>> x_sgl = FPVal(1.0, Float32())
9786  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9787  >>> x_dbl
9788  fpToFP(RNE(), 1)
9789  >>> simplify(x_dbl)
9790  1
9791  >>> x_dbl.sort()
9792  FPSort(11, 53)
9793  """
9794  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9795  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9796  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9797  ctx = _get_ctx(ctx)
9798  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9799 
9800 def fpRealToFP(rm, v, sort, ctx=None):
9801  """Create a Z3 floating-point conversion expression that represents the
9802  conversion from a real term to a floating-point term.
9803 
9804  >>> x_r = RealVal(1.5)
9805  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9806  >>> x_fp
9807  fpToFP(RNE(), 3/2)
9808  >>> simplify(x_fp)
9809  1.5
9810  """
9811  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9812  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9813  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9814  ctx = _get_ctx(ctx)
9815  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9816 
9817 def fpSignedToFP(rm, v, sort, ctx=None):
9818  """Create a Z3 floating-point conversion expression that represents the
9819  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9820 
9821  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9822  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9823  >>> x_fp
9824  fpToFP(RNE(), 4294967291)
9825  >>> simplify(x_fp)
9826  -1.25*(2**2)
9827  """
9828  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9829  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9830  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9831  ctx = _get_ctx(ctx)
9832  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9833 
9834 def fpUnsignedToFP(rm, v, sort, ctx=None):
9835  """Create a Z3 floating-point conversion expression that represents the
9836  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9837 
9838  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9839  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9840  >>> x_fp
9841  fpToFPUnsigned(RNE(), 4294967291)
9842  >>> simplify(x_fp)
9843  1*(2**32)
9844  """
9845  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9846  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9847  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9848  ctx = _get_ctx(ctx)
9849  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9850 
9851 def fpToFPUnsigned(rm, x, s, ctx=None):
9852  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9853  if z3_debug():
9854  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9855  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9856  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9857  ctx = _get_ctx(ctx)
9858  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9859 
9860 def fpToSBV(rm, x, s, ctx=None):
9861  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9862 
9863  >>> x = FP('x', FPSort(8, 24))
9864  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9865  >>> print(is_fp(x))
9866  True
9867  >>> print(is_bv(y))
9868  True
9869  >>> print(is_fp(y))
9870  False
9871  >>> print(is_bv(x))
9872  False
9873  """
9874  if z3_debug():
9875  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9876  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9877  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9878  ctx = _get_ctx(ctx)
9879  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9880 
9881 def fpToUBV(rm, x, s, ctx=None):
9882  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9883 
9884  >>> x = FP('x', FPSort(8, 24))
9885  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9886  >>> print(is_fp(x))
9887  True
9888  >>> print(is_bv(y))
9889  True
9890  >>> print(is_fp(y))
9891  False
9892  >>> print(is_bv(x))
9893  False
9894  """
9895  if z3_debug():
9896  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9897  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9898  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9899  ctx = _get_ctx(ctx)
9900  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9901 
9902 def fpToReal(x, ctx=None):
9903  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9904 
9905  >>> x = FP('x', FPSort(8, 24))
9906  >>> y = fpToReal(x)
9907  >>> print(is_fp(x))
9908  True
9909  >>> print(is_real(y))
9910  True
9911  >>> print(is_fp(y))
9912  False
9913  >>> print(is_real(x))
9914  False
9915  """
9916  if z3_debug():
9917  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9918  ctx = _get_ctx(ctx)
9919  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9920 
9921 def fpToIEEEBV(x, ctx=None):
9922  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9923 
9924  The size of the resulting bit-vector is automatically determined.
9925 
9926  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9927  knows only one NaN and it will always produce the same bit-vector representation of
9928  that NaN.
9929 
9930  >>> x = FP('x', FPSort(8, 24))
9931  >>> y = fpToIEEEBV(x)
9932  >>> print(is_fp(x))
9933  True
9934  >>> print(is_bv(y))
9935  True
9936  >>> print(is_fp(y))
9937  False
9938  >>> print(is_bv(x))
9939  False
9940  """
9941  if z3_debug():
9942  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9943  ctx = _get_ctx(ctx)
9944  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9945 
9946 
9947 
9948 
9953 
9955  """Sequence sort."""
9956 
9957  def is_string(self):
9958  """Determine if sort is a string
9959  >>> s = StringSort()
9960  >>> s.is_string()
9961  True
9962  >>> s = SeqSort(IntSort())
9963  >>> s.is_string()
9964  False
9965  """
9966  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9967 
9968  def basis(self):
9969  return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
9970 
9971 
9972 def StringSort(ctx=None):
9973  """Create a string sort
9974  >>> s = StringSort()
9975  >>> print(s)
9976  String
9977  """
9978  ctx = _get_ctx(ctx)
9979  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9980 
9981 
9982 def SeqSort(s):
9983  """Create a sequence sort over elements provided in the argument
9984  >>> s = SeqSort(IntSort())
9985  >>> s == Unit(IntVal(1)).sort()
9986  True
9987  """
9988  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9989 
9991  """Sequence expression."""
9992 
9993  def sort(self):
9994  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9995 
9996  def __add__(self, other):
9997  return Concat(self, other)
9998 
9999  def __radd__(self, other):
10000  return Concat(other, self)
10001 
10002  def __getitem__(self, i):
10003  if _is_int(i):
10004  i = IntVal(i, self.ctx)
10005  return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
10006 
10007  def at(self, i):
10008  if _is_int(i):
10009  i = IntVal(i, self.ctx)
10010  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
10011 
10012  def is_string(self):
10013  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
10014 
10015  def is_string_value(self):
10016  return Z3_is_string(self.ctx_ref(), self.as_ast())
10017 
10018  def as_string(self):
10019  """Return a string representation of sequence expression."""
10020  if self.is_string_value():
10021  return Z3_get_string(self.ctx_ref(), self.as_ast())
10022  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10023 
10024  def __le__(self, other):
10025  return SeqRef(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
10026 
10027  def __lt__(self, other):
10028  return SeqRef(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
10029 
10030  def __ge__(self, other):
10031  return SeqRef(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
10032 
10033  def __gt__(self, other):
10034  return SeqRef(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
10035 
10036 
10037 def _coerce_seq(s, ctx=None):
10038  if isinstance(s, str):
10039  ctx = _get_ctx(ctx)
10040  s = StringVal(s, ctx)
10041  if not is_expr(s):
10042  raise Z3Exception("Non-expression passed as a sequence")
10043  if not is_seq(s):
10044  raise Z3Exception("Non-sequence passed as a sequence")
10045  return s
10046 
10047 def _get_ctx2(a, b, ctx=None):
10048  if is_expr(a):
10049  return a.ctx
10050  if is_expr(b):
10051  return b.ctx
10052  if ctx is None:
10053  ctx = main_ctx()
10054  return ctx
10055 
10056 def is_seq(a):
10057  """Return `True` if `a` is a Z3 sequence expression.
10058  >>> print (is_seq(Unit(IntVal(0))))
10059  True
10060  >>> print (is_seq(StringVal("abc")))
10061  True
10062  """
10063  return isinstance(a, SeqRef)
10064 
10065 def is_string(a):
10066  """Return `True` if `a` is a Z3 string expression.
10067  >>> print (is_string(StringVal("ab")))
10068  True
10069  """
10070  return isinstance(a, SeqRef) and a.is_string()
10071 
10073  """return 'True' if 'a' is a Z3 string constant expression.
10074  >>> print (is_string_value(StringVal("a")))
10075  True
10076  >>> print (is_string_value(StringVal("a") + StringVal("b")))
10077  False
10078  """
10079  return isinstance(a, SeqRef) and a.is_string_value()
10080 
10081 
10082 def StringVal(s, ctx=None):
10083  """create a string expression"""
10084  ctx = _get_ctx(ctx)
10085  return SeqRef(Z3_mk_lstring(ctx.ref(), len(s), s), ctx)
10086 
10087 def String(name, ctx=None):
10088  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10089 
10090  >>> x = String('x')
10091  """
10092  ctx = _get_ctx(ctx)
10093  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10094 
10095 def Strings(names, ctx=None):
10096  """Return string constants"""
10097  ctx = _get_ctx(ctx)
10098  if isinstance(names, str):
10099  names = names.split(" ")
10100  return [String(name, ctx) for name in names]
10101 
10102 def SubString(s, offset, length):
10103  """Extract substring or subsequence starting at offset"""
10104  return Extract(s, offset, length)
10105 
10106 def SubSeq(s, offset, length):
10107  """Extract substring or subsequence starting at offset"""
10108  return Extract(s, offset, length)
10109 
10110 def Strings(names, ctx=None):
10111  """Return a tuple of String constants. """
10112  ctx = _get_ctx(ctx)
10113  if isinstance(names, str):
10114  names = names.split(" ")
10115  return [String(name, ctx) for name in names]
10116 
10117 def Empty(s):
10118  """Create the empty sequence of the given sort
10119  >>> e = Empty(StringSort())
10120  >>> e2 = StringVal("")
10121  >>> print(e.eq(e2))
10122  True
10123  >>> e3 = Empty(SeqSort(IntSort()))
10124  >>> print(e3)
10125  Empty(Seq(Int))
10126  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10127  >>> print(e4)
10128  Empty(ReSort(Seq(Int)))
10129  """
10130  if isinstance(s, SeqSortRef):
10131  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10132  if isinstance(s, ReSortRef):
10133  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10134  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10135 
10136 def Full(s):
10137  """Create the regular expression that accepts the universal language
10138  >>> e = Full(ReSort(SeqSort(IntSort())))
10139  >>> print(e)
10140  Full(ReSort(Seq(Int)))
10141  >>> e1 = Full(ReSort(StringSort()))
10142  >>> print(e1)
10143  Full(ReSort(String))
10144  """
10145  if isinstance(s, ReSortRef):
10146  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10147  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10148 
10149 
10150 def Unit(a):
10151  """Create a singleton sequence"""
10152  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10153 
10154 def PrefixOf(a, b):
10155  """Check if 'a' is a prefix of 'b'
10156  >>> s1 = PrefixOf("ab", "abc")
10157  >>> simplify(s1)
10158  True
10159  >>> s2 = PrefixOf("bc", "abc")
10160  >>> simplify(s2)
10161  False
10162  """
10163  ctx = _get_ctx2(a, b)
10164  a = _coerce_seq(a, ctx)
10165  b = _coerce_seq(b, ctx)
10166  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10167 
10168 def SuffixOf(a, b):
10169  """Check if 'a' is a suffix of 'b'
10170  >>> s1 = SuffixOf("ab", "abc")
10171  >>> simplify(s1)
10172  False
10173  >>> s2 = SuffixOf("bc", "abc")
10174  >>> simplify(s2)
10175  True
10176  """
10177  ctx = _get_ctx2(a, b)
10178  a = _coerce_seq(a, ctx)
10179  b = _coerce_seq(b, ctx)
10180  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10181 
10182 def Contains(a, b):
10183  """Check if 'a' contains 'b'
10184  >>> s1 = Contains("abc", "ab")
10185  >>> simplify(s1)
10186  True
10187  >>> s2 = Contains("abc", "bc")
10188  >>> simplify(s2)
10189  True
10190  >>> x, y, z = Strings('x y z')
10191  >>> s3 = Contains(Concat(x,y,z), y)
10192  >>> simplify(s3)
10193  True
10194  """
10195  ctx = _get_ctx2(a, b)
10196  a = _coerce_seq(a, ctx)
10197  b = _coerce_seq(b, ctx)
10198  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10199 
10200 
10201 def Replace(s, src, dst):
10202  """Replace the first occurrence of 'src' by 'dst' in 's'
10203  >>> r = Replace("aaa", "a", "b")
10204  >>> simplify(r)
10205  "baa"
10206  """
10207  ctx = _get_ctx2(dst, s)
10208  if ctx is None and is_expr(src):
10209  ctx = src.ctx
10210  src = _coerce_seq(src, ctx)
10211  dst = _coerce_seq(dst, ctx)
10212  s = _coerce_seq(s, ctx)
10213  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10214 
10215 def IndexOf(s, substr):
10216  return IndexOf(s, substr, IntVal(0))
10217 
10218 def IndexOf(s, substr, offset):
10219  """Retrieve the index of substring within a string starting at a specified offset.
10220  >>> simplify(IndexOf("abcabc", "bc", 0))
10221  1
10222  >>> simplify(IndexOf("abcabc", "bc", 2))
10223  4
10224  """
10225  ctx = None
10226  if is_expr(offset):
10227  ctx = offset.ctx
10228  ctx = _get_ctx2(s, substr, ctx)
10229  s = _coerce_seq(s, ctx)
10230  substr = _coerce_seq(substr, ctx)
10231  if _is_int(offset):
10232  offset = IntVal(offset, ctx)
10233  return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10234 
10235 def LastIndexOf(s, substr):
10236  """Retrieve the last index of substring within a string"""
10237  ctx = None
10238  ctx = _get_ctx2(s, substr, ctx)
10239  s = _coerce_seq(s, ctx)
10240  substr = _coerce_seq(substr, ctx)
10241  return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10242 
10243 
10244 def Length(s):
10245  """Obtain the length of a sequence 's'
10246  >>> l = Length(StringVal("abc"))
10247  >>> simplify(l)
10248  3
10249  """
10250  s = _coerce_seq(s)
10251  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10252 
10253 def StrToInt(s):
10254  """Convert string expression to integer
10255  >>> a = StrToInt("1")
10256  >>> simplify(1 == a)
10257  True
10258  >>> b = StrToInt("2")
10259  >>> simplify(1 == b)
10260  False
10261  >>> c = StrToInt(IntToStr(2))
10262  >>> simplify(1 == c)
10263  False
10264  """
10265  s = _coerce_seq(s)
10266  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10267 
10268 
10269 def IntToStr(s):
10270  """Convert integer expression to string"""
10271  if not is_expr(s):
10272  s = _py2expr(s)
10273  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10274 
10275 
10276 def Re(s, ctx=None):
10277  """The regular expression that accepts sequence 's'
10278  >>> s1 = Re("ab")
10279  >>> s2 = Re(StringVal("ab"))
10280  >>> s3 = Re(Unit(BoolVal(True)))
10281  """
10282  s = _coerce_seq(s, ctx)
10283  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10284 
10285 
10286 
10287 
10288 
10289 
10291  """Regular expression sort."""
10292 
10293  def basis(self):
10294  return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10295 
10296 def ReSort(s):
10297  if is_ast(s):
10298  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10299  if s is None or isinstance(s, Context):
10300  ctx = _get_ctx(s)
10301  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10302  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10303 
10304 
10306  """Regular expressions."""
10307 
10308  def __add__(self, other):
10309  return Union(self, other)
10310 
10311 def is_re(s):
10312  return isinstance(s, ReRef)
10313 
10314 
10315 def InRe(s, re):
10316  """Create regular expression membership test
10317  >>> re = Union(Re("a"),Re("b"))
10318  >>> print (simplify(InRe("a", re)))
10319  True
10320  >>> print (simplify(InRe("b", re)))
10321  True
10322  >>> print (simplify(InRe("c", re)))
10323  False
10324  """
10325  s = _coerce_seq(s, re.ctx)
10326  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10327 
10328 def Union(*args):
10329  """Create union of regular expressions.
10330  >>> re = Union(Re("a"), Re("b"), Re("c"))
10331  >>> print (simplify(InRe("d", re)))
10332  False
10333  """
10334  args = _get_args(args)
10335  sz = len(args)
10336  if z3_debug():
10337  _z3_assert(sz > 0, "At least one argument expected.")
10338  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10339  if sz == 1:
10340  return args[0]
10341  ctx = args[0].ctx
10342  v = (Ast * sz)()
10343  for i in range(sz):
10344  v[i] = args[i].as_ast()
10345  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10346 
10347 def Intersect(*args):
10348  """Create intersection of regular expressions.
10349  >>> re = Intersect(Re("a"), Re("b"), Re("c"))
10350  """
10351  args = _get_args(args)
10352  sz = len(args)
10353  if z3_debug():
10354  _z3_assert(sz > 0, "At least one argument expected.")
10355  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10356  if sz == 1:
10357  return args[0]
10358  ctx = args[0].ctx
10359  v = (Ast * sz)()
10360  for i in range(sz):
10361  v[i] = args[i].as_ast()
10362  return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
10363 
10364 def Plus(re):
10365  """Create the regular expression accepting one or more repetitions of argument.
10366  >>> re = Plus(Re("a"))
10367  >>> print(simplify(InRe("aa", re)))
10368  True
10369  >>> print(simplify(InRe("ab", re)))
10370  False
10371  >>> print(simplify(InRe("", re)))
10372  False
10373  """
10374  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10375 
10376 def Option(re):
10377  """Create the regular expression that optionally accepts the argument.
10378  >>> re = Option(Re("a"))
10379  >>> print(simplify(InRe("a", re)))
10380  True
10381  >>> print(simplify(InRe("", re)))
10382  True
10383  >>> print(simplify(InRe("aa", re)))
10384  False
10385  """
10386  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10387 
10388 def Complement(re):
10389  """Create the complement regular expression."""
10390  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10391 
10392 def Star(re):
10393  """Create the regular expression accepting zero or more repetitions of argument.
10394  >>> re = Star(Re("a"))
10395  >>> print(simplify(InRe("aa", re)))
10396  True
10397  >>> print(simplify(InRe("ab", re)))
10398  False
10399  >>> print(simplify(InRe("", re)))
10400  True
10401  """
10402  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10403 
10404 def Loop(re, lo, hi=0):
10405  """Create the regular expression accepting between a lower and upper bound repetitions
10406  >>> re = Loop(Re("a"), 1, 3)
10407  >>> print(simplify(InRe("aa", re)))
10408  True
10409  >>> print(simplify(InRe("aaaa", re)))
10410  False
10411  >>> print(simplify(InRe("", re)))
10412  False
10413  """
10414  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
10415 
10416 def Range(lo, hi, ctx = None):
10417  """Create the range regular expression over two sequences of length 1
10418  >>> range = Range("a","z")
10419  >>> print(simplify(InRe("b", range)))
10420  True
10421  >>> print(simplify(InRe("bb", range)))
10422  False
10423  """
10424  lo = _coerce_seq(lo, ctx)
10425  hi = _coerce_seq(hi, ctx)
10426  return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
10427 
10428 # Special Relations
10429 
10430 def PartialOrder(a, index):
10431  return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx);
10432 
10433 def LinearOrder(a, index):
10434  return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10435 
10436 def TreeOrder(a, index):
10437  return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx);
10438 
10439 def PiecewiseLinearOrder(a, index):
10440  return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10441 
10443  """Given a binary relation R, such that the two arguments have the same sort
10444  create the transitive closure relation R+.
10445  The transitive closure R+ is a new relation.
10446  """
10447  return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
Z3_sort Z3_API Z3_mk_fpa_sort_32(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
def param_descrs(self)
Definition: z3py.py:7384
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
def value(self)
Definition: z3py.py:7349
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
def lower(self, obj)
Definition: z3py.py:7495
def translate(self, target)
Definition: z3py.py:5383
def __rrshift__(self, other)
Definition: z3py.py:3620
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
Z3_ast Z3_API Z3_mk_re_loop(Z3_context c, Z3_ast r, unsigned lo, unsigned hi)
Create a regular expression loop. The supplied regular expression r is repeated between lo and hi tim...
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
def name(self)
Definition: z3py.py:679
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
def significand_as_long(self)
Definition: z3py.py:9078
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9921
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
def is_lt(a)
Definition: z3py.py:2682
def __init__(self, entry, ctx)
Definition: z3py.py:5739
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...
Z3_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
def __ge__(self, other)
Definition: z3py.py:7996
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
def basis(self)
Definition: z3py.py:10293
def __len__(self)
Definition: z3py.py:5633
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def __rdiv__(self, other)
Definition: z3py.py:2361
def TransitiveClosure(f)
Definition: z3py.py:10442
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:3101
def children(self)
Definition: z3py.py:1990
def is_distinct(a)
Definition: z3py.py:1524
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
Regular expressions.
Definition: z3py.py:10290
def __gt__(self, other)
Definition: z3py.py:7970
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 reset(self)
Definition: z3py.py:5703
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
def __xor__(self, other)
Definition: z3py.py:3376
def fpIsNegative(a, ctx=None)
Definition: z3py.py:9619
def units(self)
Definition: z3py.py:6797
def __rxor__(self, other)
Definition: z3py.py:3389
def SignExt(n, a)
Definition: z3py.py:4078
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
def __del__(self)
Definition: z3py.py:5856
def update_rule(self, head, body, name)
Definition: z3py.py:7085
def SeqSort(s)
Definition: z3py.py:9982
Fixedpoint.
Definition: z3py.py:6951
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_solver_get_assertions(Z3_context c, Z3_solver s)
Return the set of asserted formulas on the solver.
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
def size(self)
Definition: z3py.py:5241
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9116
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...
Z3_sort Z3_API Z3_mk_fpa_sort_quadruple(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
def upper(self)
Definition: z3py.py:7337
def Map(f, *args)
Definition: z3py.py:4483
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4188
def is_fprm_sort(s)
Definition: z3py.py:8785
def get_version_string()
Definition: z3py.py:75
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:1815
Z3_ast Z3_API Z3_mk_fpa_fp(Z3_context c, Z3_ast sgn, Z3_ast exp, Z3_ast sig)
Create an expression of FloatingPoint sort from three bit-vector expressions.
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5074
def __iadd__(self, fml)
Definition: z3py.py:6576
def entry(self, idx)
Definition: z3py.py:5913
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7120
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:4975
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
def RoundTowardPositive(ctx=None)
Definition: z3py.py:8998
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def FloatSingle(ctx=None)
Definition: z3py.py:8746
def upper_values(self, obj)
Definition: z3py.py:7510
def set_param(*args, **kws)
Definition: z3py.py:242
def as_ast(self)
Definition: z3py.py:1818
def RatVal(a, b, ctx=None)
Definition: z3py.py:2987
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
def __rmod__(self, other)
Definition: z3py.py:2397
def __del__(self)
Definition: z3py.py:5973
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
def __deepcopy__(self, memo={})
Definition: z3py.py:6237
def add(self, *args)
Definition: z3py.py:5332
Z3_ast Z3_API Z3_mk_fpa_to_ubv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into an unsigned bit-vector.
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].
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_func_decl Z3_API Z3_mk_transitive_closure(Z3_context c, Z3_func_decl f)
create transitive closure of binary relation.
def sign_as_bv(self)
Definition: z3py.py:9060
def __getitem__(self, idx)
Definition: z3py.py:7587
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Function Declarations.
Definition: z3py.py:663
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def __del__(self)
Definition: z3py.py:5629
def get_name(self, i)
Definition: z3py.py:5122
def from_string(self, s)
Definition: z3py.py:6747
def ParOr(*ts, **ks)
Definition: z3py.py:7800
def __gt__(self, other)
Definition: z3py.py:8840
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3088
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Booleans.
Definition: z3py.py:1372
Z3_sort Z3_API Z3_mk_fpa_sort(Z3_context c, unsigned ebits, unsigned sbits)
Create a FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_to_real(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a real-numbered term.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
def as_string(self)
Definition: z3py.py:3684
def SetIntersect(*args)
Definition: z3py.py:4604
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
def prec(self)
Definition: z3py.py:5211
def IsInt(a)
Definition: z3py.py:3148
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
def RTN(ctx=None)
Definition: z3py.py:9010
Z3_ast Z3_API Z3_mk_seq_at(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the unit sequence positioned at position index. The sequence is empty if the index is...
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:4986
def __repr__(self)
Definition: z3py.py:325
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
def is_arith_sort(s)
Definition: z3py.py:2182
Z3_sort Z3_API Z3_get_seq_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for sequence sort.
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...
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
def isInf(self)
Definition: z3py.py:9124
def ReSort(s)
Definition: z3py.py:10296
def RTZ(ctx=None)
Definition: z3py.py:9018
def translate(self, other_ctx)
Definition: z3py.py:5581
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.
Z3_ast Z3_API Z3_mk_fpa_to_sbv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into a signed bit-vector.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
def set(self, *args, **keys)
Definition: z3py.py:7374
def SetHasSize(a, k)
Definition: z3py.py:4537
def as_ast(self)
Definition: z3py.py:885
def SubSeq(s, offset, length)
Definition: z3py.py:10106
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
def __iadd__(self, fml)
Definition: z3py.py:7404
def RealSort(ctx=None)
Definition: z3py.py:2927
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3370
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9765
def SubString(s, offset, length)
Definition: z3py.py:10102
def __eq__(self, other)
Definition: z3py.py:6407
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
def cast(self, val)
Definition: z3py.py:8715
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9369
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9302
def get_rules(self)
Definition: z3py.py:7153
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
def __add__(self, other)
Definition: z3py.py:2235
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context....
def RealVarVector(n, ctx=None)
Definition: z3py.py:1355
def sort(self)
Definition: z3py.py:7244
def __rmul__(self, other)
Definition: z3py.py:8904
def ZeroExt(n, a)
Definition: z3py.py:4107
def assertions(self)
Definition: z3py.py:7523
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
def RTP(ctx=None)
Definition: z3py.py:9002
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
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 as_string(self)
Definition: z3py.py:10018
def __deepcopy__(self, memo={})
Definition: z3py.py:5105
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def get_id(self)
Definition: z3py.py:1760
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
def is_int(self)
Definition: z3py.py:2128
def Var(idx, s)
Definition: z3py.py:1333
def __del__(self)
Definition: z3py.py:7953
def get_id(self)
Definition: z3py.py:1821
def is_bool(self)
Definition: z3py.py:1402
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 AtLeast(*args)
Definition: z3py.py:8330
def RNA(ctx=None)
Definition: z3py.py:8994
def Strings(names, ctx=None)
Definition: z3py.py:10095
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:7703
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def probes(ctx=None)
Definition: z3py.py:8080
def __mod__(self, other)
Definition: z3py.py:3473
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:9578
def to_symbol(s, ctx=None)
Definition: z3py.py:111
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
def help(self)
Definition: z3py.py:6851
def isNaN(self)
Definition: z3py.py:9120
def __lt__(self, other)
Definition: z3py.py:2442
def reset_params()
Definition: z3py.py:265
def __init__(self, descr, ctx=None)
Definition: z3py.py:5099
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 ...
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
def __sub__(self, other)
Definition: z3py.py:3307
def is_string_value(a)
Definition: z3py.py:10072
def as_ast(self)
Definition: z3py.py:356
def default(self)
Definition: z3py.py:4291
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
def LShR(a, b)
Definition: z3py.py:4017
def is_default(a)
Definition: z3py.py:4350
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....
Bit-Vectors.
Definition: z3py.py:3194
def __getattr__(self, name)
Definition: z3py.py:6362
def Consts(names, sort)
Definition: z3py.py:1314
def use_pp(self)
Definition: z3py.py:296
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
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 __deepcopy__(self, memo={})
Definition: z3py.py:5626
def IntVal(val, ctx=None)
Definition: z3py.py:2958
Z3_sort Z3_API Z3_mk_fpa_sort_single(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
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.
Z3_ast Z3_API Z3_mk_str_to_int(Z3_context c, Z3_ast s)
Convert string to integer.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
def __nonzero__(self)
Definition: z3py.py:334
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
def is_and(a)
Definition: z3py.py:1471
def ref(self)
Definition: z3py.py:198
def __div__(self, other)
Definition: z3py.py:3430
def push(self)
Definition: z3py.py:6470
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def fpGT(a, b, ctx=None)
Definition: z3py.py:9655
def exponent_as_long(self, biased=True)
Definition: z3py.py:9106
def sort(self)
Definition: z3py.py:1408
def BVSubNoOverflow(a, b)
Definition: z3py.py:4181
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8585
def ULT(a, b)
Definition: z3py.py:3906
def fpIsInf(a, ctx=None)
Definition: z3py.py:9594
Z3_string Z3_API Z3_solver_to_dimacs_string(Z3_context c, Z3_solver s)
Convert a solver into a DIMACS formatted string.
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9006
Arithmetic.
Definition: z3py.py:2111
Z3_ast Z3_API Z3_fpa_get_numeral_sign_bv(Z3_context c, Z3_ast t)
Retrieves the sign of a floating-point literal as a bit-vector expression.
def And(*args)
Definition: z3py.py:1684
def var_sort(self, idx)
Definition: z3py.py:1974
FP Expressions.
Definition: z3py.py:8797
def Or(*args)
Definition: z3py.py:1717
Z3_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
def __init__(self, ctx=None)
Definition: z3py.py:7362
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
def minimize(self, arg)
Definition: z3py.py:7460
def help(self)
Definition: z3py.py:7380
def as_decimal(self, prec)
Definition: z3py.py:2888
def __init__(self, c, ctx)
Definition: z3py.py:4770
def sort(self)
Definition: z3py.py:2200
def is_to_real(a)
Definition: z3py.py:2726
def as_ast(self)
Definition: z3py.py:515
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9727
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
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 fpMinusInfinity(s)
Definition: z3py.py:9275
def sort(self)
Definition: z3py.py:1824
def Float64(ctx=None)
Definition: z3py.py:8751
def param_descrs(self)
Definition: z3py.py:6982
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
def is_select(a)
Definition: z3py.py:4542
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8184
def is_real(self)
Definition: z3py.py:2224
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 sorts(self)
Definition: z3py.py:6126
def is_int(self)
Definition: z3py.py:2210
ASTs base class.
Definition: z3py.py:294
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
def __ne__(self, other)
Definition: z3py.py:935
bool Z3_API Z3_fpa_get_numeral_significand_uint64(Z3_context c, Z3_ast t, uint64_t *n)
Return the significand value of a floating-point numeral as a uint64.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
def __repr__(self)
Definition: z3py.py:5143
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:4722
def __and__(self, other)
Definition: z3py.py:3353
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9834
def is_int_value(self)
Definition: z3py.py:2837
def is_gt(a)
Definition: z3py.py:2704
Z3_ast Z3_API Z3_mk_re_intersect(Z3_context c, unsigned n, Z3_ast const args[])
Create the intersection of the regular languages.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_even(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
def lower_values(self, obj)
Definition: z3py.py:7505
def pop(self)
Definition: z3py.py:7468
def isPositive(self)
Definition: z3py.py:9140
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
def sexpr(self)
Definition: z3py.py:7607
Z3_ast Z3_API Z3_solver_get_proof(Z3_context c, Z3_solver s)
Retrieve the proof for the last Z3_solver_check or Z3_solver_check_assumptions.
def append(self, *args)
Definition: z3py.py:5310
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
def solve(*args, **keywords)
Definition: z3py.py:8403
unsigned Z3_API Z3_fpa_get_ebits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the exponent in a FloatingPoint sort.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:8982
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def __eq__(self, other)
Definition: z3py.py:914
def domain(self, i)
Definition: z3py.py:699
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
def as_string(self)
Definition: z3py.py:7248
def translate(self, target)
Definition: z3py.py:6863
def TreeOrder(a, index)
Definition: z3py.py:10436
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 __le__(self, other)
Definition: z3py.py:3512
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2065
def is_implies(a)
Definition: z3py.py:1493
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....
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
def Loop(re, lo, hi=0)
Definition: z3py.py:10404
def __pos__(self)
Definition: z3py.py:3399
def __deepcopy__(self, memo={})
Definition: z3py.py:7561
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
def is_array_sort(a)
Definition: z3py.py:4294
def get_documentation(self, n)
Definition: z3py.py:5132
def With(t, *args, **keys)
Definition: z3py.py:7836
unsigned Z3_API Z3_fpa_get_sbits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the significand in a FloatingPoint sort.
def as_decimal(self, prec)
Definition: z3py.py:2844
def IndexOf(s, substr)
Definition: z3py.py:10215
def is_app(a)
Definition: z3py.py:1139
def as_fraction(self)
Definition: z3py.py:2865
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
def __del__(self)
Definition: z3py.py:6454
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
def __deepcopy__(self, memo={})
Definition: z3py.py:5853
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9881
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
def __ge__(self, other)
Definition: z3py.py:3560
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5412
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 __or__(self, other)
Definition: z3py.py:3330
Z3_ast Z3_API Z3_mk_seq_length(Z3_context c, Z3_ast s)
Return the length of the sequence s.
def __len__(self)
Definition: z3py.py:7568
def __lt__(self, other)
Definition: z3py.py:3528
def __repr__(self)
Definition: z3py.py:6413
def mk_not(a)
Definition: z3py.py:1671
def StringSort(ctx=None)
Definition: z3py.py:9972
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_mk_seq_prefix(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if prefix is a prefix of s.
Z3_ast_vector Z3_API Z3_solver_get_units(Z3_context c, Z3_solver s)
Return the set of units modulo model conversion.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
def __pos__(self)
Definition: z3py.py:2420
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.
Z3_string Z3_API Z3_solver_get_help(Z3_context c, Z3_solver s)
Return a string describing all solver available parameters.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
Z3_ast Z3_API Z3_mk_re_complement(Z3_context c, Z3_ast re)
Create the complement of the regular language re.
def open_log(fname)
Definition: z3py.py:103
def __deepcopy__(self, memo={})
Definition: z3py.py:7662
def get_universe(self, s)
Definition: z3py.py:6143
def push(self, v)
Definition: z3py.py:5533
Z3_ast Z3_API Z3_mk_seq_nth(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the element positioned at position index. The function is under-specified if the inde...
def assert_exprs(self, *args)
Definition: z3py.py:6986
def EmptySet(s)
Definition: z3py.py:4576
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
def solver(self)
Definition: z3py.py:7669
def PrefixOf(a, b)
Definition: z3py.py:10154
def __rtruediv__(self, other)
Definition: z3py.py:8962
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9666
Z3_stats Z3_API Z3_solver_get_statistics(Z3_context c, Z3_solver s)
Return statistics for the given solver.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
Z3_ast Z3_API Z3_mk_fpa_round_toward_zero(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardZero rounding mode.
def num_no_patterns(self)
Definition: z3py.py:1925
def PbEq(args, k, ctx=None)
Definition: z3py.py:8392
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.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
def rule(self, head, body=None, name=None)
Definition: z3py.py:7039
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
def __call__(self, *args)
Definition: z3py.py:757
def range(self)
Definition: z3py.py:4269
def __repr__(self)
Definition: z3py.py:7604
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
def fpRem(a, b, ctx=None)
Definition: z3py.py:9527
def Cbrt(a, ctx=None)
Definition: z3py.py:3176
def __repr__(self)
Definition: z3py.py:5841
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def BVRedOr(a)
Definition: z3py.py:4163
bool Z3_API Z3_fpa_get_numeral_exponent_int64(Z3_context c, Z3_ast t, int64_t *n, bool biased)
Return the exponent value of a floating-point numeral as a signed 64-bit integer.
def SetDifference(a, b)
Definition: z3py.py:4645
def is_forall(self)
Definition: z3py.py:1830
def disable_trace(msg)
Definition: z3py.py:72
def insert(self, *args)
Definition: z3py.py:5321
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
def fpMinusZero(s)
Definition: z3py.py:9291
def RotateRight(a, b)
Definition: z3py.py:4063
def set(self, *args, **keys)
Definition: z3py.py:6972
def sort(self)
Definition: z3py.py:3239
def get_ctx(ctx)
Definition: z3py.py:239
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
def __setitem__(self, k, v)
Definition: z3py.py:5670
def exponent(self, biased=True)
Definition: z3py.py:9097
def isNegative(self)
Definition: z3py.py:9144
def is_ge(a)
Definition: z3py.py:2693
bool Z3_API Z3_fpa_is_numeral_normal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is normal.
def assert_exprs(self, *args)
Definition: z3py.py:7388
def is_K(a)
Definition: z3py.py:4323
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def Range(lo, hi, ctx=None)
Definition: z3py.py:10416
def sort_kind(self)
Definition: z3py.py:903
def tactics(ctx=None)
Definition: z3py.py:7889
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_ast Z3_API Z3_fpa_get_numeral_exponent_bv(Z3_context c, Z3_ast t, bool biased)
Retrieves the exponent of a floating-point literal as a bit-vector expression.
def is_const(a)
Definition: z3py.py:1164
def __rsub__(self, other)
Definition: z3py.py:8879
Z3_ast Z3_API Z3_mk_fpa_abs(Z3_context c, Z3_ast t)
Floating-point absolute value.
void Z3_API Z3_solver_from_string(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a string.
def Star(re)
Definition: z3py.py:10392
def InRe(s, re)
Definition: z3py.py:10315
def is_finite_domain_sort(s)
Definition: z3py.py:7230
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
def __init__(self, stats, ctx)
Definition: z3py.py:6262
def push(self)
Definition: z3py.py:7464
def inconsistent(self)
Definition: z3py.py:5193
def z3_error_handler(c, e)
Definition: z3py.py:158
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
def denominator_as_long(self)
Definition: z3py.py:2820
Z3_sort Z3_API Z3_mk_fpa_sort_half(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
def assert_and_track(self, a, p)
Definition: z3py.py:6602
def RotateLeft(a, b)
Definition: z3py.py:4048
Z3_sort Z3_API Z3_mk_string_sort(Z3_context c)
Create a sort for 8 bit strings.
def Const(name, sort)
Definition: z3py.py:1303
def sexpr(self)
Definition: z3py.py:6882
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1596
def as_string(self)
Definition: z3py.py:2856
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
def __repr__(self)
Definition: z3py.py:5067
def __deepcopy__(self, memo={})
Definition: z3py.py:4717
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 significand_as_bv(self)
Definition: z3py.py:9088
def Array(name, dom, rng)
Definition: z3py.py:4407
def main_ctx()
Definition: z3py.py:213
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
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.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
def __pos__(self)
Definition: z3py.py:8917
def var_name(self, idx)
Definition: z3py.py:1958
def __repr__(self)
Definition: z3py.py:5600
def as_string(self)
Definition: z3py.py:2770
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort_opt const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def If(a, b, c, ctx=None)
Definition: z3py.py:1250
def __repr__(self)
Definition: z3py.py:4749
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3758
def get_id(self)
Definition: z3py.py:673
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7069
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
def sbits(self)
Definition: z3py.py:8707
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
def get(self, i)
Definition: z3py.py:5267
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
def append(self, *args)
Definition: z3py.py:7008
def Intersect(*args)
Definition: z3py.py:10347
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 set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:8642
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
def is_array(a)
Definition: z3py.py:4298
def is_pattern(a)
Definition: z3py.py:1763
Statistics.
Definition: z3py.py:6259
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8168
Z3_ast Z3_API Z3_mk_fpa_to_fp_bv(Z3_context c, Z3_ast bv, Z3_sort s)
Conversion of a single IEEE 754-2008 bit-vector into a floating-point number.
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
def model(self)
Definition: z3py.py:6660
def is_fp_value(a)
Definition: z3py.py:9171
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
def help_simplify()
Definition: z3py.py:8208
def fpMax(a, b, ctx=None)
Definition: z3py.py:9554
def insert(self, *args)
Definition: z3py.py:7012
def IsSubset(a, b)
Definition: z3py.py:4665
def get_as_array_func(n)
Definition: z3py.py:6248
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
def upper(self, obj)
Definition: z3py.py:7500
def get_rule_names_along_trace(self)
Definition: z3py.py:7108
def Int(name, ctx=None)
Definition: z3py.py:3014
def __neg__(self)
Definition: z3py.py:3408
def register_relation(self, *relations)
Definition: z3py.py:7129
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6954
def set(self, *args, **keys)
Definition: z3py.py:6458
def __repr__(self)
Definition: z3py.py:7531
def __repr__(self)
Definition: z3py.py:7161
Z3_ast_vector Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Parse the given string using the SMT-LIB2 parser.
def simplify_param_descrs()
Definition: z3py.py:8212
def is_map(a)
Definition: z3py.py:4335
def is_or(a)
Definition: z3py.py:1482
def approx(self, precision=10)
Definition: z3py.py:2877
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9851
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9499
def is_lambda(self)
Definition: z3py.py:1858
def __len__(self)
Definition: z3py.py:6039
bool Z3_API Z3_fpa_is_numeral_subnormal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is subnormal.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
Patterns.
Definition: z3py.py:1753
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
def fpAbs(a, ctx=None)
Definition: z3py.py:9387
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9677
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3774
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
def is_int_value(a)
Definition: z3py.py:2543
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
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 is_fprm_value(a)
Definition: z3py.py:9034
def __del__(self)
Definition: z3py.py:4773
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_ast Z3_API Z3_mk_seq_suffix(Z3_context c, Z3_ast suffix, Z3_ast s)
Check if suffix is a suffix of s.
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
Z3_bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
def __getitem__(self, arg)
Definition: z3py.py:5280
def __hash__(self)
Definition: z3py.py:594
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.
Z3_ast Z3_API Z3_mk_fpa_to_fp_unsigned(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement unsigned bit-vector term into a term of FloatingPoint sort.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
Z3_ast_vector Z3_API Z3_solver_cube(Z3_context c, Z3_solver s, Z3_ast_vector vars, unsigned backtrack_level)
extract a next cube for a solver. The last cube is the constant true or false. The number of (non-con...
def __add__(self, other)
Definition: z3py.py:3261
def num_patterns(self)
Definition: z3py.py:1895
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
def __mul__(self, other)
Definition: z3py.py:3284
def substitute(t, *m)
Definition: z3py.py:8216
def Union(*args)
Definition: z3py.py:10328
def __getitem__(self, arg)
Definition: z3py.py:4278
def Default(a)
Definition: z3py.py:4441
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7223
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_fpa_to_fp_real(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a term of real sort into a term of FloatingPoint sort.
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5462
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_mk_seq_replace(Z3_context c, Z3_ast s, Z3_ast src, Z3_ast dst)
Replace the first occurrence of src with dst in s.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
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 BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4169
def sexpr(self)
Definition: z3py.py:5375
def Distinct(*args)
Definition: z3py.py:1272
def __radd__(self, other)
Definition: z3py.py:3274
def __rdiv__(self, other)
Definition: z3py.py:3453
def fpIsNormal(a, ctx=None)
Definition: z3py.py:9609
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
def MultiPattern(*args)
Definition: z3py.py:1780
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def FreshConst(sort, prefix='c')
Definition: z3py.py:1328
def URem(a, b)
Definition: z3py.py:3977
Z3_ast Z3_API Z3_mk_fpa_to_fp_signed(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort.
def PbGe(args, k)
Definition: z3py.py:8382
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def add(self, *args)
Definition: z3py.py:7400
def SuffixOf(a, b)
Definition: z3py.py:10168
def __eq__(self, other)
Definition: z3py.py:328
def __mul__(self, other)
Definition: z3py.py:1414
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9817
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:8628
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
def is_mod(a)
Definition: z3py.py:2660
def sort(self)
Definition: z3py.py:4251
def fact(self, head, name=None)
Definition: z3py.py:7043
def Model(ctx=None)
Definition: z3py.py:6240
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
def convert_model(self, model)
Definition: z3py.py:5343
Z3_ast Z3_API Z3_mk_re_option(Z3_context c, Z3_ast re)
Create the regular language [re].
def sbits(self)
Definition: z3py.py:8819
def UGE(a, b)
Definition: z3py.py:3923
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
def __getitem__(self, arg)
Definition: z3py.py:1872
def Replace(s, src, dst)
Definition: z3py.py:10201
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs,...
def Real(name, ctx=None)
Definition: z3py.py:3062
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast Z3_API Z3_mk_str_le(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is equal or lexicographically strictly less than s2.
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 __del__(self)
Definition: z3py.py:5476
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
def lower_values(self)
Definition: z3py.py:7341
def cast(self, val)
Definition: z3py.py:545
def Length(s)
Definition: z3py.py:10244
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
def __init__(self, solver=None, ctx=None)
Definition: z3py.py:6443
def append(self, *args)
Definition: z3py.py:6580
def decl(self)
Definition: z3py.py:956
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7832
Definition: z3py.py:5736
Z3_string Z3_API Z3_fpa_get_numeral_significand_string(Z3_context c, Z3_ast t)
Return the significand value of a floating-point numeral as a string.
def num_args(self)
Definition: z3py.py:5751
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
def Float16(ctx=None)
Definition: z3py.py:8731
def __rtruediv__(self, other)
Definition: z3py.py:3469
def Bools(names, ctx=None)
Definition: z3py.py:1581
def is_eq(a)
Definition: z3py.py:1515
def fpPlusZero(s)
Definition: z3py.py:9286
def Sum(*args)
Definition: z3py.py:8262
def __del__(self)
Definition: z3py.py:193
def Float32(ctx=None)
Definition: z3py.py:8741
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:8990
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9583
def __deepcopy__(self, memo={})
Definition: z3py.py:6879
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def statistics(self)
Definition: z3py.py:7540
def depth(self)
Definition: z3py.py:5176
def __str__(self)
Definition: z3py.py:7355
def to_smt2(self)
Definition: z3py.py:6897
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
def sort(self)
Definition: z3py.py:891
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def is_real(a)
Definition: z3py.py:2519
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
def RealVal(val, ctx=None)
Definition: z3py.py:2969
def PbLe(args, k)
Definition: z3py.py:8372
def get_id(self)
Definition: z3py.py:888
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
def Extract(high, low, a)
Definition: z3py.py:3862
def __del__(self)
Definition: z3py.py:5172
def __getitem__(self, idx)
Definition: z3py.py:6163
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:7686
Z3_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
def RealVar(idx, ctx=None)
Definition: z3py.py:1345
def size(self)
Definition: z3py.py:3197
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2048
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 maximize(self, arg)
Definition: z3py.py:7456
def CreateDatatypes(*ds)
Definition: z3py.py:4786
def FloatQuadruple(ctx=None)
Definition: z3py.py:8766
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1....
def basis(self)
Definition: z3py.py:9968
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
def eq(a, b)
Definition: z3py.py:434
def as_expr(self)
Definition: z3py.py:5432
def subsort(self, other)
Definition: z3py.py:2142
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query.
def FloatDouble(ctx=None)
Definition: z3py.py:8756
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def help(self)
Definition: z3py.py:7713
def __bool__(self)
Definition: z3py.py:337
def declare_var(self, *vars)
Definition: z3py.py:7188
def is_re(s)
Definition: z3py.py:10311
Z3_sort Z3_API Z3_get_re_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for regex sort.
Z3_ast Z3_API Z3_mk_fpa_round_toward_positive(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardPositive rounding mode.
void Z3_API Z3_solver_from_file(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a file.
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7437
def sexpr(self)
Definition: z3py.py:7535
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8605
def substitute_vars(t, *m)
Definition: z3py.py:8242
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
Parameter Sets.
Definition: z3py.py:5030
def is_le(a)
Definition: z3py.py:2671
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
def domain(self)
Definition: z3py.py:4230
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
def get_key_value(self, key)
Definition: z3py.py:6342
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:9568
def __deepcopy__(self, memo={})
Definition: z3py.py:319
Z3_ast Z3_API Z3_mk_sign_ext(Z3_context c, unsigned i, Z3_ast t1)
Sign-extend of the given bit-vector to the (signed) equivalent bit-vector of size m+i,...
def is_not(a)
Definition: z3py.py:1504
Strings, Sequences and Regular expressions.
Definition: z3py.py:9954
def get_map_func(a)
Definition: z3py.py:4358
def Implies(a, b, ctx=None)
Definition: z3py.py:1623
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7648
def __repr__(self)
Definition: z3py.py:5372
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
def __getitem__(self, i)
Definition: z3py.py:10002
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_ast Z3_API Z3_fpa_get_numeral_significand_bv(Z3_context c, Z3_ast t)
Retrieves the significand of a floating-point literal as a bit-vector expression.
Z3_func_decl Z3_API Z3_mk_piecewise_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a piecewise linear ordering relation over signature a and index id.
Z3_string Z3_API Z3_get_string(Z3_context c, Z3_ast s)
Retrieve the string constant stored in s.
def cast(self, val)
Definition: z3py.py:3209
def add(self, *args)
Definition: z3py.py:7000
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
def __deepcopy__(self, memo={})
Definition: z3py.py:7367
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def __le__(self, other)
Definition: z3py.py:10024
def __truediv__(self, other)
Definition: z3py.py:2357
Z3_ast Z3_API Z3_mk_fpa_to_ieee_bv(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
def __len__(self)
Definition: z3py.py:5480
def is_arith(a)
Definition: z3py.py:2481
def __del__(self)
Definition: z3py.py:7665
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
def is_sort(s)
Definition: z3py.py:598
def objectives(self)
Definition: z3py.py:7527
def validate(self, ds)
Definition: z3py.py:5070
def reason_unknown(self)
Definition: z3py.py:6838
def __init__(self, opt, value, is_max)
Definition: z3py.py:7328
def __del__(self)
Definition: z3py.py:5046
def num_sorts(self)
Definition: z3py.py:6088
def accessor(self, i, j)
Definition: z3py.py:4940
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
def hash(self)
Definition: z3py.py:404
def SetSort(s)
Sets.
Definition: z3py.py:4572
def is_int(a)
Definition: z3py.py:2501
def LastIndexOf(s, substr)
Definition: z3py.py:10235
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
def fpPlusInfinity(s)
Definition: z3py.py:9259
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
def is_quantifier(a)
Definition: z3py.py:2001
def solve_using(s, *args, **keywords)
Definition: z3py.py:8431
def as_string(self)
Definition: z3py.py:7280
def is_string(a)
Definition: z3py.py:10065
void Z3_API Z3_solver_import_model_converter(Z3_context ctx, Z3_solver src, Z3_solver dst)
Ad-hoc method for importing model conversion from solver.
Z3_solver Z3_API Z3_solver_translate(Z3_context source, Z3_solver s, Z3_context target)
Copy a solver s from the context source to the context target.
def StringVal(s, ctx=None)
Definition: z3py.py:10082
def Plus(re)
Definition: z3py.py:10364
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:10253
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
def isSubnormal(self)
Definition: z3py.py:9136
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7291
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....
Z3_ast_vector Z3_API Z3_solver_get_unsat_core(Z3_context c, Z3_solver s)
Retrieve the unsat core for the last Z3_solver_check_assumptions The unsat core is a subset of the as...
def __gt__(self, other)
Definition: z3py.py:2455
def __deepcopy__(self, memo={})
Definition: z3py.py:5473
def params(self)
Definition: z3py.py:953
def Float128(ctx=None)
Definition: z3py.py:8761
def as_long(self)
Definition: z3py.py:3651
def num_args(self)
Definition: z3py.py:971
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9185
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
def __del__(self)
Definition: z3py.py:7564
def __pow__(self, other)
Definition: z3py.py:2306
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
def DeclareSort(name, ctx=None)
Definition: z3py.py:639
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
def LinearOrder(a, index)
Definition: z3py.py:10433
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def Ints(names, ctx=None)
Definition: z3py.py:3026
def __ge__(self, other)
Definition: z3py.py:8837
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
def parse_file(self, f)
Definition: z3py.py:7149
def __lt__(self, other)
Definition: z3py.py:10027
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
bool Z3_API Z3_fpa_is_numeral_inf(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a +oo or -oo.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
def is_exists(self)
Definition: z3py.py:1844
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
def __ge__(self, other)
Definition: z3py.py:10030
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
def is_true(a)
Definition: z3py.py:1441
def Int2BV(a, num_bits)
Definition: z3py.py:3736
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def Contains(a, b)
Definition: z3py.py:10182
def is_finite_domain_value(a)
Definition: z3py.py:7305
def is_real(self)
Definition: z3py.py:2114
def value(self)
Definition: z3py.py:5800
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 assert_exprs(self, *args)
Definition: z3py.py:6546
bool Z3_API Z3_is_string(Z3_context c, Z3_ast s)
Determine if s is a string constant.
def FreshBool(prefix='b', ctx=None)
Definition: z3py.py:1610
def Bool(name, ctx=None)
Definition: z3py.py:1570
def probe_description(name, ctx=None)
Definition: z3py.py:8090
def __ne__(self, other)
Definition: z3py.py:6410
def insert(self, *args)
Definition: z3py.py:6591
Z3_ast_vector Z3_API Z3_parse_smtlib2_file(Z3_context c, Z3_string file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Similar to Z3_parse_smtlib2_string, but reads the benchmark from a file.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
def get_rules_along_trace(self)
Definition: z3py.py:7104
def __deepcopy__(self, memo={})
Definition: z3py.py:6965
def __neg__(self)
Definition: z3py.py:2409
def __del__(self)
Definition: z3py.py:7370
def Lambda(vs, body)
Definition: z3py.py:2085
def tactic_description(name, ctx=None)
Definition: z3py.py:7899
def param_descrs(self)
Definition: z3py.py:7717
def RNE(ctx=None)
Definition: z3py.py:8986
def pattern(self, idx)
Definition: z3py.py:1907
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4175
Z3_ast Z3_API Z3_mk_re_plus(Z3_context c, Z3_ast re)
Create the regular language re+.
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
def __getitem__(self, i)
Definition: z3py.py:5493
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
def __rshift__(self, other)
Definition: z3py.py:3576
def isNormal(self)
Definition: z3py.py:9132
bool Z3_API Z3_fpa_is_numeral_positive(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is positive.
def is_store(a)
Definition: z3py.py:4554
ctx
Definition: z3py.py:5741
def get_version()
Definition: z3py.py:83
def is_string_value(self)
Definition: z3py.py:10015
def from_string(self, s)
Definition: z3py.py:7519
def num_constructors(self)
Definition: z3py.py:4880
def decls(self)
Definition: z3py.py:6207
def as_list(self)
Definition: z3py.py:5822
def SetDel(s, e)
Definition: z3py.py:4626
def add(self, *args)
Definition: z3py.py:6565
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
def __contains__(self, item)
Definition: z3py.py:5558
def eval(self, t, model_completion=False)
Definition: z3py.py:5984
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
def __contains__(self, key)
Definition: z3py.py:5646
def __rmul__(self, other)
Definition: z3py.py:2273
def fpZero(s, negative)
Definition: z3py.py:9296
Z3_func_decl Z3_API Z3_mk_tree_order(Z3_context c, Z3_sort a, unsigned id)
create a tree ordering relation over signature a identified using index id.
def SRem(a, b)
Definition: z3py.py:3997
def numerator_as_long(self)
Definition: z3py.py:2807
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9346
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:9860
def assert_and_track(self, a, p)
Definition: z3py.py:7408
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9513
def __del__(self)
Definition: z3py.py:6270
def get_default_fp_sort(ctx=None)
Definition: z3py.py:8655
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:8658
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4194
def get_sort(self, idx)
Definition: z3py.py:6103
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
def eq(self, other)
Definition: z3py.py:368
def __add__(self, other)
Definition: z3py.py:9996
def FullSet(s)
Definition: z3py.py:4584
def get_id(self)
Definition: z3py.py:518
def ToReal(a)
Definition: z3py.py:3114
def is_bv_value(a)
Definition: z3py.py:3700
def reset(self)
Definition: z3py.py:6532
def range(self)
Definition: z3py.py:712
Z3_sort Z3_API Z3_mk_seq_sort(Z3_context c, Z3_sort s)
Create a sequence sort out of the sort for the elements.
Z3_func_decl Z3_API Z3_mk_partial_order(Z3_context c, Z3_sort a, unsigned id)
create a partial ordering relation over signature a and index id.
def __repr__(self)
Definition: z3py.py:6274
def is_idiv(a)
Definition: z3py.py:2649
bool Z3_API Z3_is_string_sort(Z3_context c, Z3_sort s)
Check if s is a string sort.
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3797
def translate(self, target)
Definition: z3py.py:385
def __le__(self, other)
Definition: z3py.py:8831
def Concat(*args)
Definition: z3py.py:3817
def from_file(self, filename)
Definition: z3py.py:7515
def __le__(self, other)
Definition: z3py.py:2429
def __mod__(self, other)
Definition: z3py.py:2382
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
def __init__(self, probe, ctx=None)
Definition: z3py.py:7927
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
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 __init__(self, f, ctx)
Definition: z3py.py:5847
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.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
def __ne__(self, other)
Definition: z3py.py:583
Z3_string Z3_API Z3_solver_to_string(Z3_context c, Z3_solver s)
Convert a solver into a string.
Z3_ast Z3_API Z3_mk_re_star(Z3_context c, Z3_ast re)
Create the regular language re*.
def AtMost(*args)
Definition: z3py.py:8313
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
def __le__(self, other)
Definition: z3py.py:7983
def param_descrs(self)
Definition: z3py.py:6855
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.
Z3_ast Z3_API Z3_mk_fpa_to_fp_float(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
def __add__(self, other)
Definition: z3py.py:8843
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.
Z3_ast Z3_API Z3_mk_fpa_neg(Z3_context c, Z3_ast t)
Floating-point negation.
Z3_ast Z3_API Z3_mk_is_int(Z3_context c, Z3_ast t1)
Check if a real number is an integer.
def cast(self, val)
Definition: z3py.py:1374
def resize(self, sz)
Definition: z3py.py:5545
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
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....
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
def __radd__(self, other)
Definition: z3py.py:2248
def as_func_decl(self)
Definition: z3py.py:676
def size(self)
Definition: z3py.py:3250
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_ast Z3_API Z3_mk_seq_index(Z3_context c, Z3_ast s, Z3_ast substr, Z3_ast offset)
Return index of first occurrence of substr in s starting from offset offset. If s does not contain su...
def non_units(self)
Definition: z3py.py:6802
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def BVRedAnd(a)
Definition: z3py.py:4157
def to_string(self, queries)
Definition: z3py.py:7170
def assertions(self)
Definition: z3py.py:6783
def z3_debug()
Definition: z3py.py:58
Z3_ast Z3_API Z3_mk_re_range(Z3_context c, Z3_ast lo, Z3_ast hi)
Create the range regular expression over two sequences of length 1.
def as_long(self)
Definition: z3py.py:2757
def constructor(self, idx)
Definition: z3py.py:4893
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def unsat_core(self)
Definition: z3py.py:6683
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
def isZero(self)
Definition: z3py.py:9128
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...
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
def __getitem__(self, key)
Definition: z3py.py:5659
def get_id(self)
Definition: z3py.py:360
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9485
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9699
def __lt__(self, other)
Definition: z3py.py:7957
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
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.
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
def create(self)
Definition: z3py.py:4752
def Full(s)
Definition: z3py.py:10136
def is_const_array(a)
Definition: z3py.py:4311
def __sub__(self, other)
Definition: z3py.py:8866
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
def fpNaN(s)
Definition: z3py.py:9243
def cast(self, val)
Definition: z3py.py:2146
def as_long(self)
Definition: z3py.py:7268
def sexpr(self)
Definition: z3py.py:347
def reason_unknown(self)
Definition: z3py.py:7481
def __setitem__(self, i, v)
Definition: z3py.py:5517
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
def kind(self)
Definition: z3py.py:521
def IntSort(ctx=None)
Definition: z3py.py:2911
def Unit(a)
Definition: z3py.py:10150
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def parse_string(self, s)
Definition: z3py.py:7145
def is_rational_value(a)
Definition: z3py.py:2566
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:9573
def is_finite_domain(a)
Definition: z3py.py:7252
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 __init__(self, r)
Definition: z3py.py:6401
def at(self, i)
Definition: z3py.py:10007
def __init__(self, *args, **kws)
Definition: z3py.py:174
def fpNeg(a, ctx=None)
Definition: z3py.py:9409
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:9644
def get_ground_sat_answer(self)
Definition: z3py.py:7099
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4998
Z3_string Z3_API Z3_solver_get_reason_unknown(Z3_context c, Z3_solver s)
Return a brief justification for an "unknown" result (i.e., Z3_L_UNDEF) for the commands Z3_solver_ch...
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_re_empty(Z3_context c, Z3_sort re)
Create an empty regular expression of sort re.
def __div__(self, other)
Definition: z3py.py:8930
def get_interp(self, decl)
Definition: z3py.py:6054
def is_as_array(n)
Definition: z3py.py:6244
def __gt__(self, other)
Definition: z3py.py:3544
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
def is_string(self)
Definition: z3py.py:10012
def sexpr(self)
Definition: z3py.py:7165
def __ne__(self, other)
Definition: z3py.py:8022
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
def __init__(self, c, ctx)
Definition: z3py.py:4779
def erase(self, k)
Definition: z3py.py:5689
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
def arg(self, idx)
Definition: z3py.py:987
def sort(self)
Definition: z3py.py:8800
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
def __init__(self, name, ctx=None)
Definition: z3py.py:4712
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_ast Z3_API Z3_mk_fpa_round_toward_negative(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardNegative rounding mode.
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.
def get_kind(self, n)
Definition: z3py.py:5127
def RoundTowardZero(ctx=None)
Definition: z3py.py:9014
def consequences(self, assumptions, variables)
Definition: z3py.py:6715
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 PiecewiseLinearOrder(a, index)
Definition: z3py.py:10439
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
def IntToStr(s)
Definition: z3py.py:10269
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
def Xor(a, b, ctx=None)
Definition: z3py.py:1638
def declare(self, name, *args)
Definition: z3py.py:4729
Z3_lbool Z3_API Z3_solver_get_consequences(Z3_context c, Z3_solver s, Z3_ast_vector assumptions, Z3_ast_vector variables, Z3_ast_vector consequences)
retrieve consequences from solver that determine values of the supplied function symbols.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def Select(a, i)
Definition: z3py.py:4468
def check(self, *assumptions)
Definition: z3py.py:7472
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7016
def __rmul__(self, other)
Definition: z3py.py:1411
def __ge__(self, other)
Definition: z3py.py:2468
def from_file(self, filename)
Definition: z3py.py:6743
def params(self)
Definition: z3py.py:733
def denominator(self)
Definition: z3py.py:2796
def __mod__(self, other)
Definition: z3py.py:8966
def RecAddDefinition(f, args, body)
Definition: z3py.py:843
def get_var_index(a)
Definition: z3py.py:1206
def Not(a, ctx=None)
Definition: z3py.py:1653
def sexpr(self)
Definition: z3py.py:5603
def BoolVal(val, ctx=None)
Definition: z3py.py:1552
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
def upper_values(self)
Definition: z3py.py:7345
def model(self)
Definition: z3py.py:7485
def __repr__(self)
Definition: z3py.py:6859
def is_div(a)
Definition: z3py.py:2633
FP Numerals.
Definition: z3py.py:9040
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
def trail_levels(self)
Definition: z3py.py:6807
FP Sorts.
Definition: z3py.py:8696
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def ctx_ref(self)
Definition: z3py.py:364
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
def help(self)
Definition: z3py.py:6978
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
def Re(s, ctx=None)
Definition: z3py.py:10276
def __len__(self)
Definition: z3py.py:5117
Z3_ast Z3_API Z3_mk_re_full(Z3_context c, Z3_sort re)
Create an universal regular expression of sort re.
bool Z3_API Z3_fpa_is_numeral_nan(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a NaN.
def fpMin(a, b, ctx=None)
Definition: z3py.py:9540
def is_fp_sort(s)
Definition: z3py.py:8775
def cube(self, vars=None)
Definition: z3py.py:6751
Z3_ast Z3_API Z3_mk_lstring(Z3_context c, unsigned len, Z3_string s)
Create a string constant out of the string that is passed in It takes the length of the string as wel...
Expressions.
Definition: z3py.py:875
def OrElse(*ts, **ks)
Definition: z3py.py:7780
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_away(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
def __init__(self, m, ctx)
Definition: z3py.py:5967
def SetComplement(s)
Definition: z3py.py:4636
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
def is_app_of(a, k)
Definition: z3py.py:1238
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def is_probe(p)
Definition: z3py.py:8064
def is_mul(a)
Definition: z3py.py:2611
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4206
def no_pattern(self, idx)
Definition: z3py.py:1929
def ebits(self)
Definition: z3py.py:8699
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:3049
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def subsort(self, other)
Definition: z3py.py:537
def kind(self)
Definition: z3py.py:721
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
def set(self, name, val)
Definition: z3py.py:5050
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
def is_bv_sort(s)
Definition: z3py.py:3226
def Update(a, i, v)
Definition: z3py.py:4420
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
def Function(name, *sig)
Definition: z3py.py:801
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
def append_log(s)
Definition: z3py.py:107
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
def __rmod__(self, other)
Definition: z3py.py:8970
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
def statistics(self)
Definition: z3py.py:7178
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
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 __deepcopy__(self, memo={})
Definition: z3py.py:6404
def as_ast(self)
Definition: z3py.py:1757
def __deepcopy__(self, memo={})
Definition: z3py.py:5169
def is_add(a)
Definition: z3py.py:2600
def Then(*ts, **ks)
Definition: z3py.py:7768
Z3_ast_vector Z3_API Z3_solver_get_non_units(Z3_context c, Z3_solver s)
Return the set of non units in the solver state.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
def __init__(self, m=None, ctx=None)
Definition: z3py.py:5615
def recognizer(self, idx)
Definition: z3py.py:4912
def K(dom, v)
Definition: z3py.py:4505
def __div__(self, other)
Definition: z3py.py:2334
def __copy__(self)
Definition: z3py.py:5406
def ArraySort(*sig)
Definition: z3py.py:4375
def __repr__(self)
Definition: z3py.py:5977
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3744
def __del__(self)
Definition: z3py.py:5747
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
def __getitem__(self, arg)
Definition: z3py.py:5137
def weight(self)
Definition: z3py.py:1881
def Ext(a, b)
Definition: z3py.py:4526
def PartialOrder(a, index)
Definition: z3py.py:10430
def dimacs(self)
Definition: z3py.py:5379
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7135
def BVSNegNoOverflow(a)
Definition: z3py.py:4200
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.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
def is_int(self)
Definition: z3py.py:2831
def __hash__(self)
Definition: z3py.py:931
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3038
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9469
def get_assertions(self)
Definition: z3py.py:7157
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...
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
def sexpr(self)
Definition: z3py.py:5980
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def SetUnion(*args)
Definition: z3py.py:4592
def get_num_levels(self, predicate)
Definition: z3py.py:7116
def __neg__(self)
Definition: z3py.py:8921
Z3_string Z3_API Z3_fpa_get_numeral_exponent_string(Z3_context c, Z3_ast t, bool biased)
Return the exponent value of a floating-point numeral as a string.
def UGT(a, b)
Definition: z3py.py:3940
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
Z3_ast Z3_API Z3_mk_seq_in_re(Z3_context c, Z3_ast seq, Z3_ast re)
Check if seq is in the language generated by the regular expression re.
def check(self, *assumptions)
Definition: z3py.py:6632
def get_answer(self)
Definition: z3py.py:7094
Z3_func_decl Z3_API Z3_mk_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a linear ordering relation over signature a. The relation is identified by the index id.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
def children(self)
Definition: z3py.py:1008
def __len__(self)
Definition: z3py.py:6292
def BV2Int(a, is_signed=False)
Definition: z3py.py:3714
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
def arity(self)
Definition: z3py.py:5899
Z3_ast Z3_API Z3_mk_str_lt(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is lexicographically strictly less than s2.
def Product(*args)
Definition: z3py.py:8288
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
bool Z3_API Z3_fpa_is_numeral_zero(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is +zero or -zero.
def size(self)
Definition: z3py.py:5112
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def WithParams(t, p)
Definition: z3py.py:7849
def Store(a, i, v)
Definition: z3py.py:4452
Z3_sort Z3_API Z3_mk_fpa_sort_64(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
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.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7881
def AndThen(*ts, **ks)
Definition: z3py.py:7749
Z3_param_descrs Z3_API Z3_solver_get_param_descrs(Z3_context c, Z3_solver s)
Return the parameter description set for the given solver object.
def numerator(self)
Definition: z3py.py:2781
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_solver_get_levels(Z3_context c, Z3_solver s, Z3_ast_vector literals, unsigned sz, unsigned levels[])
retrieve the decision depth of Boolean literals (variables or their negations). Assumes a check-sat c...
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5035
def __mul__(self, other)
Definition: z3py.py:2258
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
def __str__(self)
Definition: z3py.py:322
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4213
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
def keys(self)
Definition: z3py.py:5718
def is_int(self)
Definition: z3py.py:1399
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_seq_empty(Z3_context c, Z3_sort seq)
Create an empty sequence of the sequence sort seq.
def trail(self)
Definition: z3py.py:6815
def is_ast(a)
Definition: z3py.py:414
Z3_ast Z3_API Z3_mk_seq_to_re(Z3_context c, Z3_ast seq)
Create a regular expression that accepts the sequence seq.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_fpa_zero(Z3_context c, Z3_sort s, bool negative)
Create a floating-point zero of sort s.
Z3_sort Z3_API Z3_mk_fpa_sort_double(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
def __len__(self)
Definition: z3py.py:5254
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5160
def __mul__(self, other)
Definition: z3py.py:8889
def query(self, *query)
Definition: z3py.py:7047
def domain(self)
Definition: z3py.py:4260
def Empty(s)
Definition: z3py.py:10117
def __rmod__(self, other)
Definition: z3py.py:3494
def __init__(self, ast, ctx=None)
Definition: z3py.py:309
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_params_set_bool(Z3_context c, Z3_params p, Z3_symbol k, bool v)
Add a Boolean parameter k with value v to the parameter set p.
def UDiv(a, b)
Definition: z3py.py:3957
def __add__(self, other)
Definition: z3py.py:10308
def __lt__(self, other)
Definition: z3py.py:8834
def pop(self, num=1)
Definition: z3py.py:6492
def is_expr(a)
Definition: z3py.py:1117
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
def __radd__(self, other)
Definition: z3py.py:9999
def __init__(self, result, ctx)
Definition: z3py.py:7556
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7197
def keys(self)
Definition: z3py.py:6330
def RecFunction(name, *sig)
Definition: z3py.py:826
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
def fpToReal(x, ctx=None)
Definition: z3py.py:9902
def __rtruediv__(self, other)
Definition: z3py.py:2378
def set_option(*args, **kws)
Definition: z3py.py:270
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 statistics(self)
Definition: z3py.py:6820
def subsort(self, other)
Definition: z3py.py:3206
def else_value(self)
Definition: z3py.py:5860
def __rlshift__(self, other)
Definition: z3py.py:3634
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
def subsort(self, other)
Definition: z3py.py:1396
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
def describe_probes()
Definition: z3py.py:8098
def add_cover(self, level, predicate, property)
Definition: z3py.py:7125
def sort(self)
Definition: z3py.py:4971
def describe_tactics()
Definition: z3py.py:7907
def is_bool(a)
Definition: z3py.py:1424
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 __truediv__(self, other)
Definition: z3py.py:8958
def cube_vars(self)
Definition: z3py.py:6772
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6013
def as_string(self)
Definition: z3py.py:8977
def __call__(self, goal)
Definition: z3py.py:8036
Z3_ast Z3_API Z3_mk_fpa_inf(Z3_context c, Z3_sort s, bool negative)
Create a floating-point infinity of sort s.
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 translate(self, other_ctx)
Definition: z3py.py:5933
def unsat_core(self)
Definition: z3py.py:7492
def body(self)
Definition: z3py.py:1935
def as_list(self)
Definition: z3py.py:5944
def __del__(self)
Definition: z3py.py:5108
entry
Definition: z3py.py:5740
Z3_ast Z3_API Z3_mk_re_union(Z3_context c, unsigned n, Z3_ast const args[])
Create the union of the regular languages.
def prove(claim, **keywords)
Definition: z3py.py:8460
def arity(self)
Definition: z3py.py:690
def assert_exprs(self, *args)
Definition: z3py.py:5295
def Reals(names, ctx=None)
Definition: z3py.py:3074
def is_bv(a)
Definition: z3py.py:3687
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def __rpow__(self, other)
Definition: z3py.py:2320
def SetAdd(s, e)
Definition: z3py.py:4616
def fpInfinity(s, negative)
Definition: z3py.py:9280
def is_var(a)
Definition: z3py.py:1182
def as_expr(self)
Definition: z3py.py:7612
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
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....
def as_string(self)
Definition: z3py.py:9154
def __copy__(self)
Definition: z3py.py:401
def __rdiv__(self, other)
Definition: z3py.py:8945
def __copy__(self)
Definition: z3py.py:6876
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9781
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9688
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:7862
def RepeatBitVec(n, a)
Definition: z3py.py:4134
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 ...
def sort(self)
Definition: z3py.py:9993
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
Z3_ast Z3_API Z3_mk_fpa_nan(Z3_context c, Z3_sort s)
Create a floating-point NaN of sort s.
def __invert__(self)
Definition: z3py.py:3419
def precision(self)
Definition: z3py.py:5232
def __getitem__(self, idx)
Definition: z3py.py:6306
def __repr__(self)
Definition: z3py.py:5686
def SolverFor(logic, ctx=None)
Definition: z3py.py:6913
def import_model_converter(self, other)
Definition: z3py.py:6679
def proof(self)
Definition: z3py.py:6779
def get_full_version()
Definition: z3py.py:91
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7818
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.
bool Z3_API Z3_fpa_get_numeral_sign(Z3_context c, Z3_ast t, int *sgn)
Retrieves the sign of a floating-point literal.
def lower(self)
Definition: z3py.py:7333
def as_ast(self)
Definition: z3py.py:670
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def is_false(a)
Definition: z3py.py:1458
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
Z3_sort Z3_API Z3_mk_fpa_sort_16(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
def FloatHalf(ctx=None)
Definition: z3py.py:8736
def ULE(a, b)
Definition: z3py.py:3889
def __rmul__(self, other)
Definition: z3py.py:3297
def is_is_int(a)
Definition: z3py.py:2715
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
def ebits(self)
Definition: z3py.py:8811
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 __copy__(self)
Definition: z3py.py:5594
Z3_sort Z3_API Z3_mk_fpa_sort_128(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
def sign(self)
Definition: z3py.py:9050
def as_string(self)
Definition: z3py.py:8827
def fpIsZero(a, ctx=None)
Definition: z3py.py:9604
def __rand__(self, other)
Definition: z3py.py:3366
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:9614
def enable_trace(msg)
Definition: z3py.py:69
def range(self)
Definition: z3py.py:4239
Z3_ast Z3_API Z3_mk_seq_unit(Z3_context c, Z3_ast a)
Create a unit sequence of a.
def arg_value(self, idx)
Definition: z3py.py:5769
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
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 __deepcopy__(self, memo={})
Definition: z3py.py:6267
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
def name(self)
Definition: z3py.py:560
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9800
def is_fprm(a)
Definition: z3py.py:9022
def Complement(re)
Definition: z3py.py:10388
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
def __deepcopy__(self, memo={})
Definition: z3py.py:5744
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def __iadd__(self, fml)
Definition: z3py.py:7004
def __truediv__(self, other)
Definition: z3py.py:3449
Z3_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i)
Array read. The argument a is the array and i is the index of the array that gets read.
def significand(self)
Definition: z3py.py:9069
bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a)
The (_ as-array f) AST node is a construct for assigning interpretations for arrays in Z3....
def Option(re)
Definition: z3py.py:10376
def __copy__(self)
Definition: z3py.py:5938
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_sort Z3_API Z3_mk_re_sort(Z3_context c, Z3_sort seq)
Create a regular expression sort out of a sequence sort.
def as_signed_long(self)
Definition: z3py.py:3662
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_ast Z3_API Z3_mk_set_has_size(Z3_context c, Z3_ast set, Z3_ast k)
Create predicate that holds if Boolean array set has k elements set to true.
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.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
def __repr__(self)
Definition: z3py.py:5961
backtrack_level
Definition: z3py.py:6446
def fpIsPositive(a, ctx=None)
Definition: z3py.py:9624
def __del__(self)
Definition: z3py.py:6968
def is_func_decl(a)
Definition: z3py.py:789
def interrupt(self)
Definition: z3py.py:202
def __rsub__(self, other)
Definition: z3py.py:2296
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
def is_sub(a)
Definition: z3py.py:2622
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
def FailIf(p, ctx=None)
Definition: z3py.py:8131
def __hash__(self)
Definition: z3py.py:331
def __gt__(self, other)
Definition: z3py.py:10033
def as_long(self)
Definition: z3py.py:2840
def When(p, t, ctx=None)
Definition: z3py.py:8150
def is_seq(a)
Definition: z3py.py:10056
def num_vars(self)
Definition: z3py.py:1946
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
def is_real(self)
Definition: z3py.py:2834
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
def is_algebraic_value(a)
Definition: z3py.py:2587
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
def num_scopes(self)
Definition: z3py.py:6514
def BoolSort(ctx=None)
Definition: z3py.py:1535
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def get_param(name)
Definition: z3py.py:275
def is_to_int(a)
Definition: z3py.py:2740
def __copy__(self)
Definition: z3py.py:6234
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
def __eq__(self, other)
Definition: z3py.py:8009
def Q(a, b, ctx=None)
Definition: z3py.py:3002
def __deepcopy__(self, memo={})
Definition: z3py.py:7950
def String(name, ctx=None)
Definition: z3py.py:10087
def is_string(self)
Definition: z3py.py:9957
def __deepcopy__(self, memo={})
Definition: z3py.py:5043
def __radd__(self, other)
Definition: z3py.py:8856
def translate(self, target)
Definition: z3py.py:6226
def reason_unknown(self)
Definition: z3py.py:7183
Z3_ast Z3_API Z3_mk_int_to_str(Z3_context c, Z3_ast s)
Integer to string conversion.
def __lshift__(self, other)
Definition: z3py.py:3606
def __ror__(self, other)
Definition: z3py.py:3343
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
def IsMember(e, s)
Definition: z3py.py:4655
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.
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
def ToInt(a)
Definition: z3py.py:3131
def num_entries(self)
Definition: z3py.py:5883
Z3_ast Z3_API Z3_mk_seq_last_index(Z3_context c, Z3_ast, Z3_ast substr)
Return the last occurrence of substr in s. If s does not contain substr, then the value is -1,...
def dimacs(self)
Definition: z3py.py:6893
def __del__(self)
Definition: z3py.py:314
Z3_ast_vector Z3_API Z3_solver_get_trail(Z3_context c, Z3_solver s)
Return the trail modulo model conversion, in order of decision level The decision level can be retrie...
def is_fp(a)
Definition: z3py.py:9158
def __eq__(self, other)
Definition: z3py.py:570
def Sqrt(a, ctx=None)
Definition: z3py.py:3164
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....
def fpLT(a, b, ctx=None)
Definition: z3py.py:9633
Z3_ast Z3_API Z3_mk_seq_contains(Z3_context c, Z3_ast container, Z3_ast containee)
Check if container contains containee.
def __sub__(self, other)
Definition: z3py.py:2283
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
def SimpleSolver(ctx=None)
Definition: z3py.py:6933
def __rsub__(self, other)
Definition: z3py.py:3320
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.