Z3
z3py.py
Go to the documentation of this file.
1 
2 
3 
10 
11 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
12 
13 Several online tutorials for Z3Py are available at:
14 http://rise4fun.com/Z3Py/tutorial/guide
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
17 
18 Small example:
19 
20 >>> x = Int('x')
21 >>> y = Int('y')
22 >>> s = Solver()
23 >>> s.add(x > 0)
24 >>> s.add(x < 2)
25 >>> s.add(y == x + 1)
26 >>> s.check()
27 sat
28 >>> m = s.model()
29 >>> m[x]
30 1
31 >>> m[y]
32 2
33 
34 Z3 exceptions:
35 
36 >>> try:
37 ... x = BitVec('x', 32)
38 ... y = Bool('y')
39 ... # the expression x + y is type incorrect
40 ... n = x + y
41 ... except Z3Exception as ex:
42 ... print("failed: %s" % ex)
43 failed: sort mismatch
44 """
45 from . import z3core
46 from .z3core import *
47 from .z3types import *
48 from .z3consts import *
49 from .z3printer import *
50 from fractions import Fraction
51 import sys
52 import io
53 import math
54 import copy
55 
56 if sys.version < '3':
57  def _is_int(v):
58  return isinstance(v, (int, long))
59 else:
60  def _is_int(v):
61  return isinstance(v, int)
62 
63 def enable_trace(msg):
64  Z3_enable_trace(msg)
65 
66 def disable_trace(msg):
67  Z3_disable_trace(msg)
68 
70  major = ctypes.c_uint(0)
71  minor = ctypes.c_uint(0)
72  build = ctypes.c_uint(0)
73  rev = ctypes.c_uint(0)
74  Z3_get_version(major, minor, build, rev)
75  return "%s.%s.%s" % (major.value, minor.value, build.value)
76 
78  major = ctypes.c_uint(0)
79  minor = ctypes.c_uint(0)
80  build = ctypes.c_uint(0)
81  rev = ctypes.c_uint(0)
82  Z3_get_version(major, minor, build, rev)
83  return (major.value, minor.value, build.value, rev.value)
84 
86  return Z3_get_full_version()
87 
88 # We use _z3_assert instead of the assert command because we want to
89 # produce nice error messages in Z3Py at rise4fun.com
90 def _z3_assert(cond, msg):
91  if not cond:
92  raise Z3Exception(msg)
93 
94 def _z3_check_cint_overflow(n, name):
95  _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
96 
97 def open_log(fname):
98  """Log interaction to a file. This function must be invoked immediately after init(). """
99  Z3_open_log(fname)
100 
101 def append_log(s):
102  """Append user-defined string to interaction log. """
103  Z3_append_log(s)
104 
105 def to_symbol(s, ctx=None):
106  """Convert an integer or string into a Z3 symbol."""
107  if _is_int(s):
108  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
109  else:
110  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
111 
112 def _symbol2py(ctx, s):
113  """Convert a Z3 symbol back into a Python object. """
114  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
115  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
116  else:
117  return Z3_get_symbol_string(ctx.ref(), s)
118 
119 # Hack for having nary functions that can receive one argument that is the
120 # list of arguments.
121 # Use this when function takes a single list of arguments
122 def _get_args(args):
123  try:
124  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
125  return args[0]
126  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
127  return [arg for arg in args[0]]
128  else:
129  return args
130  except: # len is not necessarily defined when args is not a sequence (use reflection?)
131  return args
132 
133 # Use this when function takes multiple arguments
134 def _get_args_ast_list(args):
135  try:
136  if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
137  return [arg for arg in args]
138  else:
139  return args
140  except:
141  return args
142 
143 def _to_param_value(val):
144  if isinstance(val, bool):
145  if val == True:
146  return "true"
147  else:
148  return "false"
149  else:
150  return str(val)
151 
153  # Do nothing error handler, just avoid exit(0)
154  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
155  return
156 
157 class Context:
158  """A Context manages all other Z3 objects, global configuration options, etc.
159 
160  Z3Py uses a default global context. For most applications this is sufficient.
161  An application may use multiple Z3 contexts. Objects created in one context
162  cannot be used in another one. However, several objects may be "translated" from
163  one context to another. It is not safe to access Z3 objects from multiple threads.
164  The only exception is the method `interrupt()` that can be used to interrupt() a long
165  computation.
166  The initialization method receives global configuration options for the new context.
167  """
168  def __init__(self, *args, **kws):
169  if __debug__:
170  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
171  conf = Z3_mk_config()
172  for key in kws:
173  value = kws[key]
174  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
175  prev = None
176  for a in args:
177  if prev is None:
178  prev = a
179  else:
180  Z3_set_param_value(conf, str(prev), _to_param_value(a))
181  prev = None
182  self.ctx = Z3_mk_context_rc(conf)
183  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
184  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
185  Z3_del_config(conf)
186 
187  def __del__(self):
188  Z3_del_context(self.ctx)
189  self.ctx = None
190  self.eh = None
191 
192  def ref(self):
193  """Return a reference to the actual C pointer to the Z3 context."""
194  return self.ctx
195 
196  def interrupt(self):
197  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
198 
199  This method can be invoked from a thread different from the one executing the
200  interruptible procedure.
201  """
202  Z3_interrupt(self.ref())
203 
204 
205 # Global Z3 context
206 _main_ctx = None
207 def main_ctx():
208  """Return a reference to the global Z3 context.
209 
210  >>> x = Real('x')
211  >>> x.ctx == main_ctx()
212  True
213  >>> c = Context()
214  >>> c == main_ctx()
215  False
216  >>> x2 = Real('x', c)
217  >>> x2.ctx == c
218  True
219  >>> eq(x, x2)
220  False
221  """
222  global _main_ctx
223  if _main_ctx is None:
224  _main_ctx = Context()
225  return _main_ctx
226 
227 def _get_ctx(ctx):
228  if ctx is None:
229  return main_ctx()
230  else:
231  return ctx
232 
233 def set_param(*args, **kws):
234  """Set Z3 global (or module) parameters.
235 
236  >>> set_param(precision=10)
237  """
238  if __debug__:
239  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
240  new_kws = {}
241  for k in kws:
242  v = kws[k]
243  if not set_pp_option(k, v):
244  new_kws[k] = v
245  for key in new_kws:
246  value = new_kws[key]
247  Z3_global_param_set(str(key).upper(), _to_param_value(value))
248  prev = None
249  for a in args:
250  if prev is None:
251  prev = a
252  else:
253  Z3_global_param_set(str(prev), _to_param_value(a))
254  prev = None
255 
257  """Reset all global (or module) parameters.
258  """
260 
261 def set_option(*args, **kws):
262  """Alias for 'set_param' for backward compatibility.
263  """
264  return set_param(*args, **kws)
265 
266 def get_param(name):
267  """Return the value of a Z3 global (or module) parameter
268 
269  >>> get_param('nlsat.reorder')
270  'true'
271  """
272  ptr = (ctypes.c_char_p * 1)()
273  if Z3_global_param_get(str(name), ptr):
274  r = z3core._to_pystr(ptr[0])
275  return r
276  raise Z3Exception("failed to retrieve value for '%s'" % name)
277 
278 
283 
284 # Mark objects that use pretty printer
286  """Superclass for all Z3 objects that have support for pretty printing."""
287  def use_pp(self):
288  return True
289 
291  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
292  def __init__(self, ast, ctx=None):
293  self.ast = ast
294  self.ctx = _get_ctx(ctx)
295  Z3_inc_ref(self.ctx.ref(), self.as_ast())
296 
297  def __del__(self):
298  if self.ctx.ref() is not None:
299  Z3_dec_ref(self.ctx.ref(), self.as_ast())
300 
301  def __deepcopy__(self, memo={}):
302  return _to_ast_ref(self.ast, self.ctx)
303 
304  def __str__(self):
305  return obj_to_string(self)
306 
307  def __repr__(self):
308  return obj_to_string(self)
309 
310  def __eq__(self, other):
311  return self.eq(other)
312 
313  def __hash__(self):
314  return self.hash()
315 
316  def __nonzero__(self):
317  return self.__bool__()
318 
319  def __bool__(self):
320  if is_true(self):
321  return True
322  elif is_false(self):
323  return False
324  elif is_eq(self) and self.num_args() == 2:
325  return self.arg(0).eq(self.arg(1))
326  else:
327  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
328 
329  def sexpr(self):
330  """Return a string representing the AST node in s-expression notation.
331 
332  >>> x = Int('x')
333  >>> ((x + 1)*x).sexpr()
334  '(* (+ x 1) x)'
335  """
336  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
337 
338  def as_ast(self):
339  """Return a pointer to the corresponding C Z3_ast object."""
340  return self.ast
341 
342  def get_id(self):
343  """Return unique identifier for object. It can be used for hash-tables and maps."""
344  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
345 
346  def ctx_ref(self):
347  """Return a reference to the C context where this AST node is stored."""
348  return self.ctx.ref()
349 
350  def eq(self, other):
351  """Return `True` if `self` and `other` are structurally identical.
352 
353  >>> x = Int('x')
354  >>> n1 = x + 1
355  >>> n2 = 1 + x
356  >>> n1.eq(n2)
357  False
358  >>> n1 = simplify(n1)
359  >>> n2 = simplify(n2)
360  >>> n1.eq(n2)
361  True
362  """
363  if __debug__:
364  _z3_assert(is_ast(other), "Z3 AST expected")
365  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
366 
367  def translate(self, target):
368  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
369 
370  >>> c1 = Context()
371  >>> c2 = Context()
372  >>> x = Int('x', c1)
373  >>> y = Int('y', c2)
374  >>> # Nodes in different contexts can't be mixed.
375  >>> # However, we can translate nodes from one context to another.
376  >>> x.translate(c2) + y
377  x + y
378  """
379  if __debug__:
380  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
381  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
382 
383  def __copy__(self):
384  return self.translate(self.ctx)
385 
386  def hash(self):
387  """Return a hashcode for the `self`.
388 
389  >>> n1 = simplify(Int('x') + 1)
390  >>> n2 = simplify(2 + Int('x') - 1)
391  >>> n1.hash() == n2.hash()
392  True
393  """
394  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
395 
396 def is_ast(a):
397  """Return `True` if `a` is an AST node.
398 
399  >>> is_ast(10)
400  False
401  >>> is_ast(IntVal(10))
402  True
403  >>> is_ast(Int('x'))
404  True
405  >>> is_ast(BoolSort())
406  True
407  >>> is_ast(Function('f', IntSort(), IntSort()))
408  True
409  >>> is_ast("x")
410  False
411  >>> is_ast(Solver())
412  False
413  """
414  return isinstance(a, AstRef)
415 
416 def eq(a, b):
417  """Return `True` if `a` and `b` are structurally identical AST nodes.
418 
419  >>> x = Int('x')
420  >>> y = Int('y')
421  >>> eq(x, y)
422  False
423  >>> eq(x + 1, x + 1)
424  True
425  >>> eq(x + 1, 1 + x)
426  False
427  >>> eq(simplify(x + 1), simplify(1 + x))
428  True
429  """
430  if __debug__:
431  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
432  return a.eq(b)
433 
434 def _ast_kind(ctx, a):
435  if is_ast(a):
436  a = a.as_ast()
437  return Z3_get_ast_kind(ctx.ref(), a)
438 
439 def _ctx_from_ast_arg_list(args, default_ctx=None):
440  ctx = None
441  for a in args:
442  if is_ast(a) or is_probe(a):
443  if ctx is None:
444  ctx = a.ctx
445  else:
446  if __debug__:
447  _z3_assert(ctx == a.ctx, "Context mismatch")
448  if ctx is None:
449  ctx = default_ctx
450  return ctx
451 
452 def _ctx_from_ast_args(*args):
453  return _ctx_from_ast_arg_list(args)
454 
455 def _to_func_decl_array(args):
456  sz = len(args)
457  _args = (FuncDecl * sz)()
458  for i in range(sz):
459  _args[i] = args[i].as_func_decl()
460  return _args, sz
461 
462 def _to_ast_array(args):
463  sz = len(args)
464  _args = (Ast * sz)()
465  for i in range(sz):
466  _args[i] = args[i].as_ast()
467  return _args, sz
468 
469 def _to_ref_array(ref, args):
470  sz = len(args)
471  _args = (ref * sz)()
472  for i in range(sz):
473  _args[i] = args[i].as_ast()
474  return _args, sz
475 
476 def _to_ast_ref(a, ctx):
477  k = _ast_kind(ctx, a)
478  if k == Z3_SORT_AST:
479  return _to_sort_ref(a, ctx)
480  elif k == Z3_FUNC_DECL_AST:
481  return _to_func_decl_ref(a, ctx)
482  else:
483  return _to_expr_ref(a, ctx)
484 
485 
490 
491 def _sort_kind(ctx, s):
492  return Z3_get_sort_kind(ctx.ref(), s)
493 
495  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
496  def as_ast(self):
497  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
498 
499  def get_id(self):
500  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
501 
502  def kind(self):
503  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
504 
505  >>> b = BoolSort()
506  >>> b.kind() == Z3_BOOL_SORT
507  True
508  >>> b.kind() == Z3_INT_SORT
509  False
510  >>> A = ArraySort(IntSort(), IntSort())
511  >>> A.kind() == Z3_ARRAY_SORT
512  True
513  >>> A.kind() == Z3_INT_SORT
514  False
515  """
516  return _sort_kind(self.ctx, self.ast)
517 
518  def subsort(self, other):
519  """Return `True` if `self` is a subsort of `other`.
520 
521  >>> IntSort().subsort(RealSort())
522  True
523  """
524  return False
525 
526  def cast(self, val):
527  """Try to cast `val` as an element of sort `self`.
528 
529  This method is used in Z3Py to convert Python objects such as integers,
530  floats, longs and strings into Z3 expressions.
531 
532  >>> x = Int('x')
533  >>> RealSort().cast(x)
534  ToReal(x)
535  """
536  if __debug__:
537  _z3_assert(is_expr(val), "Z3 expression expected")
538  _z3_assert(self.eq(val.sort()), "Sort mismatch")
539  return val
540 
541  def name(self):
542  """Return the name (string) of sort `self`.
543 
544  >>> BoolSort().name()
545  'Bool'
546  >>> ArraySort(IntSort(), IntSort()).name()
547  'Array'
548  """
549  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
550 
551  def __eq__(self, other):
552  """Return `True` if `self` and `other` are the same Z3 sort.
553 
554  >>> p = Bool('p')
555  >>> p.sort() == BoolSort()
556  True
557  >>> p.sort() == IntSort()
558  False
559  """
560  if other is None:
561  return False
562  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
563 
564  def __ne__(self, other):
565  """Return `True` if `self` and `other` are not the same Z3 sort.
566 
567  >>> p = Bool('p')
568  >>> p.sort() != BoolSort()
569  False
570  >>> p.sort() != IntSort()
571  True
572  """
573  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
574 
575  def __hash__(self):
576  """ Hash code. """
577  return AstRef.__hash__(self)
578 
579 def is_sort(s):
580  """Return `True` if `s` is a Z3 sort.
581 
582  >>> is_sort(IntSort())
583  True
584  >>> is_sort(Int('x'))
585  False
586  >>> is_expr(Int('x'))
587  True
588  """
589  return isinstance(s, SortRef)
590 
591 def _to_sort_ref(s, ctx):
592  if __debug__:
593  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
594  k = _sort_kind(ctx, s)
595  if k == Z3_BOOL_SORT:
596  return BoolSortRef(s, ctx)
597  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
598  return ArithSortRef(s, ctx)
599  elif k == Z3_BV_SORT:
600  return BitVecSortRef(s, ctx)
601  elif k == Z3_ARRAY_SORT:
602  return ArraySortRef(s, ctx)
603  elif k == Z3_DATATYPE_SORT:
604  return DatatypeSortRef(s, ctx)
605  elif k == Z3_FINITE_DOMAIN_SORT:
606  return FiniteDomainSortRef(s, ctx)
607  elif k == Z3_FLOATING_POINT_SORT:
608  return FPSortRef(s, ctx)
609  elif k == Z3_ROUNDING_MODE_SORT:
610  return FPRMSortRef(s, ctx)
611  return SortRef(s, ctx)
612 
613 def _sort(ctx, a):
614  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
615 
616 def DeclareSort(name, ctx=None):
617  """Create a new uninterpreted sort named `name`.
618 
619  If `ctx=None`, then the new sort is declared in the global Z3Py context.
620 
621  >>> A = DeclareSort('A')
622  >>> a = Const('a', A)
623  >>> b = Const('b', A)
624  >>> a.sort() == A
625  True
626  >>> b.sort() == A
627  True
628  >>> a == b
629  a == b
630  """
631  ctx = _get_ctx(ctx)
632  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
633 
634 
639 
641  """Function declaration. Every constant and function have an associated declaration.
642 
643  The declaration assigns a name, a sort (i.e., type), and for function
644  the sort (i.e., type) of each of its arguments. Note that, in Z3,
645  a constant is a function with 0 arguments.
646  """
647  def as_ast(self):
648  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
649 
650  def get_id(self):
651  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
652 
653  def as_func_decl(self):
654  return self.ast
655 
656  def name(self):
657  """Return the name of the function declaration `self`.
658 
659  >>> f = Function('f', IntSort(), IntSort())
660  >>> f.name()
661  'f'
662  >>> isinstance(f.name(), str)
663  True
664  """
665  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
666 
667  def arity(self):
668  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
669 
670  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
671  >>> f.arity()
672  2
673  """
674  return int(Z3_get_arity(self.ctx_ref(), self.ast))
675 
676  def domain(self, i):
677  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
678 
679  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
680  >>> f.domain(0)
681  Int
682  >>> f.domain(1)
683  Real
684  """
685  if __debug__:
686  _z3_assert(i < self.arity(), "Index out of bounds")
687  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
688 
689  def range(self):
690  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
691 
692  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
693  >>> f.range()
694  Bool
695  """
696  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
697 
698  def kind(self):
699  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
700 
701  >>> x = Int('x')
702  >>> d = (x + 1).decl()
703  >>> d.kind() == Z3_OP_ADD
704  True
705  >>> d.kind() == Z3_OP_MUL
706  False
707  """
708  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
709 
710  def params(self):
711  ctx = self.ctx
712  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
713  result = [ None for i in range(n) ]
714  for i in range(n):
715  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
716  if k == Z3_PARAMETER_INT:
717  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
718  elif k == Z3_PARAMETER_DOUBLE:
719  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
720  elif k == Z3_PARAMETER_RATIONAL:
721  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
722  elif k == Z3_PARAMETER_SYMBOL:
723  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
724  elif k == Z3_PARAMETER_SORT:
725  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
726  elif k == Z3_PARAMETER_AST:
727  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
728  elif k == Z3_PARAMETER_FUNC_DECL:
729  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
730  else:
731  assert(False)
732  return result
733 
734  def __call__(self, *args):
735  """Create a Z3 application expression using the function `self`, and the given arguments.
736 
737  The arguments must be Z3 expressions. This method assumes that
738  the sorts of the elements in `args` match the sorts of the
739  domain. Limited coercion is supported. For example, if
740  args[0] is a Python integer, and the function expects a Z3
741  integer, then the argument is automatically converted into a
742  Z3 integer.
743 
744  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
745  >>> x = Int('x')
746  >>> y = Real('y')
747  >>> f(x, y)
748  f(x, y)
749  >>> f(x, x)
750  f(x, ToReal(x))
751  """
752  args = _get_args(args)
753  num = len(args)
754  if __debug__:
755  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
756  _args = (Ast * num)()
757  saved = []
758  for i in range(num):
759  # self.domain(i).cast(args[i]) may create a new Z3 expression,
760  # then we must save in 'saved' to prevent it from being garbage collected.
761  tmp = self.domain(i).cast(args[i])
762  saved.append(tmp)
763  _args[i] = tmp.as_ast()
764  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
765 
767  """Return `True` if `a` is a Z3 function declaration.
768 
769  >>> f = Function('f', IntSort(), IntSort())
770  >>> is_func_decl(f)
771  True
772  >>> x = Real('x')
773  >>> is_func_decl(x)
774  False
775  """
776  return isinstance(a, FuncDeclRef)
777 
778 def Function(name, *sig):
779  """Create a new Z3 uninterpreted function with the given sorts.
780 
781  >>> f = Function('f', IntSort(), IntSort())
782  >>> f(f(0))
783  f(f(0))
784  """
785  sig = _get_args(sig)
786  if __debug__:
787  _z3_assert(len(sig) > 0, "At least two arguments expected")
788  arity = len(sig) - 1
789  rng = sig[arity]
790  if __debug__:
791  _z3_assert(is_sort(rng), "Z3 sort expected")
792  dom = (Sort * arity)()
793  for i in range(arity):
794  if __debug__:
795  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
796  dom[i] = sig[i].ast
797  ctx = rng.ctx
798  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
799 
800 def _to_func_decl_ref(a, ctx):
801  return FuncDeclRef(a, ctx)
802 
803 def RecFunction(name, *sig):
804  """Create a new Z3 recursive with the given sorts."""
805  sig = _get_args(sig)
806  if __debug__:
807  _z3_assert(len(sig) > 0, "At least two arguments expected")
808  arity = len(sig) - 1
809  rng = sig[arity]
810  if __debug__:
811  _z3_assert(is_sort(rng), "Z3 sort expected")
812  dom = (Sort * arity)()
813  for i in range(arity):
814  if __debug__:
815  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
816  dom[i] = sig[i].ast
817  ctx = rng.ctx
818  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
819 
820 def RecAddDefinition(f, args, body):
821  """Set the body of a recursive function.
822  Recursive definitions are only unfolded during search.
823  >>> ctx = Context()
824  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
825  >>> n = Int('n', ctx)
826  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
827  >>> simplify(fac(5))
828  fac(5)
829  >>> s = Solver(ctx=ctx)
830  >>> s.add(fac(n) < 3)
831  >>> s.check()
832  sat
833  >>> s.model().eval(fac(5))
834  120
835  """
836  if is_app(args):
837  args = [args]
838  ctx = body.ctx
839  args = _get_args(args)
840  n = len(args)
841  _args = (Ast * n)()
842  for i in range(n):
843  _args[i] = args[i].ast
844  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
845 
846 
851 
853  """Constraints, formulas and terms are expressions in Z3.
854 
855  Expressions are ASTs. Every expression has a sort.
856  There are three main kinds of expressions:
857  function applications, quantifiers and bounded variables.
858  A constant is a function application with 0 arguments.
859  For quantifier free problems, all expressions are
860  function applications.
861  """
862  def as_ast(self):
863  return self.ast
864 
865  def get_id(self):
866  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
867 
868  def sort(self):
869  """Return the sort of expression `self`.
870 
871  >>> x = Int('x')
872  >>> (x + 1).sort()
873  Int
874  >>> y = Real('y')
875  >>> (x + y).sort()
876  Real
877  """
878  return _sort(self.ctx, self.as_ast())
879 
880  def sort_kind(self):
881  """Shorthand for `self.sort().kind()`.
882 
883  >>> a = Array('a', IntSort(), IntSort())
884  >>> a.sort_kind() == Z3_ARRAY_SORT
885  True
886  >>> a.sort_kind() == Z3_INT_SORT
887  False
888  """
889  return self.sort().kind()
890 
891  def __eq__(self, other):
892  """Return a Z3 expression that represents the constraint `self == other`.
893 
894  If `other` is `None`, then this method simply returns `False`.
895 
896  >>> a = Int('a')
897  >>> b = Int('b')
898  >>> a == b
899  a == b
900  >>> a is None
901  False
902  """
903  if other is None:
904  return False
905  a, b = _coerce_exprs(self, other)
906  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
907 
908  def __hash__(self):
909  """ Hash code. """
910  return AstRef.__hash__(self)
911 
912  def __ne__(self, other):
913  """Return a Z3 expression that represents the constraint `self != other`.
914 
915  If `other` is `None`, then this method simply returns `True`.
916 
917  >>> a = Int('a')
918  >>> b = Int('b')
919  >>> a != b
920  a != b
921  >>> a is not None
922  True
923  """
924  if other is None:
925  return True
926  a, b = _coerce_exprs(self, other)
927  _args, sz = _to_ast_array((a, b))
928  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
929 
930  def params(self):
931  return self.decl().params()
932 
933  def decl(self):
934  """Return the Z3 function declaration associated with a Z3 application.
935 
936  >>> f = Function('f', IntSort(), IntSort())
937  >>> a = Int('a')
938  >>> t = f(a)
939  >>> eq(t.decl(), f)
940  True
941  >>> (a + 1).decl()
942  +
943  """
944  if __debug__:
945  _z3_assert(is_app(self), "Z3 application expected")
946  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
947 
948  def num_args(self):
949  """Return the number of arguments of a Z3 application.
950 
951  >>> a = Int('a')
952  >>> b = Int('b')
953  >>> (a + b).num_args()
954  2
955  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
956  >>> t = f(a, b, 0)
957  >>> t.num_args()
958  3
959  """
960  if __debug__:
961  _z3_assert(is_app(self), "Z3 application expected")
962  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
963 
964  def arg(self, idx):
965  """Return argument `idx` of the application `self`.
966 
967  This method assumes that `self` is a function application with at least `idx+1` arguments.
968 
969  >>> a = Int('a')
970  >>> b = Int('b')
971  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
972  >>> t = f(a, b, 0)
973  >>> t.arg(0)
974  a
975  >>> t.arg(1)
976  b
977  >>> t.arg(2)
978  0
979  """
980  if __debug__:
981  _z3_assert(is_app(self), "Z3 application expected")
982  _z3_assert(idx < self.num_args(), "Invalid argument index")
983  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
984 
985  def children(self):
986  """Return a list containing the children of the given expression
987 
988  >>> a = Int('a')
989  >>> b = Int('b')
990  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
991  >>> t = f(a, b, 0)
992  >>> t.children()
993  [a, b, 0]
994  """
995  if is_app(self):
996  return [self.arg(i) for i in range(self.num_args())]
997  else:
998  return []
999 
1000 def _to_expr_ref(a, ctx):
1001  if isinstance(a, Pattern):
1002  return PatternRef(a, ctx)
1003  ctx_ref = ctx.ref()
1004  k = Z3_get_ast_kind(ctx_ref, a)
1005  if k == Z3_QUANTIFIER_AST:
1006  return QuantifierRef(a, ctx)
1007  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1008  if sk == Z3_BOOL_SORT:
1009  return BoolRef(a, ctx)
1010  if sk == Z3_INT_SORT:
1011  if k == Z3_NUMERAL_AST:
1012  return IntNumRef(a, ctx)
1013  return ArithRef(a, ctx)
1014  if sk == Z3_REAL_SORT:
1015  if k == Z3_NUMERAL_AST:
1016  return RatNumRef(a, ctx)
1017  if _is_algebraic(ctx, a):
1018  return AlgebraicNumRef(a, ctx)
1019  return ArithRef(a, ctx)
1020  if sk == Z3_BV_SORT:
1021  if k == Z3_NUMERAL_AST:
1022  return BitVecNumRef(a, ctx)
1023  else:
1024  return BitVecRef(a, ctx)
1025  if sk == Z3_ARRAY_SORT:
1026  return ArrayRef(a, ctx)
1027  if sk == Z3_DATATYPE_SORT:
1028  return DatatypeRef(a, ctx)
1029  if sk == Z3_FLOATING_POINT_SORT:
1030  if k == Z3_APP_AST and _is_numeral(ctx, a):
1031  return FPNumRef(a, ctx)
1032  else:
1033  return FPRef(a, ctx)
1034  if sk == Z3_FINITE_DOMAIN_SORT:
1035  if k == Z3_NUMERAL_AST:
1036  return FiniteDomainNumRef(a, ctx)
1037  else:
1038  return FiniteDomainRef(a, ctx)
1039  if sk == Z3_ROUNDING_MODE_SORT:
1040  return FPRMRef(a, ctx)
1041  if sk == Z3_SEQ_SORT:
1042  return SeqRef(a, ctx)
1043  if sk == Z3_RE_SORT:
1044  return ReRef(a, ctx)
1045  return ExprRef(a, ctx)
1046 
1047 def _coerce_expr_merge(s, a):
1048  if is_expr(a):
1049  s1 = a.sort()
1050  if s is None:
1051  return s1
1052  if s1.eq(s):
1053  return s
1054  elif s.subsort(s1):
1055  return s1
1056  elif s1.subsort(s):
1057  return s
1058  else:
1059  if __debug__:
1060  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1061  _z3_assert(False, "sort mismatch")
1062  else:
1063  return s
1064 
1065 def _coerce_exprs(a, b, ctx=None):
1066  if not is_expr(a) and not is_expr(b):
1067  a = _py2expr(a, ctx)
1068  b = _py2expr(b, ctx)
1069  s = None
1070  s = _coerce_expr_merge(s, a)
1071  s = _coerce_expr_merge(s, b)
1072  a = s.cast(a)
1073  b = s.cast(b)
1074  return (a, b)
1075 
1076 
1077 def _reduce(f, l, a):
1078  r = a
1079  for e in l:
1080  r = f(r, e)
1081  return r
1082 
1083 def _coerce_expr_list(alist, ctx=None):
1084  has_expr = False
1085  for a in alist:
1086  if is_expr(a):
1087  has_expr = True
1088  break
1089  if not has_expr:
1090  alist = [ _py2expr(a, ctx) for a in alist ]
1091  s = _reduce(_coerce_expr_merge, alist, None)
1092  return [ s.cast(a) for a in alist ]
1093 
1094 def is_expr(a):
1095  """Return `True` if `a` is a Z3 expression.
1096 
1097  >>> a = Int('a')
1098  >>> is_expr(a)
1099  True
1100  >>> is_expr(a + 1)
1101  True
1102  >>> is_expr(IntSort())
1103  False
1104  >>> is_expr(1)
1105  False
1106  >>> is_expr(IntVal(1))
1107  True
1108  >>> x = Int('x')
1109  >>> is_expr(ForAll(x, x >= 0))
1110  True
1111  >>> is_expr(FPVal(1.0))
1112  True
1113  """
1114  return isinstance(a, ExprRef)
1115 
1116 def is_app(a):
1117  """Return `True` if `a` is a Z3 function application.
1118 
1119  Note that, constants are function applications with 0 arguments.
1120 
1121  >>> a = Int('a')
1122  >>> is_app(a)
1123  True
1124  >>> is_app(a + 1)
1125  True
1126  >>> is_app(IntSort())
1127  False
1128  >>> is_app(1)
1129  False
1130  >>> is_app(IntVal(1))
1131  True
1132  >>> x = Int('x')
1133  >>> is_app(ForAll(x, x >= 0))
1134  False
1135  """
1136  if not isinstance(a, ExprRef):
1137  return False
1138  k = _ast_kind(a.ctx, a)
1139  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1140 
1141 def is_const(a):
1142  """Return `True` if `a` is Z3 constant/variable expression.
1143 
1144  >>> a = Int('a')
1145  >>> is_const(a)
1146  True
1147  >>> is_const(a + 1)
1148  False
1149  >>> is_const(1)
1150  False
1151  >>> is_const(IntVal(1))
1152  True
1153  >>> x = Int('x')
1154  >>> is_const(ForAll(x, x >= 0))
1155  False
1156  """
1157  return is_app(a) and a.num_args() == 0
1158 
1159 def is_var(a):
1160  """Return `True` if `a` is variable.
1161 
1162  Z3 uses de-Bruijn indices for representing bound variables in
1163  quantifiers.
1164 
1165  >>> x = Int('x')
1166  >>> is_var(x)
1167  False
1168  >>> is_const(x)
1169  True
1170  >>> f = Function('f', IntSort(), IntSort())
1171  >>> # Z3 replaces x with bound variables when ForAll is executed.
1172  >>> q = ForAll(x, f(x) == x)
1173  >>> b = q.body()
1174  >>> b
1175  f(Var(0)) == Var(0)
1176  >>> b.arg(1)
1177  Var(0)
1178  >>> is_var(b.arg(1))
1179  True
1180  """
1181  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1182 
1184  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1185 
1186  >>> x = Int('x')
1187  >>> y = Int('y')
1188  >>> is_var(x)
1189  False
1190  >>> is_const(x)
1191  True
1192  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1193  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1194  >>> q = ForAll([x, y], f(x, y) == x + y)
1195  >>> q.body()
1196  f(Var(1), Var(0)) == Var(1) + Var(0)
1197  >>> b = q.body()
1198  >>> b.arg(0)
1199  f(Var(1), Var(0))
1200  >>> v1 = b.arg(0).arg(0)
1201  >>> v2 = b.arg(0).arg(1)
1202  >>> v1
1203  Var(1)
1204  >>> v2
1205  Var(0)
1206  >>> get_var_index(v1)
1207  1
1208  >>> get_var_index(v2)
1209  0
1210  """
1211  if __debug__:
1212  _z3_assert(is_var(a), "Z3 bound variable expected")
1213  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1214 
1215 def is_app_of(a, k):
1216  """Return `True` if `a` is an application of the given kind `k`.
1217 
1218  >>> x = Int('x')
1219  >>> n = x + 1
1220  >>> is_app_of(n, Z3_OP_ADD)
1221  True
1222  >>> is_app_of(n, Z3_OP_MUL)
1223  False
1224  """
1225  return is_app(a) and a.decl().kind() == k
1226 
1227 def If(a, b, c, ctx=None):
1228  """Create a Z3 if-then-else expression.
1229 
1230  >>> x = Int('x')
1231  >>> y = Int('y')
1232  >>> max = If(x > y, x, y)
1233  >>> max
1234  If(x > y, x, y)
1235  >>> simplify(max)
1236  If(x <= y, y, x)
1237  """
1238  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1239  return Cond(a, b, c, ctx)
1240  else:
1241  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1242  s = BoolSort(ctx)
1243  a = s.cast(a)
1244  b, c = _coerce_exprs(b, c, ctx)
1245  if __debug__:
1246  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1247  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1248 
1249 def Distinct(*args):
1250  """Create a Z3 distinct expression.
1251 
1252  >>> x = Int('x')
1253  >>> y = Int('y')
1254  >>> Distinct(x, y)
1255  x != y
1256  >>> z = Int('z')
1257  >>> Distinct(x, y, z)
1258  Distinct(x, y, z)
1259  >>> simplify(Distinct(x, y, z))
1260  Distinct(x, y, z)
1261  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1262  And(Not(x == y), Not(x == z), Not(y == z))
1263  """
1264  args = _get_args(args)
1265  ctx = _ctx_from_ast_arg_list(args)
1266  if __debug__:
1267  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1268  args = _coerce_expr_list(args, ctx)
1269  _args, sz = _to_ast_array(args)
1270  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1271 
1272 def _mk_bin(f, a, b):
1273  args = (Ast * 2)()
1274  if __debug__:
1275  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1276  args[0] = a.as_ast()
1277  args[1] = b.as_ast()
1278  return f(a.ctx.ref(), 2, args)
1279 
1280 def Const(name, sort):
1281  """Create a constant of the given sort.
1282 
1283  >>> Const('x', IntSort())
1284  x
1285  """
1286  if __debug__:
1287  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1288  ctx = sort.ctx
1289  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1290 
1291 def Consts(names, sort):
1292  """Create a several constants of the given sort.
1293 
1294  `names` is a string containing the names of all constants to be created.
1295  Blank spaces separate the names of different constants.
1296 
1297  >>> x, y, z = Consts('x y z', IntSort())
1298  >>> x + y + z
1299  x + y + z
1300  """
1301  if isinstance(names, str):
1302  names = names.split(" ")
1303  return [Const(name, sort) for name in names]
1304 
1305 def FreshConst(sort, prefix='c'):
1306  """Create a fresh constant of a specified sort"""
1307  ctx = _get_ctx(sort.ctx)
1308  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1309 
1310 def Var(idx, s):
1311  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1312 
1313  >>> Var(0, IntSort())
1314  Var(0)
1315  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1316  False
1317  """
1318  if __debug__:
1319  _z3_assert(is_sort(s), "Z3 sort expected")
1320  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1321 
1322 def RealVar(idx, ctx=None):
1323  """
1324  Create a real free variable. Free variables are used to create quantified formulas.
1325  They are also used to create polynomials.
1326 
1327  >>> RealVar(0)
1328  Var(0)
1329  """
1330  return Var(idx, RealSort(ctx))
1331 
1332 def RealVarVector(n, ctx=None):
1333  """
1334  Create a list of Real free variables.
1335  The variables have ids: 0, 1, ..., n-1
1336 
1337  >>> x0, x1, x2, x3 = RealVarVector(4)
1338  >>> x2
1339  Var(2)
1340  """
1341  return [ RealVar(i, ctx) for i in range(n) ]
1342 
1343 
1348 
1350  """Boolean sort."""
1351  def cast(self, val):
1352  """Try to cast `val` as a Boolean.
1353 
1354  >>> x = BoolSort().cast(True)
1355  >>> x
1356  True
1357  >>> is_expr(x)
1358  True
1359  >>> is_expr(True)
1360  False
1361  >>> x.sort()
1362  Bool
1363  """
1364  if isinstance(val, bool):
1365  return BoolVal(val, self.ctx)
1366  if __debug__:
1367  if not is_expr(val):
1368  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1369  if not self.eq(val.sort()):
1370  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1371  return val
1372 
1373  def subsort(self, other):
1374  return isinstance(other, ArithSortRef)
1375 
1376  def is_int(self):
1377  return True
1378 
1379  def is_bool(self):
1380  return True
1381 
1382 
1384  """All Boolean expressions are instances of this class."""
1385  def sort(self):
1386  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1387 
1388  def __rmul__(self, other):
1389  return self * other
1390 
1391  def __mul__(self, other):
1392  """Create the Z3 expression `self * other`.
1393  """
1394  if other == 1:
1395  return self
1396  if other == 0:
1397  return 0
1398  return If(self, other, 0)
1399 
1400 
1401 def is_bool(a):
1402  """Return `True` if `a` is a Z3 Boolean expression.
1403 
1404  >>> p = Bool('p')
1405  >>> is_bool(p)
1406  True
1407  >>> q = Bool('q')
1408  >>> is_bool(And(p, q))
1409  True
1410  >>> x = Real('x')
1411  >>> is_bool(x)
1412  False
1413  >>> is_bool(x == 0)
1414  True
1415  """
1416  return isinstance(a, BoolRef)
1417 
1418 def is_true(a):
1419  """Return `True` if `a` is the Z3 true expression.
1420 
1421  >>> p = Bool('p')
1422  >>> is_true(p)
1423  False
1424  >>> is_true(simplify(p == p))
1425  True
1426  >>> x = Real('x')
1427  >>> is_true(x == 0)
1428  False
1429  >>> # True is a Python Boolean expression
1430  >>> is_true(True)
1431  False
1432  """
1433  return is_app_of(a, Z3_OP_TRUE)
1434 
1435 def is_false(a):
1436  """Return `True` if `a` is the Z3 false expression.
1437 
1438  >>> p = Bool('p')
1439  >>> is_false(p)
1440  False
1441  >>> is_false(False)
1442  False
1443  >>> is_false(BoolVal(False))
1444  True
1445  """
1446  return is_app_of(a, Z3_OP_FALSE)
1447 
1448 def is_and(a):
1449  """Return `True` if `a` is a Z3 and expression.
1450 
1451  >>> p, q = Bools('p q')
1452  >>> is_and(And(p, q))
1453  True
1454  >>> is_and(Or(p, q))
1455  False
1456  """
1457  return is_app_of(a, Z3_OP_AND)
1458 
1459 def is_or(a):
1460  """Return `True` if `a` is a Z3 or expression.
1461 
1462  >>> p, q = Bools('p q')
1463  >>> is_or(Or(p, q))
1464  True
1465  >>> is_or(And(p, q))
1466  False
1467  """
1468  return is_app_of(a, Z3_OP_OR)
1469 
1470 def is_implies(a):
1471  """Return `True` if `a` is a Z3 implication expression.
1472 
1473  >>> p, q = Bools('p q')
1474  >>> is_implies(Implies(p, q))
1475  True
1476  >>> is_implies(And(p, q))
1477  False
1478  """
1479  return is_app_of(a, Z3_OP_IMPLIES)
1480 
1481 def is_not(a):
1482  """Return `True` if `a` is a Z3 not expression.
1483 
1484  >>> p = Bool('p')
1485  >>> is_not(p)
1486  False
1487  >>> is_not(Not(p))
1488  True
1489  """
1490  return is_app_of(a, Z3_OP_NOT)
1491 
1492 def is_eq(a):
1493  """Return `True` if `a` is a Z3 equality expression.
1494 
1495  >>> x, y = Ints('x y')
1496  >>> is_eq(x == y)
1497  True
1498  """
1499  return is_app_of(a, Z3_OP_EQ)
1500 
1502  """Return `True` if `a` is a Z3 distinct expression.
1503 
1504  >>> x, y, z = Ints('x y z')
1505  >>> is_distinct(x == y)
1506  False
1507  >>> is_distinct(Distinct(x, y, z))
1508  True
1509  """
1510  return is_app_of(a, Z3_OP_DISTINCT)
1511 
1512 def BoolSort(ctx=None):
1513  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1514 
1515  >>> BoolSort()
1516  Bool
1517  >>> p = Const('p', BoolSort())
1518  >>> is_bool(p)
1519  True
1520  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1521  >>> r(0, 1)
1522  r(0, 1)
1523  >>> is_bool(r(0, 1))
1524  True
1525  """
1526  ctx = _get_ctx(ctx)
1527  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1528 
1529 def BoolVal(val, ctx=None):
1530  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1531 
1532  >>> BoolVal(True)
1533  True
1534  >>> is_true(BoolVal(True))
1535  True
1536  >>> is_true(True)
1537  False
1538  >>> is_false(BoolVal(False))
1539  True
1540  """
1541  ctx = _get_ctx(ctx)
1542  if val == False:
1543  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1544  else:
1545  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1546 
1547 def Bool(name, ctx=None):
1548  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1549 
1550  >>> p = Bool('p')
1551  >>> q = Bool('q')
1552  >>> And(p, q)
1553  And(p, q)
1554  """
1555  ctx = _get_ctx(ctx)
1556  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1557 
1558 def Bools(names, ctx=None):
1559  """Return a tuple of Boolean constants.
1560 
1561  `names` is a single string containing all names separated by blank spaces.
1562  If `ctx=None`, then the global context is used.
1563 
1564  >>> p, q, r = Bools('p q r')
1565  >>> And(p, Or(q, r))
1566  And(p, Or(q, r))
1567  """
1568  ctx = _get_ctx(ctx)
1569  if isinstance(names, str):
1570  names = names.split(" ")
1571  return [Bool(name, ctx) for name in names]
1572 
1573 def BoolVector(prefix, sz, ctx=None):
1574  """Return a list of Boolean constants of size `sz`.
1575 
1576  The constants are named using the given prefix.
1577  If `ctx=None`, then the global context is used.
1578 
1579  >>> P = BoolVector('p', 3)
1580  >>> P
1581  [p__0, p__1, p__2]
1582  >>> And(P)
1583  And(p__0, p__1, p__2)
1584  """
1585  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1586 
1587 def FreshBool(prefix='b', ctx=None):
1588  """Return a fresh Boolean constant in the given context using the given prefix.
1589 
1590  If `ctx=None`, then the global context is used.
1591 
1592  >>> b1 = FreshBool()
1593  >>> b2 = FreshBool()
1594  >>> eq(b1, b2)
1595  False
1596  """
1597  ctx = _get_ctx(ctx)
1598  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1599 
1600 def Implies(a, b, ctx=None):
1601  """Create a Z3 implies expression.
1602 
1603  >>> p, q = Bools('p q')
1604  >>> Implies(p, q)
1605  Implies(p, q)
1606  >>> simplify(Implies(p, q))
1607  Or(Not(p), q)
1608  """
1609  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1610  s = BoolSort(ctx)
1611  a = s.cast(a)
1612  b = s.cast(b)
1613  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1614 
1615 def Xor(a, b, ctx=None):
1616  """Create a Z3 Xor expression.
1617 
1618  >>> p, q = Bools('p q')
1619  >>> Xor(p, q)
1620  Xor(p, q)
1621  >>> simplify(Xor(p, q))
1622  Not(p) == q
1623  """
1624  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1625  s = BoolSort(ctx)
1626  a = s.cast(a)
1627  b = s.cast(b)
1628  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1629 
1630 def Not(a, ctx=None):
1631  """Create a Z3 not expression or probe.
1632 
1633  >>> p = Bool('p')
1634  >>> Not(Not(p))
1635  Not(Not(p))
1636  >>> simplify(Not(Not(p)))
1637  p
1638  """
1639  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1640  if is_probe(a):
1641  # Not is also used to build probes
1642  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1643  else:
1644  s = BoolSort(ctx)
1645  a = s.cast(a)
1646  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1647 
1648 def mk_not(a):
1649  if is_not(a):
1650  return a.arg(0)
1651  else:
1652  return Not(a)
1653 
1654 def _has_probe(args):
1655  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1656  for arg in args:
1657  if is_probe(arg):
1658  return True
1659  return False
1660 
1661 def And(*args):
1662  """Create a Z3 and-expression or and-probe.
1663 
1664  >>> p, q, r = Bools('p q r')
1665  >>> And(p, q, r)
1666  And(p, q, r)
1667  >>> P = BoolVector('p', 5)
1668  >>> And(P)
1669  And(p__0, p__1, p__2, p__3, p__4)
1670  """
1671  last_arg = None
1672  if len(args) > 0:
1673  last_arg = args[len(args)-1]
1674  if isinstance(last_arg, Context):
1675  ctx = args[len(args)-1]
1676  args = args[:len(args)-1]
1677  elif len(args) == 1 and isinstance(args[0], AstVector):
1678  ctx = args[0].ctx
1679  args = [a for a in args[0]]
1680  else:
1681  ctx = main_ctx()
1682  args = _get_args(args)
1683  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1684  if __debug__:
1685  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1686  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1687  if _has_probe(args):
1688  return _probe_and(args, ctx)
1689  else:
1690  args = _coerce_expr_list(args, ctx)
1691  _args, sz = _to_ast_array(args)
1692  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1693 
1694 def Or(*args):
1695  """Create a Z3 or-expression or or-probe.
1696 
1697  >>> p, q, r = Bools('p q r')
1698  >>> Or(p, q, r)
1699  Or(p, q, r)
1700  >>> P = BoolVector('p', 5)
1701  >>> Or(P)
1702  Or(p__0, p__1, p__2, p__3, p__4)
1703  """
1704  last_arg = None
1705  if len(args) > 0:
1706  last_arg = args[len(args)-1]
1707  if isinstance(last_arg, Context):
1708  ctx = args[len(args)-1]
1709  args = args[:len(args)-1]
1710  else:
1711  ctx = main_ctx()
1712  args = _get_args(args)
1713  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1714  if __debug__:
1715  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1716  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1717  if _has_probe(args):
1718  return _probe_or(args, ctx)
1719  else:
1720  args = _coerce_expr_list(args, ctx)
1721  _args, sz = _to_ast_array(args)
1722  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1723 
1724 #########################################
1725 #
1726 # Patterns
1727 #
1728 #########################################
1729 
1730 class PatternRef(ExprRef):
1731  """Patterns are hints for quantifier instantiation.
1732 
1733  """
1734  def as_ast(self):
1735  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1736 
1737  def get_id(self):
1738  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1739 
1740 def is_pattern(a):
1741  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1742 
1743  >>> f = Function('f', IntSort(), IntSort())
1744  >>> x = Int('x')
1745  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1746  >>> q
1747  ForAll(x, f(x) == 0)
1748  >>> q.num_patterns()
1749  1
1750  >>> is_pattern(q.pattern(0))
1751  True
1752  >>> q.pattern(0)
1753  f(Var(0))
1754  """
1755  return isinstance(a, PatternRef)
1756 
1757 def MultiPattern(*args):
1758  """Create a Z3 multi-pattern using the given expressions `*args`
1759 
1760  >>> f = Function('f', IntSort(), IntSort())
1761  >>> g = Function('g', IntSort(), IntSort())
1762  >>> x = Int('x')
1763  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1764  >>> q
1765  ForAll(x, f(x) != g(x))
1766  >>> q.num_patterns()
1767  1
1768  >>> is_pattern(q.pattern(0))
1769  True
1770  >>> q.pattern(0)
1771  MultiPattern(f(Var(0)), g(Var(0)))
1772  """
1773  if __debug__:
1774  _z3_assert(len(args) > 0, "At least one argument expected")
1775  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1776  ctx = args[0].ctx
1777  args, sz = _to_ast_array(args)
1778  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1779 
1780 def _to_pattern(arg):
1781  if is_pattern(arg):
1782  return arg
1783  else:
1784  return MultiPattern(arg)
1785 
1786 #########################################
1787 #
1788 # Quantifiers
1789 #
1790 #########################################
1791 
1792 class QuantifierRef(BoolRef):
1793  """Universally and Existentially quantified formulas."""
1794 
1795  def as_ast(self):
1796  return self.ast
1797 
1798  def get_id(self):
1799  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1800 
1801  def sort(self):
1802  """Return the Boolean sort or sort of Lambda."""
1803  if self.is_lambda():
1804  return _sort(self.ctx, self.as_ast())
1805  return BoolSort(self.ctx)
1806 
1807  def is_forall(self):
1808  """Return `True` if `self` is a universal quantifier.
1809 
1810  >>> f = Function('f', IntSort(), IntSort())
1811  >>> x = Int('x')
1812  >>> q = ForAll(x, f(x) == 0)
1813  >>> q.is_forall()
1814  True
1815  >>> q = Exists(x, f(x) != 0)
1816  >>> q.is_forall()
1817  False
1818  """
1819  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1820 
1821  def is_exists(self):
1822  """Return `True` if `self` is an existential quantifier.
1823 
1824  >>> f = Function('f', IntSort(), IntSort())
1825  >>> x = Int('x')
1826  >>> q = ForAll(x, f(x) == 0)
1827  >>> q.is_exists()
1828  False
1829  >>> q = Exists(x, f(x) != 0)
1830  >>> q.is_exists()
1831  True
1832  """
1833  return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1834 
1835  def is_lambda(self):
1836  """Return `True` if `self` is a lambda expression.
1837 
1838  >>> f = Function('f', IntSort(), IntSort())
1839  >>> x = Int('x')
1840  >>> q = Lambda(x, f(x))
1841  >>> q.is_lambda()
1842  True
1843  >>> q = Exists(x, f(x) != 0)
1844  >>> q.is_lambda()
1845  False
1846  """
1847  return Z3_is_lambda(self.ctx_ref(), self.ast)
1848 
1849  def weight(self):
1850  """Return the weight annotation of `self`.
1851 
1852  >>> f = Function('f', IntSort(), IntSort())
1853  >>> x = Int('x')
1854  >>> q = ForAll(x, f(x) == 0)
1855  >>> q.weight()
1856  1
1857  >>> q = ForAll(x, f(x) == 0, weight=10)
1858  >>> q.weight()
1859  10
1860  """
1861  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1862 
1863  def num_patterns(self):
1864  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1865 
1866  >>> f = Function('f', IntSort(), IntSort())
1867  >>> g = Function('g', IntSort(), IntSort())
1868  >>> x = Int('x')
1869  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1870  >>> q.num_patterns()
1871  2
1872  """
1873  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1874 
1875  def pattern(self, idx):
1876  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1877 
1878  >>> f = Function('f', IntSort(), IntSort())
1879  >>> g = Function('g', IntSort(), IntSort())
1880  >>> x = Int('x')
1881  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1882  >>> q.num_patterns()
1883  2
1884  >>> q.pattern(0)
1885  f(Var(0))
1886  >>> q.pattern(1)
1887  g(Var(0))
1888  """
1889  if __debug__:
1890  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1891  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1892 
1893  def num_no_patterns(self):
1894  """Return the number of no-patterns."""
1895  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1896 
1897  def no_pattern(self, idx):
1898  """Return a no-pattern."""
1899  if __debug__:
1900  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1901  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1902 
1903  def body(self):
1904  """Return the expression being quantified.
1905 
1906  >>> f = Function('f', IntSort(), IntSort())
1907  >>> x = Int('x')
1908  >>> q = ForAll(x, f(x) == 0)
1909  >>> q.body()
1910  f(Var(0)) == 0
1911  """
1912  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1913 
1914  def num_vars(self):
1915  """Return the number of variables bounded by this quantifier.
1916 
1917  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1918  >>> x = Int('x')
1919  >>> y = Int('y')
1920  >>> q = ForAll([x, y], f(x, y) >= x)
1921  >>> q.num_vars()
1922  2
1923  """
1924  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1925 
1926  def var_name(self, idx):
1927  """Return a string representing a name used when displaying the quantifier.
1928 
1929  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1930  >>> x = Int('x')
1931  >>> y = Int('y')
1932  >>> q = ForAll([x, y], f(x, y) >= x)
1933  >>> q.var_name(0)
1934  'x'
1935  >>> q.var_name(1)
1936  'y'
1937  """
1938  if __debug__:
1939  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1940  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1941 
1942  def var_sort(self, idx):
1943  """Return the sort of a bound variable.
1944 
1945  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1946  >>> x = Int('x')
1947  >>> y = Real('y')
1948  >>> q = ForAll([x, y], f(x, y) >= x)
1949  >>> q.var_sort(0)
1950  Int
1951  >>> q.var_sort(1)
1952  Real
1953  """
1954  if __debug__:
1955  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1956  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1957 
1958  def children(self):
1959  """Return a list containing a single element self.body()
1960 
1961  >>> f = Function('f', IntSort(), IntSort())
1962  >>> x = Int('x')
1963  >>> q = ForAll(x, f(x) == 0)
1964  >>> q.children()
1965  [f(Var(0)) == 0]
1966  """
1967  return [ self.body() ]
1968 
1969 def is_quantifier(a):
1970  """Return `True` if `a` is a Z3 quantifier.
1971 
1972  >>> f = Function('f', IntSort(), IntSort())
1973  >>> x = Int('x')
1974  >>> q = ForAll(x, f(x) == 0)
1975  >>> is_quantifier(q)
1976  True
1977  >>> is_quantifier(f(x))
1978  False
1979  """
1980  return isinstance(a, QuantifierRef)
1981 
1982 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1983  if __debug__:
1984  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
1985  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1986  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1987  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1988  if is_app(vs):
1989  ctx = vs.ctx
1990  vs = [vs]
1991  else:
1992  ctx = vs[0].ctx
1993  if not is_expr(body):
1994  body = BoolVal(body, ctx)
1995  num_vars = len(vs)
1996  if num_vars == 0:
1997  return body
1998  _vs = (Ast * num_vars)()
1999  for i in range(num_vars):
2000  ## TODO: Check if is constant
2001  _vs[i] = vs[i].as_ast()
2002  patterns = [ _to_pattern(p) for p in patterns ]
2003  num_pats = len(patterns)
2004  _pats = (Pattern * num_pats)()
2005  for i in range(num_pats):
2006  _pats[i] = patterns[i].ast
2007  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2008  qid = to_symbol(qid, ctx)
2009  skid = to_symbol(skid, ctx)
2010  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2011  num_vars, _vs,
2012  num_pats, _pats,
2013  num_no_pats, _no_pats,
2014  body.as_ast()), ctx)
2015 
2016 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2017  """Create a Z3 forall formula.
2018 
2019  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2020 
2021  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2022  >>> x = Int('x')
2023  >>> y = Int('y')
2024  >>> ForAll([x, y], f(x, y) >= x)
2025  ForAll([x, y], f(x, y) >= x)
2026  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2027  ForAll([x, y], f(x, y) >= x)
2028  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2029  ForAll([x, y], f(x, y) >= x)
2030  """
2031  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2032 
2033 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2034  """Create a Z3 exists formula.
2035 
2036  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2037 
2038 
2039  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2040  >>> x = Int('x')
2041  >>> y = Int('y')
2042  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2043  >>> q
2044  Exists([x, y], f(x, y) >= x)
2045  >>> is_quantifier(q)
2046  True
2047  >>> r = Tactic('nnf')(q).as_expr()
2048  >>> is_quantifier(r)
2049  False
2050  """
2051  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2052 
2053 def Lambda(vs, body):
2054  """Create a Z3 lambda expression.
2055 
2056  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2057  >>> mem0 = Array('mem0', IntSort(), IntSort())
2058  >>> lo, hi, e, i = Ints('lo hi e i')
2059  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2060  >>> mem1
2061  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2062  """
2063  ctx = body.ctx
2064  if is_app(vs):
2065  vs = [vs]
2066  num_vars = len(vs)
2067  _vs = (Ast * num_vars)()
2068  for i in range(num_vars):
2069  ## TODO: Check if is constant
2070  _vs[i] = vs[i].as_ast()
2071  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2072 
2073 #########################################
2074 #
2075 # Arithmetic
2076 #
2077 #########################################
2078 
2079 class ArithSortRef(SortRef):
2080  """Real and Integer sorts."""
2081 
2082  def is_real(self):
2083  """Return `True` if `self` is of the sort Real.
2084 
2085  >>> x = Real('x')
2086  >>> x.is_real()
2087  True
2088  >>> (x + 1).is_real()
2089  True
2090  >>> x = Int('x')
2091  >>> x.is_real()
2092  False
2093  """
2094  return self.kind() == Z3_REAL_SORT
2095 
2096  def is_int(self):
2097  """Return `True` if `self` is of the sort Integer.
2098 
2099  >>> x = Int('x')
2100  >>> x.is_int()
2101  True
2102  >>> (x + 1).is_int()
2103  True
2104  >>> x = Real('x')
2105  >>> x.is_int()
2106  False
2107  """
2108  return self.kind() == Z3_INT_SORT
2109 
2110  def subsort(self, other):
2111  """Return `True` if `self` is a subsort of `other`."""
2112  return self.is_int() and is_arith_sort(other) and other.is_real()
2113 
2114  def cast(self, val):
2115  """Try to cast `val` as an Integer or Real.
2116 
2117  >>> IntSort().cast(10)
2118  10
2119  >>> is_int(IntSort().cast(10))
2120  True
2121  >>> is_int(10)
2122  False
2123  >>> RealSort().cast(10)
2124  10
2125  >>> is_real(RealSort().cast(10))
2126  True
2127  """
2128  if is_expr(val):
2129  if __debug__:
2130  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2131  val_s = val.sort()
2132  if self.eq(val_s):
2133  return val
2134  if val_s.is_int() and self.is_real():
2135  return ToReal(val)
2136  if val_s.is_bool() and self.is_int():
2137  return If(val, 1, 0)
2138  if val_s.is_bool() and self.is_real():
2139  return ToReal(If(val, 1, 0))
2140  if __debug__:
2141  _z3_assert(False, "Z3 Integer/Real expression expected" )
2142  else:
2143  if self.is_int():
2144  return IntVal(val, self.ctx)
2145  if self.is_real():
2146  return RealVal(val, self.ctx)
2147  if __debug__:
2148  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2149 
2150 def is_arith_sort(s):
2151  """Return `True` if s is an arithmetical sort (type).
2152 
2153  >>> is_arith_sort(IntSort())
2154  True
2155  >>> is_arith_sort(RealSort())
2156  True
2157  >>> is_arith_sort(BoolSort())
2158  False
2159  >>> n = Int('x') + 1
2160  >>> is_arith_sort(n.sort())
2161  True
2162  """
2163  return isinstance(s, ArithSortRef)
2164 
2165 class ArithRef(ExprRef):
2166  """Integer and Real expressions."""
2167 
2168  def sort(self):
2169  """Return the sort (type) of the arithmetical expression `self`.
2170 
2171  >>> Int('x').sort()
2172  Int
2173  >>> (Real('x') + 1).sort()
2174  Real
2175  """
2176  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2177 
2178  def is_int(self):
2179  """Return `True` if `self` is an integer expression.
2180 
2181  >>> x = Int('x')
2182  >>> x.is_int()
2183  True
2184  >>> (x + 1).is_int()
2185  True
2186  >>> y = Real('y')
2187  >>> (x + y).is_int()
2188  False
2189  """
2190  return self.sort().is_int()
2191 
2192  def is_real(self):
2193  """Return `True` if `self` is an real expression.
2194 
2195  >>> x = Real('x')
2196  >>> x.is_real()
2197  True
2198  >>> (x + 1).is_real()
2199  True
2200  """
2201  return self.sort().is_real()
2202 
2203  def __add__(self, other):
2204  """Create the Z3 expression `self + other`.
2205 
2206  >>> x = Int('x')
2207  >>> y = Int('y')
2208  >>> x + y
2209  x + y
2210  >>> (x + y).sort()
2211  Int
2212  """
2213  a, b = _coerce_exprs(self, other)
2214  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2215 
2216  def __radd__(self, other):
2217  """Create the Z3 expression `other + self`.
2218 
2219  >>> x = Int('x')
2220  >>> 10 + x
2221  10 + x
2222  """
2223  a, b = _coerce_exprs(self, other)
2224  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2225 
2226  def __mul__(self, other):
2227  """Create the Z3 expression `self * other`.
2228 
2229  >>> x = Real('x')
2230  >>> y = Real('y')
2231  >>> x * y
2232  x*y
2233  >>> (x * y).sort()
2234  Real
2235  """
2236  if isinstance(other, BoolRef):
2237  return If(other, self, 0)
2238  a, b = _coerce_exprs(self, other)
2239  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2240 
2241  def __rmul__(self, other):
2242  """Create the Z3 expression `other * self`.
2243 
2244  >>> x = Real('x')
2245  >>> 10 * x
2246  10*x
2247  """
2248  a, b = _coerce_exprs(self, other)
2249  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2250 
2251  def __sub__(self, other):
2252  """Create the Z3 expression `self - other`.
2253 
2254  >>> x = Int('x')
2255  >>> y = Int('y')
2256  >>> x - y
2257  x - y
2258  >>> (x - y).sort()
2259  Int
2260  """
2261  a, b = _coerce_exprs(self, other)
2262  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2263 
2264  def __rsub__(self, other):
2265  """Create the Z3 expression `other - self`.
2266 
2267  >>> x = Int('x')
2268  >>> 10 - x
2269  10 - x
2270  """
2271  a, b = _coerce_exprs(self, other)
2272  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2273 
2274  def __pow__(self, other):
2275  """Create the Z3 expression `self**other` (** is the power operator).
2276 
2277  >>> x = Real('x')
2278  >>> x**3
2279  x**3
2280  >>> (x**3).sort()
2281  Real
2282  >>> simplify(IntVal(2)**8)
2283  256
2284  """
2285  a, b = _coerce_exprs(self, other)
2286  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2287 
2288  def __rpow__(self, other):
2289  """Create the Z3 expression `other**self` (** is the power operator).
2290 
2291  >>> x = Real('x')
2292  >>> 2**x
2293  2**x
2294  >>> (2**x).sort()
2295  Real
2296  >>> simplify(2**IntVal(8))
2297  256
2298  """
2299  a, b = _coerce_exprs(self, other)
2300  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2301 
2302  def __div__(self, other):
2303  """Create the Z3 expression `other/self`.
2304 
2305  >>> x = Int('x')
2306  >>> y = Int('y')
2307  >>> x/y
2308  x/y
2309  >>> (x/y).sort()
2310  Int
2311  >>> (x/y).sexpr()
2312  '(div x y)'
2313  >>> x = Real('x')
2314  >>> y = Real('y')
2315  >>> x/y
2316  x/y
2317  >>> (x/y).sort()
2318  Real
2319  >>> (x/y).sexpr()
2320  '(/ x y)'
2321  """
2322  a, b = _coerce_exprs(self, other)
2323  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2324 
2325  def __truediv__(self, other):
2326  """Create the Z3 expression `other/self`."""
2327  return self.__div__(other)
2328 
2329  def __rdiv__(self, other):
2330  """Create the Z3 expression `other/self`.
2331 
2332  >>> x = Int('x')
2333  >>> 10/x
2334  10/x
2335  >>> (10/x).sexpr()
2336  '(div 10 x)'
2337  >>> x = Real('x')
2338  >>> 10/x
2339  10/x
2340  >>> (10/x).sexpr()
2341  '(/ 10.0 x)'
2342  """
2343  a, b = _coerce_exprs(self, other)
2344  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2345 
2346  def __rtruediv__(self, other):
2347  """Create the Z3 expression `other/self`."""
2348  return self.__rdiv__(other)
2349 
2350  def __mod__(self, other):
2351  """Create the Z3 expression `other%self`.
2352 
2353  >>> x = Int('x')
2354  >>> y = Int('y')
2355  >>> x % y
2356  x%y
2357  >>> simplify(IntVal(10) % IntVal(3))
2358  1
2359  """
2360  a, b = _coerce_exprs(self, other)
2361  if __debug__:
2362  _z3_assert(a.is_int(), "Z3 integer expression expected")
2363  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2364 
2365  def __rmod__(self, other):
2366  """Create the Z3 expression `other%self`.
2367 
2368  >>> x = Int('x')
2369  >>> 10 % x
2370  10%x
2371  """
2372  a, b = _coerce_exprs(self, other)
2373  if __debug__:
2374  _z3_assert(a.is_int(), "Z3 integer expression expected")
2375  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2376 
2377  def __neg__(self):
2378  """Return an expression representing `-self`.
2379 
2380  >>> x = Int('x')
2381  >>> -x
2382  -x
2383  >>> simplify(-(-x))
2384  x
2385  """
2386  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2387 
2388  def __pos__(self):
2389  """Return `self`.
2390 
2391  >>> x = Int('x')
2392  >>> +x
2393  x
2394  """
2395  return self
2396 
2397  def __le__(self, other):
2398  """Create the Z3 expression `other <= self`.
2399 
2400  >>> x, y = Ints('x y')
2401  >>> x <= y
2402  x <= y
2403  >>> y = Real('y')
2404  >>> x <= y
2405  ToReal(x) <= y
2406  """
2407  a, b = _coerce_exprs(self, other)
2408  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2409 
2410  def __lt__(self, other):
2411  """Create the Z3 expression `other < self`.
2412 
2413  >>> x, y = Ints('x y')
2414  >>> x < y
2415  x < y
2416  >>> y = Real('y')
2417  >>> x < y
2418  ToReal(x) < y
2419  """
2420  a, b = _coerce_exprs(self, other)
2421  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2422 
2423  def __gt__(self, other):
2424  """Create the Z3 expression `other > self`.
2425 
2426  >>> x, y = Ints('x y')
2427  >>> x > y
2428  x > y
2429  >>> y = Real('y')
2430  >>> x > y
2431  ToReal(x) > y
2432  """
2433  a, b = _coerce_exprs(self, other)
2434  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2435 
2436  def __ge__(self, other):
2437  """Create the Z3 expression `other >= self`.
2438 
2439  >>> x, y = Ints('x y')
2440  >>> x >= y
2441  x >= y
2442  >>> y = Real('y')
2443  >>> x >= y
2444  ToReal(x) >= y
2445  """
2446  a, b = _coerce_exprs(self, other)
2447  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2448 
2449 def is_arith(a):
2450  """Return `True` if `a` is an arithmetical expression.
2451 
2452  >>> x = Int('x')
2453  >>> is_arith(x)
2454  True
2455  >>> is_arith(x + 1)
2456  True
2457  >>> is_arith(1)
2458  False
2459  >>> is_arith(IntVal(1))
2460  True
2461  >>> y = Real('y')
2462  >>> is_arith(y)
2463  True
2464  >>> is_arith(y + 1)
2465  True
2466  """
2467  return isinstance(a, ArithRef)
2468 
2469 def is_int(a):
2470  """Return `True` if `a` is an integer expression.
2471 
2472  >>> x = Int('x')
2473  >>> is_int(x + 1)
2474  True
2475  >>> is_int(1)
2476  False
2477  >>> is_int(IntVal(1))
2478  True
2479  >>> y = Real('y')
2480  >>> is_int(y)
2481  False
2482  >>> is_int(y + 1)
2483  False
2484  """
2485  return is_arith(a) and a.is_int()
2486 
2487 def is_real(a):
2488  """Return `True` if `a` is a real expression.
2489 
2490  >>> x = Int('x')
2491  >>> is_real(x + 1)
2492  False
2493  >>> y = Real('y')
2494  >>> is_real(y)
2495  True
2496  >>> is_real(y + 1)
2497  True
2498  >>> is_real(1)
2499  False
2500  >>> is_real(RealVal(1))
2501  True
2502  """
2503  return is_arith(a) and a.is_real()
2504 
2505 def _is_numeral(ctx, a):
2506  return Z3_is_numeral_ast(ctx.ref(), a)
2507 
2508 def _is_algebraic(ctx, a):
2509  return Z3_is_algebraic_number(ctx.ref(), a)
2510 
2511 def is_int_value(a):
2512  """Return `True` if `a` is an integer value of sort Int.
2513 
2514  >>> is_int_value(IntVal(1))
2515  True
2516  >>> is_int_value(1)
2517  False
2518  >>> is_int_value(Int('x'))
2519  False
2520  >>> n = Int('x') + 1
2521  >>> n
2522  x + 1
2523  >>> n.arg(1)
2524  1
2525  >>> is_int_value(n.arg(1))
2526  True
2527  >>> is_int_value(RealVal("1/3"))
2528  False
2529  >>> is_int_value(RealVal(1))
2530  False
2531  """
2532  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2533 
2534 def is_rational_value(a):
2535  """Return `True` if `a` is rational value of sort Real.
2536 
2537  >>> is_rational_value(RealVal(1))
2538  True
2539  >>> is_rational_value(RealVal("3/5"))
2540  True
2541  >>> is_rational_value(IntVal(1))
2542  False
2543  >>> is_rational_value(1)
2544  False
2545  >>> n = Real('x') + 1
2546  >>> n.arg(1)
2547  1
2548  >>> is_rational_value(n.arg(1))
2549  True
2550  >>> is_rational_value(Real('x'))
2551  False
2552  """
2553  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2554 
2555 def is_algebraic_value(a):
2556  """Return `True` if `a` is an algebraic value of sort Real.
2557 
2558  >>> is_algebraic_value(RealVal("3/5"))
2559  False
2560  >>> n = simplify(Sqrt(2))
2561  >>> n
2562  1.4142135623?
2563  >>> is_algebraic_value(n)
2564  True
2565  """
2566  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2567 
2568 def is_add(a):
2569  """Return `True` if `a` is an expression of the form b + c.
2570 
2571  >>> x, y = Ints('x y')
2572  >>> is_add(x + y)
2573  True
2574  >>> is_add(x - y)
2575  False
2576  """
2577  return is_app_of(a, Z3_OP_ADD)
2578 
2579 def is_mul(a):
2580  """Return `True` if `a` is an expression of the form b * c.
2581 
2582  >>> x, y = Ints('x y')
2583  >>> is_mul(x * y)
2584  True
2585  >>> is_mul(x - y)
2586  False
2587  """
2588  return is_app_of(a, Z3_OP_MUL)
2589 
2590 def is_sub(a):
2591  """Return `True` if `a` is an expression of the form b - c.
2592 
2593  >>> x, y = Ints('x y')
2594  >>> is_sub(x - y)
2595  True
2596  >>> is_sub(x + y)
2597  False
2598  """
2599  return is_app_of(a, Z3_OP_SUB)
2600 
2601 def is_div(a):
2602  """Return `True` if `a` is an expression of the form b / c.
2603 
2604  >>> x, y = Reals('x y')
2605  >>> is_div(x / y)
2606  True
2607  >>> is_div(x + y)
2608  False
2609  >>> x, y = Ints('x y')
2610  >>> is_div(x / y)
2611  False
2612  >>> is_idiv(x / y)
2613  True
2614  """
2615  return is_app_of(a, Z3_OP_DIV)
2616 
2617 def is_idiv(a):
2618  """Return `True` if `a` is an expression of the form b div c.
2619 
2620  >>> x, y = Ints('x y')
2621  >>> is_idiv(x / y)
2622  True
2623  >>> is_idiv(x + y)
2624  False
2625  """
2626  return is_app_of(a, Z3_OP_IDIV)
2627 
2628 def is_mod(a):
2629  """Return `True` if `a` is an expression of the form b % c.
2630 
2631  >>> x, y = Ints('x y')
2632  >>> is_mod(x % y)
2633  True
2634  >>> is_mod(x + y)
2635  False
2636  """
2637  return is_app_of(a, Z3_OP_MOD)
2638 
2639 def is_le(a):
2640  """Return `True` if `a` is an expression of the form b <= c.
2641 
2642  >>> x, y = Ints('x y')
2643  >>> is_le(x <= y)
2644  True
2645  >>> is_le(x < y)
2646  False
2647  """
2648  return is_app_of(a, Z3_OP_LE)
2649 
2650 def is_lt(a):
2651  """Return `True` if `a` is an expression of the form b < c.
2652 
2653  >>> x, y = Ints('x y')
2654  >>> is_lt(x < y)
2655  True
2656  >>> is_lt(x == y)
2657  False
2658  """
2659  return is_app_of(a, Z3_OP_LT)
2660 
2661 def is_ge(a):
2662  """Return `True` if `a` is an expression of the form b >= c.
2663 
2664  >>> x, y = Ints('x y')
2665  >>> is_ge(x >= y)
2666  True
2667  >>> is_ge(x == y)
2668  False
2669  """
2670  return is_app_of(a, Z3_OP_GE)
2671 
2672 def is_gt(a):
2673  """Return `True` if `a` is an expression of the form b > c.
2674 
2675  >>> x, y = Ints('x y')
2676  >>> is_gt(x > y)
2677  True
2678  >>> is_gt(x == y)
2679  False
2680  """
2681  return is_app_of(a, Z3_OP_GT)
2682 
2683 def is_is_int(a):
2684  """Return `True` if `a` is an expression of the form IsInt(b).
2685 
2686  >>> x = Real('x')
2687  >>> is_is_int(IsInt(x))
2688  True
2689  >>> is_is_int(x)
2690  False
2691  """
2692  return is_app_of(a, Z3_OP_IS_INT)
2693 
2694 def is_to_real(a):
2695  """Return `True` if `a` is an expression of the form ToReal(b).
2696 
2697  >>> x = Int('x')
2698  >>> n = ToReal(x)
2699  >>> n
2700  ToReal(x)
2701  >>> is_to_real(n)
2702  True
2703  >>> is_to_real(x)
2704  False
2705  """
2706  return is_app_of(a, Z3_OP_TO_REAL)
2707 
2708 def is_to_int(a):
2709  """Return `True` if `a` is an expression of the form ToInt(b).
2710 
2711  >>> x = Real('x')
2712  >>> n = ToInt(x)
2713  >>> n
2714  ToInt(x)
2715  >>> is_to_int(n)
2716  True
2717  >>> is_to_int(x)
2718  False
2719  """
2720  return is_app_of(a, Z3_OP_TO_INT)
2721 
2722 class IntNumRef(ArithRef):
2723  """Integer values."""
2724 
2725  def as_long(self):
2726  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2727 
2728  >>> v = IntVal(1)
2729  >>> v + 1
2730  1 + 1
2731  >>> v.as_long() + 1
2732  2
2733  """
2734  if __debug__:
2735  _z3_assert(self.is_int(), "Integer value expected")
2736  return int(self.as_string())
2737 
2738  def as_string(self):
2739  """Return a Z3 integer numeral as a Python string.
2740  >>> v = IntVal(100)
2741  >>> v.as_string()
2742  '100'
2743  """
2744  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2745 
2746 class RatNumRef(ArithRef):
2747  """Rational values."""
2748 
2749  def numerator(self):
2750  """ Return the numerator of a Z3 rational numeral.
2751 
2752  >>> is_rational_value(RealVal("3/5"))
2753  True
2754  >>> n = RealVal("3/5")
2755  >>> n.numerator()
2756  3
2757  >>> is_rational_value(Q(3,5))
2758  True
2759  >>> Q(3,5).numerator()
2760  3
2761  """
2762  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2763 
2764  def denominator(self):
2765  """ Return the denominator of a Z3 rational numeral.
2766 
2767  >>> is_rational_value(Q(3,5))
2768  True
2769  >>> n = Q(3,5)
2770  >>> n.denominator()
2771  5
2772  """
2773  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2774 
2775  def numerator_as_long(self):
2776  """ Return the numerator as a Python long.
2777 
2778  >>> v = RealVal(10000000000)
2779  >>> v
2780  10000000000
2781  >>> v + 1
2782  10000000000 + 1
2783  >>> v.numerator_as_long() + 1 == 10000000001
2784  True
2785  """
2786  return self.numerator().as_long()
2787 
2788  def denominator_as_long(self):
2789  """ Return the denominator as a Python long.
2790 
2791  >>> v = RealVal("1/3")
2792  >>> v
2793  1/3
2794  >>> v.denominator_as_long()
2795  3
2796  """
2797  return self.denominator().as_long()
2798 
2799  def is_int(self):
2800  return False
2801 
2802  def is_real(self):
2803  return True
2804 
2805  def is_int_value(self):
2806  return self.denominator().is_int() and self.denominator_as_long() == 1
2807 
2808  def as_long(self):
2809  _z3_assert(self.is_int_value(), "Expected integer fraction")
2810  return self.numerator_as_long()
2811 
2812  def as_decimal(self, prec):
2813  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2814 
2815  >>> v = RealVal("1/5")
2816  >>> v.as_decimal(3)
2817  '0.2'
2818  >>> v = RealVal("1/3")
2819  >>> v.as_decimal(3)
2820  '0.333?'
2821  """
2822  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2823 
2824  def as_string(self):
2825  """Return a Z3 rational numeral as a Python string.
2826 
2827  >>> v = Q(3,6)
2828  >>> v.as_string()
2829  '1/2'
2830  """
2831  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2832 
2833  def as_fraction(self):
2834  """Return a Z3 rational as a Python Fraction object.
2835 
2836  >>> v = RealVal("1/5")
2837  >>> v.as_fraction()
2838  Fraction(1, 5)
2839  """
2840  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2841 
2842 class AlgebraicNumRef(ArithRef):
2843  """Algebraic irrational values."""
2844 
2845  def approx(self, precision=10):
2846  """Return a Z3 rational number that approximates the algebraic number `self`.
2847  The result `r` is such that |r - self| <= 1/10^precision
2848 
2849  >>> x = simplify(Sqrt(2))
2850  >>> x.approx(20)
2851  6838717160008073720548335/4835703278458516698824704
2852  >>> x.approx(5)
2853  2965821/2097152
2854  """
2855  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2856  def as_decimal(self, prec):
2857  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2858 
2859  >>> x = simplify(Sqrt(2))
2860  >>> x.as_decimal(10)
2861  '1.4142135623?'
2862  >>> x.as_decimal(20)
2863  '1.41421356237309504880?'
2864  """
2865  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2866 
2867 def _py2expr(a, ctx=None):
2868  if isinstance(a, bool):
2869  return BoolVal(a, ctx)
2870  if _is_int(a):
2871  return IntVal(a, ctx)
2872  if isinstance(a, float):
2873  return RealVal(a, ctx)
2874  if is_expr(a):
2875  return a
2876  if __debug__:
2877  _z3_assert(False, "Python bool, int, long or float expected")
2878 
2879 def IntSort(ctx=None):
2880  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2881 
2882  >>> IntSort()
2883  Int
2884  >>> x = Const('x', IntSort())
2885  >>> is_int(x)
2886  True
2887  >>> x.sort() == IntSort()
2888  True
2889  >>> x.sort() == BoolSort()
2890  False
2891  """
2892  ctx = _get_ctx(ctx)
2893  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2894 
2895 def RealSort(ctx=None):
2896  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2897 
2898  >>> RealSort()
2899  Real
2900  >>> x = Const('x', RealSort())
2901  >>> is_real(x)
2902  True
2903  >>> is_int(x)
2904  False
2905  >>> x.sort() == RealSort()
2906  True
2907  """
2908  ctx = _get_ctx(ctx)
2909  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2910 
2911 def _to_int_str(val):
2912  if isinstance(val, float):
2913  return str(int(val))
2914  elif isinstance(val, bool):
2915  if val:
2916  return "1"
2917  else:
2918  return "0"
2919  elif _is_int(val):
2920  return str(val)
2921  elif isinstance(val, str):
2922  return val
2923  if __debug__:
2924  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2925 
2926 def IntVal(val, ctx=None):
2927  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2928 
2929  >>> IntVal(1)
2930  1
2931  >>> IntVal("100")
2932  100
2933  """
2934  ctx = _get_ctx(ctx)
2935  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2936 
2937 def RealVal(val, ctx=None):
2938  """Return a Z3 real value.
2939 
2940  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2941  If `ctx=None`, then the global context is used.
2942 
2943  >>> RealVal(1)
2944  1
2945  >>> RealVal(1).sort()
2946  Real
2947  >>> RealVal("3/5")
2948  3/5
2949  >>> RealVal("1.5")
2950  3/2
2951  """
2952  ctx = _get_ctx(ctx)
2953  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2954 
2955 def RatVal(a, b, ctx=None):
2956  """Return a Z3 rational a/b.
2957 
2958  If `ctx=None`, then the global context is used.
2959 
2960  >>> RatVal(3,5)
2961  3/5
2962  >>> RatVal(3,5).sort()
2963  Real
2964  """
2965  if __debug__:
2966  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2967  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2968  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2969 
2970 def Q(a, b, ctx=None):
2971  """Return a Z3 rational a/b.
2972 
2973  If `ctx=None`, then the global context is used.
2974 
2975  >>> Q(3,5)
2976  3/5
2977  >>> Q(3,5).sort()
2978  Real
2979  """
2980  return simplify(RatVal(a, b))
2981 
2982 def Int(name, ctx=None):
2983  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2984 
2985  >>> x = Int('x')
2986  >>> is_int(x)
2987  True
2988  >>> is_int(x + 1)
2989  True
2990  """
2991  ctx = _get_ctx(ctx)
2992  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2993 
2994 def Ints(names, ctx=None):
2995  """Return a tuple of Integer constants.
2996 
2997  >>> x, y, z = Ints('x y z')
2998  >>> Sum(x, y, z)
2999  x + y + z
3000  """
3001  ctx = _get_ctx(ctx)
3002  if isinstance(names, str):
3003  names = names.split(" ")
3004  return [Int(name, ctx) for name in names]
3005 
3006 def IntVector(prefix, sz, ctx=None):
3007  """Return a list of integer constants of size `sz`.
3008 
3009  >>> X = IntVector('x', 3)
3010  >>> X
3011  [x__0, x__1, x__2]
3012  >>> Sum(X)
3013  x__0 + x__1 + x__2
3014  """
3015  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
3016 
3017 def FreshInt(prefix='x', ctx=None):
3018  """Return a fresh integer constant in the given context using the given prefix.
3019 
3020  >>> x = FreshInt()
3021  >>> y = FreshInt()
3022  >>> eq(x, y)
3023  False
3024  >>> x.sort()
3025  Int
3026  """
3027  ctx = _get_ctx(ctx)
3028  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3029 
3030 def Real(name, ctx=None):
3031  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3032 
3033  >>> x = Real('x')
3034  >>> is_real(x)
3035  True
3036  >>> is_real(x + 1)
3037  True
3038  """
3039  ctx = _get_ctx(ctx)
3040  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3041 
3042 def Reals(names, ctx=None):
3043  """Return a tuple of real constants.
3044 
3045  >>> x, y, z = Reals('x y z')
3046  >>> Sum(x, y, z)
3047  x + y + z
3048  >>> Sum(x, y, z).sort()
3049  Real
3050  """
3051  ctx = _get_ctx(ctx)
3052  if isinstance(names, str):
3053  names = names.split(" ")
3054  return [Real(name, ctx) for name in names]
3055 
3056 def RealVector(prefix, sz, ctx=None):
3057  """Return a list of real constants of size `sz`.
3058 
3059  >>> X = RealVector('x', 3)
3060  >>> X
3061  [x__0, x__1, x__2]
3062  >>> Sum(X)
3063  x__0 + x__1 + x__2
3064  >>> Sum(X).sort()
3065  Real
3066  """
3067  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
3068 
3069 def FreshReal(prefix='b', ctx=None):
3070  """Return a fresh real constant in the given context using the given prefix.
3071 
3072  >>> x = FreshReal()
3073  >>> y = FreshReal()
3074  >>> eq(x, y)
3075  False
3076  >>> x.sort()
3077  Real
3078  """
3079  ctx = _get_ctx(ctx)
3080  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3081 
3082 def ToReal(a):
3083  """ Return the Z3 expression ToReal(a).
3084 
3085  >>> x = Int('x')
3086  >>> x.sort()
3087  Int
3088  >>> n = ToReal(x)
3089  >>> n
3090  ToReal(x)
3091  >>> n.sort()
3092  Real
3093  """
3094  if __debug__:
3095  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3096  ctx = a.ctx
3097  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3098 
3099 def ToInt(a):
3100  """ Return the Z3 expression ToInt(a).
3101 
3102  >>> x = Real('x')
3103  >>> x.sort()
3104  Real
3105  >>> n = ToInt(x)
3106  >>> n
3107  ToInt(x)
3108  >>> n.sort()
3109  Int
3110  """
3111  if __debug__:
3112  _z3_assert(a.is_real(), "Z3 real expression expected.")
3113  ctx = a.ctx
3114  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3115 
3116 def IsInt(a):
3117  """ Return the Z3 predicate IsInt(a).
3118 
3119  >>> x = Real('x')
3120  >>> IsInt(x + "1/2")
3121  IsInt(x + 1/2)
3122  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3123  [x = 1/2]
3124  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3125  no solution
3126  """
3127  if __debug__:
3128  _z3_assert(a.is_real(), "Z3 real expression expected.")
3129  ctx = a.ctx
3130  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3131 
3132 def Sqrt(a, ctx=None):
3133  """ Return a Z3 expression which represents the square root of a.
3134 
3135  >>> x = Real('x')
3136  >>> Sqrt(x)
3137  x**(1/2)
3138  """
3139  if not is_expr(a):
3140  ctx = _get_ctx(ctx)
3141  a = RealVal(a, ctx)
3142  return a ** "1/2"
3143 
3144 def Cbrt(a, ctx=None):
3145  """ Return a Z3 expression which represents the cubic root of a.
3146 
3147  >>> x = Real('x')
3148  >>> Cbrt(x)
3149  x**(1/3)
3150  """
3151  if not is_expr(a):
3152  ctx = _get_ctx(ctx)
3153  a = RealVal(a, ctx)
3154  return a ** "1/3"
3155 
3156 #########################################
3157 #
3158 # Bit-Vectors
3159 #
3160 #########################################
3161 
3162 class BitVecSortRef(SortRef):
3163  """Bit-vector sort."""
3164 
3165  def size(self):
3166  """Return the size (number of bits) of the bit-vector sort `self`.
3167 
3168  >>> b = BitVecSort(32)
3169  >>> b.size()
3170  32
3171  """
3172  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3173 
3174  def subsort(self, other):
3175  return is_bv_sort(other) and self.size() < other.size()
3176 
3177  def cast(self, val):
3178  """Try to cast `val` as a Bit-Vector.
3179 
3180  >>> b = BitVecSort(32)
3181  >>> b.cast(10)
3182  10
3183  >>> b.cast(10).sexpr()
3184  '#x0000000a'
3185  """
3186  if is_expr(val):
3187  if __debug__:
3188  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3189  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3190  return val
3191  else:
3192  return BitVecVal(val, self)
3193 
3194 def is_bv_sort(s):
3195  """Return True if `s` is a Z3 bit-vector sort.
3196 
3197  >>> is_bv_sort(BitVecSort(32))
3198  True
3199  >>> is_bv_sort(IntSort())
3200  False
3201  """
3202  return isinstance(s, BitVecSortRef)
3203 
3204 class BitVecRef(ExprRef):
3205  """Bit-vector expressions."""
3206 
3207  def sort(self):
3208  """Return the sort of the bit-vector expression `self`.
3209 
3210  >>> x = BitVec('x', 32)
3211  >>> x.sort()
3212  BitVec(32)
3213  >>> x.sort() == BitVecSort(32)
3214  True
3215  """
3216  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3217 
3218  def size(self):
3219  """Return the number of bits of the bit-vector expression `self`.
3220 
3221  >>> x = BitVec('x', 32)
3222  >>> (x + 1).size()
3223  32
3224  >>> Concat(x, x).size()
3225  64
3226  """
3227  return self.sort().size()
3228 
3229  def __add__(self, other):
3230  """Create the Z3 expression `self + other`.
3231 
3232  >>> x = BitVec('x', 32)
3233  >>> y = BitVec('y', 32)
3234  >>> x + y
3235  x + y
3236  >>> (x + y).sort()
3237  BitVec(32)
3238  """
3239  a, b = _coerce_exprs(self, other)
3240  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3241 
3242  def __radd__(self, other):
3243  """Create the Z3 expression `other + self`.
3244 
3245  >>> x = BitVec('x', 32)
3246  >>> 10 + x
3247  10 + x
3248  """
3249  a, b = _coerce_exprs(self, other)
3250  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3251 
3252  def __mul__(self, other):
3253  """Create the Z3 expression `self * other`.
3254 
3255  >>> x = BitVec('x', 32)
3256  >>> y = BitVec('y', 32)
3257  >>> x * y
3258  x*y
3259  >>> (x * y).sort()
3260  BitVec(32)
3261  """
3262  a, b = _coerce_exprs(self, other)
3263  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3264 
3265  def __rmul__(self, other):
3266  """Create the Z3 expression `other * self`.
3267 
3268  >>> x = BitVec('x', 32)
3269  >>> 10 * x
3270  10*x
3271  """
3272  a, b = _coerce_exprs(self, other)
3273  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3274 
3275  def __sub__(self, other):
3276  """Create the Z3 expression `self - other`.
3277 
3278  >>> x = BitVec('x', 32)
3279  >>> y = BitVec('y', 32)
3280  >>> x - y
3281  x - y
3282  >>> (x - y).sort()
3283  BitVec(32)
3284  """
3285  a, b = _coerce_exprs(self, other)
3286  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3287 
3288  def __rsub__(self, other):
3289  """Create the Z3 expression `other - self`.
3290 
3291  >>> x = BitVec('x', 32)
3292  >>> 10 - x
3293  10 - x
3294  """
3295  a, b = _coerce_exprs(self, other)
3296  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3297 
3298  def __or__(self, other):
3299  """Create the Z3 expression bitwise-or `self | other`.
3300 
3301  >>> x = BitVec('x', 32)
3302  >>> y = BitVec('y', 32)
3303  >>> x | y
3304  x | y
3305  >>> (x | y).sort()
3306  BitVec(32)
3307  """
3308  a, b = _coerce_exprs(self, other)
3309  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3310 
3311  def __ror__(self, other):
3312  """Create the Z3 expression bitwise-or `other | self`.
3313 
3314  >>> x = BitVec('x', 32)
3315  >>> 10 | x
3316  10 | x
3317  """
3318  a, b = _coerce_exprs(self, other)
3319  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3320 
3321  def __and__(self, other):
3322  """Create the Z3 expression bitwise-and `self & other`.
3323 
3324  >>> x = BitVec('x', 32)
3325  >>> y = BitVec('y', 32)
3326  >>> x & y
3327  x & y
3328  >>> (x & y).sort()
3329  BitVec(32)
3330  """
3331  a, b = _coerce_exprs(self, other)
3332  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3333 
3334  def __rand__(self, other):
3335  """Create the Z3 expression bitwise-or `other & self`.
3336 
3337  >>> x = BitVec('x', 32)
3338  >>> 10 & x
3339  10 & x
3340  """
3341  a, b = _coerce_exprs(self, other)
3342  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3343 
3344  def __xor__(self, other):
3345  """Create the Z3 expression bitwise-xor `self ^ other`.
3346 
3347  >>> x = BitVec('x', 32)
3348  >>> y = BitVec('y', 32)
3349  >>> x ^ y
3350  x ^ y
3351  >>> (x ^ y).sort()
3352  BitVec(32)
3353  """
3354  a, b = _coerce_exprs(self, other)
3355  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3356 
3357  def __rxor__(self, other):
3358  """Create the Z3 expression bitwise-xor `other ^ self`.
3359 
3360  >>> x = BitVec('x', 32)
3361  >>> 10 ^ x
3362  10 ^ x
3363  """
3364  a, b = _coerce_exprs(self, other)
3365  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3366 
3367  def __pos__(self):
3368  """Return `self`.
3369 
3370  >>> x = BitVec('x', 32)
3371  >>> +x
3372  x
3373  """
3374  return self
3375 
3376  def __neg__(self):
3377  """Return an expression representing `-self`.
3378 
3379  >>> x = BitVec('x', 32)
3380  >>> -x
3381  -x
3382  >>> simplify(-(-x))
3383  x
3384  """
3385  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3386 
3387  def __invert__(self):
3388  """Create the Z3 expression bitwise-not `~self`.
3389 
3390  >>> x = BitVec('x', 32)
3391  >>> ~x
3392  ~x
3393  >>> simplify(~(~x))
3394  x
3395  """
3396  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3397 
3398  def __div__(self, other):
3399  """Create the Z3 expression (signed) division `self / other`.
3400 
3401  Use the function UDiv() for unsigned division.
3402 
3403  >>> x = BitVec('x', 32)
3404  >>> y = BitVec('y', 32)
3405  >>> x / y
3406  x/y
3407  >>> (x / y).sort()
3408  BitVec(32)
3409  >>> (x / y).sexpr()
3410  '(bvsdiv x y)'
3411  >>> UDiv(x, y).sexpr()
3412  '(bvudiv x y)'
3413  """
3414  a, b = _coerce_exprs(self, other)
3415  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3416 
3417  def __truediv__(self, other):
3418  """Create the Z3 expression (signed) division `self / other`."""
3419  return self.__div__(other)
3420 
3421  def __rdiv__(self, other):
3422  """Create the Z3 expression (signed) division `other / self`.
3423 
3424  Use the function UDiv() for unsigned division.
3425 
3426  >>> x = BitVec('x', 32)
3427  >>> 10 / x
3428  10/x
3429  >>> (10 / x).sexpr()
3430  '(bvsdiv #x0000000a x)'
3431  >>> UDiv(10, x).sexpr()
3432  '(bvudiv #x0000000a x)'
3433  """
3434  a, b = _coerce_exprs(self, other)
3435  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3436 
3437  def __rtruediv__(self, other):
3438  """Create the Z3 expression (signed) division `other / self`."""
3439  return self.__rdiv__(other)
3440 
3441  def __mod__(self, other):
3442  """Create the Z3 expression (signed) mod `self % other`.
3443 
3444  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3445 
3446  >>> x = BitVec('x', 32)
3447  >>> y = BitVec('y', 32)
3448  >>> x % y
3449  x%y
3450  >>> (x % y).sort()
3451  BitVec(32)
3452  >>> (x % y).sexpr()
3453  '(bvsmod x y)'
3454  >>> URem(x, y).sexpr()
3455  '(bvurem x y)'
3456  >>> SRem(x, y).sexpr()
3457  '(bvsrem x y)'
3458  """
3459  a, b = _coerce_exprs(self, other)
3460  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3461 
3462  def __rmod__(self, other):
3463  """Create the Z3 expression (signed) mod `other % self`.
3464 
3465  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3466 
3467  >>> x = BitVec('x', 32)
3468  >>> 10 % x
3469  10%x
3470  >>> (10 % x).sexpr()
3471  '(bvsmod #x0000000a x)'
3472  >>> URem(10, x).sexpr()
3473  '(bvurem #x0000000a x)'
3474  >>> SRem(10, x).sexpr()
3475  '(bvsrem #x0000000a x)'
3476  """
3477  a, b = _coerce_exprs(self, other)
3478  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3479 
3480  def __le__(self, other):
3481  """Create the Z3 expression (signed) `other <= self`.
3482 
3483  Use the function ULE() for unsigned less than or equal to.
3484 
3485  >>> x, y = BitVecs('x y', 32)
3486  >>> x <= y
3487  x <= y
3488  >>> (x <= y).sexpr()
3489  '(bvsle x y)'
3490  >>> ULE(x, y).sexpr()
3491  '(bvule x y)'
3492  """
3493  a, b = _coerce_exprs(self, other)
3494  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3495 
3496  def __lt__(self, other):
3497  """Create the Z3 expression (signed) `other < self`.
3498 
3499  Use the function ULT() for unsigned less than.
3500 
3501  >>> x, y = BitVecs('x y', 32)
3502  >>> x < y
3503  x < y
3504  >>> (x < y).sexpr()
3505  '(bvslt x y)'
3506  >>> ULT(x, y).sexpr()
3507  '(bvult x y)'
3508  """
3509  a, b = _coerce_exprs(self, other)
3510  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3511 
3512  def __gt__(self, other):
3513  """Create the Z3 expression (signed) `other > self`.
3514 
3515  Use the function UGT() for unsigned greater than.
3516 
3517  >>> x, y = BitVecs('x y', 32)
3518  >>> x > y
3519  x > y
3520  >>> (x > y).sexpr()
3521  '(bvsgt x y)'
3522  >>> UGT(x, y).sexpr()
3523  '(bvugt x y)'
3524  """
3525  a, b = _coerce_exprs(self, other)
3526  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3527 
3528  def __ge__(self, other):
3529  """Create the Z3 expression (signed) `other >= self`.
3530 
3531  Use the function UGE() for unsigned greater than or equal to.
3532 
3533  >>> x, y = BitVecs('x y', 32)
3534  >>> x >= y
3535  x >= y
3536  >>> (x >= y).sexpr()
3537  '(bvsge x y)'
3538  >>> UGE(x, y).sexpr()
3539  '(bvuge x y)'
3540  """
3541  a, b = _coerce_exprs(self, other)
3542  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3543 
3544  def __rshift__(self, other):
3545  """Create the Z3 expression (arithmetical) right shift `self >> other`
3546 
3547  Use the function LShR() for the right logical shift
3548 
3549  >>> x, y = BitVecs('x y', 32)
3550  >>> x >> y
3551  x >> y
3552  >>> (x >> y).sexpr()
3553  '(bvashr x y)'
3554  >>> LShR(x, y).sexpr()
3555  '(bvlshr x y)'
3556  >>> BitVecVal(4, 3)
3557  4
3558  >>> BitVecVal(4, 3).as_signed_long()
3559  -4
3560  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3561  -2
3562  >>> simplify(BitVecVal(4, 3) >> 1)
3563  6
3564  >>> simplify(LShR(BitVecVal(4, 3), 1))
3565  2
3566  >>> simplify(BitVecVal(2, 3) >> 1)
3567  1
3568  >>> simplify(LShR(BitVecVal(2, 3), 1))
3569  1
3570  """
3571  a, b = _coerce_exprs(self, other)
3572  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3573 
3574  def __lshift__(self, other):
3575  """Create the Z3 expression left shift `self << other`
3576 
3577  >>> x, y = BitVecs('x y', 32)
3578  >>> x << y
3579  x << y
3580  >>> (x << y).sexpr()
3581  '(bvshl x y)'
3582  >>> simplify(BitVecVal(2, 3) << 1)
3583  4
3584  """
3585  a, b = _coerce_exprs(self, other)
3586  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3587 
3588  def __rrshift__(self, other):
3589  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3590 
3591  Use the function LShR() for the right logical shift
3592 
3593  >>> x = BitVec('x', 32)
3594  >>> 10 >> x
3595  10 >> x
3596  >>> (10 >> x).sexpr()
3597  '(bvashr #x0000000a x)'
3598  """
3599  a, b = _coerce_exprs(self, other)
3600  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3601 
3602  def __rlshift__(self, other):
3603  """Create the Z3 expression left shift `other << self`.
3604 
3605  Use the function LShR() for the right logical shift
3606 
3607  >>> x = BitVec('x', 32)
3608  >>> 10 << x
3609  10 << x
3610  >>> (10 << x).sexpr()
3611  '(bvshl #x0000000a x)'
3612  """
3613  a, b = _coerce_exprs(self, other)
3614  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3615 
3616 class BitVecNumRef(BitVecRef):
3617  """Bit-vector values."""
3618 
3619  def as_long(self):
3620  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3621 
3622  >>> v = BitVecVal(0xbadc0de, 32)
3623  >>> v
3624  195936478
3625  >>> print("0x%.8x" % v.as_long())
3626  0x0badc0de
3627  """
3628  return int(self.as_string())
3629 
3630  def as_signed_long(self):
3631  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3632 
3633  >>> BitVecVal(4, 3).as_signed_long()
3634  -4
3635  >>> BitVecVal(7, 3).as_signed_long()
3636  -1
3637  >>> BitVecVal(3, 3).as_signed_long()
3638  3
3639  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3640  -1
3641  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3642  -1
3643  """
3644  sz = self.size()
3645  val = self.as_long()
3646  if val >= 2**(sz - 1):
3647  val = val - 2**sz
3648  if val < -2**(sz - 1):
3649  val = val + 2**sz
3650  return int(val)
3651 
3652  def as_string(self):
3653  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3654 
3655 def is_bv(a):
3656  """Return `True` if `a` is a Z3 bit-vector expression.
3657 
3658  >>> b = BitVec('b', 32)
3659  >>> is_bv(b)
3660  True
3661  >>> is_bv(b + 10)
3662  True
3663  >>> is_bv(Int('x'))
3664  False
3665  """
3666  return isinstance(a, BitVecRef)
3667 
3668 def is_bv_value(a):
3669  """Return `True` if `a` is a Z3 bit-vector numeral value.
3670 
3671  >>> b = BitVec('b', 32)
3672  >>> is_bv_value(b)
3673  False
3674  >>> b = BitVecVal(10, 32)
3675  >>> b
3676  10
3677  >>> is_bv_value(b)
3678  True
3679  """
3680  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3681 
3682 def BV2Int(a, is_signed=False):
3683  """Return the Z3 expression BV2Int(a).
3684 
3685  >>> b = BitVec('b', 3)
3686  >>> BV2Int(b).sort()
3687  Int
3688  >>> x = Int('x')
3689  >>> x > BV2Int(b)
3690  x > BV2Int(b)
3691  >>> x > BV2Int(b, is_signed=False)
3692  x > BV2Int(b)
3693  >>> x > BV2Int(b, is_signed=True)
3694  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3695  >>> solve(x > BV2Int(b), b == 1, x < 3)
3696  [b = 1, x = 2]
3697  """
3698  if __debug__:
3699  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3700  ctx = a.ctx
3701  ## investigate problem with bv2int
3702  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3703 
3704 def Int2BV(a, num_bits):
3705  """Return the z3 expression Int2BV(a, num_bits).
3706  It is a bit-vector of width num_bits and represents the
3707  modulo of a by 2^num_bits
3708  """
3709  ctx = a.ctx
3710  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3711 
3712 def BitVecSort(sz, ctx=None):
3713  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3714 
3715  >>> Byte = BitVecSort(8)
3716  >>> Word = BitVecSort(16)
3717  >>> Byte
3718  BitVec(8)
3719  >>> x = Const('x', Byte)
3720  >>> eq(x, BitVec('x', 8))
3721  True
3722  """
3723  ctx = _get_ctx(ctx)
3724  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3725 
3726 def BitVecVal(val, bv, ctx=None):
3727  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3728 
3729  >>> v = BitVecVal(10, 32)
3730  >>> v
3731  10
3732  >>> print("0x%.8x" % v.as_long())
3733  0x0000000a
3734  """
3735  if is_bv_sort(bv):
3736  ctx = bv.ctx
3737  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3738  else:
3739  ctx = _get_ctx(ctx)
3740  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3741 
3742 def BitVec(name, bv, ctx=None):
3743  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3744  If `ctx=None`, then the global context is used.
3745 
3746  >>> x = BitVec('x', 16)
3747  >>> is_bv(x)
3748  True
3749  >>> x.size()
3750  16
3751  >>> x.sort()
3752  BitVec(16)
3753  >>> word = BitVecSort(16)
3754  >>> x2 = BitVec('x', word)
3755  >>> eq(x, x2)
3756  True
3757  """
3758  if isinstance(bv, BitVecSortRef):
3759  ctx = bv.ctx
3760  else:
3761  ctx = _get_ctx(ctx)
3762  bv = BitVecSort(bv, ctx)
3763  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3764 
3765 def BitVecs(names, bv, ctx=None):
3766  """Return a tuple of bit-vector constants of size bv.
3767 
3768  >>> x, y, z = BitVecs('x y z', 16)
3769  >>> x.size()
3770  16
3771  >>> x.sort()
3772  BitVec(16)
3773  >>> Sum(x, y, z)
3774  0 + x + y + z
3775  >>> Product(x, y, z)
3776  1*x*y*z
3777  >>> simplify(Product(x, y, z))
3778  x*y*z
3779  """
3780  ctx = _get_ctx(ctx)
3781  if isinstance(names, str):
3782  names = names.split(" ")
3783  return [BitVec(name, bv, ctx) for name in names]
3784 
3785 def Concat(*args):
3786  """Create a Z3 bit-vector concatenation expression.
3787 
3788  >>> v = BitVecVal(1, 4)
3789  >>> Concat(v, v+1, v)
3790  Concat(Concat(1, 1 + 1), 1)
3791  >>> simplify(Concat(v, v+1, v))
3792  289
3793  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3794  121
3795  """
3796  args = _get_args(args)
3797  sz = len(args)
3798  if __debug__:
3799  _z3_assert(sz >= 2, "At least two arguments expected.")
3800 
3801  ctx = None
3802  for a in args:
3803  if is_expr(a):
3804  ctx = a.ctx
3805  break
3806  if is_seq(args[0]) or isinstance(args[0], str):
3807  args = [_coerce_seq(s, ctx) for s in args]
3808  if __debug__:
3809  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3810  v = (Ast * sz)()
3811  for i in range(sz):
3812  v[i] = args[i].as_ast()
3813  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3814 
3815  if is_re(args[0]):
3816  if __debug__:
3817  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3818  v = (Ast * sz)()
3819  for i in range(sz):
3820  v[i] = args[i].as_ast()
3821  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3822 
3823  if __debug__:
3824  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3825  r = args[0]
3826  for i in range(sz - 1):
3827  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3828  return r
3829 
3830 def Extract(high, low, a):
3831  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3832 
3833  >>> x = BitVec('x', 8)
3834  >>> Extract(6, 2, x)
3835  Extract(6, 2, x)
3836  >>> Extract(6, 2, x).sort()
3837  BitVec(5)
3838  >>> simplify(Extract(StringVal("abcd"),2,1))
3839  c
3840  """
3841  if isinstance(high, str):
3842  high = StringVal(high)
3843  if is_seq(high):
3844  s = high
3845  offset, length = _coerce_exprs(low, a, s.ctx)
3846  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3847  if __debug__:
3848  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3849  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3850  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3851  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3852 
3853 def _check_bv_args(a, b):
3854  if __debug__:
3855  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3856 
3857 def ULE(a, b):
3858  """Create the Z3 expression (unsigned) `other <= self`.
3859 
3860  Use the operator <= for signed less than or equal to.
3861 
3862  >>> x, y = BitVecs('x y', 32)
3863  >>> ULE(x, y)
3864  ULE(x, y)
3865  >>> (x <= y).sexpr()
3866  '(bvsle x y)'
3867  >>> ULE(x, y).sexpr()
3868  '(bvule x y)'
3869  """
3870  _check_bv_args(a, b)
3871  a, b = _coerce_exprs(a, b)
3872  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3873 
3874 def ULT(a, b):
3875  """Create the Z3 expression (unsigned) `other < self`.
3876 
3877  Use the operator < for signed less than.
3878 
3879  >>> x, y = BitVecs('x y', 32)
3880  >>> ULT(x, y)
3881  ULT(x, y)
3882  >>> (x < y).sexpr()
3883  '(bvslt x y)'
3884  >>> ULT(x, y).sexpr()
3885  '(bvult x y)'
3886  """
3887  _check_bv_args(a, b)
3888  a, b = _coerce_exprs(a, b)
3889  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3890 
3891 def UGE(a, b):
3892  """Create the Z3 expression (unsigned) `other >= self`.
3893 
3894  Use the operator >= for signed greater than or equal to.
3895 
3896  >>> x, y = BitVecs('x y', 32)
3897  >>> UGE(x, y)
3898  UGE(x, y)
3899  >>> (x >= y).sexpr()
3900  '(bvsge x y)'
3901  >>> UGE(x, y).sexpr()
3902  '(bvuge x y)'
3903  """
3904  _check_bv_args(a, b)
3905  a, b = _coerce_exprs(a, b)
3906  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3907 
3908 def UGT(a, b):
3909  """Create the Z3 expression (unsigned) `other > self`.
3910 
3911  Use the operator > for signed greater than.
3912 
3913  >>> x, y = BitVecs('x y', 32)
3914  >>> UGT(x, y)
3915  UGT(x, y)
3916  >>> (x > y).sexpr()
3917  '(bvsgt x y)'
3918  >>> UGT(x, y).sexpr()
3919  '(bvugt x y)'
3920  """
3921  _check_bv_args(a, b)
3922  a, b = _coerce_exprs(a, b)
3923  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3924 
3925 def UDiv(a, b):
3926  """Create the Z3 expression (unsigned) division `self / other`.
3927 
3928  Use the operator / for signed division.
3929 
3930  >>> x = BitVec('x', 32)
3931  >>> y = BitVec('y', 32)
3932  >>> UDiv(x, y)
3933  UDiv(x, y)
3934  >>> UDiv(x, y).sort()
3935  BitVec(32)
3936  >>> (x / y).sexpr()
3937  '(bvsdiv x y)'
3938  >>> UDiv(x, y).sexpr()
3939  '(bvudiv x y)'
3940  """
3941  _check_bv_args(a, b)
3942  a, b = _coerce_exprs(a, b)
3943  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3944 
3945 def URem(a, b):
3946  """Create the Z3 expression (unsigned) remainder `self % other`.
3947 
3948  Use the operator % for signed modulus, and SRem() for signed remainder.
3949 
3950  >>> x = BitVec('x', 32)
3951  >>> y = BitVec('y', 32)
3952  >>> URem(x, y)
3953  URem(x, y)
3954  >>> URem(x, y).sort()
3955  BitVec(32)
3956  >>> (x % y).sexpr()
3957  '(bvsmod x y)'
3958  >>> URem(x, y).sexpr()
3959  '(bvurem x y)'
3960  """
3961  _check_bv_args(a, b)
3962  a, b = _coerce_exprs(a, b)
3963  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3964 
3965 def SRem(a, b):
3966  """Create the Z3 expression signed remainder.
3967 
3968  Use the operator % for signed modulus, and URem() for unsigned remainder.
3969 
3970  >>> x = BitVec('x', 32)
3971  >>> y = BitVec('y', 32)
3972  >>> SRem(x, y)
3973  SRem(x, y)
3974  >>> SRem(x, y).sort()
3975  BitVec(32)
3976  >>> (x % y).sexpr()
3977  '(bvsmod x y)'
3978  >>> SRem(x, y).sexpr()
3979  '(bvsrem x y)'
3980  """
3981  _check_bv_args(a, b)
3982  a, b = _coerce_exprs(a, b)
3983  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3984 
3985 def LShR(a, b):
3986  """Create the Z3 expression logical right shift.
3987 
3988  Use the operator >> for the arithmetical right shift.
3989 
3990  >>> x, y = BitVecs('x y', 32)
3991  >>> LShR(x, y)
3992  LShR(x, y)
3993  >>> (x >> y).sexpr()
3994  '(bvashr x y)'
3995  >>> LShR(x, y).sexpr()
3996  '(bvlshr x y)'
3997  >>> BitVecVal(4, 3)
3998  4
3999  >>> BitVecVal(4, 3).as_signed_long()
4000  -4
4001  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4002  -2
4003  >>> simplify(BitVecVal(4, 3) >> 1)
4004  6
4005  >>> simplify(LShR(BitVecVal(4, 3), 1))
4006  2
4007  >>> simplify(BitVecVal(2, 3) >> 1)
4008  1
4009  >>> simplify(LShR(BitVecVal(2, 3), 1))
4010  1
4011  """
4012  _check_bv_args(a, b)
4013  a, b = _coerce_exprs(a, b)
4014  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4015 
4016 def RotateLeft(a, b):
4017  """Return an expression representing `a` rotated to the left `b` times.
4018 
4019  >>> a, b = BitVecs('a b', 16)
4020  >>> RotateLeft(a, b)
4021  RotateLeft(a, b)
4022  >>> simplify(RotateLeft(a, 0))
4023  a
4024  >>> simplify(RotateLeft(a, 16))
4025  a
4026  """
4027  _check_bv_args(a, b)
4028  a, b = _coerce_exprs(a, b)
4029  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4030 
4031 def RotateRight(a, b):
4032  """Return an expression representing `a` rotated to the right `b` times.
4033 
4034  >>> a, b = BitVecs('a b', 16)
4035  >>> RotateRight(a, b)
4036  RotateRight(a, b)
4037  >>> simplify(RotateRight(a, 0))
4038  a
4039  >>> simplify(RotateRight(a, 16))
4040  a
4041  """
4042  _check_bv_args(a, b)
4043  a, b = _coerce_exprs(a, b)
4044  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4045 
4046 def SignExt(n, a):
4047  """Return a bit-vector expression with `n` extra sign-bits.
4048 
4049  >>> x = BitVec('x', 16)
4050  >>> n = SignExt(8, x)
4051  >>> n.size()
4052  24
4053  >>> n
4054  SignExt(8, x)
4055  >>> n.sort()
4056  BitVec(24)
4057  >>> v0 = BitVecVal(2, 2)
4058  >>> v0
4059  2
4060  >>> v0.size()
4061  2
4062  >>> v = simplify(SignExt(6, v0))
4063  >>> v
4064  254
4065  >>> v.size()
4066  8
4067  >>> print("%.x" % v.as_long())
4068  fe
4069  """
4070  if __debug__:
4071  _z3_assert(_is_int(n), "First argument must be an integer")
4072  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4073  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4074 
4075 def ZeroExt(n, a):
4076  """Return a bit-vector expression with `n` extra zero-bits.
4077 
4078  >>> x = BitVec('x', 16)
4079  >>> n = ZeroExt(8, x)
4080  >>> n.size()
4081  24
4082  >>> n
4083  ZeroExt(8, x)
4084  >>> n.sort()
4085  BitVec(24)
4086  >>> v0 = BitVecVal(2, 2)
4087  >>> v0
4088  2
4089  >>> v0.size()
4090  2
4091  >>> v = simplify(ZeroExt(6, v0))
4092  >>> v
4093  2
4094  >>> v.size()
4095  8
4096  """
4097  if __debug__:
4098  _z3_assert(_is_int(n), "First argument must be an integer")
4099  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4100  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4101 
4102 def RepeatBitVec(n, a):
4103  """Return an expression representing `n` copies of `a`.
4104 
4105  >>> x = BitVec('x', 8)
4106  >>> n = RepeatBitVec(4, x)
4107  >>> n
4108  RepeatBitVec(4, x)
4109  >>> n.size()
4110  32
4111  >>> v0 = BitVecVal(10, 4)
4112  >>> print("%.x" % v0.as_long())
4113  a
4114  >>> v = simplify(RepeatBitVec(4, v0))
4115  >>> v.size()
4116  16
4117  >>> print("%.x" % v.as_long())
4118  aaaa
4119  """
4120  if __debug__:
4121  _z3_assert(_is_int(n), "First argument must be an integer")
4122  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4123  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4124 
4125 def BVRedAnd(a):
4126  """Return the reduction-and expression of `a`."""
4127  if __debug__:
4128  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4129  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4130 
4131 def BVRedOr(a):
4132  """Return the reduction-or expression of `a`."""
4133  if __debug__:
4134  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4135  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4136 
4137 def BVAddNoOverflow(a, b, signed):
4138  """A predicate the determines that bit-vector addition does not overflow"""
4139  _check_bv_args(a, b)
4140  a, b = _coerce_exprs(a, b)
4141  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4142 
4143 def BVAddNoUnderflow(a, b):
4144  """A predicate the determines that signed bit-vector addition does not underflow"""
4145  _check_bv_args(a, b)
4146  a, b = _coerce_exprs(a, b)
4147  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4148 
4149 def BVSubNoOverflow(a, b):
4150  """A predicate the determines that bit-vector subtraction does not overflow"""
4151  _check_bv_args(a, b)
4152  a, b = _coerce_exprs(a, b)
4153  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4154 
4155 
4156 def BVSubNoUnderflow(a, b, signed):
4157  """A predicate the determines that bit-vector subtraction does not underflow"""
4158  _check_bv_args(a, b)
4159  a, b = _coerce_exprs(a, b)
4160  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4161 
4162 def BVSDivNoOverflow(a, b):
4163  """A predicate the determines that bit-vector signed division does not overflow"""
4164  _check_bv_args(a, b)
4165  a, b = _coerce_exprs(a, b)
4166  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4167 
4168 def BVSNegNoOverflow(a):
4169  """A predicate the determines that bit-vector unary negation does not overflow"""
4170  if __debug__:
4171  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4172  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4173 
4174 def BVMulNoOverflow(a, b, signed):
4175  """A predicate the determines that bit-vector multiplication does not overflow"""
4176  _check_bv_args(a, b)
4177  a, b = _coerce_exprs(a, b)
4178  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4179 
4180 
4181 def BVMulNoUnderflow(a, b):
4182  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4183  _check_bv_args(a, b)
4184  a, b = _coerce_exprs(a, b)
4185  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4186 
4187 
4188 
4189 #########################################
4190 #
4191 # Arrays
4192 #
4193 #########################################
4194 
4195 class ArraySortRef(SortRef):
4196  """Array sorts."""
4197 
4198  def domain(self):
4199  """Return the domain of the array sort `self`.
4200 
4201  >>> A = ArraySort(IntSort(), BoolSort())
4202  >>> A.domain()
4203  Int
4204  """
4205  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4206 
4207  def range(self):
4208  """Return the range of the array sort `self`.
4209 
4210  >>> A = ArraySort(IntSort(), BoolSort())
4211  >>> A.range()
4212  Bool
4213  """
4214  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4215 
4216 class ArrayRef(ExprRef):
4217  """Array expressions. """
4218 
4219  def sort(self):
4220  """Return the array sort of the array expression `self`.
4221 
4222  >>> a = Array('a', IntSort(), BoolSort())
4223  >>> a.sort()
4224  Array(Int, Bool)
4225  """
4226  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4227 
4228  def domain(self):
4229  """Shorthand for `self.sort().domain()`.
4230 
4231  >>> a = Array('a', IntSort(), BoolSort())
4232  >>> a.domain()
4233  Int
4234  """
4235  return self.sort().domain()
4236 
4237  def range(self):
4238  """Shorthand for `self.sort().range()`.
4239 
4240  >>> a = Array('a', IntSort(), BoolSort())
4241  >>> a.range()
4242  Bool
4243  """
4244  return self.sort().range()
4245 
4246  def __getitem__(self, arg):
4247  """Return the Z3 expression `self[arg]`.
4248 
4249  >>> a = Array('a', IntSort(), BoolSort())
4250  >>> i = Int('i')
4251  >>> a[i]
4252  a[i]
4253  >>> a[i].sexpr()
4254  '(select a i)'
4255  """
4256  arg = self.domain().cast(arg)
4257  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4258 
4259  def default(self):
4260  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4261 
4262 
4263 def is_array(a):
4264  """Return `True` if `a` is a Z3 array expression.
4265 
4266  >>> a = Array('a', IntSort(), IntSort())
4267  >>> is_array(a)
4268  True
4269  >>> is_array(Store(a, 0, 1))
4270  True
4271  >>> is_array(a[0])
4272  False
4273  """
4274  return isinstance(a, ArrayRef)
4275 
4276 def is_const_array(a):
4277  """Return `True` if `a` is a Z3 constant array.
4278 
4279  >>> a = K(IntSort(), 10)
4280  >>> is_const_array(a)
4281  True
4282  >>> a = Array('a', IntSort(), IntSort())
4283  >>> is_const_array(a)
4284  False
4285  """
4286  return is_app_of(a, Z3_OP_CONST_ARRAY)
4287 
4288 def is_K(a):
4289  """Return `True` if `a` is a Z3 constant array.
4290 
4291  >>> a = K(IntSort(), 10)
4292  >>> is_K(a)
4293  True
4294  >>> a = Array('a', IntSort(), IntSort())
4295  >>> is_K(a)
4296  False
4297  """
4298  return is_app_of(a, Z3_OP_CONST_ARRAY)
4299 
4300 def is_map(a):
4301  """Return `True` if `a` is a Z3 map array expression.
4302 
4303  >>> f = Function('f', IntSort(), IntSort())
4304  >>> b = Array('b', IntSort(), IntSort())
4305  >>> a = Map(f, b)
4306  >>> a
4307  Map(f, b)
4308  >>> is_map(a)
4309  True
4310  >>> is_map(b)
4311  False
4312  """
4313  return is_app_of(a, Z3_OP_ARRAY_MAP)
4314 
4315 def is_default(a):
4316  """Return `True` if `a` is a Z3 default array expression.
4317  >>> d = Default(K(IntSort(), 10))
4318  >>> is_default(d)
4319  True
4320  """
4321  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4322 
4323 def get_map_func(a):
4324  """Return the function declaration associated with a Z3 map array expression.
4325 
4326  >>> f = Function('f', IntSort(), IntSort())
4327  >>> b = Array('b', IntSort(), IntSort())
4328  >>> a = Map(f, b)
4329  >>> eq(f, get_map_func(a))
4330  True
4331  >>> get_map_func(a)
4332  f
4333  >>> get_map_func(a)(0)
4334  f(0)
4335  """
4336  if __debug__:
4337  _z3_assert(is_map(a), "Z3 array map expression expected.")
4338  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4339 
4340 def ArraySort(*sig):
4341  """Return the Z3 array sort with the given domain and range sorts.
4342 
4343  >>> A = ArraySort(IntSort(), BoolSort())
4344  >>> A
4345  Array(Int, Bool)
4346  >>> A.domain()
4347  Int
4348  >>> A.range()
4349  Bool
4350  >>> AA = ArraySort(IntSort(), A)
4351  >>> AA
4352  Array(Int, Array(Int, Bool))
4353  """
4354  sig = _get_args(sig)
4355  if __debug__:
4356  _z3_assert(len(sig) > 1, "At least two arguments expected")
4357  arity = len(sig) - 1
4358  r = sig[arity]
4359  d = sig[0]
4360  if __debug__:
4361  for s in sig:
4362  _z3_assert(is_sort(s), "Z3 sort expected")
4363  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4364  ctx = d.ctx
4365  if len(sig) == 2:
4366  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4367  dom = (Sort * arity)()
4368  for i in range(arity):
4369  dom[i] = sig[i].ast
4370  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4371 
4372 def Array(name, dom, rng):
4373  """Return an array constant named `name` with the given domain and range sorts.
4374 
4375  >>> a = Array('a', IntSort(), IntSort())
4376  >>> a.sort()
4377  Array(Int, Int)
4378  >>> a[0]
4379  a[0]
4380  """
4381  s = ArraySort(dom, rng)
4382  ctx = s.ctx
4383  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4384 
4385 def Update(a, i, v):
4386  """Return a Z3 store array expression.
4387 
4388  >>> a = Array('a', IntSort(), IntSort())
4389  >>> i, v = Ints('i v')
4390  >>> s = Update(a, i, v)
4391  >>> s.sort()
4392  Array(Int, Int)
4393  >>> prove(s[i] == v)
4394  proved
4395  >>> j = Int('j')
4396  >>> prove(Implies(i != j, s[j] == a[j]))
4397  proved
4398  """
4399  if __debug__:
4400  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4401  i = a.domain().cast(i)
4402  v = a.range().cast(v)
4403  ctx = a.ctx
4404  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4405 
4406 def Default(a):
4407  """ Return a default value for array expression.
4408  >>> b = K(IntSort(), 1)
4409  >>> prove(Default(b) == 1)
4410  proved
4411  """
4412  if __debug__:
4413  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4414  return a.default()
4415 
4416 
4417 def Store(a, i, v):
4418  """Return a Z3 store array expression.
4419 
4420  >>> a = Array('a', IntSort(), IntSort())
4421  >>> i, v = Ints('i v')
4422  >>> s = Store(a, i, v)
4423  >>> s.sort()
4424  Array(Int, Int)
4425  >>> prove(s[i] == v)
4426  proved
4427  >>> j = Int('j')
4428  >>> prove(Implies(i != j, s[j] == a[j]))
4429  proved
4430  """
4431  return Update(a, i, v)
4432 
4433 def Select(a, i):
4434  """Return a Z3 select array expression.
4435 
4436  >>> a = Array('a', IntSort(), IntSort())
4437  >>> i = Int('i')
4438  >>> Select(a, i)
4439  a[i]
4440  >>> eq(Select(a, i), a[i])
4441  True
4442  """
4443  if __debug__:
4444  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4445  return a[i]
4446 
4447 
4448 def Map(f, *args):
4449  """Return a Z3 map array expression.
4450 
4451  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4452  >>> a1 = Array('a1', IntSort(), IntSort())
4453  >>> a2 = Array('a2', IntSort(), IntSort())
4454  >>> b = Map(f, a1, a2)
4455  >>> b
4456  Map(f, a1, a2)
4457  >>> prove(b[0] == f(a1[0], a2[0]))
4458  proved
4459  """
4460  args = _get_args(args)
4461  if __debug__:
4462  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4463  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4464  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4465  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4466  _args, sz = _to_ast_array(args)
4467  ctx = f.ctx
4468  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4469 
4470 def K(dom, v):
4471  """Return a Z3 constant array expression.
4472 
4473  >>> a = K(IntSort(), 10)
4474  >>> a
4475  K(Int, 10)
4476  >>> a.sort()
4477  Array(Int, Int)
4478  >>> i = Int('i')
4479  >>> a[i]
4480  K(Int, 10)[i]
4481  >>> simplify(a[i])
4482  10
4483  """
4484  if __debug__:
4485  _z3_assert(is_sort(dom), "Z3 sort expected")
4486  ctx = dom.ctx
4487  if not is_expr(v):
4488  v = _py2expr(v, ctx)
4489  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4490 
4491 def Ext(a, b):
4492  """Return extensionality index for arrays.
4493  """
4494  if __debug__:
4495  _z3_assert(is_array(a) and is_array(b))
4496  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
4497 
4498 def is_select(a):
4499  """Return `True` if `a` is a Z3 array select application.
4500 
4501  >>> a = Array('a', IntSort(), IntSort())
4502  >>> is_select(a)
4503  False
4504  >>> i = Int('i')
4505  >>> is_select(a[i])
4506  True
4507  """
4508  return is_app_of(a, Z3_OP_SELECT)
4509 
4510 def is_store(a):
4511  """Return `True` if `a` is a Z3 array store application.
4512 
4513  >>> a = Array('a', IntSort(), IntSort())
4514  >>> is_store(a)
4515  False
4516  >>> is_store(Store(a, 0, 1))
4517  True
4518  """
4519  return is_app_of(a, Z3_OP_STORE)
4520 
4521 #########################################
4522 #
4523 # Sets
4524 #
4525 #########################################
4526 
4527 
4528 def SetSort(s):
4529  """ Create a set sort over element sort s"""
4530  return ArraySort(s, BoolSort())
4531 
4532 def EmptySet(s):
4533  """Create the empty set
4534  >>> EmptySet(IntSort())
4535  K(Int, False)
4536  """
4537  ctx = s.ctx
4538  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4539 
4540 def FullSet(s):
4541  """Create the full set
4542  >>> FullSet(IntSort())
4543  K(Int, True)
4544  """
4545  ctx = s.ctx
4546  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4547 
4548 def SetUnion(*args):
4549  """ Take the union of sets
4550  >>> a = Const('a', SetSort(IntSort()))
4551  >>> b = Const('b', SetSort(IntSort()))
4552  >>> SetUnion(a, b)
4553  union(a, b)
4554  """
4555  args = _get_args(args)
4556  ctx = _ctx_from_ast_arg_list(args)
4557  _args, sz = _to_ast_array(args)
4558  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4559 
4560 def SetIntersect(*args):
4561  """ Take the union of sets
4562  >>> a = Const('a', SetSort(IntSort()))
4563  >>> b = Const('b', SetSort(IntSort()))
4564  >>> SetIntersect(a, b)
4565  intersect(a, b)
4566  """
4567  args = _get_args(args)
4568  ctx = _ctx_from_ast_arg_list(args)
4569  _args, sz = _to_ast_array(args)
4570  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4571 
4572 def SetAdd(s, e):
4573  """ Add element e to set s
4574  >>> a = Const('a', SetSort(IntSort()))
4575  >>> SetAdd(a, 1)
4576  Store(a, 1, True)
4577  """
4578  ctx = _ctx_from_ast_arg_list([s,e])
4579  e = _py2expr(e, ctx)
4580  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4581 
4582 def SetDel(s, e):
4583  """ Remove element e to set s
4584  >>> a = Const('a', SetSort(IntSort()))
4585  >>> SetDel(a, 1)
4586  Store(a, 1, False)
4587  """
4588  ctx = _ctx_from_ast_arg_list([s,e])
4589  e = _py2expr(e, ctx)
4590  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4591 
4592 def SetComplement(s):
4593  """ The complement of set s
4594  >>> a = Const('a', SetSort(IntSort()))
4595  >>> SetComplement(a)
4596  complement(a)
4597  """
4598  ctx = s.ctx
4599  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4600 
4601 def SetDifference(a, b):
4602  """ The set difference of a and b
4603  >>> a = Const('a', SetSort(IntSort()))
4604  >>> b = Const('b', SetSort(IntSort()))
4605  >>> SetDifference(a, b)
4606  difference(a, b)
4607  """
4608  ctx = _ctx_from_ast_arg_list([a, b])
4609  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4610 
4611 def IsMember(e, s):
4612  """ Check if e is a member of set s
4613  >>> a = Const('a', SetSort(IntSort()))
4614  >>> IsMember(1, a)
4615  a[1]
4616  """
4617  ctx = _ctx_from_ast_arg_list([s,e])
4618  e = _py2expr(e, ctx)
4619  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4620 
4621 def IsSubset(a, b):
4622  """ Check if a is a subset of b
4623  >>> a = Const('a', SetSort(IntSort()))
4624  >>> b = Const('b', SetSort(IntSort()))
4625  >>> IsSubset(a, b)
4626  subset(a, b)
4627  """
4628  ctx = _ctx_from_ast_arg_list([a, b])
4629  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4630 
4631 
4632 #########################################
4633 #
4634 # Datatypes
4635 #
4636 #########################################
4637 
4638 def _valid_accessor(acc):
4639  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4640  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4641 
4642 class Datatype:
4643  """Helper class for declaring Z3 datatypes.
4644 
4645  >>> List = Datatype('List')
4646  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4647  >>> List.declare('nil')
4648  >>> List = List.create()
4649  >>> # List is now a Z3 declaration
4650  >>> List.nil
4651  nil
4652  >>> List.cons(10, List.nil)
4653  cons(10, nil)
4654  >>> List.cons(10, List.nil).sort()
4655  List
4656  >>> cons = List.cons
4657  >>> nil = List.nil
4658  >>> car = List.car
4659  >>> cdr = List.cdr
4660  >>> n = cons(1, cons(0, nil))
4661  >>> n
4662  cons(1, cons(0, nil))
4663  >>> simplify(cdr(n))
4664  cons(0, nil)
4665  >>> simplify(car(n))
4666  1
4667  """
4668  def __init__(self, name, ctx=None):
4669  self.ctx = _get_ctx(ctx)
4670  self.name = name
4671  self.constructors = []
4672 
4673  def __deepcopy__(self, memo={}):
4674  r = Datatype(self.name, self.ctx)
4675  r.constructors = copy.deepcopy(self.constructors)
4676  return r
4677 
4678  def declare_core(self, name, rec_name, *args):
4679  if __debug__:
4680  _z3_assert(isinstance(name, str), "String expected")
4681  _z3_assert(isinstance(rec_name, str), "String expected")
4682  _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)")
4683  self.constructors.append((name, rec_name, args))
4684 
4685  def declare(self, name, *args):
4686  """Declare constructor named `name` with the given accessors `args`.
4687  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.
4688 
4689  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4690  declares the constructor named `cons` that builds a new List using an integer and a List.
4691  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4692  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4693  the actual datatype in Z3.
4694 
4695  >>> List = Datatype('List')
4696  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4697  >>> List.declare('nil')
4698  >>> List = List.create()
4699  """
4700  if __debug__:
4701  _z3_assert(isinstance(name, str), "String expected")
4702  _z3_assert(name != "", "Constructor name cannot be empty")
4703  return self.declare_core(name, "is-" + name, *args)
4704 
4705  def __repr__(self):
4706  return "Datatype(%s, %s)" % (self.name, self.constructors)
4707 
4708  def create(self):
4709  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4710 
4711  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4712 
4713  >>> List = Datatype('List')
4714  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4715  >>> List.declare('nil')
4716  >>> List = List.create()
4717  >>> List.nil
4718  nil
4719  >>> List.cons(10, List.nil)
4720  cons(10, nil)
4721  """
4722  return CreateDatatypes([self])[0]
4723 
4724 class ScopedConstructor:
4725  """Auxiliary object used to create Z3 datatypes."""
4726  def __init__(self, c, ctx):
4727  self.c = c
4728  self.ctx = ctx
4729  def __del__(self):
4730  if self.ctx.ref() is not None:
4731  Z3_del_constructor(self.ctx.ref(), self.c)
4732 
4733 class ScopedConstructorList:
4734  """Auxiliary object used to create Z3 datatypes."""
4735  def __init__(self, c, ctx):
4736  self.c = c
4737  self.ctx = ctx
4738  def __del__(self):
4739  if self.ctx.ref() is not None:
4740  Z3_del_constructor_list(self.ctx.ref(), self.c)
4741 
4742 def CreateDatatypes(*ds):
4743  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4744 
4745  In the following example we define a Tree-List using two mutually recursive datatypes.
4746 
4747  >>> TreeList = Datatype('TreeList')
4748  >>> Tree = Datatype('Tree')
4749  >>> # Tree has two constructors: leaf and node
4750  >>> Tree.declare('leaf', ('val', IntSort()))
4751  >>> # a node contains a list of trees
4752  >>> Tree.declare('node', ('children', TreeList))
4753  >>> TreeList.declare('nil')
4754  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4755  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4756  >>> Tree.val(Tree.leaf(10))
4757  val(leaf(10))
4758  >>> simplify(Tree.val(Tree.leaf(10)))
4759  10
4760  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4761  >>> n1
4762  node(cons(leaf(10), cons(leaf(20), nil)))
4763  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4764  >>> simplify(n2 == n1)
4765  False
4766  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4767  True
4768  """
4769  ds = _get_args(ds)
4770  if __debug__:
4771  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4772  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4773  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4774  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4775  ctx = ds[0].ctx
4776  num = len(ds)
4777  names = (Symbol * num)()
4778  out = (Sort * num)()
4779  clists = (ConstructorList * num)()
4780  to_delete = []
4781  for i in range(num):
4782  d = ds[i]
4783  names[i] = to_symbol(d.name, ctx)
4784  num_cs = len(d.constructors)
4785  cs = (Constructor * num_cs)()
4786  for j in range(num_cs):
4787  c = d.constructors[j]
4788  cname = to_symbol(c[0], ctx)
4789  rname = to_symbol(c[1], ctx)
4790  fs = c[2]
4791  num_fs = len(fs)
4792  fnames = (Symbol * num_fs)()
4793  sorts = (Sort * num_fs)()
4794  refs = (ctypes.c_uint * num_fs)()
4795  for k in range(num_fs):
4796  fname = fs[k][0]
4797  ftype = fs[k][1]
4798  fnames[k] = to_symbol(fname, ctx)
4799  if isinstance(ftype, Datatype):
4800  if __debug__:
4801  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4802  sorts[k] = None
4803  refs[k] = ds.index(ftype)
4804  else:
4805  if __debug__:
4806  _z3_assert(is_sort(ftype), "Z3 sort expected")
4807  sorts[k] = ftype.ast
4808  refs[k] = 0
4809  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4810  to_delete.append(ScopedConstructor(cs[j], ctx))
4811  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4812  to_delete.append(ScopedConstructorList(clists[i], ctx))
4813  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4814  result = []
4815  ## Create a field for every constructor, recognizer and accessor
4816  for i in range(num):
4817  dref = DatatypeSortRef(out[i], ctx)
4818  num_cs = dref.num_constructors()
4819  for j in range(num_cs):
4820  cref = dref.constructor(j)
4821  cref_name = cref.name()
4822  cref_arity = cref.arity()
4823  if cref.arity() == 0:
4824  cref = cref()
4825  setattr(dref, cref_name, cref)
4826  rref = dref.recognizer(j)
4827  setattr(dref, "is_" + cref_name, rref)
4828  for k in range(cref_arity):
4829  aref = dref.accessor(j, k)
4830  setattr(dref, aref.name(), aref)
4831  result.append(dref)
4832  return tuple(result)
4833 
4834 class DatatypeSortRef(SortRef):
4835  """Datatype sorts."""
4836  def num_constructors(self):
4837  """Return the number of constructors in the given Z3 datatype.
4838 
4839  >>> List = Datatype('List')
4840  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4841  >>> List.declare('nil')
4842  >>> List = List.create()
4843  >>> # List is now a Z3 declaration
4844  >>> List.num_constructors()
4845  2
4846  """
4847  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4848 
4849  def constructor(self, idx):
4850  """Return a constructor of the datatype `self`.
4851 
4852  >>> List = Datatype('List')
4853  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4854  >>> List.declare('nil')
4855  >>> List = List.create()
4856  >>> # List is now a Z3 declaration
4857  >>> List.num_constructors()
4858  2
4859  >>> List.constructor(0)
4860  cons
4861  >>> List.constructor(1)
4862  nil
4863  """
4864  if __debug__:
4865  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4866  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4867 
4868  def recognizer(self, idx):
4869  """In Z3, each constructor has an associated recognizer predicate.
4870 
4871  If the constructor is named `name`, then the recognizer `is_name`.
4872 
4873  >>> List = Datatype('List')
4874  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4875  >>> List.declare('nil')
4876  >>> List = List.create()
4877  >>> # List is now a Z3 declaration
4878  >>> List.num_constructors()
4879  2
4880  >>> List.recognizer(0)
4881  is(cons)
4882  >>> List.recognizer(1)
4883  is(nil)
4884  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4885  False
4886  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4887  True
4888  >>> l = Const('l', List)
4889  >>> simplify(List.is_cons(l))
4890  is(cons, l)
4891  """
4892  if __debug__:
4893  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4894  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4895 
4896  def accessor(self, i, j):
4897  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4898 
4899  >>> List = Datatype('List')
4900  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4901  >>> List.declare('nil')
4902  >>> List = List.create()
4903  >>> List.num_constructors()
4904  2
4905  >>> List.constructor(0)
4906  cons
4907  >>> num_accs = List.constructor(0).arity()
4908  >>> num_accs
4909  2
4910  >>> List.accessor(0, 0)
4911  car
4912  >>> List.accessor(0, 1)
4913  cdr
4914  >>> List.constructor(1)
4915  nil
4916  >>> num_accs = List.constructor(1).arity()
4917  >>> num_accs
4918  0
4919  """
4920  if __debug__:
4921  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4922  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4923  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4924 
4925 class DatatypeRef(ExprRef):
4926  """Datatype expressions."""
4927  def sort(self):
4928  """Return the datatype sort of the datatype expression `self`."""
4929  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4930 
4931 def EnumSort(name, values, ctx=None):
4932  """Return a new enumeration sort named `name` containing the given values.
4933 
4934  The result is a pair (sort, list of constants).
4935  Example:
4936  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4937  """
4938  if __debug__:
4939  _z3_assert(isinstance(name, str), "Name must be a string")
4940  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4941  _z3_assert(len(values) > 0, "At least one value expected")
4942  ctx = _get_ctx(ctx)
4943  num = len(values)
4944  _val_names = (Symbol * num)()
4945  for i in range(num):
4946  _val_names[i] = to_symbol(values[i])
4947  _values = (FuncDecl * num)()
4948  _testers = (FuncDecl * num)()
4949  name = to_symbol(name)
4950  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4951  V = []
4952  for i in range(num):
4953  V.append(FuncDeclRef(_values[i], ctx))
4954  V = [a() for a in V]
4955  return S, V
4956 
4957 #########################################
4958 #
4959 # Parameter Sets
4960 #
4961 #########################################
4962 
4963 class ParamsRef:
4964  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4965 
4966  Consider using the function `args2params` to create instances of this object.
4967  """
4968  def __init__(self, ctx=None, params=None):
4969  self.ctx = _get_ctx(ctx)
4970  if params is None:
4971  self.params = Z3_mk_params(self.ctx.ref())
4972  else:
4973  self.params = params
4974  Z3_params_inc_ref(self.ctx.ref(), self.params)
4975 
4976  def __deepcopy__(self, memo={}):
4977  return ParamsRef(self.ctx, self.params)
4978 
4979  def __del__(self):
4980  if self.ctx.ref() is not None:
4981  Z3_params_dec_ref(self.ctx.ref(), self.params)
4982 
4983  def set(self, name, val):
4984  """Set parameter name with value val."""
4985  if __debug__:
4986  _z3_assert(isinstance(name, str), "parameter name must be a string")
4987  name_sym = to_symbol(name, self.ctx)
4988  if isinstance(val, bool):
4989  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4990  elif _is_int(val):
4991  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4992  elif isinstance(val, float):
4993  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4994  elif isinstance(val, str):
4995  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4996  else:
4997  if __debug__:
4998  _z3_assert(False, "invalid parameter value")
4999 
5000  def __repr__(self):
5001  return Z3_params_to_string(self.ctx.ref(), self.params)
5002 
5003  def validate(self, ds):
5004  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5005  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5006 
5007 def args2params(arguments, keywords, ctx=None):
5008  """Convert python arguments into a Z3_params object.
5009  A ':' is added to the keywords, and '_' is replaced with '-'
5010 
5011  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5012  (params model true relevancy 2 elim_and true)
5013  """
5014  if __debug__:
5015  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5016  prev = None
5017  r = ParamsRef(ctx)
5018  for a in arguments:
5019  if prev is None:
5020  prev = a
5021  else:
5022  r.set(prev, a)
5023  prev = None
5024  for k in keywords:
5025  v = keywords[k]
5026  r.set(k, v)
5027  return r
5028 
5029 class ParamDescrsRef:
5030  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5031  """
5032  def __init__(self, descr, ctx=None):
5033  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5034  self.ctx = _get_ctx(ctx)
5035  self.descr = descr
5036  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5037 
5038  def __deepcopy__(self, memo={}):
5039  return ParamsDescrsRef(self.descr, self.ctx)
5040 
5041  def __del__(self):
5042  if self.ctx.ref() is not None:
5043  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5044 
5045  def size(self):
5046  """Return the size of in the parameter description `self`.
5047  """
5048  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5049 
5050  def __len__(self):
5051  """Return the size of in the parameter description `self`.
5052  """
5053  return self.size()
5054 
5055  def get_name(self, i):
5056  """Return the i-th parameter name in the parameter description `self`.
5057  """
5058  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5059 
5060  def get_kind(self, n):
5061  """Return the kind of the parameter named `n`.
5062  """
5063  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5064 
5065  def get_documentation(self, n):
5066  """Return the documentation string of the parameter named `n`.
5067  """
5068  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5069 
5070  def __getitem__(self, arg):
5071  if _is_int(arg):
5072  return self.get_name(arg)
5073  else:
5074  return self.get_kind(arg)
5075 
5076  def __repr__(self):
5077  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5078 
5079 #########################################
5080 #
5081 # Goals
5082 #
5083 #########################################
5084 
5085 class Goal(Z3PPObject):
5086  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5087 
5088  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5089  A goal has a solution if one of its subgoals has a solution.
5090  A goal is unsatisfiable if all subgoals are unsatisfiable.
5091  """
5092 
5093  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5094  if __debug__:
5095  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
5096  self.ctx = _get_ctx(ctx)
5097  self.goal = goal
5098  if self.goal is None:
5099  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5100  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5101 
5102  def __deepcopy__(self, memo={}):
5103  return Goal(False, False, False, self.ctx, self.goal)
5104 
5105  def __del__(self):
5106  if self.goal is not None and self.ctx.ref() is not None:
5107  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5108 
5109  def depth(self):
5110  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
5111 
5112  >>> x, y = Ints('x y')
5113  >>> g = Goal()
5114  >>> g.add(x == 0, y >= x + 1)
5115  >>> g.depth()
5116  0
5117  >>> r = Then('simplify', 'solve-eqs')(g)
5118  >>> # r has 1 subgoal
5119  >>> len(r)
5120  1
5121  >>> r[0].depth()
5122  2
5123  """
5124  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5125 
5126  def inconsistent(self):
5127  """Return `True` if `self` contains the `False` constraints.
5128 
5129  >>> x, y = Ints('x y')
5130  >>> g = Goal()
5131  >>> g.inconsistent()
5132  False
5133  >>> g.add(x == 0, x == 1)
5134  >>> g
5135  [x == 0, x == 1]
5136  >>> g.inconsistent()
5137  False
5138  >>> g2 = Tactic('propagate-values')(g)[0]
5139  >>> g2.inconsistent()
5140  True
5141  """
5142  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5143 
5144  def prec(self):
5145  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5146 
5147  >>> g = Goal()
5148  >>> g.prec() == Z3_GOAL_PRECISE
5149  True
5150  >>> x, y = Ints('x y')
5151  >>> g.add(x == y + 1)
5152  >>> g.prec() == Z3_GOAL_PRECISE
5153  True
5154  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5155  >>> g2 = t(g)[0]
5156  >>> g2
5157  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5158  >>> g2.prec() == Z3_GOAL_PRECISE
5159  False
5160  >>> g2.prec() == Z3_GOAL_UNDER
5161  True
5162  """
5163  return Z3_goal_precision(self.ctx.ref(), self.goal)
5164 
5165  def precision(self):
5166  """Alias for `prec()`.
5167 
5168  >>> g = Goal()
5169  >>> g.precision() == Z3_GOAL_PRECISE
5170  True
5171  """
5172  return self.prec()
5173 
5174  def size(self):
5175  """Return the number of constraints in the goal `self`.
5176 
5177  >>> g = Goal()
5178  >>> g.size()
5179  0
5180  >>> x, y = Ints('x y')
5181  >>> g.add(x == 0, y > x)
5182  >>> g.size()
5183  2
5184  """
5185  return int(Z3_goal_size(self.ctx.ref(), self.goal))
5186 
5187  def __len__(self):
5188  """Return the number of constraints in the goal `self`.
5189 
5190  >>> g = Goal()
5191  >>> len(g)
5192  0
5193  >>> x, y = Ints('x y')
5194  >>> g.add(x == 0, y > x)
5195  >>> len(g)
5196  2
5197  """
5198  return self.size()
5199 
5200  def get(self, i):
5201  """Return a constraint in the goal `self`.
5202 
5203  >>> g = Goal()
5204  >>> x, y = Ints('x y')
5205  >>> g.add(x == 0, y > x)
5206  >>> g.get(0)
5207  x == 0
5208  >>> g.get(1)
5209  y > x
5210  """
5211  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5212 
5213  def __getitem__(self, arg):
5214  """Return a constraint in the goal `self`.
5215 
5216  >>> g = Goal()
5217  >>> x, y = Ints('x y')
5218  >>> g.add(x == 0, y > x)
5219  >>> g[0]
5220  x == 0
5221  >>> g[1]
5222  y > x
5223  """
5224  if arg >= len(self):
5225  raise IndexError
5226  return self.get(arg)
5227 
5228  def assert_exprs(self, *args):
5229  """Assert constraints into the goal.
5230 
5231  >>> x = Int('x')
5232  >>> g = Goal()
5233  >>> g.assert_exprs(x > 0, x < 2)
5234  >>> g
5235  [x > 0, x < 2]
5236  """
5237  args = _get_args(args)
5238  s = BoolSort(self.ctx)
5239  for arg in args:
5240  arg = s.cast(arg)
5241  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5242 
5243  def append(self, *args):
5244  """Add constraints.
5245 
5246  >>> x = Int('x')
5247  >>> g = Goal()
5248  >>> g.append(x > 0, x < 2)
5249  >>> g
5250  [x > 0, x < 2]
5251  """
5252  self.assert_exprs(*args)
5253 
5254  def insert(self, *args):
5255  """Add constraints.
5256 
5257  >>> x = Int('x')
5258  >>> g = Goal()
5259  >>> g.insert(x > 0, x < 2)
5260  >>> g
5261  [x > 0, x < 2]
5262  """
5263  self.assert_exprs(*args)
5264 
5265  def add(self, *args):
5266  """Add constraints.
5267 
5268  >>> x = Int('x')
5269  >>> g = Goal()
5270  >>> g.add(x > 0, x < 2)
5271  >>> g
5272  [x > 0, x < 2]
5273  """
5274  self.assert_exprs(*args)
5275 
5276  def convert_model(self, model):
5277  """Retrieve model from a satisfiable goal
5278  >>> a, b = Ints('a b')
5279  >>> g = Goal()
5280  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5281  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5282  >>> r = t(g)
5283  >>> r[0]
5284  [Or(b == 0, b == 1), Not(0 <= b)]
5285  >>> r[1]
5286  [Or(b == 0, b == 1), Not(1 <= b)]
5287  >>> # Remark: the subgoal r[0] is unsatisfiable
5288  >>> # Creating a solver for solving the second subgoal
5289  >>> s = Solver()
5290  >>> s.add(r[1])
5291  >>> s.check()
5292  sat
5293  >>> s.model()
5294  [b = 0]
5295  >>> # Model s.model() does not assign a value to `a`
5296  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5297  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5298  >>> r[1].convert_model(s.model())
5299  [b = 0, a = 1]
5300  """
5301  if __debug__:
5302  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5303  return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5304 
5305  def __repr__(self):
5306  return obj_to_string(self)
5307 
5308  def sexpr(self):
5309  """Return a textual representation of the s-expression representing the goal."""
5310  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5311 
5312  def dimacs(self):
5313  """Return a textual representation of the goal in DIMACS format."""
5314  return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
5315 
5316  def translate(self, target):
5317  """Copy goal `self` to context `target`.
5318 
5319  >>> x = Int('x')
5320  >>> g = Goal()
5321  >>> g.add(x > 10)
5322  >>> g
5323  [x > 10]
5324  >>> c2 = Context()
5325  >>> g2 = g.translate(c2)
5326  >>> g2
5327  [x > 10]
5328  >>> g.ctx == main_ctx()
5329  True
5330  >>> g2.ctx == c2
5331  True
5332  >>> g2.ctx == main_ctx()
5333  False
5334  """
5335  if __debug__:
5336  _z3_assert(isinstance(target, Context), "target must be a context")
5337  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5338 
5339  def __copy__(self):
5340  return self.translate(self.ctx)
5341 
5342  def __deepcopy__(self):
5343  return self.translate(self.ctx)
5344 
5345  def simplify(self, *arguments, **keywords):
5346  """Return a new simplified goal.
5347 
5348  This method is essentially invoking the simplify tactic.
5349 
5350  >>> g = Goal()
5351  >>> x = Int('x')
5352  >>> g.add(x + 1 >= 2)
5353  >>> g
5354  [x + 1 >= 2]
5355  >>> g2 = g.simplify()
5356  >>> g2
5357  [x >= 1]
5358  >>> # g was not modified
5359  >>> g
5360  [x + 1 >= 2]
5361  """
5362  t = Tactic('simplify')
5363  return t.apply(self, *arguments, **keywords)[0]
5364 
5365  def as_expr(self):
5366  """Return goal `self` as a single Z3 expression.
5367 
5368  >>> x = Int('x')
5369  >>> g = Goal()
5370  >>> g.as_expr()
5371  True
5372  >>> g.add(x > 1)
5373  >>> g.as_expr()
5374  x > 1
5375  >>> g.add(x < 10)
5376  >>> g.as_expr()
5377  And(x > 1, x < 10)
5378  """
5379  sz = len(self)
5380  if sz == 0:
5381  return BoolVal(True, self.ctx)
5382  elif sz == 1:
5383  return self.get(0)
5384  else:
5385  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5386 
5387 #########################################
5388 #
5389 # AST Vector
5390 #
5391 #########################################
5392 class AstVector(Z3PPObject):
5393  """A collection (vector) of ASTs."""
5394 
5395  def __init__(self, v=None, ctx=None):
5396  self.vector = None
5397  if v is None:
5398  self.ctx = _get_ctx(ctx)
5399  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5400  else:
5401  self.vector = v
5402  assert ctx is not None
5403  self.ctx = ctx
5404  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5405 
5406  def __deepcopy__(self, memo={}):
5407  return AstVector(self.vector, self.ctx)
5408 
5409  def __del__(self):
5410  if self.vector is not None and self.ctx.ref() is not None:
5411  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5412 
5413  def __len__(self):
5414  """Return the size of the vector `self`.
5415 
5416  >>> A = AstVector()
5417  >>> len(A)
5418  0
5419  >>> A.push(Int('x'))
5420  >>> A.push(Int('x'))
5421  >>> len(A)
5422  2
5423  """
5424  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5425 
5426  def __getitem__(self, i):
5427  """Return the AST at position `i`.
5428 
5429  >>> A = AstVector()
5430  >>> A.push(Int('x') + 1)
5431  >>> A.push(Int('y'))
5432  >>> A[0]
5433  x + 1
5434  >>> A[1]
5435  y
5436  """
5437 
5438  if isinstance(i, int):
5439  if i < 0:
5440  i += self.__len__()
5441 
5442  if i >= self.__len__():
5443  raise IndexError
5444  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5445 
5446  elif isinstance(i, slice):
5447  return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5448 
5449 
5450  def __setitem__(self, i, v):
5451  """Update AST at position `i`.
5452 
5453  >>> A = AstVector()
5454  >>> A.push(Int('x') + 1)
5455  >>> A.push(Int('y'))
5456  >>> A[0]
5457  x + 1
5458  >>> A[0] = Int('x')
5459  >>> A[0]
5460  x
5461  """
5462  if i >= self.__len__():
5463  raise IndexError
5464  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5465 
5466  def push(self, v):
5467  """Add `v` in the end of the vector.
5468 
5469  >>> A = AstVector()
5470  >>> len(A)
5471  0
5472  >>> A.push(Int('x'))
5473  >>> len(A)
5474  1
5475  """
5476  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5477 
5478  def resize(self, sz):
5479  """Resize the vector to `sz` elements.
5480 
5481  >>> A = AstVector()
5482  >>> A.resize(10)
5483  >>> len(A)
5484  10
5485  >>> for i in range(10): A[i] = Int('x')
5486  >>> A[5]
5487  x
5488  """
5489  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5490 
5491  def __contains__(self, item):
5492  """Return `True` if the vector contains `item`.
5493 
5494  >>> x = Int('x')
5495  >>> A = AstVector()
5496  >>> x in A
5497  False
5498  >>> A.push(x)
5499  >>> x in A
5500  True
5501  >>> (x+1) in A
5502  False
5503  >>> A.push(x+1)
5504  >>> (x+1) in A
5505  True
5506  >>> A
5507  [x, x + 1]
5508  """
5509  for elem in self:
5510  if elem.eq(item):
5511  return True
5512  return False
5513 
5514  def translate(self, other_ctx):
5515  """Copy vector `self` to context `other_ctx`.
5516 
5517  >>> x = Int('x')
5518  >>> A = AstVector()
5519  >>> A.push(x)
5520  >>> c2 = Context()
5521  >>> B = A.translate(c2)
5522  >>> B
5523  [x]
5524  """
5525  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5526 
5527  def __copy__(self):
5528  return self.translate(self.ctx)
5529 
5530  def __deepcopy__(self):
5531  return self.translate(self.ctx)
5532 
5533  def __repr__(self):
5534  return obj_to_string(self)
5535 
5536  def sexpr(self):
5537  """Return a textual representation of the s-expression representing the vector."""
5538  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5539 
5540 #########################################
5541 #
5542 # AST Map
5543 #
5544 #########################################
5545 class AstMap:
5546  """A mapping from ASTs to ASTs."""
5547 
5548  def __init__(self, m=None, ctx=None):
5549  self.map = None
5550  if m is None:
5551  self.ctx = _get_ctx(ctx)
5552  self.map = Z3_mk_ast_map(self.ctx.ref())
5553  else:
5554  self.map = m
5555  assert ctx is not None
5556  self.ctx = ctx
5557  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5558 
5559  def __deepcopy__(self, memo={}):
5560  return AstMap(self.map, self.ctx)
5561 
5562  def __del__(self):
5563  if self.map is not None and self.ctx.ref() is not None:
5564  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5565 
5566  def __len__(self):
5567  """Return the size of the map.
5568 
5569  >>> M = AstMap()
5570  >>> len(M)
5571  0
5572  >>> x = Int('x')
5573  >>> M[x] = IntVal(1)
5574  >>> len(M)
5575  1
5576  """
5577  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5578 
5579  def __contains__(self, key):
5580  """Return `True` if the map contains key `key`.
5581 
5582  >>> M = AstMap()
5583  >>> x = Int('x')
5584  >>> M[x] = x + 1
5585  >>> x in M
5586  True
5587  >>> x+1 in M
5588  False
5589  """
5590  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5591 
5592  def __getitem__(self, key):
5593  """Retrieve the value associated with key `key`.
5594 
5595  >>> M = AstMap()
5596  >>> x = Int('x')
5597  >>> M[x] = x + 1
5598  >>> M[x]
5599  x + 1
5600  """
5601  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5602 
5603  def __setitem__(self, k, v):
5604  """Add/Update key `k` with value `v`.
5605 
5606  >>> M = AstMap()
5607  >>> x = Int('x')
5608  >>> M[x] = x + 1
5609  >>> len(M)
5610  1
5611  >>> M[x]
5612  x + 1
5613  >>> M[x] = IntVal(1)
5614  >>> M[x]
5615  1
5616  """
5617  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5618 
5619  def __repr__(self):
5620  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5621 
5622  def erase(self, k):
5623  """Remove the entry associated with key `k`.
5624 
5625  >>> M = AstMap()
5626  >>> x = Int('x')
5627  >>> M[x] = x + 1
5628  >>> len(M)
5629  1
5630  >>> M.erase(x)
5631  >>> len(M)
5632  0
5633  """
5634  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5635 
5636  def reset(self):
5637  """Remove all entries from the map.
5638 
5639  >>> M = AstMap()
5640  >>> x = Int('x')
5641  >>> M[x] = x + 1
5642  >>> M[x+x] = IntVal(1)
5643  >>> len(M)
5644  2
5645  >>> M.reset()
5646  >>> len(M)
5647  0
5648  """
5649  Z3_ast_map_reset(self.ctx.ref(), self.map)
5650 
5651  def keys(self):
5652  """Return an AstVector containing all keys in the map.
5653 
5654  >>> M = AstMap()
5655  >>> x = Int('x')
5656  >>> M[x] = x + 1
5657  >>> M[x+x] = IntVal(1)
5658  >>> M.keys()
5659  [x, x + x]
5660  """
5661  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5662 
5663 #########################################
5664 #
5665 # Model
5666 #
5667 #########################################
5668 
5669 class FuncEntry:
5670  """Store the value of the interpretation of a function in a particular point."""
5671 
5672  def __init__(self, entry, ctx):
5673  self.entry = entry
5674  self.ctx = ctx
5675  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5676 
5677  def __deepcopy__(self, memo={}):
5678  return FuncEntry(self.entry, self.ctx)
5679 
5680  def __del__(self):
5681  if self.ctx.ref() is not None:
5682  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5683 
5684  def num_args(self):
5685  """Return the number of arguments in the given entry.
5686 
5687  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5688  >>> s = Solver()
5689  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5690  >>> s.check()
5691  sat
5692  >>> m = s.model()
5693  >>> f_i = m[f]
5694  >>> f_i.num_entries()
5695  1
5696  >>> e = f_i.entry(0)
5697  >>> e.num_args()
5698  2
5699  """
5700  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5701 
5702  def arg_value(self, idx):
5703  """Return the value of argument `idx`.
5704 
5705  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5706  >>> s = Solver()
5707  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5708  >>> s.check()
5709  sat
5710  >>> m = s.model()
5711  >>> f_i = m[f]
5712  >>> f_i.num_entries()
5713  1
5714  >>> e = f_i.entry(0)
5715  >>> e
5716  [1, 2, 20]
5717  >>> e.num_args()
5718  2
5719  >>> e.arg_value(0)
5720  1
5721  >>> e.arg_value(1)
5722  2
5723  >>> try:
5724  ... e.arg_value(2)
5725  ... except IndexError:
5726  ... print("index error")
5727  index error
5728  """
5729  if idx >= self.num_args():
5730  raise IndexError
5731  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5732 
5733  def value(self):
5734  """Return the value of the function at point `self`.
5735 
5736  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5737  >>> s = Solver()
5738  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5739  >>> s.check()
5740  sat
5741  >>> m = s.model()
5742  >>> f_i = m[f]
5743  >>> f_i.num_entries()
5744  1
5745  >>> e = f_i.entry(0)
5746  >>> e
5747  [1, 2, 20]
5748  >>> e.num_args()
5749  2
5750  >>> e.value()
5751  20
5752  """
5753  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5754 
5755  def as_list(self):
5756  """Return entry `self` as a Python list.
5757  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5758  >>> s = Solver()
5759  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5760  >>> s.check()
5761  sat
5762  >>> m = s.model()
5763  >>> f_i = m[f]
5764  >>> f_i.num_entries()
5765  1
5766  >>> e = f_i.entry(0)
5767  >>> e.as_list()
5768  [1, 2, 20]
5769  """
5770  args = [ self.arg_value(i) for i in range(self.num_args())]
5771  args.append(self.value())
5772  return args
5773 
5774  def __repr__(self):
5775  return repr(self.as_list())
5776 
5777 class FuncInterp(Z3PPObject):
5778  """Stores the interpretation of a function in a Z3 model."""
5779 
5780  def __init__(self, f, ctx):
5781  self.f = f
5782  self.ctx = ctx
5783  if self.f is not None:
5784  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5785 
5786  def __deepcopy__(self, memo={}):
5787  return FuncInterp(self.f, self.ctx)
5788 
5789  def __del__(self):
5790  if self.f is not None and self.ctx.ref() is not None:
5791  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5792 
5793  def else_value(self):
5794  """
5795  Return the `else` value for a function interpretation.
5796  Return None if Z3 did not specify the `else` value for
5797  this object.
5798 
5799  >>> f = Function('f', IntSort(), IntSort())
5800  >>> s = Solver()
5801  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5802  >>> s.check()
5803  sat
5804  >>> m = s.model()
5805  >>> m[f]
5806  [2 -> 0, else -> 1]
5807  >>> m[f].else_value()
5808  1
5809  """
5810  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5811  if r:
5812  return _to_expr_ref(r, self.ctx)
5813  else:
5814  return None
5815 
5816  def num_entries(self):
5817  """Return the number of entries/points in the function interpretation `self`.
5818 
5819  >>> f = Function('f', IntSort(), IntSort())
5820  >>> s = Solver()
5821  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5822  >>> s.check()
5823  sat
5824  >>> m = s.model()
5825  >>> m[f]
5826  [2 -> 0, else -> 1]
5827  >>> m[f].num_entries()
5828  1
5829  """
5830  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5831 
5832  def arity(self):
5833  """Return the number of arguments for each entry in the function interpretation `self`.
5834 
5835  >>> f = Function('f', IntSort(), IntSort())
5836  >>> s = Solver()
5837  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5838  >>> s.check()
5839  sat
5840  >>> m = s.model()
5841  >>> m[f].arity()
5842  1
5843  """
5844  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5845 
5846  def entry(self, idx):
5847  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5848 
5849  >>> f = Function('f', IntSort(), IntSort())
5850  >>> s = Solver()
5851  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5852  >>> s.check()
5853  sat
5854  >>> m = s.model()
5855  >>> m[f]
5856  [2 -> 0, else -> 1]
5857  >>> m[f].num_entries()
5858  1
5859  >>> m[f].entry(0)
5860  [2, 0]
5861  """
5862  if idx >= self.num_entries():
5863  raise IndexError
5864  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5865 
5866  def translate(self, other_ctx):
5867  """Copy model 'self' to context 'other_ctx'.
5868  """
5869  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5870 
5871  def __copy__(self):
5872  return self.translate(self.ctx)
5873 
5874  def __deepcopy__(self):
5875  return self.translate(self.ctx)
5876 
5877  def as_list(self):
5878  """Return the function interpretation as a Python list.
5879  >>> f = Function('f', IntSort(), IntSort())
5880  >>> s = Solver()
5881  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5882  >>> s.check()
5883  sat
5884  >>> m = s.model()
5885  >>> m[f]
5886  [2 -> 0, else -> 1]
5887  >>> m[f].as_list()
5888  [[2, 0], 1]
5889  """
5890  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5891  r.append(self.else_value())
5892  return r
5893 
5894  def __repr__(self):
5895  return obj_to_string(self)
5896 
5897 class ModelRef(Z3PPObject):
5898  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5899 
5900  def __init__(self, m, ctx):
5901  assert ctx is not None
5902  self.model = m
5903  self.ctx = ctx
5904  Z3_model_inc_ref(self.ctx.ref(), self.model)
5905 
5906  def __del__(self):
5907  if self.ctx.ref() is not None:
5908  Z3_model_dec_ref(self.ctx.ref(), self.model)
5909 
5910  def __repr__(self):
5911  return obj_to_string(self)
5912 
5913  def sexpr(self):
5914  """Return a textual representation of the s-expression representing the model."""
5915  return Z3_model_to_string(self.ctx.ref(), self.model)
5916 
5917  def eval(self, t, model_completion=False):
5918  """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`.
5919 
5920  >>> x = Int('x')
5921  >>> s = Solver()
5922  >>> s.add(x > 0, x < 2)
5923  >>> s.check()
5924  sat
5925  >>> m = s.model()
5926  >>> m.eval(x + 1)
5927  2
5928  >>> m.eval(x == 1)
5929  True
5930  >>> y = Int('y')
5931  >>> m.eval(y + x)
5932  1 + y
5933  >>> m.eval(y)
5934  y
5935  >>> m.eval(y, model_completion=True)
5936  0
5937  >>> # Now, m contains an interpretation for y
5938  >>> m.eval(y + x)
5939  1
5940  """
5941  r = (Ast * 1)()
5942  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5943  return _to_expr_ref(r[0], self.ctx)
5944  raise Z3Exception("failed to evaluate expression in the model")
5945 
5946  def evaluate(self, t, model_completion=False):
5947  """Alias for `eval`.
5948 
5949  >>> x = Int('x')
5950  >>> s = Solver()
5951  >>> s.add(x > 0, x < 2)
5952  >>> s.check()
5953  sat
5954  >>> m = s.model()
5955  >>> m.evaluate(x + 1)
5956  2
5957  >>> m.evaluate(x == 1)
5958  True
5959  >>> y = Int('y')
5960  >>> m.evaluate(y + x)
5961  1 + y
5962  >>> m.evaluate(y)
5963  y
5964  >>> m.evaluate(y, model_completion=True)
5965  0
5966  >>> # Now, m contains an interpretation for y
5967  >>> m.evaluate(y + x)
5968  1
5969  """
5970  return self.eval(t, model_completion)
5971 
5972  def __len__(self):
5973  """Return the number of constant and function declarations in the model `self`.
5974 
5975  >>> f = Function('f', IntSort(), IntSort())
5976  >>> x = Int('x')
5977  >>> s = Solver()
5978  >>> s.add(x > 0, f(x) != x)
5979  >>> s.check()
5980  sat
5981  >>> m = s.model()
5982  >>> len(m)
5983  2
5984  """
5985  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5986 
5987  def get_interp(self, decl):
5988  """Return the interpretation for a given declaration or constant.
5989 
5990  >>> f = Function('f', IntSort(), IntSort())
5991  >>> x = Int('x')
5992  >>> s = Solver()
5993  >>> s.add(x > 0, x < 2, f(x) == 0)
5994  >>> s.check()
5995  sat
5996  >>> m = s.model()
5997  >>> m[x]
5998  1
5999  >>> m[f]
6000  [else -> 0]
6001  """
6002  if __debug__:
6003  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6004  if is_const(decl):
6005  decl = decl.decl()
6006  try:
6007  if decl.arity() == 0:
6008  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6009  if _r.value is None:
6010  return None
6011  r = _to_expr_ref(_r, self.ctx)
6012  if is_as_array(r):
6013  return self.get_interp(get_as_array_func(r))
6014  else:
6015  return r
6016  else:
6017  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6018  except Z3Exception:
6019  return None
6020 
6021  def num_sorts(self):
6022  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6023 
6024  >>> A = DeclareSort('A')
6025  >>> a, b = Consts('a b', A)
6026  >>> s = Solver()
6027  >>> s.add(a != b)
6028  >>> s.check()
6029  sat
6030  >>> m = s.model()
6031  >>> m.num_sorts()
6032  1
6033  """
6034  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6035 
6036  def get_sort(self, idx):
6037  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6038 
6039  >>> A = DeclareSort('A')
6040  >>> B = DeclareSort('B')
6041  >>> a1, a2 = Consts('a1 a2', A)
6042  >>> b1, b2 = Consts('b1 b2', B)
6043  >>> s = Solver()
6044  >>> s.add(a1 != a2, b1 != b2)
6045  >>> s.check()
6046  sat
6047  >>> m = s.model()
6048  >>> m.num_sorts()
6049  2
6050  >>> m.get_sort(0)
6051  A
6052  >>> m.get_sort(1)
6053  B
6054  """
6055  if idx >= self.num_sorts():
6056  raise IndexError
6057  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6058 
6059  def sorts(self):
6060  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6061 
6062  >>> A = DeclareSort('A')
6063  >>> B = DeclareSort('B')
6064  >>> a1, a2 = Consts('a1 a2', A)
6065  >>> b1, b2 = Consts('b1 b2', B)
6066  >>> s = Solver()
6067  >>> s.add(a1 != a2, b1 != b2)
6068  >>> s.check()
6069  sat
6070  >>> m = s.model()
6071  >>> m.sorts()
6072  [A, B]
6073  """
6074  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
6075 
6076  def get_universe(self, s):
6077  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6078 
6079  >>> A = DeclareSort('A')
6080  >>> a, b = Consts('a b', A)
6081  >>> s = Solver()
6082  >>> s.add(a != b)
6083  >>> s.check()
6084  sat
6085  >>> m = s.model()
6086  >>> m.get_universe(A)
6087  [A!val!0, A!val!1]
6088  """
6089  if __debug__:
6090  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6091  try:
6092  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6093  except Z3Exception:
6094  return None
6095 
6096  def __getitem__(self, idx):
6097  """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.
6098 
6099  The elements can be retrieved using position or the actual declaration.
6100 
6101  >>> f = Function('f', IntSort(), IntSort())
6102  >>> x = Int('x')
6103  >>> s = Solver()
6104  >>> s.add(x > 0, x < 2, f(x) == 0)
6105  >>> s.check()
6106  sat
6107  >>> m = s.model()
6108  >>> len(m)
6109  2
6110  >>> m[0]
6111  x
6112  >>> m[1]
6113  f
6114  >>> m[x]
6115  1
6116  >>> m[f]
6117  [else -> 0]
6118  >>> for d in m: print("%s -> %s" % (d, m[d]))
6119  x -> 1
6120  f -> [else -> 0]
6121  """
6122  if _is_int(idx):
6123  if idx >= len(self):
6124  raise IndexError
6125  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6126  if (idx < num_consts):
6127  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6128  else:
6129  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6130  if isinstance(idx, FuncDeclRef):
6131  return self.get_interp(idx)
6132  if is_const(idx):
6133  return self.get_interp(idx.decl())
6134  if isinstance(idx, SortRef):
6135  return self.get_universe(idx)
6136  if __debug__:
6137  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6138  return None
6139 
6140  def decls(self):
6141  """Return a list with all symbols that have an interpretation in the model `self`.
6142  >>> f = Function('f', IntSort(), IntSort())
6143  >>> x = Int('x')
6144  >>> s = Solver()
6145  >>> s.add(x > 0, x < 2, f(x) == 0)
6146  >>> s.check()
6147  sat
6148  >>> m = s.model()
6149  >>> m.decls()
6150  [x, f]
6151  """
6152  r = []
6153  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6154  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6155  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6156  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6157  return r
6158 
6159  def translate(self, target):
6160  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6161  """
6162  if __debug__:
6163  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6164  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6165  return Model(model, target)
6166 
6167  def __copy__(self):
6168  return self.translate(self.ctx)
6169 
6170  def __deepcopy__(self):
6171  return self.translate(self.ctx)
6172 
6173 def Model(ctx = None):
6174  ctx = _get_ctx(ctx)
6175  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6176 
6177 def is_as_array(n):
6178  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6179  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6180 
6181 def get_as_array_func(n):
6182  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6183  if __debug__:
6184  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6185  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6186 
6187 #########################################
6188 #
6189 # Statistics
6190 #
6191 #########################################
6192 class Statistics:
6193  """Statistics for `Solver.check()`."""
6194 
6195  def __init__(self, stats, ctx):
6196  self.stats = stats
6197  self.ctx = ctx
6198  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6199 
6200  def __deepcopy__(self, memo={}):
6201  return Statistics(self.stats, self.ctx)
6202 
6203  def __del__(self):
6204  if self.ctx.ref() is not None:
6205  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6206 
6207  def __repr__(self):
6208  if in_html_mode():
6209  out = io.StringIO()
6210  even = True
6211  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6212  for k, v in self:
6213  if even:
6214  out.write(u('<tr style="background-color:#CFCFCF">'))
6215  even = False
6216  else:
6217  out.write(u('<tr>'))
6218  even = True
6219  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
6220  out.write(u('</table>'))
6221  return out.getvalue()
6222  else:
6223  return Z3_stats_to_string(self.ctx.ref(), self.stats)
6224 
6225  def __len__(self):
6226  """Return the number of statistical counters.
6227 
6228  >>> x = Int('x')
6229  >>> s = Then('simplify', 'nlsat').solver()
6230  >>> s.add(x > 0)
6231  >>> s.check()
6232  sat
6233  >>> st = s.statistics()
6234  >>> len(st)
6235  6
6236  """
6237  return int(Z3_stats_size(self.ctx.ref(), self.stats))
6238 
6239  def __getitem__(self, idx):
6240  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6241 
6242  >>> x = Int('x')
6243  >>> s = Then('simplify', 'nlsat').solver()
6244  >>> s.add(x > 0)
6245  >>> s.check()
6246  sat
6247  >>> st = s.statistics()
6248  >>> len(st)
6249  6
6250  >>> st[0]
6251  ('nlsat propagations', 2)
6252  >>> st[1]
6253  ('nlsat stages', 2)
6254  """
6255  if idx >= len(self):
6256  raise IndexError
6257  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6258  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6259  else:
6260  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6261  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6262 
6263  def keys(self):
6264  """Return the list of statistical counters.
6265 
6266  >>> x = Int('x')
6267  >>> s = Then('simplify', 'nlsat').solver()
6268  >>> s.add(x > 0)
6269  >>> s.check()
6270  sat
6271  >>> st = s.statistics()
6272  """
6273  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6274 
6275  def get_key_value(self, key):
6276  """Return the value of a particular statistical counter.
6277 
6278  >>> x = Int('x')
6279  >>> s = Then('simplify', 'nlsat').solver()
6280  >>> s.add(x > 0)
6281  >>> s.check()
6282  sat
6283  >>> st = s.statistics()
6284  >>> st.get_key_value('nlsat propagations')
6285  2
6286  """
6287  for idx in range(len(self)):
6288  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6289  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6290  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6291  else:
6292  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6293  raise Z3Exception("unknown key")
6294 
6295  def __getattr__(self, name):
6296  """Access the value of statistical using attributes.
6297 
6298  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6299  we should use '_' (e.g., 'nlsat_propagations').
6300 
6301  >>> x = Int('x')
6302  >>> s = Then('simplify', 'nlsat').solver()
6303  >>> s.add(x > 0)
6304  >>> s.check()
6305  sat
6306  >>> st = s.statistics()
6307  >>> st.nlsat_propagations
6308  2
6309  >>> st.nlsat_stages
6310  2
6311  """
6312  key = name.replace('_', ' ')
6313  try:
6314  return self.get_key_value(key)
6315  except Z3Exception:
6316  raise AttributeError
6317 
6318 #########################################
6319 #
6320 # Solver
6321 #
6322 #########################################
6323 class CheckSatResult:
6324  """Represents the result of a satisfiability check: sat, unsat, unknown.
6325 
6326  >>> s = Solver()
6327  >>> s.check()
6328  sat
6329  >>> r = s.check()
6330  >>> isinstance(r, CheckSatResult)
6331  True
6332  """
6333 
6334  def __init__(self, r):
6335  self.r = r
6336 
6337  def __deepcopy__(self, memo={}):
6338  return CheckSatResult(self.r)
6339 
6340  def __eq__(self, other):
6341  return isinstance(other, CheckSatResult) and self.r == other.r
6342 
6343  def __ne__(self, other):
6344  return not self.__eq__(other)
6345 
6346  def __repr__(self):
6347  if in_html_mode():
6348  if self.r == Z3_L_TRUE:
6349  return "<b>sat</b>"
6350  elif self.r == Z3_L_FALSE:
6351  return "<b>unsat</b>"
6352  else:
6353  return "<b>unknown</b>"
6354  else:
6355  if self.r == Z3_L_TRUE:
6356  return "sat"
6357  elif self.r == Z3_L_FALSE:
6358  return "unsat"
6359  else:
6360  return "unknown"
6361 
6362 sat = CheckSatResult(Z3_L_TRUE)
6363 unsat = CheckSatResult(Z3_L_FALSE)
6364 unknown = CheckSatResult(Z3_L_UNDEF)
6365 
6366 class Solver(Z3PPObject):
6367  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6368 
6369  def __init__(self, solver=None, ctx=None):
6370  assert solver is None or ctx is not None
6371  self.ctx = _get_ctx(ctx)
6372  self.backtrack_level = 4000000000
6373  self.solver = None
6374  if solver is None:
6375  self.solver = Z3_mk_solver(self.ctx.ref())
6376  else:
6377  self.solver = solver
6378  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6379 
6380  def __del__(self):
6381  if self.solver is not None and self.ctx.ref() is not None:
6382  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6383 
6384  def set(self, *args, **keys):
6385  """Set a configuration option. The method `help()` return a string containing all available options.
6386 
6387  >>> s = Solver()
6388  >>> # The option MBQI can be set using three different approaches.
6389  >>> s.set(mbqi=True)
6390  >>> s.set('MBQI', True)
6391  >>> s.set(':mbqi', True)
6392  """
6393  p = args2params(args, keys, self.ctx)
6394  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6395 
6396  def push(self):
6397  """Create a backtracking point.
6398 
6399  >>> x = Int('x')
6400  >>> s = Solver()
6401  >>> s.add(x > 0)
6402  >>> s
6403  [x > 0]
6404  >>> s.push()
6405  >>> s.add(x < 1)
6406  >>> s
6407  [x > 0, x < 1]
6408  >>> s.check()
6409  unsat
6410  >>> s.pop()
6411  >>> s.check()
6412  sat
6413  >>> s
6414  [x > 0]
6415  """
6416  Z3_solver_push(self.ctx.ref(), self.solver)
6417 
6418  def pop(self, num=1):
6419  """Backtrack \c num backtracking points.
6420 
6421  >>> x = Int('x')
6422  >>> s = Solver()
6423  >>> s.add(x > 0)
6424  >>> s
6425  [x > 0]
6426  >>> s.push()
6427  >>> s.add(x < 1)
6428  >>> s
6429  [x > 0, x < 1]
6430  >>> s.check()
6431  unsat
6432  >>> s.pop()
6433  >>> s.check()
6434  sat
6435  >>> s
6436  [x > 0]
6437  """
6438  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6439 
6440  def num_scopes(self):
6441  """Return the current number of backtracking points.
6442 
6443  >>> s = Solver()
6444  >>> s.num_scopes()
6445  0L
6446  >>> s.push()
6447  >>> s.num_scopes()
6448  1L
6449  >>> s.push()
6450  >>> s.num_scopes()
6451  2L
6452  >>> s.pop()
6453  >>> s.num_scopes()
6454  1L
6455  """
6456  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6457 
6458  def reset(self):
6459  """Remove all asserted constraints and backtracking points created using `push()`.
6460 
6461  >>> x = Int('x')
6462  >>> s = Solver()
6463  >>> s.add(x > 0)
6464  >>> s
6465  [x > 0]
6466  >>> s.reset()
6467  >>> s
6468  []
6469  """
6470  Z3_solver_reset(self.ctx.ref(), self.solver)
6471 
6472  def assert_exprs(self, *args):
6473  """Assert constraints into the solver.
6474 
6475  >>> x = Int('x')
6476  >>> s = Solver()
6477  >>> s.assert_exprs(x > 0, x < 2)
6478  >>> s
6479  [x > 0, x < 2]
6480  """
6481  args = _get_args(args)
6482  s = BoolSort(self.ctx)
6483  for arg in args:
6484  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6485  for f in arg:
6486  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6487  else:
6488  arg = s.cast(arg)
6489  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6490 
6491  def add(self, *args):
6492  """Assert constraints into the solver.
6493 
6494  >>> x = Int('x')
6495  >>> s = Solver()
6496  >>> s.add(x > 0, x < 2)
6497  >>> s
6498  [x > 0, x < 2]
6499  """
6500  self.assert_exprs(*args)
6501 
6502  def __iadd__(self, fml):
6503  self.add(fml)
6504  return self
6505 
6506  def append(self, *args):
6507  """Assert constraints into the solver.
6508 
6509  >>> x = Int('x')
6510  >>> s = Solver()
6511  >>> s.append(x > 0, x < 2)
6512  >>> s
6513  [x > 0, x < 2]
6514  """
6515  self.assert_exprs(*args)
6516 
6517  def insert(self, *args):
6518  """Assert constraints into the solver.
6519 
6520  >>> x = Int('x')
6521  >>> s = Solver()
6522  >>> s.insert(x > 0, x < 2)
6523  >>> s
6524  [x > 0, x < 2]
6525  """
6526  self.assert_exprs(*args)
6527 
6528  def assert_and_track(self, a, p):
6529  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6530 
6531  If `p` is a string, it will be automatically converted into a Boolean constant.
6532 
6533  >>> x = Int('x')
6534  >>> p3 = Bool('p3')
6535  >>> s = Solver()
6536  >>> s.set(unsat_core=True)
6537  >>> s.assert_and_track(x > 0, 'p1')
6538  >>> s.assert_and_track(x != 1, 'p2')
6539  >>> s.assert_and_track(x < 0, p3)
6540  >>> print(s.check())
6541  unsat
6542  >>> c = s.unsat_core()
6543  >>> len(c)
6544  2
6545  >>> Bool('p1') in c
6546  True
6547  >>> Bool('p2') in c
6548  False
6549  >>> p3 in c
6550  True
6551  """
6552  if isinstance(p, str):
6553  p = Bool(p, self.ctx)
6554  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6555  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6556  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6557 
6558  def check(self, *assumptions):
6559  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6560 
6561  >>> x = Int('x')
6562  >>> s = Solver()
6563  >>> s.check()
6564  sat
6565  >>> s.add(x > 0, x < 2)
6566  >>> s.check()
6567  sat
6568  >>> s.model().eval(x)
6569  1
6570  >>> s.add(x < 1)
6571  >>> s.check()
6572  unsat
6573  >>> s.reset()
6574  >>> s.add(2**x == 4)
6575  >>> s.check()
6576  unknown
6577  """
6578  assumptions = _get_args(assumptions)
6579  num = len(assumptions)
6580  _assumptions = (Ast * num)()
6581  for i in range(num):
6582  _assumptions[i] = assumptions[i].as_ast()
6583  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6584  return CheckSatResult(r)
6585 
6586  def model(self):
6587  """Return a model for the last `check()`.
6588 
6589  This function raises an exception if
6590  a model is not available (e.g., last `check()` returned unsat).
6591 
6592  >>> s = Solver()
6593  >>> a = Int('a')
6594  >>> s.add(a + 2 == 0)
6595  >>> s.check()
6596  sat
6597  >>> s.model()
6598  [a = -2]
6599  """
6600  try:
6601  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6602  except Z3Exception:
6603  raise Z3Exception("model is not available")
6604 
6605  def unsat_core(self):
6606  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6607 
6608  These are the assumptions Z3 used in the unsatisfiability proof.
6609  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6610  They may be also used to "retract" assumptions. Note that, assumptions are not really
6611  "soft constraints", but they can be used to implement them.
6612 
6613  >>> p1, p2, p3 = Bools('p1 p2 p3')
6614  >>> x, y = Ints('x y')
6615  >>> s = Solver()
6616  >>> s.add(Implies(p1, x > 0))
6617  >>> s.add(Implies(p2, y > x))
6618  >>> s.add(Implies(p2, y < 1))
6619  >>> s.add(Implies(p3, y > -3))
6620  >>> s.check(p1, p2, p3)
6621  unsat
6622  >>> core = s.unsat_core()
6623  >>> len(core)
6624  2
6625  >>> p1 in core
6626  True
6627  >>> p2 in core
6628  True
6629  >>> p3 in core
6630  False
6631  >>> # "Retracting" p2
6632  >>> s.check(p1, p3)
6633  sat
6634  """
6635  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6636 
6637  def consequences(self, assumptions, variables):
6638  """Determine fixed values for the variables based on the solver state and assumptions.
6639  >>> s = Solver()
6640  >>> a, b, c, d = Bools('a b c d')
6641  >>> s.add(Implies(a,b), Implies(b, c))
6642  >>> s.consequences([a],[b,c,d])
6643  (sat, [Implies(a, b), Implies(a, c)])
6644  >>> s.consequences([Not(c),d],[a,b,c,d])
6645  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6646  """
6647  if isinstance(assumptions, list):
6648  _asms = AstVector(None, self.ctx)
6649  for a in assumptions:
6650  _asms.push(a)
6651  assumptions = _asms
6652  if isinstance(variables, list):
6653  _vars = AstVector(None, self.ctx)
6654  for a in variables:
6655  _vars.push(a)
6656  variables = _vars
6657  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6658  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6659  consequences = AstVector(None, self.ctx)
6660  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6661  sz = len(consequences)
6662  consequences = [ consequences[i] for i in range(sz) ]
6663  return CheckSatResult(r), consequences
6664 
6665  def from_file(self, filename):
6666  """Parse assertions from a file"""
6667  try:
6668  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6669  except Z3Exception as e:
6670  _handle_parse_error(e, self.ctx)
6671 
6672  def from_string(self, s):
6673  """Parse assertions from a string"""
6674  try:
6675  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6676  except Z3Exception as e:
6677  _handle_parse_error(e, self.ctx)
6678 
6679  def cube(self, vars = None):
6680  """Get set of cubes
6681  The method takes an optional set of variables that restrict which
6682  variables may be used as a starting point for cubing.
6683  If vars is not None, then the first case split is based on a variable in
6684  this set.
6685  """
6686  self.cube_vs = AstVector(None, self.ctx)
6687  if vars is not None:
6688  for v in vars:
6689  self.cube_vs.push(v)
6690  while True:
6691  lvl = self.backtrack_level
6692  self.backtrack_level = 4000000000
6693  r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
6694  if (len(r) == 1 and is_false(r[0])):
6695  return
6696  yield r
6697  if (len(r) == 0):
6698  return
6699 
6700  def cube_vars(self):
6701  """Access the set of variables that were touched by the most recently generated cube.
6702  This set of variables can be used as a starting point for additional cubes.
6703  The idea is that variables that appear in clauses that are reduced by the most recent
6704  cube are likely more useful to cube on."""
6705  return self.cube_vs
6706 
6707  def proof(self):
6708  """Return a proof for the last `check()`. Proof construction must be enabled."""
6709  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6710 
6711  def assertions(self):
6712  """Return an AST vector containing all added constraints.
6713 
6714  >>> s = Solver()
6715  >>> s.assertions()
6716  []
6717  >>> a = Int('a')
6718  >>> s.add(a > 0)
6719  >>> s.add(a < 10)
6720  >>> s.assertions()
6721  [a > 0, a < 10]
6722  """
6723  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6724 
6725  def units(self):
6726  """Return an AST vector containing all currently inferred units.
6727  """
6728  return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
6729 
6730  def non_units(self):
6731  """Return an AST vector containing all atomic formulas in solver state that are not units.
6732  """
6733  return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
6734 
6735  def statistics(self):
6736  """Return statistics for the last `check()`.
6737 
6738  >>> s = SimpleSolver()
6739  >>> x = Int('x')
6740  >>> s.add(x > 0)
6741  >>> s.check()
6742  sat
6743  >>> st = s.statistics()
6744  >>> st.get_key_value('final checks')
6745  1
6746  >>> len(st) > 0
6747  True
6748  >>> st[0] != 0
6749  True
6750  """
6751  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6752 
6753  def reason_unknown(self):
6754  """Return a string describing why the last `check()` returned `unknown`.
6755 
6756  >>> x = Int('x')
6757  >>> s = SimpleSolver()
6758  >>> s.add(2**x == 4)
6759  >>> s.check()
6760  unknown
6761  >>> s.reason_unknown()
6762  '(incomplete (theory arithmetic))'
6763  """
6764  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6765 
6766  def help(self):
6767  """Display a string describing all available options."""
6768  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6769 
6770  def param_descrs(self):
6771  """Return the parameter description set."""
6772  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6773 
6774  def __repr__(self):
6775  """Return a formatted string with all added constraints."""
6776  return obj_to_string(self)
6777 
6778  def translate(self, target):
6779  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6780 
6781  >>> c1 = Context()
6782  >>> c2 = Context()
6783  >>> s1 = Solver(ctx=c1)
6784  >>> s2 = s1.translate(c2)
6785  """
6786  if __debug__:
6787  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6788  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6789  return Solver(solver, target)
6790 
6791  def __copy__(self):
6792  return self.translate(self.ctx)
6793 
6794  def __deepcopy__(self):
6795  return self.translate(self.ctx)
6796 
6797  def sexpr(self):
6798  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6799 
6800  >>> x = Int('x')
6801  >>> s = Solver()
6802  >>> s.add(x > 0)
6803  >>> s.add(x < 2)
6804  >>> r = s.sexpr()
6805  """
6806  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6807 
6808  def to_smt2(self):
6809  """return SMTLIB2 formatted benchmark for solver's assertions"""
6810  es = self.assertions()
6811  sz = len(es)
6812  sz1 = sz
6813  if sz1 > 0:
6814  sz1 -= 1
6815  v = (Ast * sz1)()
6816  for i in range(sz1):
6817  v[i] = es[i].as_ast()
6818  if sz > 0:
6819  e = es[sz1].as_ast()
6820  else:
6821  e = BoolVal(True, self.ctx).as_ast()
6822  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6823 
6824 def SolverFor(logic, ctx=None):
6825  """Create a solver customized for the given logic.
6826 
6827  The parameter `logic` is a string. It should be contains
6828  the name of a SMT-LIB logic.
6829  See http://www.smtlib.org/ for the name of all available logics.
6830 
6831  >>> s = SolverFor("QF_LIA")
6832  >>> x = Int('x')
6833  >>> s.add(x > 0)
6834  >>> s.add(x < 2)
6835  >>> s.check()
6836  sat
6837  >>> s.model()
6838  [x = 1]
6839  """
6840  ctx = _get_ctx(ctx)
6841  logic = to_symbol(logic)
6842  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6843 
6844 def SimpleSolver(ctx=None):
6845  """Return a simple general purpose solver with limited amount of preprocessing.
6846 
6847  >>> s = SimpleSolver()
6848  >>> x = Int('x')
6849  >>> s.add(x > 0)
6850  >>> s.check()
6851  sat
6852  """
6853  ctx = _get_ctx(ctx)
6854  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6855 
6856 
6861 
6863  """Fixedpoint API provides methods for solving with recursive predicates"""
6864 
6865  def __init__(self, fixedpoint=None, ctx=None):
6866  assert fixedpoint is None or ctx is not None
6867  self.ctx = _get_ctx(ctx)
6868  self.fixedpoint = None
6869  if fixedpoint is None:
6870  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6871  else:
6872  self.fixedpoint = fixedpoint
6873  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6874  self.vars = []
6875 
6876  def __deepcopy__(self, memo={}):
6877  return FixedPoint(self.fixedpoint, self.ctx)
6878 
6879  def __del__(self):
6880  if self.fixedpoint is not None and self.ctx.ref() is not None:
6881  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6882 
6883  def set(self, *args, **keys):
6884  """Set a configuration option. The method `help()` return a string containing all available options.
6885  """
6886  p = args2params(args, keys, self.ctx)
6887  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6888 
6889  def help(self):
6890  """Display a string describing all available options."""
6891  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6892 
6893  def param_descrs(self):
6894  """Return the parameter description set."""
6895  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6896 
6897  def assert_exprs(self, *args):
6898  """Assert constraints as background axioms for the fixedpoint solver."""
6899  args = _get_args(args)
6900  s = BoolSort(self.ctx)
6901  for arg in args:
6902  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6903  for f in arg:
6904  f = self.abstract(f)
6905  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6906  else:
6907  arg = s.cast(arg)
6908  arg = self.abstract(arg)
6909  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6910 
6911  def add(self, *args):
6912  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6913  self.assert_exprs(*args)
6914 
6915  def __iadd__(self, fml):
6916  self.add(fml)
6917  return self
6918 
6919  def append(self, *args):
6920  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6921  self.assert_exprs(*args)
6922 
6923  def insert(self, *args):
6924  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6925  self.assert_exprs(*args)
6926 
6927  def add_rule(self, head, body = None, name = None):
6928  """Assert rules defining recursive predicates to the fixedpoint solver.
6929  >>> a = Bool('a')
6930  >>> b = Bool('b')
6931  >>> s = Fixedpoint()
6932  >>> s.register_relation(a.decl())
6933  >>> s.register_relation(b.decl())
6934  >>> s.fact(a)
6935  >>> s.rule(b, a)
6936  >>> s.query(b)
6937  sat
6938  """
6939  if name is None:
6940  name = ""
6941  name = to_symbol(name, self.ctx)
6942  if body is None:
6943  head = self.abstract(head)
6944  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6945  else:
6946  body = _get_args(body)
6947  f = self.abstract(Implies(And(body, self.ctx),head))
6948  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6949 
6950  def rule(self, head, body = None, name = None):
6951  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6952  self.add_rule(head, body, name)
6953 
6954  def fact(self, head, name = None):
6955  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6956  self.add_rule(head, None, name)
6957 
6958  def query(self, *query):
6959  """Query the fixedpoint engine whether formula is derivable.
6960  You can also pass an tuple or list of recursive predicates.
6961  """
6962  query = _get_args(query)
6963  sz = len(query)
6964  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6965  _decls = (FuncDecl * sz)()
6966  i = 0
6967  for q in query:
6968  _decls[i] = q.ast
6969  i = i + 1
6970  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6971  else:
6972  if sz == 1:
6973  query = query[0]
6974  else:
6975  query = And(query, self.ctx)
6976  query = self.abstract(query, False)
6977  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6978  return CheckSatResult(r)
6979 
6980  def query_from_lvl (self, lvl, *query):
6981  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
6982  """
6983  query = _get_args(query)
6984  sz = len(query)
6985  if sz >= 1 and isinstance(query[0], FuncDecl):
6986  _z3_assert (False, "unsupported")
6987  else:
6988  if sz == 1:
6989  query = query[0]
6990  else:
6991  query = And(query)
6992  query = self.abstract(query, False)
6993  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
6994  return CheckSatResult(r)
6995 
6996  def push(self):
6997  """create a backtracking point for added rules, facts and assertions"""
6998  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6999 
7000  def pop(self):
7001  """restore to previously created backtracking point"""
7002  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
7003 
7004  def update_rule(self, head, body, name):
7005  """update rule"""
7006  if name is None:
7007  name = ""
7008  name = to_symbol(name, self.ctx)
7009  body = _get_args(body)
7010  f = self.abstract(Implies(And(body, self.ctx),head))
7011  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7012 
7013  def get_answer(self):
7014  """Retrieve answer from last query call."""
7015  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7016  return _to_expr_ref(r, self.ctx)
7017 
7019  """Retrieve a ground cex from last query call."""
7020  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7021  return _to_expr_ref(r, self.ctx)
7022 
7024  """retrieve rules along the counterexample trace"""
7025  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7026 
7028  """retrieve rule names along the counterexample trace"""
7029  # this is a hack as I don't know how to return a list of symbols from C++;
7030  # obtain names as a single string separated by semicolons
7031  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7032  # split into individual names
7033  return names.split (';')
7034 
7035  def get_num_levels(self, predicate):
7036  """Retrieve number of levels used for predicate in PDR engine"""
7037  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7038 
7039  def get_cover_delta(self, level, predicate):
7040  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
7041  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7042  return _to_expr_ref(r, self.ctx)
7043 
7044  def add_cover(self, level, predicate, property):
7045  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
7046  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7047 
7048  def register_relation(self, *relations):
7049  """Register relation as recursive"""
7050  relations = _get_args(relations)
7051  for f in relations:
7052  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7053 
7054  def set_predicate_representation(self, f, *representations):
7055  """Control how relation is represented"""
7056  representations = _get_args(representations)
7057  representations = [to_symbol(s) for s in representations]
7058  sz = len(representations)
7059  args = (Symbol * sz)()
7060  for i in range(sz):
7061  args[i] = representations[i]
7062  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7063 
7064  def parse_string(self, s):
7065  """Parse rules and queries from a string"""
7066  try:
7067  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7068  except Z3Exception as e:
7069  _handle_parse_error(e, self.ctx)
7070 
7071  def parse_file(self, f):
7072  """Parse rules and queries from a file"""
7073  try:
7074  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7075  except Z3Exception as e:
7076  _handle_parse_error(e, self.ctx)
7077 
7078  def get_rules(self):
7079  """retrieve rules that have been added to fixedpoint context"""
7080  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7081 
7082  def get_assertions(self):
7083  """retrieve assertions that have been added to fixedpoint context"""
7084  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7085 
7086  def __repr__(self):
7087  """Return a formatted string with all added rules and constraints."""
7088  return self.sexpr()
7089 
7090  def sexpr(self):
7091  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7092  """
7093  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7094 
7095  def to_string(self, queries):
7096  """Return a formatted string (in Lisp-like format) with all added constraints.
7097  We say the string is in s-expression format.
7098  Include also queries.
7099  """
7100  args, len = _to_ast_array(queries)
7101  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7102 
7103  def statistics(self):
7104  """Return statistics for the last `query()`.
7105  """
7106  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7107 
7108  def reason_unknown(self):
7109  """Return a string describing why the last `query()` returned `unknown`.
7110  """
7111  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7112 
7113  def declare_var(self, *vars):
7114  """Add variable or several variables.
7115  The added variable or variables will be bound in the rules
7116  and queries
7117  """
7118  vars = _get_args(vars)
7119  for v in vars:
7120  self.vars += [v]
7121 
7122  def abstract(self, fml, is_forall=True):
7123  if self.vars == []:
7124  return fml
7125  if is_forall:
7126  return ForAll(self.vars, fml)
7127  else:
7128  return Exists(self.vars, fml)
7129 
7130 
7131 
7136 
7138  """Finite domain sort."""
7139 
7140  def size(self):
7141  """Return the size of the finite domain sort"""
7142  r = (ctypes.c_ulonglong * 1)()
7143  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7144  return r[0]
7145  else:
7146  raise Z3Exception("Failed to retrieve finite domain sort size")
7147 
7148 def FiniteDomainSort(name, sz, ctx=None):
7149  """Create a named finite domain sort of a given size sz"""
7150  if not isinstance(name, Symbol):
7151  name = to_symbol(name)
7152  ctx = _get_ctx(ctx)
7153  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7154 
7156  """Return True if `s` is a Z3 finite-domain sort.
7157 
7158  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7159  True
7160  >>> is_finite_domain_sort(IntSort())
7161  False
7162  """
7163  return isinstance(s, FiniteDomainSortRef)
7164 
7165 
7167  """Finite-domain expressions."""
7168 
7169  def sort(self):
7170  """Return the sort of the finite-domain expression `self`."""
7171  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7172 
7173  def as_string(self):
7174  """Return a Z3 floating point expression as a Python string."""
7175  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7176 
7178  """Return `True` if `a` is a Z3 finite-domain expression.
7179 
7180  >>> s = FiniteDomainSort('S', 100)
7181  >>> b = Const('b', s)
7182  >>> is_finite_domain(b)
7183  True
7184  >>> is_finite_domain(Int('x'))
7185  False
7186  """
7187  return isinstance(a, FiniteDomainRef)
7188 
7189 
7191  """Integer values."""
7192 
7193  def as_long(self):
7194  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7195 
7196  >>> s = FiniteDomainSort('S', 100)
7197  >>> v = FiniteDomainVal(3, s)
7198  >>> v
7199  3
7200  >>> v.as_long() + 1
7201  4
7202  """
7203  return int(self.as_string())
7204 
7205  def as_string(self):
7206  """Return a Z3 finite-domain numeral as a Python string.
7207 
7208  >>> s = FiniteDomainSort('S', 100)
7209  >>> v = FiniteDomainVal(42, s)
7210  >>> v.as_string()
7211  '42'
7212  """
7213  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
7214 
7215 
7216 def FiniteDomainVal(val, sort, ctx=None):
7217  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7218 
7219  >>> s = FiniteDomainSort('S', 256)
7220  >>> FiniteDomainVal(255, s)
7221  255
7222  >>> FiniteDomainVal('100', s)
7223  100
7224  """
7225  if __debug__:
7226  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
7227  ctx = sort.ctx
7228  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7229 
7231  """Return `True` if `a` is a Z3 finite-domain value.
7232 
7233  >>> s = FiniteDomainSort('S', 100)
7234  >>> b = Const('b', s)
7235  >>> is_finite_domain_value(b)
7236  False
7237  >>> b = FiniteDomainVal(10, s)
7238  >>> b
7239  10
7240  >>> is_finite_domain_value(b)
7241  True
7242  """
7243  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7244 
7245 
7246 
7251 
7253  def __init__(self, opt, value, is_max):
7254  self._opt = opt
7255  self._value = value
7256  self._is_max = is_max
7257 
7258  def lower(self):
7259  opt = self._opt
7260  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7261 
7262  def upper(self):
7263  opt = self._opt
7264  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7265 
7266  def lower_values(self):
7267  opt = self._opt
7268  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7269 
7270  def upper_values(self):
7271  opt = self._opt
7272  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7273 
7274  def value(self):
7275  if self._is_max:
7276  return self.upper()
7277  else:
7278  return self.lower()
7279 
7280  def __str__(self):
7281  return "%s:%s" % (self._value, self._is_max)
7282 
7283 
7285  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7286 
7287  def __init__(self, ctx=None):
7288  self.ctx = _get_ctx(ctx)
7289  self.optimize = Z3_mk_optimize(self.ctx.ref())
7290  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7291 
7292  def __deepcopy__(self, memo={}):
7293  return Optimize(self.optimize, self.ctx)
7294 
7295  def __del__(self):
7296  if self.optimize is not None and self.ctx.ref() is not None:
7297  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7298 
7299  def set(self, *args, **keys):
7300  """Set a configuration option. The method `help()` return a string containing all available options.
7301  """
7302  p = args2params(args, keys, self.ctx)
7303  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7304 
7305  def help(self):
7306  """Display a string describing all available options."""
7307  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7308 
7309  def param_descrs(self):
7310  """Return the parameter description set."""
7311  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7312 
7313  def assert_exprs(self, *args):
7314  """Assert constraints as background axioms for the optimize solver."""
7315  args = _get_args(args)
7316  s = BoolSort(self.ctx)
7317  for arg in args:
7318  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7319  for f in arg:
7320  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7321  else:
7322  arg = s.cast(arg)
7323  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7324 
7325  def add(self, *args):
7326  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7327  self.assert_exprs(*args)
7328 
7329  def __iadd__(self, fml):
7330  self.add(fml)
7331  return self
7332 
7333  def add_soft(self, arg, weight = "1", id = None):
7334  """Add soft constraint with optional weight and optional identifier.
7335  If no weight is supplied, then the penalty for violating the soft constraint
7336  is 1.
7337  Soft constraints are grouped by identifiers. Soft constraints that are
7338  added without identifiers are grouped by default.
7339  """
7340  if _is_int(weight):
7341  weight = "%d" % weight
7342  elif isinstance(weight, float):
7343  weight = "%f" % weight
7344  if not isinstance(weight, str):
7345  raise Z3Exception("weight should be a string or an integer")
7346  if id is None:
7347  id = ""
7348  id = to_symbol(id, self.ctx)
7349  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7350  return OptimizeObjective(self, v, False)
7351 
7352  def maximize(self, arg):
7353  """Add objective function to maximize."""
7354  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7355 
7356  def minimize(self, arg):
7357  """Add objective function to minimize."""
7358  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7359 
7360  def push(self):
7361  """create a backtracking point for added rules, facts and assertions"""
7362  Z3_optimize_push(self.ctx.ref(), self.optimize)
7363 
7364  def pop(self):
7365  """restore to previously created backtracking point"""
7366  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7367 
7368  def check(self, *assumptions):
7369  """Check satisfiability while optimizing objective functions."""
7370  assumptions = _get_args(assumptions)
7371  num = len(assumptions)
7372  _assumptions = (Ast * num)()
7373  for i in range(num):
7374  _assumptions[i] = assumptions[i].as_ast()
7375  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7376 
7377  def reason_unknown(self):
7378  """Return a string that describes why the last `check()` returned `unknown`."""
7379  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7380 
7381  def model(self):
7382  """Return a model for the last check()."""
7383  try:
7384  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7385  except Z3Exception:
7386  raise Z3Exception("model is not available")
7387 
7388  def unsat_core(self):
7389  return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7390 
7391  def lower(self, obj):
7392  if not isinstance(obj, OptimizeObjective):
7393  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7394  return obj.lower()
7395 
7396  def upper(self, obj):
7397  if not isinstance(obj, OptimizeObjective):
7398  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7399  return obj.upper()
7400 
7401  def lower_values(self, obj):
7402  if not isinstance(obj, OptimizeObjective):
7403  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7404  return obj.lower_values()
7405 
7406  def upper_values(self, obj):
7407  if not isinstance(obj, OptimizeObjective):
7408  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7409  return obj.upper_values()
7410 
7411  def from_file(self, filename):
7412  """Parse assertions and objectives from a file"""
7413  try:
7414  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7415  except Z3Exception as e:
7416  _handle_parse_error(e, self.ctx)
7417 
7418  def from_string(self, s):
7419  """Parse assertions and objectives from a string"""
7420  try:
7421  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7422  except Z3Exception as e:
7423  _handle_parse_error(e, self.ctx)
7424 
7425  def assertions(self):
7426  """Return an AST vector containing all added constraints."""
7427  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7428 
7429  def objectives(self):
7430  """returns set of objective functions"""
7431  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7432 
7433  def __repr__(self):
7434  """Return a formatted string with all added rules and constraints."""
7435  return self.sexpr()
7436 
7437  def sexpr(self):
7438  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7439  """
7440  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7441 
7442  def statistics(self):
7443  """Return statistics for the last check`.
7444  """
7445  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7446 
7447 
7448 
7449 
7450 
7456  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7457 
7458  def __init__(self, result, ctx):
7459  self.result = result
7460  self.ctx = ctx
7461  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7462 
7463  def __deepcopy__(self, memo={}):
7464  return ApplyResult(self.result, self.ctx)
7465 
7466  def __del__(self):
7467  if self.ctx.ref() is not None:
7468  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7469 
7470  def __len__(self):
7471  """Return the number of subgoals in `self`.
7472 
7473  >>> a, b = Ints('a b')
7474  >>> g = Goal()
7475  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7476  >>> t = Tactic('split-clause')
7477  >>> r = t(g)
7478  >>> len(r)
7479  2
7480  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7481  >>> len(t(g))
7482  4
7483  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7484  >>> len(t(g))
7485  1
7486  """
7487  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7488 
7489  def __getitem__(self, idx):
7490  """Return one of the subgoals stored in ApplyResult object `self`.
7491 
7492  >>> a, b = Ints('a b')
7493  >>> g = Goal()
7494  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7495  >>> t = Tactic('split-clause')
7496  >>> r = t(g)
7497  >>> r[0]
7498  [a == 0, Or(b == 0, b == 1), a > b]
7499  >>> r[1]
7500  [a == 1, Or(b == 0, b == 1), a > b]
7501  """
7502  if idx >= len(self):
7503  raise IndexError
7504  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7505 
7506  def __repr__(self):
7507  return obj_to_string(self)
7508 
7509  def sexpr(self):
7510  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7511  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7512 
7513 
7514  def as_expr(self):
7515  """Return a Z3 expression consisting of all subgoals.
7516 
7517  >>> x = Int('x')
7518  >>> g = Goal()
7519  >>> g.add(x > 1)
7520  >>> g.add(Or(x == 2, x == 3))
7521  >>> r = Tactic('simplify')(g)
7522  >>> r
7523  [[Not(x <= 1), Or(x == 2, x == 3)]]
7524  >>> r.as_expr()
7525  And(Not(x <= 1), Or(x == 2, x == 3))
7526  >>> r = Tactic('split-clause')(g)
7527  >>> r
7528  [[x > 1, x == 2], [x > 1, x == 3]]
7529  >>> r.as_expr()
7530  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7531  """
7532  sz = len(self)
7533  if sz == 0:
7534  return BoolVal(False, self.ctx)
7535  elif sz == 1:
7536  return self[0].as_expr()
7537  else:
7538  return Or([ self[i].as_expr() for i in range(len(self)) ])
7539 
7540 
7545 class Tactic:
7546  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7547 
7548  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7549  """
7550  def __init__(self, tactic, ctx=None):
7551  self.ctx = _get_ctx(ctx)
7552  self.tactic = None
7553  if isinstance(tactic, TacticObj):
7554  self.tactic = tactic
7555  else:
7556  if __debug__:
7557  _z3_assert(isinstance(tactic, str), "tactic name expected")
7558  try:
7559  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7560  except Z3Exception:
7561  raise Z3Exception("unknown tactic '%s'" % tactic)
7562  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7563 
7564  def __deepcopy__(self, memo={}):
7565  return Tactic(self.tactic, self.ctx)
7566 
7567  def __del__(self):
7568  if self.tactic is not None and self.ctx.ref() is not None:
7569  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7570 
7571  def solver(self):
7572  """Create a solver using the tactic `self`.
7573 
7574  The solver supports the methods `push()` and `pop()`, but it
7575  will always solve each `check()` from scratch.
7576 
7577  >>> t = Then('simplify', 'nlsat')
7578  >>> s = t.solver()
7579  >>> x = Real('x')
7580  >>> s.add(x**2 == 2, x > 0)
7581  >>> s.check()
7582  sat
7583  >>> s.model()
7584  [x = 1.4142135623?]
7585  """
7586  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7587 
7588  def apply(self, goal, *arguments, **keywords):
7589  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7590 
7591  >>> x, y = Ints('x y')
7592  >>> t = Tactic('solve-eqs')
7593  >>> t.apply(And(x == 0, y >= x + 1))
7594  [[y >= 1]]
7595  """
7596  if __debug__:
7597  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7598  goal = _to_goal(goal)
7599  if len(arguments) > 0 or len(keywords) > 0:
7600  p = args2params(arguments, keywords, self.ctx)
7601  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7602  else:
7603  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7604 
7605  def __call__(self, goal, *arguments, **keywords):
7606  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7607 
7608  >>> x, y = Ints('x y')
7609  >>> t = Tactic('solve-eqs')
7610  >>> t(And(x == 0, y >= x + 1))
7611  [[y >= 1]]
7612  """
7613  return self.apply(goal, *arguments, **keywords)
7614 
7615  def help(self):
7616  """Display a string containing a description of the available options for the `self` tactic."""
7617  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7618 
7619  def param_descrs(self):
7620  """Return the parameter description set."""
7621  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7622 
7623 def _to_goal(a):
7624  if isinstance(a, BoolRef):
7625  goal = Goal(ctx = a.ctx)
7626  goal.add(a)
7627  return goal
7628  else:
7629  return a
7630 
7631 def _to_tactic(t, ctx=None):
7632  if isinstance(t, Tactic):
7633  return t
7634  else:
7635  return Tactic(t, ctx)
7636 
7637 def _and_then(t1, t2, ctx=None):
7638  t1 = _to_tactic(t1, ctx)
7639  t2 = _to_tactic(t2, ctx)
7640  if __debug__:
7641  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7642  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7643 
7644 def _or_else(t1, t2, ctx=None):
7645  t1 = _to_tactic(t1, ctx)
7646  t2 = _to_tactic(t2, ctx)
7647  if __debug__:
7648  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7649  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7650 
7651 def AndThen(*ts, **ks):
7652  """Return a tactic that applies the tactics in `*ts` in sequence.
7653 
7654  >>> x, y = Ints('x y')
7655  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7656  >>> t(And(x == 0, y > x + 1))
7657  [[Not(y <= 1)]]
7658  >>> t(And(x == 0, y > x + 1)).as_expr()
7659  Not(y <= 1)
7660  """
7661  if __debug__:
7662  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7663  ctx = ks.get('ctx', None)
7664  num = len(ts)
7665  r = ts[0]
7666  for i in range(num - 1):
7667  r = _and_then(r, ts[i+1], ctx)
7668  return r
7669 
7670 def Then(*ts, **ks):
7671  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7672 
7673  >>> x, y = Ints('x y')
7674  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7675  >>> t(And(x == 0, y > x + 1))
7676  [[Not(y <= 1)]]
7677  >>> t(And(x == 0, y > x + 1)).as_expr()
7678  Not(y <= 1)
7679  """
7680  return AndThen(*ts, **ks)
7681 
7682 def OrElse(*ts, **ks):
7683  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7684 
7685  >>> x = Int('x')
7686  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7687  >>> # Tactic split-clause fails if there is no clause in the given goal.
7688  >>> t(x == 0)
7689  [[x == 0]]
7690  >>> t(Or(x == 0, x == 1))
7691  [[x == 0], [x == 1]]
7692  """
7693  if __debug__:
7694  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7695  ctx = ks.get('ctx', None)
7696  num = len(ts)
7697  r = ts[0]
7698  for i in range(num - 1):
7699  r = _or_else(r, ts[i+1], ctx)
7700  return r
7701 
7702 def ParOr(*ts, **ks):
7703  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7704 
7705  >>> x = Int('x')
7706  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7707  >>> t(x + 1 == 2)
7708  [[x == 1]]
7709  """
7710  if __debug__:
7711  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7712  ctx = _get_ctx(ks.get('ctx', None))
7713  ts = [ _to_tactic(t, ctx) for t in ts ]
7714  sz = len(ts)
7715  _args = (TacticObj * sz)()
7716  for i in range(sz):
7717  _args[i] = ts[i].tactic
7718  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7719 
7720 def ParThen(t1, t2, ctx=None):
7721  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7722 
7723  >>> x, y = Ints('x y')
7724  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7725  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7726  [[x == 1, y == 2], [x == 2, y == 3]]
7727  """
7728  t1 = _to_tactic(t1, ctx)
7729  t2 = _to_tactic(t2, ctx)
7730  if __debug__:
7731  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7732  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7733 
7734 def ParAndThen(t1, t2, ctx=None):
7735  """Alias for ParThen(t1, t2, ctx)."""
7736  return ParThen(t1, t2, ctx)
7737 
7738 def With(t, *args, **keys):
7739  """Return a tactic that applies tactic `t` using the given configuration options.
7740 
7741  >>> x, y = Ints('x y')
7742  >>> t = With(Tactic('simplify'), som=True)
7743  >>> t((x + 1)*(y + 2) == 0)
7744  [[2*x + y + x*y == -2]]
7745  """
7746  ctx = keys.pop('ctx', None)
7747  t = _to_tactic(t, ctx)
7748  p = args2params(args, keys, t.ctx)
7749  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7750 
7751 def WithParams(t, p):
7752  """Return a tactic that applies tactic `t` using the given configuration options.
7753 
7754  >>> x, y = Ints('x y')
7755  >>> p = ParamsRef()
7756  >>> p.set("som", True)
7757  >>> t = WithParams(Tactic('simplify'), p)
7758  >>> t((x + 1)*(y + 2) == 0)
7759  [[2*x + y + x*y == -2]]
7760  """
7761  t = _to_tactic(t, None)
7762  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7763 
7764 def Repeat(t, max=4294967295, ctx=None):
7765  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7766 
7767  >>> x, y = Ints('x y')
7768  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7769  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7770  >>> r = t(c)
7771  >>> for subgoal in r: print(subgoal)
7772  [x == 0, y == 0, x > y]
7773  [x == 0, y == 1, x > y]
7774  [x == 1, y == 0, x > y]
7775  [x == 1, y == 1, x > y]
7776  >>> t = Then(t, Tactic('propagate-values'))
7777  >>> t(c)
7778  [[x == 1, y == 0]]
7779  """
7780  t = _to_tactic(t, ctx)
7781  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7782 
7783 def TryFor(t, ms, ctx=None):
7784  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7785 
7786  If `t` does not terminate in `ms` milliseconds, then it fails.
7787  """
7788  t = _to_tactic(t, ctx)
7789  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7790 
7791 def tactics(ctx=None):
7792  """Return a list of all available tactics in Z3.
7793 
7794  >>> l = tactics()
7795  >>> l.count('simplify') == 1
7796  True
7797  """
7798  ctx = _get_ctx(ctx)
7799  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7800 
7801 def tactic_description(name, ctx=None):
7802  """Return a short description for the tactic named `name`.
7803 
7804  >>> d = tactic_description('simplify')
7805  """
7806  ctx = _get_ctx(ctx)
7807  return Z3_tactic_get_descr(ctx.ref(), name)
7808 
7810  """Display a (tabular) description of all available tactics in Z3."""
7811  if in_html_mode():
7812  even = True
7813  print('<table border="1" cellpadding="2" cellspacing="0">')
7814  for t in tactics():
7815  if even:
7816  print('<tr style="background-color:#CFCFCF">')
7817  even = False
7818  else:
7819  print('<tr>')
7820  even = True
7821  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7822  print('</table>')
7823  else:
7824  for t in tactics():
7825  print('%s : %s' % (t, tactic_description(t)))
7826 
7827 class Probe:
7828  """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."""
7829  def __init__(self, probe, ctx=None):
7830  self.ctx = _get_ctx(ctx)
7831  self.probe = None
7832  if isinstance(probe, ProbeObj):
7833  self.probe = probe
7834  elif isinstance(probe, float):
7835  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7836  elif _is_int(probe):
7837  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7838  elif isinstance(probe, bool):
7839  if probe:
7840  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7841  else:
7842  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7843  else:
7844  if __debug__:
7845  _z3_assert(isinstance(probe, str), "probe name expected")
7846  try:
7847  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7848  except Z3Exception:
7849  raise Z3Exception("unknown probe '%s'" % probe)
7850  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7851 
7852  def __deepcopy__(self, memo={}):
7853  return Probe(self.probe, self.ctx)
7854 
7855  def __del__(self):
7856  if self.probe is not None and self.ctx.ref() is not None:
7857  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7858 
7859  def __lt__(self, other):
7860  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7861 
7862  >>> p = Probe('size') < 10
7863  >>> x = Int('x')
7864  >>> g = Goal()
7865  >>> g.add(x > 0)
7866  >>> g.add(x < 10)
7867  >>> p(g)
7868  1.0
7869  """
7870  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7871 
7872  def __gt__(self, other):
7873  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7874 
7875  >>> p = Probe('size') > 10
7876  >>> x = Int('x')
7877  >>> g = Goal()
7878  >>> g.add(x > 0)
7879  >>> g.add(x < 10)
7880  >>> p(g)
7881  0.0
7882  """
7883  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7884 
7885  def __le__(self, other):
7886  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7887 
7888  >>> p = Probe('size') <= 2
7889  >>> x = Int('x')
7890  >>> g = Goal()
7891  >>> g.add(x > 0)
7892  >>> g.add(x < 10)
7893  >>> p(g)
7894  1.0
7895  """
7896  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7897 
7898  def __ge__(self, other):
7899  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7900 
7901  >>> p = Probe('size') >= 2
7902  >>> x = Int('x')
7903  >>> g = Goal()
7904  >>> g.add(x > 0)
7905  >>> g.add(x < 10)
7906  >>> p(g)
7907  1.0
7908  """
7909  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7910 
7911  def __eq__(self, other):
7912  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7913 
7914  >>> p = Probe('size') == 2
7915  >>> x = Int('x')
7916  >>> g = Goal()
7917  >>> g.add(x > 0)
7918  >>> g.add(x < 10)
7919  >>> p(g)
7920  1.0
7921  """
7922  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7923 
7924  def __ne__(self, other):
7925  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7926 
7927  >>> p = Probe('size') != 2
7928  >>> x = Int('x')
7929  >>> g = Goal()
7930  >>> g.add(x > 0)
7931  >>> g.add(x < 10)
7932  >>> p(g)
7933  0.0
7934  """
7935  p = self.__eq__(other)
7936  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
7937 
7938  def __call__(self, goal):
7939  """Evaluate the probe `self` in the given goal.
7940 
7941  >>> p = Probe('size')
7942  >>> x = Int('x')
7943  >>> g = Goal()
7944  >>> g.add(x > 0)
7945  >>> g.add(x < 10)
7946  >>> p(g)
7947  2.0
7948  >>> g.add(x < 20)
7949  >>> p(g)
7950  3.0
7951  >>> p = Probe('num-consts')
7952  >>> p(g)
7953  1.0
7954  >>> p = Probe('is-propositional')
7955  >>> p(g)
7956  0.0
7957  >>> p = Probe('is-qflia')
7958  >>> p(g)
7959  1.0
7960  """
7961  if __debug__:
7962  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
7963  goal = _to_goal(goal)
7964  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
7965 
7966 def is_probe(p):
7967  """Return `True` if `p` is a Z3 probe.
7968 
7969  >>> is_probe(Int('x'))
7970  False
7971  >>> is_probe(Probe('memory'))
7972  True
7973  """
7974  return isinstance(p, Probe)
7975 
7976 def _to_probe(p, ctx=None):
7977  if is_probe(p):
7978  return p
7979  else:
7980  return Probe(p, ctx)
7981 
7982 def probes(ctx=None):
7983  """Return a list of all available probes in Z3.
7984 
7985  >>> l = probes()
7986  >>> l.count('memory') == 1
7987  True
7988  """
7989  ctx = _get_ctx(ctx)
7990  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
7991 
7992 def probe_description(name, ctx=None):
7993  """Return a short description for the probe named `name`.
7994 
7995  >>> d = probe_description('memory')
7996  """
7997  ctx = _get_ctx(ctx)
7998  return Z3_probe_get_descr(ctx.ref(), name)
7999 
8001  """Display a (tabular) description of all available probes in Z3."""
8002  if in_html_mode():
8003  even = True
8004  print('<table border="1" cellpadding="2" cellspacing="0">')
8005  for p in probes():
8006  if even:
8007  print('<tr style="background-color:#CFCFCF">')
8008  even = False
8009  else:
8010  print('<tr>')
8011  even = True
8012  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
8013  print('</table>')
8014  else:
8015  for p in probes():
8016  print('%s : %s' % (p, probe_description(p)))
8017 
8018 def _probe_nary(f, args, ctx):
8019  if __debug__:
8020  _z3_assert(len(args) > 0, "At least one argument expected")
8021  num = len(args)
8022  r = _to_probe(args[0], ctx)
8023  for i in range(num - 1):
8024  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
8025  return r
8026 
8027 def _probe_and(args, ctx):
8028  return _probe_nary(Z3_probe_and, args, ctx)
8029 
8030 def _probe_or(args, ctx):
8031  return _probe_nary(Z3_probe_or, args, ctx)
8032 
8033 def FailIf(p, ctx=None):
8034  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8035 
8036  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
8037 
8038  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8039  >>> x, y = Ints('x y')
8040  >>> g = Goal()
8041  >>> g.add(x > 0)
8042  >>> g.add(y > 0)
8043  >>> t(g)
8044  [[x > 0, y > 0]]
8045  >>> g.add(x == y + 1)
8046  >>> t(g)
8047  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8048  """
8049  p = _to_probe(p, ctx)
8050  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8051 
8052 def When(p, t, ctx=None):
8053  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8054 
8055  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8056  >>> x, y = Ints('x y')
8057  >>> g = Goal()
8058  >>> g.add(x > 0)
8059  >>> g.add(y > 0)
8060  >>> t(g)
8061  [[x > 0, y > 0]]
8062  >>> g.add(x == y + 1)
8063  >>> t(g)
8064  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8065  """
8066  p = _to_probe(p, ctx)
8067  t = _to_tactic(t, ctx)
8068  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8069 
8070 def Cond(p, t1, t2, ctx=None):
8071  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8072 
8073  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8074  """
8075  p = _to_probe(p, ctx)
8076  t1 = _to_tactic(t1, ctx)
8077  t2 = _to_tactic(t2, ctx)
8078  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8079 
8080 
8085 
8086 def simplify(a, *arguments, **keywords):
8087  """Simplify the expression `a` using the given options.
8088 
8089  This function has many options. Use `help_simplify` to obtain the complete list.
8090 
8091  >>> x = Int('x')
8092  >>> y = Int('y')
8093  >>> simplify(x + 1 + y + x + 1)
8094  2 + 2*x + y
8095  >>> simplify((x + 1)*(y + 1), som=True)
8096  1 + x + y + x*y
8097  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8098  And(Not(x == y), Not(x == 1), Not(y == 1))
8099  >>> simplify(And(x == 0, y == 1), elim_and=True)
8100  Not(Or(Not(x == 0), Not(y == 1)))
8101  """
8102  if __debug__:
8103  _z3_assert(is_expr(a), "Z3 expression expected")
8104  if len(arguments) > 0 or len(keywords) > 0:
8105  p = args2params(arguments, keywords, a.ctx)
8106  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8107  else:
8108  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8109 
8111  """Return a string describing all options available for Z3 `simplify` procedure."""
8112  print(Z3_simplify_get_help(main_ctx().ref()))
8113 
8115  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8117 
8118 def substitute(t, *m):
8119  """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.
8120 
8121  >>> x = Int('x')
8122  >>> y = Int('y')
8123  >>> substitute(x + 1, (x, y + 1))
8124  y + 1 + 1
8125  >>> f = Function('f', IntSort(), IntSort())
8126  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8127  1 + 1
8128  """
8129  if isinstance(m, tuple):
8130  m1 = _get_args(m)
8131  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8132  m = m1
8133  if __debug__:
8134  _z3_assert(is_expr(t), "Z3 expression expected")
8135  _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.")
8136  num = len(m)
8137  _from = (Ast * num)()
8138  _to = (Ast * num)()
8139  for i in range(num):
8140  _from[i] = m[i][0].as_ast()
8141  _to[i] = m[i][1].as_ast()
8142  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8143 
8144 def substitute_vars(t, *m):
8145  """Substitute the free variables in t with the expression in m.
8146 
8147  >>> v0 = Var(0, IntSort())
8148  >>> v1 = Var(1, IntSort())
8149  >>> x = Int('x')
8150  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8151  >>> # replace v0 with x+1 and v1 with x
8152  >>> substitute_vars(f(v0, v1), x + 1, x)
8153  f(x + 1, x)
8154  """
8155  if __debug__:
8156  _z3_assert(is_expr(t), "Z3 expression expected")
8157  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8158  num = len(m)
8159  _to = (Ast * num)()
8160  for i in range(num):
8161  _to[i] = m[i].as_ast()
8162  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8163 
8164 def Sum(*args):
8165  """Create the sum of the Z3 expressions.
8166 
8167  >>> a, b, c = Ints('a b c')
8168  >>> Sum(a, b, c)
8169  a + b + c
8170  >>> Sum([a, b, c])
8171  a + b + c
8172  >>> A = IntVector('a', 5)
8173  >>> Sum(A)
8174  a__0 + a__1 + a__2 + a__3 + a__4
8175  """
8176  args = _get_args(args)
8177  if len(args) == 0:
8178  return 0
8179  ctx = _ctx_from_ast_arg_list(args)
8180  if ctx is None:
8181  return _reduce(lambda a, b: a + b, args, 0)
8182  args = _coerce_expr_list(args, ctx)
8183  if is_bv(args[0]):
8184  return _reduce(lambda a, b: a + b, args, 0)
8185  else:
8186  _args, sz = _to_ast_array(args)
8187  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8188 
8189 
8190 def Product(*args):
8191  """Create the product of the Z3 expressions.
8192 
8193  >>> a, b, c = Ints('a b c')
8194  >>> Product(a, b, c)
8195  a*b*c
8196  >>> Product([a, b, c])
8197  a*b*c
8198  >>> A = IntVector('a', 5)
8199  >>> Product(A)
8200  a__0*a__1*a__2*a__3*a__4
8201  """
8202  args = _get_args(args)
8203  if len(args) == 0:
8204  return 1
8205  ctx = _ctx_from_ast_arg_list(args)
8206  if ctx is None:
8207  return _reduce(lambda a, b: a * b, args, 1)
8208  args = _coerce_expr_list(args, ctx)
8209  if is_bv(args[0]):
8210  return _reduce(lambda a, b: a * b, args, 1)
8211  else:
8212  _args, sz = _to_ast_array(args)
8213  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8214 
8215 def AtMost(*args):
8216  """Create an at-most Pseudo-Boolean k constraint.
8217 
8218  >>> a, b, c = Bools('a b c')
8219  >>> f = AtMost(a, b, c, 2)
8220  """
8221  args = _get_args(args)
8222  if __debug__:
8223  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8224  ctx = _ctx_from_ast_arg_list(args)
8225  if __debug__:
8226  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8227  args1 = _coerce_expr_list(args[:-1], ctx)
8228  k = args[-1]
8229  _args, sz = _to_ast_array(args1)
8230  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8231 
8232 def AtLeast(*args):
8233  """Create an at-most Pseudo-Boolean k constraint.
8234 
8235  >>> a, b, c = Bools('a b c')
8236  >>> f = AtLeast(a, b, c, 2)
8237  """
8238  args = _get_args(args)
8239  if __debug__:
8240  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8241  ctx = _ctx_from_ast_arg_list(args)
8242  if __debug__:
8243  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8244  args1 = _coerce_expr_list(args[:-1], ctx)
8245  k = args[-1]
8246  _args, sz = _to_ast_array(args1)
8247  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8248 
8249 
8250 def _pb_args_coeffs(args, default_ctx = None):
8251  args = _get_args_ast_list(args)
8252  if len(args) == 0:
8253  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8254  args, coeffs = zip(*args)
8255  if __debug__:
8256  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8257  ctx = _ctx_from_ast_arg_list(args)
8258  if __debug__:
8259  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8260  args = _coerce_expr_list(args, ctx)
8261  _args, sz = _to_ast_array(args)
8262  _coeffs = (ctypes.c_int * len(coeffs))()
8263  for i in range(len(coeffs)):
8264  _z3_check_cint_overflow(coeffs[i], "coefficient")
8265  _coeffs[i] = coeffs[i]
8266  return ctx, sz, _args, _coeffs
8267 
8268 def PbLe(args, k):
8269  """Create a Pseudo-Boolean inequality k constraint.
8270 
8271  >>> a, b, c = Bools('a b c')
8272  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8273  """
8274  _z3_check_cint_overflow(k, "k")
8275  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8276  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8277 
8278 def PbGe(args, k):
8279  """Create a Pseudo-Boolean inequality k constraint.
8280 
8281  >>> a, b, c = Bools('a b c')
8282  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8283  """
8284  _z3_check_cint_overflow(k, "k")
8285  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8286  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8287 
8288 def PbEq(args, k, ctx = None):
8289  """Create a Pseudo-Boolean inequality k constraint.
8290 
8291  >>> a, b, c = Bools('a b c')
8292  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8293  """
8294  _z3_check_cint_overflow(k, "k")
8295  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8296  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8297 
8298 
8299 def solve(*args, **keywords):
8300  """Solve the constraints `*args`.
8301 
8302  This is a simple function for creating demonstrations. It creates a solver,
8303  configure it using the options in `keywords`, adds the constraints
8304  in `args`, and invokes check.
8305 
8306  >>> a = Int('a')
8307  >>> solve(a > 0, a < 2)
8308  [a = 1]
8309  """
8310  s = Solver()
8311  s.set(**keywords)
8312  s.add(*args)
8313  if keywords.get('show', False):
8314  print(s)
8315  r = s.check()
8316  if r == unsat:
8317  print("no solution")
8318  elif r == unknown:
8319  print("failed to solve")
8320  try:
8321  print(s.model())
8322  except Z3Exception:
8323  return
8324  else:
8325  print(s.model())
8326 
8327 def solve_using(s, *args, **keywords):
8328  """Solve the constraints `*args` using solver `s`.
8329 
8330  This is a simple function for creating demonstrations. It is similar to `solve`,
8331  but it uses the given solver `s`.
8332  It configures solver `s` using the options in `keywords`, adds the constraints
8333  in `args`, and invokes check.
8334  """
8335  if __debug__:
8336  _z3_assert(isinstance(s, Solver), "Solver object expected")
8337  s.set(**keywords)
8338  s.add(*args)
8339  if keywords.get('show', False):
8340  print("Problem:")
8341  print(s)
8342  r = s.check()
8343  if r == unsat:
8344  print("no solution")
8345  elif r == unknown:
8346  print("failed to solve")
8347  try:
8348  print(s.model())
8349  except Z3Exception:
8350  return
8351  else:
8352  if keywords.get('show', False):
8353  print("Solution:")
8354  print(s.model())
8355 
8356 def prove(claim, **keywords):
8357  """Try to prove the given claim.
8358 
8359  This is a simple function for creating demonstrations. It tries to prove
8360  `claim` by showing the negation is unsatisfiable.
8361 
8362  >>> p, q = Bools('p q')
8363  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8364  proved
8365  """
8366  if __debug__:
8367  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8368  s = Solver()
8369  s.set(**keywords)
8370  s.add(Not(claim))
8371  if keywords.get('show', False):
8372  print(s)
8373  r = s.check()
8374  if r == unsat:
8375  print("proved")
8376  elif r == unknown:
8377  print("failed to prove")
8378  print(s.model())
8379  else:
8380  print("counterexample")
8381  print(s.model())
8382 
8383 def _solve_html(*args, **keywords):
8384  """Version of function `solve` used in RiSE4Fun."""
8385  s = Solver()
8386  s.set(**keywords)
8387  s.add(*args)
8388  if keywords.get('show', False):
8389  print("<b>Problem:</b>")
8390  print(s)
8391  r = s.check()
8392  if r == unsat:
8393  print("<b>no solution</b>")
8394  elif r == unknown:
8395  print("<b>failed to solve</b>")
8396  try:
8397  print(s.model())
8398  except Z3Exception:
8399  return
8400  else:
8401  if keywords.get('show', False):
8402  print("<b>Solution:</b>")
8403  print(s.model())
8404 
8405 def _solve_using_html(s, *args, **keywords):
8406  """Version of function `solve_using` used in RiSE4Fun."""
8407  if __debug__:
8408  _z3_assert(isinstance(s, Solver), "Solver object expected")
8409  s.set(**keywords)
8410  s.add(*args)
8411  if keywords.get('show', False):
8412  print("<b>Problem:</b>")
8413  print(s)
8414  r = s.check()
8415  if r == unsat:
8416  print("<b>no solution</b>")
8417  elif r == unknown:
8418  print("<b>failed to solve</b>")
8419  try:
8420  print(s.model())
8421  except Z3Exception:
8422  return
8423  else:
8424  if keywords.get('show', False):
8425  print("<b>Solution:</b>")
8426  print(s.model())
8427 
8428 def _prove_html(claim, **keywords):
8429  """Version of function `prove` used in RiSE4Fun."""
8430  if __debug__:
8431  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8432  s = Solver()
8433  s.set(**keywords)
8434  s.add(Not(claim))
8435  if keywords.get('show', False):
8436  print(s)
8437  r = s.check()
8438  if r == unsat:
8439  print("<b>proved</b>")
8440  elif r == unknown:
8441  print("<b>failed to prove</b>")
8442  print(s.model())
8443  else:
8444  print("<b>counterexample</b>")
8445  print(s.model())
8446 
8447 def _dict2sarray(sorts, ctx):
8448  sz = len(sorts)
8449  _names = (Symbol * sz)()
8450  _sorts = (Sort * sz) ()
8451  i = 0
8452  for k in sorts:
8453  v = sorts[k]
8454  if __debug__:
8455  _z3_assert(isinstance(k, str), "String expected")
8456  _z3_assert(is_sort(v), "Z3 sort expected")
8457  _names[i] = to_symbol(k, ctx)
8458  _sorts[i] = v.ast
8459  i = i + 1
8460  return sz, _names, _sorts
8461 
8462 def _dict2darray(decls, ctx):
8463  sz = len(decls)
8464  _names = (Symbol * sz)()
8465  _decls = (FuncDecl * sz) ()
8466  i = 0
8467  for k in decls:
8468  v = decls[k]
8469  if __debug__:
8470  _z3_assert(isinstance(k, str), "String expected")
8471  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8472  _names[i] = to_symbol(k, ctx)
8473  if is_const(v):
8474  _decls[i] = v.decl().ast
8475  else:
8476  _decls[i] = v.ast
8477  i = i + 1
8478  return sz, _names, _decls
8479 
8480 
8481 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8482  """Parse a string in SMT 2.0 format using the given sorts and decls.
8483 
8484  The arguments sorts and decls are Python dictionaries used to initialize
8485  the symbol table used for the SMT 2.0 parser.
8486 
8487  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8488  [x > 0, x < 10]
8489  >>> x, y = Ints('x y')
8490  >>> f = Function('f', IntSort(), IntSort())
8491  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8492  [x + f(y) > 0]
8493  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8494  [a > 0]
8495  """
8496  ctx = _get_ctx(ctx)
8497  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8498  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8499  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8500 
8501 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8502  """Parse a file in SMT 2.0 format using the given sorts and decls.
8503 
8504  This function is similar to parse_smt2_string().
8505  """
8506  ctx = _get_ctx(ctx)
8507  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8508  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8509  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8510 
8511 
8512 #########################################
8513 #
8514 # Floating-Point Arithmetic
8515 #
8516 #########################################
8517 
8518 
8519 # Global default rounding mode
8520 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8521 _dflt_fpsort_ebits = 11
8522 _dflt_fpsort_sbits = 53
8523 
8524 def get_default_rounding_mode(ctx=None):
8525  """Retrieves the global default rounding mode."""
8526  global _dflt_rounding_mode
8527  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8528  return RTZ(ctx)
8529  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8530  return RTN(ctx)
8531  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8532  return RTP(ctx)
8533  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8534  return RNE(ctx)
8535  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8536  return RNA(ctx)
8537 
8538 def set_default_rounding_mode(rm, ctx=None):
8539  global _dflt_rounding_mode
8540  if is_fprm_value(rm):
8541  _dflt_rounding_mode = rm.decl().kind()
8542  else:
8543  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8544  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8545  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8546  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8547  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8548  "illegal rounding mode")
8549  _dflt_rounding_mode = rm
8550 
8551 def get_default_fp_sort(ctx=None):
8552  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8553 
8554 def set_default_fp_sort(ebits, sbits, ctx=None):
8555  global _dflt_fpsort_ebits
8556  global _dflt_fpsort_sbits
8557  _dflt_fpsort_ebits = ebits
8558  _dflt_fpsort_sbits = sbits
8559 
8560 def _dflt_rm(ctx=None):
8561  return get_default_rounding_mode(ctx)
8562 
8563 def _dflt_fps(ctx=None):
8564  return get_default_fp_sort(ctx)
8565 
8566 def _coerce_fp_expr_list(alist, ctx):
8567  first_fp_sort = None
8568  for a in alist:
8569  if is_fp(a):
8570  if first_fp_sort is None:
8571  first_fp_sort = a.sort()
8572  elif first_fp_sort == a.sort():
8573  pass # OK, same as before
8574  else:
8575  # we saw at least 2 different float sorts; something will
8576  # throw a sort mismatch later, for now assume None.
8577  first_fp_sort = None
8578  break
8579 
8580  r = []
8581  for i in range(len(alist)):
8582  a = alist[i]
8583  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8584  r.append(FPVal(a, None, first_fp_sort, ctx))
8585  else:
8586  r.append(a)
8587  return _coerce_expr_list(r, ctx)
8588 
8589 
8590 ### FP Sorts
8591 
8592 class FPSortRef(SortRef):
8593  """Floating-point sort."""
8594 
8595  def ebits(self):
8596  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8597  >>> b = FPSort(8, 24)
8598  >>> b.ebits()
8599  8
8600  """
8601  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8602 
8603  def sbits(self):
8604  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8605  >>> b = FPSort(8, 24)
8606  >>> b.sbits()
8607  24
8608  """
8609  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8610 
8611  def cast(self, val):
8612  """Try to cast `val` as a floating-point expression.
8613  >>> b = FPSort(8, 24)
8614  >>> b.cast(1.0)
8615  1
8616  >>> b.cast(1.0).sexpr()
8617  '(fp #b0 #x7f #b00000000000000000000000)'
8618  """
8619  if is_expr(val):
8620  if __debug__:
8621  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8622  return val
8623  else:
8624  return FPVal(val, None, self, self.ctx)
8625 
8626 
8627 def Float16(ctx=None):
8628  """Floating-point 16-bit (half) sort."""
8629  ctx = _get_ctx(ctx)
8630  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8631 
8632 def FloatHalf(ctx=None):
8633  """Floating-point 16-bit (half) sort."""
8634  ctx = _get_ctx(ctx)
8635  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8636 
8637 def Float32(ctx=None):
8638  """Floating-point 32-bit (single) sort."""
8639  ctx = _get_ctx(ctx)
8640  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8641 
8642 def FloatSingle(ctx=None):
8643  """Floating-point 32-bit (single) sort."""
8644  ctx = _get_ctx(ctx)
8645  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8646 
8647 def Float64(ctx=None):
8648  """Floating-point 64-bit (double) sort."""
8649  ctx = _get_ctx(ctx)
8650  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8651 
8652 def FloatDouble(ctx=None):
8653  """Floating-point 64-bit (double) sort."""
8654  ctx = _get_ctx(ctx)
8655  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8656 
8657 def Float128(ctx=None):
8658  """Floating-point 128-bit (quadruple) sort."""
8659  ctx = _get_ctx(ctx)
8660  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8661 
8662 def FloatQuadruple(ctx=None):
8663  """Floating-point 128-bit (quadruple) sort."""
8664  ctx = _get_ctx(ctx)
8665  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8666 
8667 class FPRMSortRef(SortRef):
8668  """"Floating-point rounding mode sort."""
8669 
8670 
8671 def is_fp_sort(s):
8672  """Return True if `s` is a Z3 floating-point sort.
8673 
8674  >>> is_fp_sort(FPSort(8, 24))
8675  True
8676  >>> is_fp_sort(IntSort())
8677  False
8678  """
8679  return isinstance(s, FPSortRef)
8680 
8681 def is_fprm_sort(s):
8682  """Return True if `s` is a Z3 floating-point rounding mode sort.
8683 
8684  >>> is_fprm_sort(FPSort(8, 24))
8685  False
8686  >>> is_fprm_sort(RNE().sort())
8687  True
8688  """
8689  return isinstance(s, FPRMSortRef)
8690 
8691 ### FP Expressions
8692 
8693 class FPRef(ExprRef):
8694  """Floating-point expressions."""
8695 
8696  def sort(self):
8697  """Return the sort of the floating-point expression `self`.
8698 
8699  >>> x = FP('1.0', FPSort(8, 24))
8700  >>> x.sort()
8701  FPSort(8, 24)
8702  >>> x.sort() == FPSort(8, 24)
8703  True
8704  """
8705  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8706 
8707  def ebits(self):
8708  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8709  >>> b = FPSort(8, 24)
8710  >>> b.ebits()
8711  8
8712  """
8713  return self.sort().ebits();
8714 
8715  def sbits(self):
8716  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8717  >>> b = FPSort(8, 24)
8718  >>> b.sbits()
8719  24
8720  """
8721  return self.sort().sbits();
8722 
8723  def as_string(self):
8724  """Return a Z3 floating point expression as a Python string."""
8725  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8726 
8727  def __le__(self, other):
8728  return fpLEQ(self, other, self.ctx)
8729 
8730  def __lt__(self, other):
8731  return fpLT(self, other, self.ctx)
8732 
8733  def __ge__(self, other):
8734  return fpGEQ(self, other, self.ctx)
8735 
8736  def __gt__(self, other):
8737  return fpGT(self, other, self.ctx)
8738 
8739  def __add__(self, other):
8740  """Create the Z3 expression `self + other`.
8741 
8742  >>> x = FP('x', FPSort(8, 24))
8743  >>> y = FP('y', FPSort(8, 24))
8744  >>> x + y
8745  x + y
8746  >>> (x + y).sort()
8747  FPSort(8, 24)
8748  """
8749  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8750  return fpAdd(_dflt_rm(), a, b, self.ctx)
8751 
8752  def __radd__(self, other):
8753  """Create the Z3 expression `other + self`.
8754 
8755  >>> x = FP('x', FPSort(8, 24))
8756  >>> 10 + x
8757  1.25*(2**3) + x
8758  """
8759  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8760  return fpAdd(_dflt_rm(), a, b, self.ctx)
8761 
8762  def __sub__(self, other):
8763  """Create the Z3 expression `self - other`.
8764 
8765  >>> x = FP('x', FPSort(8, 24))
8766  >>> y = FP('y', FPSort(8, 24))
8767  >>> x - y
8768  x - y
8769  >>> (x - y).sort()
8770  FPSort(8, 24)
8771  """
8772  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8773  return fpSub(_dflt_rm(), a, b, self.ctx)
8774 
8775  def __rsub__(self, other):
8776  """Create the Z3 expression `other - self`.
8777 
8778  >>> x = FP('x', FPSort(8, 24))
8779  >>> 10 - x
8780  1.25*(2**3) - x
8781  """
8782  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8783  return fpSub(_dflt_rm(), a, b, self.ctx)
8784 
8785  def __mul__(self, other):
8786  """Create the Z3 expression `self * other`.
8787 
8788  >>> x = FP('x', FPSort(8, 24))
8789  >>> y = FP('y', FPSort(8, 24))
8790  >>> x * y
8791  x * y
8792  >>> (x * y).sort()
8793  FPSort(8, 24)
8794  >>> 10 * y
8795  1.25*(2**3) * y
8796  """
8797  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8798  return fpMul(_dflt_rm(), a, b, self.ctx)
8799 
8800  def __rmul__(self, other):
8801  """Create the Z3 expression `other * self`.
8802 
8803  >>> x = FP('x', FPSort(8, 24))
8804  >>> y = FP('y', FPSort(8, 24))
8805  >>> x * y
8806  x * y
8807  >>> x * 10
8808  x * 1.25*(2**3)
8809  """
8810  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8811  return fpMul(_dflt_rm(), a, b, self.ctx)
8812 
8813  def __pos__(self):
8814  """Create the Z3 expression `+self`."""
8815  return self
8816 
8817  def __neg__(self):
8818  """Create the Z3 expression `-self`.
8819 
8820  >>> x = FP('x', Float32())
8821  >>> -x
8822  -x
8823  """
8824  return fpNeg(self)
8825 
8826  def __div__(self, other):
8827  """Create the Z3 expression `self / other`.
8828 
8829  >>> x = FP('x', FPSort(8, 24))
8830  >>> y = FP('y', FPSort(8, 24))
8831  >>> x / y
8832  x / y
8833  >>> (x / y).sort()
8834  FPSort(8, 24)
8835  >>> 10 / y
8836  1.25*(2**3) / y
8837  """
8838  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8839  return fpDiv(_dflt_rm(), a, b, self.ctx)
8840 
8841  def __rdiv__(self, other):
8842  """Create the Z3 expression `other / self`.
8843 
8844  >>> x = FP('x', FPSort(8, 24))
8845  >>> y = FP('y', FPSort(8, 24))
8846  >>> x / y
8847  x / y
8848  >>> x / 10
8849  x / 1.25*(2**3)
8850  """
8851  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8852  return fpDiv(_dflt_rm(), a, b, self.ctx)
8853 
8854  if not sys.version < '3':
8855  def __truediv__(self, other):
8856  """Create the Z3 expression division `self / other`."""
8857  return self.__div__(other)
8858 
8859  def __rtruediv__(self, other):
8860  """Create the Z3 expression division `other / self`."""
8861  return self.__rdiv__(other)
8862 
8863  def __mod__(self, other):
8864  """Create the Z3 expression mod `self % other`."""
8865  return fpRem(self, other)
8866 
8867  def __rmod__(self, other):
8868  """Create the Z3 expression mod `other % self`."""
8869  return fpRem(other, self)
8870 
8871 class FPRMRef(ExprRef):
8872  """Floating-point rounding mode expressions"""
8873 
8874  def as_string(self):
8875  """Return a Z3 floating point expression as a Python string."""
8876  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8877 
8878 
8879 def RoundNearestTiesToEven(ctx=None):
8880  ctx = _get_ctx(ctx)
8881  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8882 
8883 def RNE (ctx=None):
8884  ctx = _get_ctx(ctx)
8885  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8886 
8887 def RoundNearestTiesToAway(ctx=None):
8888  ctx = _get_ctx(ctx)
8889  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8890 
8891 def RNA (ctx=None):
8892  ctx = _get_ctx(ctx)
8893  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8894 
8895 def RoundTowardPositive(ctx=None):
8896  ctx = _get_ctx(ctx)
8897  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8898 
8899 def RTP(ctx=None):
8900  ctx = _get_ctx(ctx)
8901  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8902 
8903 def RoundTowardNegative(ctx=None):
8904  ctx = _get_ctx(ctx)
8905  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8906 
8907 def RTN(ctx=None):
8908  ctx = _get_ctx(ctx)
8909  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8910 
8911 def RoundTowardZero(ctx=None):
8912  ctx = _get_ctx(ctx)
8913  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8914 
8915 def RTZ(ctx=None):
8916  ctx = _get_ctx(ctx)
8917  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8918 
8919 def is_fprm(a):
8920  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8921 
8922  >>> rm = RNE()
8923  >>> is_fprm(rm)
8924  True
8925  >>> rm = 1.0
8926  >>> is_fprm(rm)
8927  False
8928  """
8929  return isinstance(a, FPRMRef)
8930 
8931 def is_fprm_value(a):
8932  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8933  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8934 
8935 ### FP Numerals
8936 
8937 class FPNumRef(FPRef):
8938  """The sign of the numeral.
8939 
8940  >>> x = FPVal(+1.0, FPSort(8, 24))
8941  >>> x.sign()
8942  False
8943  >>> x = FPVal(-1.0, FPSort(8, 24))
8944  >>> x.sign()
8945  True
8946  """
8947  def sign(self):
8948  l = (ctypes.c_int)()
8949  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
8950  raise Z3Exception("error retrieving the sign of a numeral.")
8951  return l.value != 0
8952 
8953  """The sign of a floating-point numeral as a bit-vector expression.
8954 
8955  Remark: NaN's are invalid arguments.
8956  """
8957  def sign_as_bv(self):
8958  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8959 
8960  """The significand of the numeral.
8961 
8962  >>> x = FPVal(2.5, FPSort(8, 24))
8963  >>> x.significand()
8964  1.25
8965  """
8966  def significand(self):
8967  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
8968 
8969  """The significand of the numeral as a long.
8970 
8971  >>> x = FPVal(2.5, FPSort(8, 24))
8972  >>> x.significand_as_long()
8973  1.25
8974  """
8975  def significand_as_long(self):
8976  ptr = (ctypes.c_ulonglong * 1)()
8977  if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
8978  raise Z3Exception("error retrieving the significand of a numeral.")
8979  return ptr[0]
8980 
8981  """The significand of the numeral as a bit-vector expression.
8982 
8983  Remark: NaN are invalid arguments.
8984  """
8985  def significand_as_bv(self):
8986  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8987 
8988  """The exponent of the numeral.
8989 
8990  >>> x = FPVal(2.5, FPSort(8, 24))
8991  >>> x.exponent()
8992  1
8993  """
8994  def exponent(self, biased=True):
8995  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
8996 
8997  """The exponent of the numeral as a long.
8998 
8999  >>> x = FPVal(2.5, FPSort(8, 24))
9000  >>> x.exponent_as_long()
9001  1
9002  """
9003  def exponent_as_long(self, biased=True):
9004  ptr = (ctypes.c_longlong * 1)()
9005  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
9006  raise Z3Exception("error retrieving the exponent of a numeral.")
9007  return ptr[0]
9008 
9009  """The exponent of the numeral as a bit-vector expression.
9010 
9011  Remark: NaNs are invalid arguments.
9012  """
9013  def exponent_as_bv(self, biased=True):
9014  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
9015 
9016  """Indicates whether the numeral is a NaN."""
9017  def isNaN(self):
9018  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
9019 
9020  """Indicates whether the numeral is +oo or -oo."""
9021  def isInf(self):
9022  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
9023 
9024  """Indicates whether the numeral is +zero or -zero."""
9025  def isZero(self):
9026  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
9027 
9028  """Indicates whether the numeral is normal."""
9029  def isNormal(self):
9030  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
9031 
9032  """Indicates whether the numeral is subnormal."""
9033  def isSubnormal(self):
9034  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
9035 
9036  """Indicates whether the numeral is positive."""
9037  def isPositive(self):
9038  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
9039 
9040  """Indicates whether the numeral is negative."""
9041  def isNegative(self):
9042  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
9043 
9044  """
9045  The string representation of the numeral.
9046 
9047  >>> x = FPVal(20, FPSort(8, 24))
9048  >>> x.as_string()
9049  1.25*(2**4)
9050  """
9051  def as_string(self):
9052  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
9053  return ("FPVal(%s, %s)" % (s, self.sort()))
9054 
9055 def is_fp(a):
9056  """Return `True` if `a` is a Z3 floating-point expression.
9057 
9058  >>> b = FP('b', FPSort(8, 24))
9059  >>> is_fp(b)
9060  True
9061  >>> is_fp(b + 1.0)
9062  True
9063  >>> is_fp(Int('x'))
9064  False
9065  """
9066  return isinstance(a, FPRef)
9067 
9068 def is_fp_value(a):
9069  """Return `True` if `a` is a Z3 floating-point numeral value.
9070 
9071  >>> b = FP('b', FPSort(8, 24))
9072  >>> is_fp_value(b)
9073  False
9074  >>> b = FPVal(1.0, FPSort(8, 24))
9075  >>> b
9076  1
9077  >>> is_fp_value(b)
9078  True
9079  """
9080  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9081 
9082 def FPSort(ebits, sbits, ctx=None):
9083  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9084 
9085  >>> Single = FPSort(8, 24)
9086  >>> Double = FPSort(11, 53)
9087  >>> Single
9088  FPSort(8, 24)
9089  >>> x = Const('x', Single)
9090  >>> eq(x, FP('x', FPSort(8, 24)))
9091  True
9092  """
9093  ctx = _get_ctx(ctx)
9094  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9095 
9096 def _to_float_str(val, exp=0):
9097  if isinstance(val, float):
9098  if math.isnan(val):
9099  res = "NaN"
9100  elif val == 0.0:
9101  sone = math.copysign(1.0, val)
9102  if sone < 0.0:
9103  return "-0.0"
9104  else:
9105  return "+0.0"
9106  elif val == float("+inf"):
9107  res = "+oo"
9108  elif val == float("-inf"):
9109  res = "-oo"
9110  else:
9111  v = val.as_integer_ratio()
9112  num = v[0]
9113  den = v[1]
9114  rvs = str(num) + '/' + str(den)
9115  res = rvs + 'p' + _to_int_str(exp)
9116  elif isinstance(val, bool):
9117  if val:
9118  res = "1.0"
9119  else:
9120  res = "0.0"
9121  elif _is_int(val):
9122  res = str(val)
9123  elif isinstance(val, str):
9124  inx = val.find('*(2**')
9125  if inx == -1:
9126  res = val
9127  elif val[-1] == ')':
9128  res = val[0:inx]
9129  exp = str(int(val[inx+5:-1]) + int(exp))
9130  else:
9131  _z3_assert(False, "String does not have floating-point numeral form.")
9132  elif __debug__:
9133  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9134  if exp == 0:
9135  return res
9136  else:
9137  return res + 'p' + exp
9138 
9139 
9140 def fpNaN(s):
9141  """Create a Z3 floating-point NaN term.
9142 
9143  >>> s = FPSort(8, 24)
9144  >>> set_fpa_pretty(True)
9145  >>> fpNaN(s)
9146  NaN
9147  >>> pb = get_fpa_pretty()
9148  >>> set_fpa_pretty(False)
9149  >>> fpNaN(s)
9150  fpNaN(FPSort(8, 24))
9151  >>> set_fpa_pretty(pb)
9152  """
9153  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9154  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9155 
9156 def fpPlusInfinity(s):
9157  """Create a Z3 floating-point +oo term.
9158 
9159  >>> s = FPSort(8, 24)
9160  >>> pb = get_fpa_pretty()
9161  >>> set_fpa_pretty(True)
9162  >>> fpPlusInfinity(s)
9163  +oo
9164  >>> set_fpa_pretty(False)
9165  >>> fpPlusInfinity(s)
9166  fpPlusInfinity(FPSort(8, 24))
9167  >>> set_fpa_pretty(pb)
9168  """
9169  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9170  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9171 
9172 def fpMinusInfinity(s):
9173  """Create a Z3 floating-point -oo term."""
9174  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9175  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9176 
9177 def fpInfinity(s, negative):
9178  """Create a Z3 floating-point +oo or -oo term."""
9179  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9180  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9181  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9182 
9183 def fpPlusZero(s):
9184  """Create a Z3 floating-point +0.0 term."""
9185  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9186  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9187 
9188 def fpMinusZero(s):
9189  """Create a Z3 floating-point -0.0 term."""
9190  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9191  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9192 
9193 def fpZero(s, negative):
9194  """Create a Z3 floating-point +0.0 or -0.0 term."""
9195  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9196  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9197  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9198 
9199 def FPVal(sig, exp=None, fps=None, ctx=None):
9200  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9201 
9202  >>> v = FPVal(20.0, FPSort(8, 24))
9203  >>> v
9204  1.25*(2**4)
9205  >>> print("0x%.8x" % v.exponent_as_long(False))
9206  0x00000004
9207  >>> v = FPVal(2.25, FPSort(8, 24))
9208  >>> v
9209  1.125*(2**1)
9210  >>> v = FPVal(-2.25, FPSort(8, 24))
9211  >>> v
9212  -1.125*(2**1)
9213  >>> FPVal(-0.0, FPSort(8, 24))
9214  -0.0
9215  >>> FPVal(0.0, FPSort(8, 24))
9216  +0.0
9217  >>> FPVal(+0.0, FPSort(8, 24))
9218  +0.0
9219  """
9220  ctx = _get_ctx(ctx)
9221  if is_fp_sort(exp):
9222  fps = exp
9223  exp = None
9224  elif fps is None:
9225  fps = _dflt_fps(ctx)
9226  _z3_assert(is_fp_sort(fps), "sort mismatch")
9227  if exp is None:
9228  exp = 0
9229  val = _to_float_str(sig)
9230  if val == "NaN" or val == "nan":
9231  return fpNaN(fps)
9232  elif val == "-0.0":
9233  return fpMinusZero(fps)
9234  elif val == "0.0" or val == "+0.0":
9235  return fpPlusZero(fps)
9236  elif val == "+oo" or val == "+inf" or val == "+Inf":
9237  return fpPlusInfinity(fps)
9238  elif val == "-oo" or val == "-inf" or val == "-Inf":
9239  return fpMinusInfinity(fps)
9240  else:
9241  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9242 
9243 def FP(name, fpsort, ctx=None):
9244  """Return a floating-point constant named `name`.
9245  `fpsort` is the floating-point sort.
9246  If `ctx=None`, then the global context is used.
9247 
9248  >>> x = FP('x', FPSort(8, 24))
9249  >>> is_fp(x)
9250  True
9251  >>> x.ebits()
9252  8
9253  >>> x.sort()
9254  FPSort(8, 24)
9255  >>> word = FPSort(8, 24)
9256  >>> x2 = FP('x', word)
9257  >>> eq(x, x2)
9258  True
9259  """
9260  if isinstance(fpsort, FPSortRef) and ctx is None:
9261  ctx = fpsort.ctx
9262  else:
9263  ctx = _get_ctx(ctx)
9264  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9265 
9266 def FPs(names, fpsort, ctx=None):
9267  """Return an array of floating-point constants.
9268 
9269  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9270  >>> x.sort()
9271  FPSort(8, 24)
9272  >>> x.sbits()
9273  24
9274  >>> x.ebits()
9275  8
9276  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9277  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9278  """
9279  ctx = _get_ctx(ctx)
9280  if isinstance(names, str):
9281  names = names.split(" ")
9282  return [FP(name, fpsort, ctx) for name in names]
9283 
9284 def fpAbs(a, ctx=None):
9285  """Create a Z3 floating-point absolute value expression.
9286 
9287  >>> s = FPSort(8, 24)
9288  >>> rm = RNE()
9289  >>> x = FPVal(1.0, s)
9290  >>> fpAbs(x)
9291  fpAbs(1)
9292  >>> y = FPVal(-20.0, s)
9293  >>> y
9294  -1.25*(2**4)
9295  >>> fpAbs(y)
9296  fpAbs(-1.25*(2**4))
9297  >>> fpAbs(-1.25*(2**4))
9298  fpAbs(-1.25*(2**4))
9299  >>> fpAbs(x).sort()
9300  FPSort(8, 24)
9301  """
9302  ctx = _get_ctx(ctx)
9303  [a] = _coerce_fp_expr_list([a], ctx)
9304  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9305 
9306 def fpNeg(a, ctx=None):
9307  """Create a Z3 floating-point addition expression.
9308 
9309  >>> s = FPSort(8, 24)
9310  >>> rm = RNE()
9311  >>> x = FP('x', s)
9312  >>> fpNeg(x)
9313  -x
9314  >>> fpNeg(x).sort()
9315  FPSort(8, 24)
9316  """
9317  ctx = _get_ctx(ctx)
9318  [a] = _coerce_fp_expr_list([a], ctx)
9319  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9320 
9321 def _mk_fp_unary(f, rm, a, ctx):
9322  ctx = _get_ctx(ctx)
9323  [a] = _coerce_fp_expr_list([a], ctx)
9324  if __debug__:
9325  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9326  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9327  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9328 
9329 def _mk_fp_unary_norm(f, a, ctx):
9330  ctx = _get_ctx(ctx)
9331  [a] = _coerce_fp_expr_list([a], ctx)
9332  if __debug__:
9333  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9334  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
9335 
9336 def _mk_fp_unary_pred(f, a, ctx):
9337  ctx = _get_ctx(ctx)
9338  [a] = _coerce_fp_expr_list([a], ctx)
9339  if __debug__:
9340  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9341  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9342 
9343 def _mk_fp_bin(f, rm, a, b, ctx):
9344  ctx = _get_ctx(ctx)
9345  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9346  if __debug__:
9347  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9348  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9349  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9350 
9351 def _mk_fp_bin_norm(f, a, b, ctx):
9352  ctx = _get_ctx(ctx)
9353  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9354  if __debug__:
9355  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9356  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9357 
9358 def _mk_fp_bin_pred(f, a, b, ctx):
9359  ctx = _get_ctx(ctx)
9360  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9361  if __debug__:
9362  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9363  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9364 
9365 def _mk_fp_tern(f, rm, a, b, c, ctx):
9366  ctx = _get_ctx(ctx)
9367  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9368  if __debug__:
9369  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9370  _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")
9371  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9372 
9373 def fpAdd(rm, a, b, ctx=None):
9374  """Create a Z3 floating-point addition expression.
9375 
9376  >>> s = FPSort(8, 24)
9377  >>> rm = RNE()
9378  >>> x = FP('x', s)
9379  >>> y = FP('y', s)
9380  >>> fpAdd(rm, x, y)
9381  fpAdd(RNE(), x, y)
9382  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9383  x + y
9384  >>> fpAdd(rm, x, y).sort()
9385  FPSort(8, 24)
9386  """
9387  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9388 
9389 def fpSub(rm, a, b, ctx=None):
9390  """Create a Z3 floating-point subtraction expression.
9391 
9392  >>> s = FPSort(8, 24)
9393  >>> rm = RNE()
9394  >>> x = FP('x', s)
9395  >>> y = FP('y', s)
9396  >>> fpSub(rm, x, y)
9397  fpSub(RNE(), x, y)
9398  >>> fpSub(rm, x, y).sort()
9399  FPSort(8, 24)
9400  """
9401  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9402 
9403 def fpMul(rm, a, b, ctx=None):
9404  """Create a Z3 floating-point multiplication expression.
9405 
9406  >>> s = FPSort(8, 24)
9407  >>> rm = RNE()
9408  >>> x = FP('x', s)
9409  >>> y = FP('y', s)
9410  >>> fpMul(rm, x, y)
9411  fpMul(RNE(), x, y)
9412  >>> fpMul(rm, x, y).sort()
9413  FPSort(8, 24)
9414  """
9415  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9416 
9417 def fpDiv(rm, a, b, ctx=None):
9418  """Create a Z3 floating-point division expression.
9419 
9420  >>> s = FPSort(8, 24)
9421  >>> rm = RNE()
9422  >>> x = FP('x', s)
9423  >>> y = FP('y', s)
9424  >>> fpDiv(rm, x, y)
9425  fpDiv(RNE(), x, y)
9426  >>> fpDiv(rm, x, y).sort()
9427  FPSort(8, 24)
9428  """
9429  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9430 
9431 def fpRem(a, b, ctx=None):
9432  """Create a Z3 floating-point remainder expression.
9433 
9434  >>> s = FPSort(8, 24)
9435  >>> x = FP('x', s)
9436  >>> y = FP('y', s)
9437  >>> fpRem(x, y)
9438  fpRem(x, y)
9439  >>> fpRem(x, y).sort()
9440  FPSort(8, 24)
9441  """
9442  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9443 
9444 def fpMin(a, b, ctx=None):
9445  """Create a Z3 floating-point minimum expression.
9446 
9447  >>> s = FPSort(8, 24)
9448  >>> rm = RNE()
9449  >>> x = FP('x', s)
9450  >>> y = FP('y', s)
9451  >>> fpMin(x, y)
9452  fpMin(x, y)
9453  >>> fpMin(x, y).sort()
9454  FPSort(8, 24)
9455  """
9456  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9457 
9458 def fpMax(a, b, ctx=None):
9459  """Create a Z3 floating-point maximum expression.
9460 
9461  >>> s = FPSort(8, 24)
9462  >>> rm = RNE()
9463  >>> x = FP('x', s)
9464  >>> y = FP('y', s)
9465  >>> fpMax(x, y)
9466  fpMax(x, y)
9467  >>> fpMax(x, y).sort()
9468  FPSort(8, 24)
9469  """
9470  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9471 
9472 def fpFMA(rm, a, b, c, ctx=None):
9473  """Create a Z3 floating-point fused multiply-add expression.
9474  """
9475  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9476 
9477 def fpSqrt(rm, a, ctx=None):
9478  """Create a Z3 floating-point square root expression.
9479  """
9480  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9481 
9482 def fpRoundToIntegral(rm, a, ctx=None):
9483  """Create a Z3 floating-point roundToIntegral expression.
9484  """
9485  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9486 
9487 def fpIsNaN(a, ctx=None):
9488  """Create a Z3 floating-point isNaN expression.
9489 
9490  >>> s = FPSort(8, 24)
9491  >>> x = FP('x', s)
9492  >>> y = FP('y', s)
9493  >>> fpIsNaN(x)
9494  fpIsNaN(x)
9495  """
9496  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
9497 
9498 def fpIsInf(a, ctx=None):
9499  """Create a Z3 floating-point isInfinite expression.
9500 
9501  >>> s = FPSort(8, 24)
9502  >>> x = FP('x', s)
9503  >>> fpIsInf(x)
9504  fpIsInf(x)
9505  """
9506  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
9507 
9508 def fpIsZero(a, ctx=None):
9509  """Create a Z3 floating-point isZero expression.
9510  """
9511  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
9512 
9513 def fpIsNormal(a, ctx=None):
9514  """Create a Z3 floating-point isNormal expression.
9515  """
9516  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
9517 
9518 def fpIsSubnormal(a, ctx=None):
9519  """Create a Z3 floating-point isSubnormal expression.
9520  """
9521  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
9522 
9523 def fpIsNegative(a, ctx=None):
9524  """Create a Z3 floating-point isNegative expression.
9525  """
9526  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9527 
9528 def fpIsPositive(a, ctx=None):
9529  """Create a Z3 floating-point isPositive expression.
9530  """
9531  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9532  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9533 
9534 def _check_fp_args(a, b):
9535  if __debug__:
9536  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9537 
9538 def fpLT(a, b, ctx=None):
9539  """Create the Z3 floating-point expression `other < self`.
9540 
9541  >>> x, y = FPs('x y', FPSort(8, 24))
9542  >>> fpLT(x, y)
9543  x < y
9544  >>> (x < y).sexpr()
9545  '(fp.lt x y)'
9546  """
9547  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9548 
9549 def fpLEQ(a, b, ctx=None):
9550  """Create the Z3 floating-point expression `other <= self`.
9551 
9552  >>> x, y = FPs('x y', FPSort(8, 24))
9553  >>> fpLEQ(x, y)
9554  x <= y
9555  >>> (x <= y).sexpr()
9556  '(fp.leq x y)'
9557  """
9558  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9559 
9560 def fpGT(a, b, ctx=None):
9561  """Create the Z3 floating-point expression `other > self`.
9562 
9563  >>> x, y = FPs('x y', FPSort(8, 24))
9564  >>> fpGT(x, y)
9565  x > y
9566  >>> (x > y).sexpr()
9567  '(fp.gt x y)'
9568  """
9569  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9570 
9571 def fpGEQ(a, b, ctx=None):
9572  """Create the Z3 floating-point expression `other >= self`.
9573 
9574  >>> x, y = FPs('x y', FPSort(8, 24))
9575  >>> fpGEQ(x, y)
9576  x >= y
9577  >>> (x >= y).sexpr()
9578  '(fp.geq x y)'
9579  """
9580  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9581 
9582 def fpEQ(a, b, ctx=None):
9583  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9584 
9585  >>> x, y = FPs('x y', FPSort(8, 24))
9586  >>> fpEQ(x, y)
9587  fpEQ(x, y)
9588  >>> fpEQ(x, y).sexpr()
9589  '(fp.eq x y)'
9590  """
9591  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9592 
9593 def fpNEQ(a, b, ctx=None):
9594  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9595 
9596  >>> x, y = FPs('x y', FPSort(8, 24))
9597  >>> fpNEQ(x, y)
9598  Not(fpEQ(x, y))
9599  >>> (x != y).sexpr()
9600  '(distinct x y)'
9601  """
9602  return Not(fpEQ(a, b, ctx))
9603 
9604 def fpFP(sgn, exp, sig, ctx=None):
9605  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9606 
9607  >>> s = FPSort(8, 24)
9608  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9609  >>> print(x)
9610  fpFP(1, 127, 4194304)
9611  >>> xv = FPVal(-1.5, s)
9612  >>> print(xv)
9613  -1.5
9614  >>> slvr = Solver()
9615  >>> slvr.add(fpEQ(x, xv))
9616  >>> slvr.check()
9617  sat
9618  >>> xv = FPVal(+1.5, s)
9619  >>> print(xv)
9620  1.5
9621  >>> slvr = Solver()
9622  >>> slvr.add(fpEQ(x, xv))
9623  >>> slvr.check()
9624  unsat
9625  """
9626  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9627  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9628  ctx = _get_ctx(ctx)
9629  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9630  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9631 
9632 def fpToFP(a1, a2=None, a3=None, ctx=None):
9633  """Create a Z3 floating-point conversion expression from other term sorts
9634  to floating-point.
9635 
9636  From a bit-vector term in IEEE 754-2008 format:
9637  >>> x = FPVal(1.0, Float32())
9638  >>> x_bv = fpToIEEEBV(x)
9639  >>> simplify(fpToFP(x_bv, Float32()))
9640  1
9641 
9642  From a floating-point term with different precision:
9643  >>> x = FPVal(1.0, Float32())
9644  >>> x_db = fpToFP(RNE(), x, Float64())
9645  >>> x_db.sort()
9646  FPSort(11, 53)
9647 
9648  From a real term:
9649  >>> x_r = RealVal(1.5)
9650  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9651  1.5
9652 
9653  From a signed bit-vector term:
9654  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9655  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9656  -1.25*(2**2)
9657  """
9658  ctx = _get_ctx(ctx)
9659  if is_bv(a1) and is_fp_sort(a2):
9660  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9661  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9662  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9663  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9664  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9665  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9666  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9667  else:
9668  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9669 
9670 def fpBVToFP(v, sort, ctx=None):
9671  """Create a Z3 floating-point conversion expression that represents the
9672  conversion from a bit-vector term to a floating-point term.
9673 
9674  >>> x_bv = BitVecVal(0x3F800000, 32)
9675  >>> x_fp = fpBVToFP(x_bv, Float32())
9676  >>> x_fp
9677  fpToFP(1065353216)
9678  >>> simplify(x_fp)
9679  1
9680  """
9681  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9682  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9683  ctx = _get_ctx(ctx)
9684  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9685 
9686 def fpFPToFP(rm, v, sort, ctx=None):
9687  """Create a Z3 floating-point conversion expression that represents the
9688  conversion from a floating-point term to a floating-point term of different precision.
9689 
9690  >>> x_sgl = FPVal(1.0, Float32())
9691  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9692  >>> x_dbl
9693  fpToFP(RNE(), 1)
9694  >>> simplify(x_dbl)
9695  1
9696  >>> x_dbl.sort()
9697  FPSort(11, 53)
9698  """
9699  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9700  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9701  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9702  ctx = _get_ctx(ctx)
9703  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9704 
9705 def fpRealToFP(rm, v, sort, ctx=None):
9706  """Create a Z3 floating-point conversion expression that represents the
9707  conversion from a real term to a floating-point term.
9708 
9709  >>> x_r = RealVal(1.5)
9710  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9711  >>> x_fp
9712  fpToFP(RNE(), 3/2)
9713  >>> simplify(x_fp)
9714  1.5
9715  """
9716  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9717  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9718  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9719  ctx = _get_ctx(ctx)
9720  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9721 
9722 def fpSignedToFP(rm, v, sort, ctx=None):
9723  """Create a Z3 floating-point conversion expression that represents the
9724  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9725 
9726  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9727  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9728  >>> x_fp
9729  fpToFP(RNE(), 4294967291)
9730  >>> simplify(x_fp)
9731  -1.25*(2**2)
9732  """
9733  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9734  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9735  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9736  ctx = _get_ctx(ctx)
9737  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9738 
9739 def fpUnsignedToFP(rm, v, sort, ctx=None):
9740  """Create a Z3 floating-point conversion expression that represents the
9741  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9742 
9743  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9744  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9745  >>> x_fp
9746  fpToFPUnsigned(RNE(), 4294967291)
9747  >>> simplify(x_fp)
9748  1*(2**32)
9749  """
9750  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9751  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9752  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9753  ctx = _get_ctx(ctx)
9754  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9755 
9756 def fpToFPUnsigned(rm, x, s, ctx=None):
9757  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9758  if __debug__:
9759  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9760  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9761  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9762  ctx = _get_ctx(ctx)
9763  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9764 
9765 def fpToSBV(rm, x, s, ctx=None):
9766  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9767 
9768  >>> x = FP('x', FPSort(8, 24))
9769  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9770  >>> print(is_fp(x))
9771  True
9772  >>> print(is_bv(y))
9773  True
9774  >>> print(is_fp(y))
9775  False
9776  >>> print(is_bv(x))
9777  False
9778  """
9779  if __debug__:
9780  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9781  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9782  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9783  ctx = _get_ctx(ctx)
9784  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9785 
9786 def fpToUBV(rm, x, s, ctx=None):
9787  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9788 
9789  >>> x = FP('x', FPSort(8, 24))
9790  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9791  >>> print(is_fp(x))
9792  True
9793  >>> print(is_bv(y))
9794  True
9795  >>> print(is_fp(y))
9796  False
9797  >>> print(is_bv(x))
9798  False
9799  """
9800  if __debug__:
9801  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9802  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9803  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9804  ctx = _get_ctx(ctx)
9805  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9806 
9807 def fpToReal(x, ctx=None):
9808  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9809 
9810  >>> x = FP('x', FPSort(8, 24))
9811  >>> y = fpToReal(x)
9812  >>> print(is_fp(x))
9813  True
9814  >>> print(is_real(y))
9815  True
9816  >>> print(is_fp(y))
9817  False
9818  >>> print(is_real(x))
9819  False
9820  """
9821  if __debug__:
9822  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9823  ctx = _get_ctx(ctx)
9824  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9825 
9826 def fpToIEEEBV(x, ctx=None):
9827  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9828 
9829  The size of the resulting bit-vector is automatically determined.
9830 
9831  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9832  knows only one NaN and it will always produce the same bit-vector representation of
9833  that NaN.
9834 
9835  >>> x = FP('x', FPSort(8, 24))
9836  >>> y = fpToIEEEBV(x)
9837  >>> print(is_fp(x))
9838  True
9839  >>> print(is_bv(y))
9840  True
9841  >>> print(is_fp(y))
9842  False
9843  >>> print(is_bv(x))
9844  False
9845  """
9846  if __debug__:
9847  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9848  ctx = _get_ctx(ctx)
9849  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9850 
9851 
9852 
9853 #########################################
9854 #
9855 # Strings, Sequences and Regular expressions
9856 #
9857 #########################################
9858 
9859 class SeqSortRef(SortRef):
9860  """Sequence sort."""
9861 
9862  def is_string(self):
9863  """Determine if sort is a string
9864  >>> s = StringSort()
9865  >>> s.is_string()
9866  True
9867  >>> s = SeqSort(IntSort())
9868  >>> s.is_string()
9869  False
9870  """
9871  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9872 
9873 
9874 def StringSort(ctx=None):
9875  """Create a string sort
9876  >>> s = StringSort()
9877  >>> print(s)
9878  String
9879  """
9880  ctx = _get_ctx(ctx)
9881  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9882 
9883 
9884 def SeqSort(s):
9885  """Create a sequence sort over elements provided in the argument
9886  >>> s = SeqSort(IntSort())
9887  >>> s == Unit(IntVal(1)).sort()
9888  True
9889  """
9890  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9891 
9892 class SeqRef(ExprRef):
9893  """Sequence expression."""
9894 
9895  def sort(self):
9896  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9897 
9898  def __add__(self, other):
9899  return Concat(self, other)
9900 
9901  def __radd__(self, other):
9902  return Concat(other, self)
9903 
9904  def __getitem__(self, i):
9905  if _is_int(i):
9906  i = IntVal(i, self.ctx)
9907  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9908 
9909  def is_string(self):
9910  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9911 
9912  def is_string_value(self):
9913  return Z3_is_string(self.ctx_ref(), self.as_ast())
9914 
9915  def as_string(self):
9916  """Return a string representation of sequence expression."""
9917  if self.is_string_value():
9918  return Z3_get_string(self.ctx_ref(), self.as_ast())
9919  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9920 
9921 
9922 def _coerce_seq(s, ctx=None):
9923  if isinstance(s, str):
9924  ctx = _get_ctx(ctx)
9925  s = StringVal(s, ctx)
9926  if not is_expr(s):
9927  raise Z3Exception("Non-expression passed as a sequence")
9928  if not is_seq(s):
9929  raise Z3Exception("Non-sequence passed as a sequence")
9930  return s
9931 
9932 def _get_ctx2(a, b, ctx=None):
9933  if is_expr(a):
9934  return a.ctx
9935  if is_expr(b):
9936  return b.ctx
9937  if ctx is None:
9938  ctx = main_ctx()
9939  return ctx
9940 
9941 def is_seq(a):
9942  """Return `True` if `a` is a Z3 sequence expression.
9943  >>> print (is_seq(Unit(IntVal(0))))
9944  True
9945  >>> print (is_seq(StringVal("abc")))
9946  True
9947  """
9948  return isinstance(a, SeqRef)
9949 
9950 def is_string(a):
9951  """Return `True` if `a` is a Z3 string expression.
9952  >>> print (is_string(StringVal("ab")))
9953  True
9954  """
9955  return isinstance(a, SeqRef) and a.is_string()
9956 
9957 def is_string_value(a):
9958  """return 'True' if 'a' is a Z3 string constant expression.
9959  >>> print (is_string_value(StringVal("a")))
9960  True
9961  >>> print (is_string_value(StringVal("a") + StringVal("b")))
9962  False
9963  """
9964  return isinstance(a, SeqRef) and a.is_string_value()
9965 
9966 
9967 def StringVal(s, ctx=None):
9968  """create a string expression"""
9969  ctx = _get_ctx(ctx)
9970  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
9971 
9972 def String(name, ctx=None):
9973  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
9974 
9975  >>> x = String('x')
9976  """
9977  ctx = _get_ctx(ctx)
9978  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
9979 
9980 def SubString(s, offset, length):
9981  """Extract substring or subsequence starting at offset"""
9982  return Extract(s, offset, length)
9983 
9984 def SubSeq(s, offset, length):
9985  """Extract substring or subsequence starting at offset"""
9986  return Extract(s, offset, length)
9987 
9988 def Strings(names, ctx=None):
9989  """Return a tuple of String constants. """
9990  ctx = _get_ctx(ctx)
9991  if isinstance(names, str):
9992  names = names.split(" ")
9993  return [String(name, ctx) for name in names]
9994 
9995 def Empty(s):
9996  """Create the empty sequence of the given sort
9997  >>> e = Empty(StringSort())
9998  >>> e2 = StringVal("")
9999  >>> print(e.eq(e2))
10000  True
10001  >>> e3 = Empty(SeqSort(IntSort()))
10002  >>> print(e3)
10003  seq.empty
10004  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10005  >>> print(e4)
10006  re.empty
10007  """
10008  if isinstance(s, SeqSortRef):
10009  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10010  if isinstance(s, ReSortRef):
10011  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10012  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10013 
10014 def Full(s):
10015  """Create the regular expression that accepts the universal language
10016  >>> e = Full(ReSort(SeqSort(IntSort())))
10017  >>> print(e)
10018  re.all
10019  >>> e1 = Full(ReSort(StringSort()))
10020  >>> print(e1)
10021  re.all
10022  """
10023  if isinstance(s, ReSortRef):
10024  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10025  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10026 
10027 
10028 def Unit(a):
10029  """Create a singleton sequence"""
10030  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10031 
10032 def PrefixOf(a, b):
10033  """Check if 'a' is a prefix of 'b'
10034  >>> s1 = PrefixOf("ab", "abc")
10035  >>> simplify(s1)
10036  True
10037  >>> s2 = PrefixOf("bc", "abc")
10038  >>> simplify(s2)
10039  False
10040  """
10041  ctx = _get_ctx2(a, b)
10042  a = _coerce_seq(a, ctx)
10043  b = _coerce_seq(b, ctx)
10044  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10045 
10046 def SuffixOf(a, b):
10047  """Check if 'a' is a suffix of 'b'
10048  >>> s1 = SuffixOf("ab", "abc")
10049  >>> simplify(s1)
10050  False
10051  >>> s2 = SuffixOf("bc", "abc")
10052  >>> simplify(s2)
10053  True
10054  """
10055  ctx = _get_ctx2(a, b)
10056  a = _coerce_seq(a, ctx)
10057  b = _coerce_seq(b, ctx)
10058  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10059 
10060 def Contains(a, b):
10061  """Check if 'a' contains 'b'
10062  >>> s1 = Contains("abc", "ab")
10063  >>> simplify(s1)
10064  True
10065  >>> s2 = Contains("abc", "bc")
10066  >>> simplify(s2)
10067  True
10068  >>> x, y, z = Strings('x y z')
10069  >>> s3 = Contains(Concat(x,y,z), y)
10070  >>> simplify(s3)
10071  True
10072  """
10073  ctx = _get_ctx2(a, b)
10074  a = _coerce_seq(a, ctx)
10075  b = _coerce_seq(b, ctx)
10076  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10077 
10078 
10079 def Replace(s, src, dst):
10080  """Replace the first occurrence of 'src' by 'dst' in 's'
10081  >>> r = Replace("aaa", "a", "b")
10082  >>> simplify(r)
10083  baa
10084  """
10085  ctx = _get_ctx2(dst, s)
10086  if ctx is None and is_expr(src):
10087  ctx = src.ctx
10088  src = _coerce_seq(src, ctx)
10089  dst = _coerce_seq(dst, ctx)
10090  s = _coerce_seq(s, ctx)
10091  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10092 
10093 def IndexOf(s, substr):
10094  return IndexOf(s, substr, IntVal(0))
10095 
10096 def IndexOf(s, substr, offset):
10097  """Retrieve the index of substring within a string starting at a specified offset.
10098  >>> simplify(IndexOf("abcabc", "bc", 0))
10099  1
10100  >>> simplify(IndexOf("abcabc", "bc", 2))
10101  4
10102  """
10103  ctx = None
10104  if is_expr(offset):
10105  ctx = offset.ctx
10106  ctx = _get_ctx2(s, substr, ctx)
10107  s = _coerce_seq(s, ctx)
10108  substr = _coerce_seq(substr, ctx)
10109  if _is_int(offset):
10110  offset = IntVal(offset, ctx)
10111  return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10112 
10113 def Length(s):
10114  """Obtain the length of a sequence 's'
10115  >>> l = Length(StringVal("abc"))
10116  >>> simplify(l)
10117  3
10118  """
10119  s = _coerce_seq(s)
10120  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10121 
10122 def StrToInt(s):
10123  """Convert string expression to integer
10124  >>> a = StrToInt("1")
10125  >>> simplify(1 == a)
10126  True
10127  >>> b = StrToInt("2")
10128  >>> simplify(1 == b)
10129  False
10130  >>> c = StrToInt(IntToStr(2))
10131  >>> simplify(1 == c)
10132  False
10133  """
10134  s = _coerce_seq(s)
10135  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10136 
10137 
10138 def IntToStr(s):
10139  """Convert integer expression to string"""
10140  if not is_expr(s):
10141  s = _py2expr(s)
10142  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10143 
10144 
10145 def Re(s, ctx=None):
10146  """The regular expression that accepts sequence 's'
10147  >>> s1 = Re("ab")
10148  >>> s2 = Re(StringVal("ab"))
10149  >>> s3 = Re(Unit(BoolVal(True)))
10150  """
10151  s = _coerce_seq(s, ctx)
10152  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10153 
10154 
10155 
10156 
10157 ## Regular expressions
10158 
10159 class ReSortRef(SortRef):
10160  """Regular expression sort."""
10161 
10162 
10163 def ReSort(s):
10164  if is_ast(s):
10165  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10166  if s is None or isinstance(s, Context):
10167  ctx = _get_ctx(s)
10168  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10169  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10170 
10171 
10172 class ReRef(ExprRef):
10173  """Regular expressions."""
10174 
10175  def __add__(self, other):
10176  return Union(self, other)
10177 
10178 
10179 def is_re(s):
10180  return isinstance(s, ReRef)
10181 
10182 
10183 def InRe(s, re):
10184  """Create regular expression membership test
10185  >>> re = Union(Re("a"),Re("b"))
10186  >>> print (simplify(InRe("a", re)))
10187  True
10188  >>> print (simplify(InRe("b", re)))
10189  True
10190  >>> print (simplify(InRe("c", re)))
10191  False
10192  """
10193  s = _coerce_seq(s, re.ctx)
10194  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10195 
10196 def Union(*args):
10197  """Create union of regular expressions.
10198  >>> re = Union(Re("a"), Re("b"), Re("c"))
10199  >>> print (simplify(InRe("d", re)))
10200  False
10201  """
10202  args = _get_args(args)
10203  sz = len(args)
10204  if __debug__:
10205  _z3_assert(sz > 0, "At least one argument expected.")
10206  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10207  if sz == 1:
10208  return args[0]
10209  ctx = args[0].ctx
10210  v = (Ast * sz)()
10211  for i in range(sz):
10212  v[i] = args[i].as_ast()
10213  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10214 
10215 def Plus(re):
10216  """Create the regular expression accepting one or more repetitions of argument.
10217  >>> re = Plus(Re("a"))
10218  >>> print(simplify(InRe("aa", re)))
10219  True
10220  >>> print(simplify(InRe("ab", re)))
10221  False
10222  >>> print(simplify(InRe("", re)))
10223  False
10224  """
10225  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10226 
10227 def Option(re):
10228  """Create the regular expression that optionally accepts the argument.
10229  >>> re = Option(Re("a"))
10230  >>> print(simplify(InRe("a", re)))
10231  True
10232  >>> print(simplify(InRe("", re)))
10233  True
10234  >>> print(simplify(InRe("aa", re)))
10235  False
10236  """
10237  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10238 
10239 def Complement(re):
10240  """Create the complement regular expression."""
10241  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10242 
10243 def Star(re):
10244  """Create the regular expression accepting zero or more repetitions of argument.
10245  >>> re = Star(Re("a"))
10246  >>> print(simplify(InRe("aa", re)))
10247  True
10248  >>> print(simplify(InRe("ab", re)))
10249  False
10250  >>> print(simplify(InRe("", re)))
10251  True
10252  """
10253  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10254 
10255 def Loop(re, lo, hi=0):
10256  """Create the regular expression accepting between a lower and upper bound repetitions
10257  >>> re = Loop(Re("a"), 1, 3)
10258  >>> print(simplify(InRe("aa", re)))
10259  True
10260  >>> print(simplify(InRe("aaaa", re)))
10261  False
10262  >>> print(simplify(InRe("", re)))
10263  False
10264  """
10265  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
def param_descrs(self)
Definition: z3py.py:7309
def value(self)
Definition: z3py.py:7274
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:7391
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
def name(self)
Definition: z3py.py:656
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9826
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:2650
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:8086
def __ge__(self, other)
Definition: z3py.py:7898
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:3069
def is_distinct(a)
Definition: z3py.py:1501
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
def __gt__(self, other)
Definition: z3py.py:7872
def Then(ts, ks)
Definition: z3py.py:7670
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def SignExt(n, a)
Definition: z3py.py:4046
def update_rule(self, head, body, name)
Definition: z3py.py:7004
def SeqSort(s)
Definition: z3py.py:9884
Fixedpoint.
Definition: z3py.py:6862
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
def upper(self)
Definition: z3py.py:7262
def OrElse(ts, ks)
Definition: z3py.py:7682
def is_fprm_sort(s)
Definition: z3py.py:8681
def get_version_string()
Definition: z3py.py:69
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
Quantifiers.
Definition: z3py.py:1792
def AtLeast(args)
Definition: z3py.py:8232
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5007
def entry(self, idx)
Definition: z3py.py:5846
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7039
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def upper_values(self, obj)
Definition: z3py.py:7406
def RatVal(a, b, ctx=None)
Definition: z3py.py:2955
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].
def add(self, args)
Definition: z3py.py:7325
def __getitem__(self, idx)
Definition: z3py.py:7489
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Function Declarations.
Definition: z3py.py:640
def SetUnion(args)
Definition: z3py.py:4548
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3056
Booleans.
Definition: z3py.py:1349
def Product(args)
Definition: z3py.py:8190
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:5144
def IsInt(a)
Definition: z3py.py:3116
def Sum(args)
Definition: z3py.py:8164
def __repr__(self)
Definition: z3py.py:307
def is_arith_sort(s)
Definition: z3py.py:2150
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
def ReSort(s)
Definition: z3py.py:10163
def push(self)
Definition: z3py.py:6996
def Function(name, sig)
Definition: z3py.py:778
def RTZ(ctx=None)
Definition: z3py.py:8915
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
def as_ast(self)
Definition: z3py.py:862
def __iadd__(self, fml)
Definition: z3py.py:7329
def RealSort(ctx=None)
Definition: z3py.py:2895
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3244
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9670
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9266
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9199
def get_rules(self)
Definition: z3py.py:7078
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
def RealVarVector(n, ctx=None)
Definition: z3py.py:1332
def sort(self)
Definition: z3py.py:7169
def AndThen(ts, ks)
Definition: z3py.py:7651
def ZeroExt(n, a)
Definition: z3py.py:4075
def assertions(self)
Definition: z3py.py:7425
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def substitute_vars(t, m)
Definition: z3py.py:8144
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def is_int(self)
Definition: z3py.py:2096
def Var(idx, s)
Definition: z3py.py:1310
def __del__(self)
Definition: z3py.py:7855
def is_bool(self)
Definition: z3py.py:1379
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def probes(ctx=None)
Definition: z3py.py:7982
def ArraySort(sig)
Definition: z3py.py:4340
def to_symbol(s, ctx=None)
Definition: z3py.py:105
def help(self)
Definition: z3py.py:6766
def reset_params()
Definition: z3py.py:256
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def declare(self, name, args)
Definition: z3py.py:4685
def is_string_value(a)
Definition: z3py.py:9957
def as_ast(self)
Definition: z3py.py:338
def assert_exprs(self, args)
Definition: z3py.py:7313
def LShR(a, b)
Definition: z3py.py:3985
def is_default(a)
Definition: z3py.py:4315
def set_option(args, kws)
Definition: z3py.py:261
Z3_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs. The result is the new AST. The arrays from and to must have size num_exprs. For every i smaller than num_exprs, we must have that sort of from[i] must be equal to sort of to[i].
Bit-Vectors.
Definition: z3py.py:3162
def Consts(names, sort)
Definition: z3py.py:1291
def use_pp(self)
Definition: z3py.py:287
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
def IntVal(val, ctx=None)
Definition: z3py.py:2926
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
def __nonzero__(self)
Definition: z3py.py:316
def is_and(a)
Definition: z3py.py:1448
def ref(self)
Definition: z3py.py:192
def push(self)
Definition: z3py.py:6396
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:9560
def sort(self)
Definition: z3py.py:1385
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8481
def ULT(a, b)
Definition: z3py.py:3874
def fpIsInf(a, ctx=None)
Definition: z3py.py:9498
Arithmetic.
Definition: z3py.py:2079
FP Expressions.
Definition: z3py.py:8693
def __init__(self, ctx=None)
Definition: z3py.py:7287
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:7356
def help(self)
Definition: z3py.py:7305
def sort(self)
Definition: z3py.py:2168
def is_to_real(a)
Definition: z3py.py:2694
def as_ast(self)
Definition: z3py.py:496
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9632
def assert_exprs(self, args)
Definition: z3py.py:6897
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
def Float64(ctx=None)
Definition: z3py.py:8647
def param_descrs(self)
Definition: z3py.py:6893
def is_select(a)
Definition: z3py.py:4498
def is_real(self)
Definition: z3py.py:2192
Z3_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
def is_int(self)
Definition: z3py.py:2178
ASTs base class.
Definition: z3py.py:285
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
def __ne__(self, other)
Definition: z3py.py:912
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9739
def is_gt(a)
Definition: z3py.py:2672
def lower_values(self, obj)
Definition: z3py.py:7401
def pop(self)
Definition: z3py.py:7364
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:7509
def set_param(args, kws)
Definition: z3py.py:233
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def __eq__(self, other)
Definition: z3py.py:891
def domain(self, i)
Definition: z3py.py:676
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
def as_string(self)
Definition: z3py.py:7173
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2033
def is_implies(a)
Definition: z3py.py:1470
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
def Loop(re, lo, hi=0)
Definition: z3py.py:10255
def AtMost(args)
Definition: z3py.py:8215
def __deepcopy__(self, memo={})
Definition: z3py.py:7463
def register_relation(self, relations)
Definition: z3py.py:7048
def IndexOf(s, substr)
Definition: z3py.py:10093
def is_app(a)
Definition: z3py.py:1116
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9786
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
def __len__(self)
Definition: z3py.py:7470
def StringSort(ctx=None)
Definition: z3py.py:9874
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
def And(args)
Definition: z3py.py:1661
def open_log(fname)
Definition: z3py.py:97
def __deepcopy__(self, memo={})
Definition: z3py.py:7564
def EmptySet(s)
Definition: z3py.py:4532
def solver(self)
Definition: z3py.py:7571
def PrefixOf(a, b)
Definition: z3py.py:10032
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9571
def PbEq(args, k, ctx=None)
Definition: z3py.py:8288
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def rule(self, head, body=None, name=None)
Definition: z3py.py:6950
def range(self)
Definition: z3py.py:4237
def __repr__(self)
Definition: z3py.py:7506
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
def fpRem(a, b, ctx=None)
Definition: z3py.py:9431
def Cbrt(a, ctx=None)
Definition: z3py.py:3144
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def SetDifference(a, b)
Definition: z3py.py:4601
def disable_trace(msg)
Definition: z3py.py:66
def RotateRight(a, b)
Definition: z3py.py:4031
def sort(self)
Definition: z3py.py:3207
def is_ge(a)
Definition: z3py.py:2661
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
def is_K(a)
Definition: z3py.py:4288
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:880
def tactics(ctx=None)
Definition: z3py.py:7791
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
def is_const(a)
Definition: z3py.py:1141
def Star(re)
Definition: z3py.py:10243
def InRe(s, re)
Definition: z3py.py:10183
def is_finite_domain_sort(s)
Definition: z3py.py:7155
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
def push(self)
Definition: z3py.py:7360
def z3_error_handler(c, e)
Definition: z3py.py:152
def RotateLeft(a, b)
Definition: z3py.py:4016
def Const(name, sort)
Definition: z3py.py:1280
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1573
def substitute(t, m)
Definition: z3py.py:8118
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
def Array(name, dom, rng)
Definition: z3py.py:4372
def main_ctx()
Definition: z3py.py:207
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def If(a, b, c, ctx=None)
Definition: z3py.py:1227
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3726
def get_id(self)
Definition: z3py.py:650
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
def is_array(a)
Definition: z3py.py:4263
def is_pattern(a)
Definition: z3py.py:1740
Statistics.
Definition: z3py.py:6192
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:8070
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
def is_fp_value(a)
Definition: z3py.py:9068
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
def help_simplify()
Definition: z3py.py:8110
def fpMax(a, b, ctx=None)
Definition: z3py.py:9458
def IsSubset(a, b)
Definition: z3py.py:4621
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:7396
def get_rule_names_along_trace(self)
Definition: z3py.py:7027
def Int(name, ctx=None)
Definition: z3py.py:2982
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6865
def __repr__(self)
Definition: z3py.py:7433
def __repr__(self)
Definition: z3py.py:7086
Arrays.
Definition: z3py.py:4195
def simplify_param_descrs()
Definition: z3py.py:8114
def is_map(a)
Definition: z3py.py:4300
def is_or(a)
Definition: z3py.py:1459
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9756
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9403
Patterns.
Definition: z3py.py:1730
def fpAbs(a, ctx=None)
Definition: z3py.py:9284
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9582
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3742
def SetIntersect(args)
Definition: z3py.py:4560
def is_int_value(a)
Definition: z3py.py:2511
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
def __hash__(self)
Definition: z3py.py:575
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def Default(a)
Definition: z3py.py:4406
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7148
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
def CreateDatatypes(ds)
Definition: z3py.py:4742
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def FreshConst(sort, prefix='c')
Definition: z3py.py:1305
def URem(a, b)
Definition: z3py.py:3945
def PbGe(args, k)
Definition: z3py.py:8278
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def Union(args)
Definition: z3py.py:10196
def SuffixOf(a, b)
Definition: z3py.py:10046
def __eq__(self, other)
Definition: z3py.py:310
def __mul__(self, other)
Definition: z3py.py:1391
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9722
def is_mod(a)
Definition: z3py.py:2628
def fact(self, head, name=None)
Definition: z3py.py:6954
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
def convert_model(self, model)
Definition: z3py.py:5276
def UGE(a, b)
Definition: z3py.py:3891
def Replace(s, src, dst)
Definition: z3py.py:10079
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:3030
def __init__(self, args, kws)
Definition: z3py.py:168
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective.
def lower_values(self)
Definition: z3py.py:7266
def cast(self, val)
Definition: z3py.py:526
def Length(s)
Definition: z3py.py:10113
def decl(self)
Definition: z3py.py:933
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7734
def Bools(names, ctx=None)
Definition: z3py.py:1558
def is_eq(a)
Definition: z3py.py:1492
def __del__(self)
Definition: z3py.py:187
def Float32(ctx=None)
Definition: z3py.py:8637
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9487
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:7442
def depth(self)
Definition: z3py.py:5109
def __str__(self)
Definition: z3py.py:7280
def sort(self)
Definition: z3py.py:868
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def is_real(a)
Definition: z3py.py:2487
def RealVal(val, ctx=None)
Definition: z3py.py:2937
def PbLe(args, k)
Definition: z3py.py:8268
def get_id(self)
Definition: z3py.py:865
def Extract(high, low, a)
Definition: z3py.py:3830
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def RealVar(idx, ctx=None)
Definition: z3py.py:1322
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2016
def solve_using(s, args, keywords)
Definition: z3py.py:8327
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def set_predicate_representation(self, f, representations)
Definition: z3py.py:7054
def maximize(self, arg)
Definition: z3py.py:7352
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
def eq(a, b)
Definition: z3py.py:416
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
def RecFunction(name, sig)
Definition: z3py.py:803
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def help(self)
Definition: z3py.py:7615
def __bool__(self)
Definition: z3py.py:319
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7333
def sexpr(self)
Definition: z3py.py:7437
def is_le(a)
Definition: z3py.py:2639
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def __deepcopy__(self, memo={})
Definition: z3py.py:301
def is_not(a)
Definition: z3py.py:1481
def get_map_func(a)
Definition: z3py.py:4323
def Implies(a, b, ctx=None)
Definition: z3py.py:1600
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7550
def __deepcopy__(self, memo={})
Definition: z3py.py:7292
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def apply(self, goal, arguments, keywords)
Definition: z3py.py:7588
def solve(args, keywords)
Definition: z3py.py:8299
def is_arith(a)
Definition: z3py.py:2449
def __del__(self)
Definition: z3py.py:7567
def is_sort(s)
Definition: z3py.py:579
def objectives(self)
Definition: z3py.py:7429
def Or(args)
Definition: z3py.py:1694
def __init__(self, opt, value, is_max)
Definition: z3py.py:7253
def num_sorts(self)
Definition: z3py.py:6021
def add(self, args)
Definition: z3py.py:6911
def hash(self)
Definition: z3py.py:386
def SetSort(s)
Sets.
Definition: z3py.py:4528
def is_int(a)
Definition: z3py.py:2469
def check(self, assumptions)
Definition: z3py.py:6558
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:9156
def insert(self, args)
Definition: z3py.py:6923
def is_quantifier(a)
Definition: z3py.py:1969
def as_string(self)
Definition: z3py.py:7205
def is_string(a)
Definition: z3py.py:9950
def StringVal(s, ctx=None)
Definition: z3py.py:9967
def Plus(re)
Definition: z3py.py:10215
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:10122
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:7605
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:7216
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0...
def params(self)
Definition: z3py.py:930
def num_args(self)
Definition: z3py.py:948
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9082
def __del__(self)
Definition: z3py.py:7466
def prove(claim, keywords)
Definition: z3py.py:8356
def DeclareSort(name, ctx=None)
Definition: z3py.py:616
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def Ints(names, ctx=None)
Definition: z3py.py:2994
def parse_file(self, f)
Definition: z3py.py:7071
def pop(self)
Definition: z3py.py:7000
def is_true(a)
Definition: z3py.py:1418
def Int2BV(a, num_bits)
Definition: z3py.py:3704
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:10060
def is_finite_domain_value(a)
Definition: z3py.py:7230
def is_real(self)
Definition: z3py.py:2082
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a string of a numeric constant term.
def FreshBool(prefix='b', ctx=None)
Definition: z3py.py:1587
def Bool(name, ctx=None)
Definition: z3py.py:1547
def probe_description(name, ctx=None)
Definition: z3py.py:7992
def get_rules_along_trace(self)
Definition: z3py.py:7023
def __deepcopy__(self, memo={})
Definition: z3py.py:6876
def __del__(self)
Definition: z3py.py:7295
def Lambda(vs, body)
Definition: z3py.py:2053
def tactic_description(name, ctx=None)
Definition: z3py.py:7801
def param_descrs(self)
Definition: z3py.py:7619
def RNE(ctx=None)
Definition: z3py.py:8883
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
def is_store(a)
Definition: z3py.py:4510
def get_version()
Definition: z3py.py:77
def from_string(self, s)
Definition: z3py.py:7418
def SetDel(s, e)
Definition: z3py.py:4582
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def SRem(a, b)
Definition: z3py.py:3965
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9243
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:9765
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9417
def eq(self, other)
Definition: z3py.py:350
def FullSet(s)
Definition: z3py.py:4540
def get_id(self)
Definition: z3py.py:499
def ToReal(a)
Definition: z3py.py:3082
def is_bv_value(a)
Definition: z3py.py:3668
def range(self)
Definition: z3py.py:689
def is_idiv(a)
Definition: z3py.py:2617
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3765
def translate(self, target)
Definition: z3py.py:367
def from_file(self, filename)
Definition: z3py.py:7411
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:7829
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate. ...
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
def query_from_lvl(self, lvl, query)
Definition: z3py.py:6980
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
def __ne__(self, other)
Definition: z3py.py:564
def __le__(self, other)
Definition: z3py.py:7885
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
def cast(self, val)
Definition: z3py.py:1351
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality. Thus, two ast nodes created by the same context and having the same children and same function symbols have the same identifiers. Ast nodes created in the same context, but having different children or different functions have different identifiers. Variables and quantifiers are also assigned different identifiers according to their structure.
def as_func_decl(self)
Definition: z3py.py:653
def size(self)
Definition: z3py.py:3218
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def to_string(self, queries)
Definition: z3py.py:7095
def assertions(self)
Definition: z3py.py:6711
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def Strings(names, ctx=None)
Definition: z3py.py:9988
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
def get_id(self)
Definition: z3py.py:342
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9389
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9604
def __lt__(self, other)
Definition: z3py.py:7859
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
def create(self)
Definition: z3py.py:4708
def Full(s)
Definition: z3py.py:10014
def is_const_array(a)
Definition: z3py.py:4276
def fpNaN(s)
Definition: z3py.py:9140
def cast(self, val)
Definition: z3py.py:2114
def as_long(self)
Definition: z3py.py:7193
def sexpr(self)
Definition: z3py.py:329
def reason_unknown(self)
Definition: z3py.py:7377
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
def kind(self)
Definition: z3py.py:502
def IntSort(ctx=None)
Definition: z3py.py:2879
def Unit(a)
Definition: z3py.py:10028
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:7064
def is_rational_value(a)
Definition: z3py.py:2534
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def is_finite_domain(a)
Definition: z3py.py:7177
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
def fpNeg(a, ctx=None)
Definition: z3py.py:9306
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:9549
def get_ground_sat_answer(self)
Definition: z3py.py:7018
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4931
def sexpr(self)
Definition: z3py.py:7090
def __ne__(self, other)
Definition: z3py.py:7924
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
def declare_var(self, vars)
Definition: z3py.py:7113
def arg(self, idx)
Definition: z3py.py:964
def sort(self)
Definition: z3py.py:8696
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
def IntToStr(s)
Definition: z3py.py:10138
def Xor(a, b, ctx=None)
Definition: z3py.py:1615
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def Select(a, i)
Definition: z3py.py:4433
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:6927
def __rmul__(self, other)
Definition: z3py.py:1388
def params(self)
Definition: z3py.py:710
def query(self, query)
Definition: z3py.py:6958
def RecAddDefinition(f, args, body)
Definition: z3py.py:820
def get_var_index(a)
Definition: z3py.py:1183
def Not(a, ctx=None)
Definition: z3py.py:1630
def MultiPattern(args)
Definition: z3py.py:1757
def BoolVal(val, ctx=None)
Definition: z3py.py:1529
def upper_values(self)
Definition: z3py.py:7270
def model(self)
Definition: z3py.py:7381
def is_div(a)
Definition: z3py.py:2601
FP Numerals.
Definition: z3py.py:8937
FP Sorts.
Definition: z3py.py:8592
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def ctx_ref(self)
Definition: z3py.py:346
def help(self)
Definition: z3py.py:6889
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:10145
def fpMin(a, b, ctx=None)
Definition: z3py.py:9444
def is_fp_sort(s)
Definition: z3py.py:8671
Expressions.
Definition: z3py.py:852
def SetComplement(s)
Definition: z3py.py:4592
def is_app_of(a, k)
Definition: z3py.py:1215
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def is_probe(p)
Definition: z3py.py:7966
def is_mul(a)
Definition: z3py.py:2579
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:3017
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def subsort(self, other)
Definition: z3py.py:518
def kind(self)
Definition: z3py.py:698
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
def is_bv_sort(s)
Definition: z3py.py:3194
def Update(a, i, v)
Definition: z3py.py:4385
def With(t, args, keys)
Definition: z3py.py:7738
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
def append_log(s)
Definition: z3py.py:101
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
def statistics(self)
Definition: z3py.py:7103
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
def is_add(a)
Definition: z3py.py:2568
def ParOr(ts, ks)
Definition: z3py.py:7702
def K(dom, v)
Definition: z3py.py:4470
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3712
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def __hash__(self)
Definition: z3py.py:908
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3006
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9373
def get_assertions(self)
Definition: z3py.py:7082
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def get_num_levels(self, predicate)
Definition: z3py.py:7035
def UGT(a, b)
Definition: z3py.py:3908
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
def get_answer(self)
Definition: z3py.py:7013
def children(self)
Definition: z3py.py:985
def BV2Int(a, is_signed=False)
Definition: z3py.py:3682
def arity(self)
Definition: z3py.py:5832
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def WithParams(t, p)
Definition: z3py.py:7751
def Store(a, i, v)
Definition: z3py.py:4417
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7783
def numerator(self)
Definition: z3py.py:2749
def __str__(self)
Definition: z3py.py:304
def is_int(self)
Definition: z3py.py:1376
def is_ast(a)
Definition: z3py.py:396
def domain(self)
Definition: z3py.py:4228
def Empty(s)
Definition: z3py.py:9995
def __init__(self, ast, ctx=None)
Definition: z3py.py:292
def UDiv(a, b)
Definition: z3py.py:3925
def is_expr(a)
Definition: z3py.py:1094
def __init__(self, result, ctx)
Definition: z3py.py:7458
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7122
def set(self, args, keys)
Definition: z3py.py:6883
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:9807
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
def Map(f, args)
Definition: z3py.py:4448
def __call__(self, args)
Definition: z3py.py:734
def else_value(self)
Definition: z3py.py:5793
def subsort(self, other)
Definition: z3py.py:1373
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
def describe_probes()
Definition: z3py.py:8000
def add_cover(self, level, predicate, property)
Definition: z3py.py:7044
def describe_tactics()
Definition: z3py.py:7809
def is_bool(a)
Definition: z3py.py:1401
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
def Distinct(args)
Definition: z3py.py:1249
def __call__(self, goal)
Definition: z3py.py:7938
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
def unsat_core(self)
Definition: z3py.py:7388
def body(self)
Definition: z3py.py:1903
def as_list(self)
Definition: z3py.py:5877
def arity(self)
Definition: z3py.py:667
def Reals(names, ctx=None)
Definition: z3py.py:3042
def is_bv(a)
Definition: z3py.py:3655
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def SetAdd(s, e)
Definition: z3py.py:4572
def is_var(a)
Definition: z3py.py:1159
def as_expr(self)
Definition: z3py.py:7514
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def __copy__(self)
Definition: z3py.py:383
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9686
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9593
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:7764
def RepeatBitVec(n, a)
Definition: z3py.py:4102
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective. The returned vector ...
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
def SolverFor(logic, ctx=None)
Definition: z3py.py:6824
def get_full_version()
Definition: z3py.py:85
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7720
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
def lower(self)
Definition: z3py.py:7258
def as_ast(self)
Definition: z3py.py:647
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def is_false(a)
Definition: z3py.py:1435
def set(self, args, keys)
Definition: z3py.py:7299
def ULE(a, b)
Definition: z3py.py:3857
def is_is_int(a)
Definition: z3py.py:2683
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
def enable_trace(msg)
Definition: z3py.py:63
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
def name(self)
Definition: z3py.py:541
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9705
def is_fprm(a)
Definition: z3py.py:8919
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def __iadd__(self, fml)
Definition: z3py.py:6915
def Option(re)
Definition: z3py.py:10227
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def check(self, assumptions)
Definition: z3py.py:7368
def as_signed_long(self)
Definition: z3py.py:3630
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def __del__(self)
Definition: z3py.py:6879
def is_func_decl(a)
Definition: z3py.py:766
def interrupt(self)
Definition: z3py.py:196
def is_sub(a)
Definition: z3py.py:2590
def Concat(args)
Definition: z3py.py:3785
def FailIf(p, ctx=None)
Definition: z3py.py:8033
def __hash__(self)
Definition: z3py.py:313
def append(self, args)
Definition: z3py.py:6919
def When(p, t, ctx=None)
Definition: z3py.py:8052
def is_seq(a)
Definition: z3py.py:9941
def is_algebraic_value(a)
Definition: z3py.py:2555
def BoolSort(ctx=None)
Definition: z3py.py:1512
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def get_param(name)
Definition: z3py.py:266
def is_to_int(a)
Definition: z3py.py:2708
def __eq__(self, other)
Definition: z3py.py:7911
def Q(a, b, ctx=None)
Definition: z3py.py:2970
def __deepcopy__(self, memo={})
Definition: z3py.py:7852
def String(name, ctx=None)
Definition: z3py.py:9972
def reason_unknown(self)
Definition: z3py.py:7108
def IsMember(e, s)
Definition: z3py.py:4611
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
def ToInt(a)
Definition: z3py.py:3099
def num_entries(self)
Definition: z3py.py:5816
def __del__(self)
Definition: z3py.py:297
def is_fp(a)
Definition: z3py.py:9055
def __eq__(self, other)
Definition: z3py.py:551
def Sqrt(a, ctx=None)
Definition: z3py.py:3132
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def fpLT(a, b, ctx=None)
Definition: z3py.py:9538
def SimpleSolver(ctx=None)
Definition: z3py.py:6844
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.