Z3
z3py.py
Go to the documentation of this file.
1 
2 
9 
10 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
11 
12 Several online tutorials for Z3Py are available at:
13 http://rise4fun.com/Z3Py/tutorial/guide
14 
15 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
16 
17 Small example:
18 
19 >>> x = Int('x')
20 >>> y = Int('y')
21 >>> s = Solver()
22 >>> s.add(x > 0)
23 >>> s.add(x < 2)
24 >>> s.add(y == x + 1)
25 >>> s.check()
26 sat
27 >>> m = s.model()
28 >>> m[x]
29 1
30 >>> m[y]
31 2
32 
33 Z3 exceptions:
34 
35 >>> try:
36 ... x = BitVec('x', 32)
37 ... y = Bool('y')
38 ... # the expression x + y is type incorrect
39 ... n = x + y
40 ... except Z3Exception as ex:
41 ... print("failed: %s" % ex)
42 failed: sort mismatch
43 """
44 from . import z3core
45 from .z3core import *
46 from .z3types import *
47 from .z3consts import *
48 from .z3printer import *
49 from fractions import Fraction
50 import sys
51 import io
52 import math
53 import copy
54 
55 if sys.version < '3':
56  def _is_int(v):
57  return isinstance(v, (int, long))
58 else:
59  def _is_int(v):
60  return isinstance(v, int)
61 
62 def enable_trace(msg):
63  Z3_enable_trace(msg)
64 
65 def disable_trace(msg):
66  Z3_disable_trace(msg)
67 
69  major = ctypes.c_uint(0)
70  minor = ctypes.c_uint(0)
71  build = ctypes.c_uint(0)
72  rev = ctypes.c_uint(0)
73  Z3_get_version(major, minor, build, rev)
74  return "%s.%s.%s" % (major.value, minor.value, build.value)
75 
77  major = ctypes.c_uint(0)
78  minor = ctypes.c_uint(0)
79  build = ctypes.c_uint(0)
80  rev = ctypes.c_uint(0)
81  Z3_get_version(major, minor, build, rev)
82  return (major.value, minor.value, build.value, rev.value)
83 
85  return Z3_get_full_version()
86 
87 # We use _z3_assert instead of the assert command because we want to
88 # produce nice error messages in Z3Py at rise4fun.com
89 def _z3_assert(cond, msg):
90  if not cond:
91  raise Z3Exception(msg)
92 
93 def open_log(fname):
94  """Log interaction to a file. This function must be invoked immediately after init(). """
95  Z3_open_log(fname)
96 
97 def append_log(s):
98  """Append user-defined string to interaction log. """
99  Z3_append_log(s)
100 
101 def to_symbol(s, ctx=None):
102  """Convert an integer or string into a Z3 symbol."""
103  if _is_int(s):
104  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
105  else:
106  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
107 
108 def _symbol2py(ctx, s):
109  """Convert a Z3 symbol back into a Python object. """
110  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
111  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
112  else:
113  return Z3_get_symbol_string(ctx.ref(), s)
114 
115 # Hack for having nary functions that can receive one argument that is the
116 # list of arguments.
117 # Use this when function takes a single list of arguments
118 def _get_args(args):
119  try:
120  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
121  return args[0]
122  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
123  return [arg for arg in args[0]]
124  else:
125  return args
126  except: # len is not necessarily defined when args is not a sequence (use reflection?)
127  return args
128 
129 # Use this when function takes multiple arguments
130 def _get_args_ast_list(args):
131  try:
132  if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
133  return [arg for arg in args]
134  else:
135  return args
136  except:
137  return args
138 
139 def _to_param_value(val):
140  if isinstance(val, bool):
141  if val == True:
142  return "true"
143  else:
144  return "false"
145  else:
146  return str(val)
147 
149  # Do nothing error handler, just avoid exit(0)
150  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
151  return
152 
153 class Context:
154  """A Context manages all other Z3 objects, global configuration options, etc.
155 
156  Z3Py uses a default global context. For most applications this is sufficient.
157  An application may use multiple Z3 contexts. Objects created in one context
158  cannot be used in another one. However, several objects may be "translated" from
159  one context to another. It is not safe to access Z3 objects from multiple threads.
160  The only exception is the method `interrupt()` that can be used to interrupt() a long
161  computation.
162  The initialization method receives global configuration options for the new context.
163  """
164  def __init__(self, *args, **kws):
165  if __debug__:
166  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
167  conf = Z3_mk_config()
168  for key in kws:
169  value = kws[key]
170  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
171  prev = None
172  for a in args:
173  if prev is None:
174  prev = a
175  else:
176  Z3_set_param_value(conf, str(prev), _to_param_value(a))
177  prev = None
178  self.ctx = Z3_mk_context_rc(conf)
179  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
180  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
181  Z3_del_config(conf)
182 
183  def __del__(self):
184  Z3_del_context(self.ctx)
185  self.ctx = None
186  self.eh = None
187 
188  def ref(self):
189  """Return a reference to the actual C pointer to the Z3 context."""
190  return self.ctx
191 
192  def interrupt(self):
193  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
194 
195  This method can be invoked from a thread different from the one executing the
196  interruptible procedure.
197  """
198  Z3_interrupt(self.ref())
199 
200 
201 # Global Z3 context
202 _main_ctx = None
203 def main_ctx():
204  """Return a reference to the global Z3 context.
205 
206  >>> x = Real('x')
207  >>> x.ctx == main_ctx()
208  True
209  >>> c = Context()
210  >>> c == main_ctx()
211  False
212  >>> x2 = Real('x', c)
213  >>> x2.ctx == c
214  True
215  >>> eq(x, x2)
216  False
217  """
218  global _main_ctx
219  if _main_ctx is None:
220  _main_ctx = Context()
221  return _main_ctx
222 
223 def _get_ctx(ctx):
224  if ctx is None:
225  return main_ctx()
226  else:
227  return ctx
228 
229 def set_param(*args, **kws):
230  """Set Z3 global (or module) parameters.
231 
232  >>> set_param(precision=10)
233  """
234  if __debug__:
235  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
236  new_kws = {}
237  for k in kws:
238  v = kws[k]
239  if not set_pp_option(k, v):
240  new_kws[k] = v
241  for key in new_kws:
242  value = new_kws[key]
243  Z3_global_param_set(str(key).upper(), _to_param_value(value))
244  prev = None
245  for a in args:
246  if prev is None:
247  prev = a
248  else:
249  Z3_global_param_set(str(prev), _to_param_value(a))
250  prev = None
251 
253  """Reset all global (or module) parameters.
254  """
256 
257 def set_option(*args, **kws):
258  """Alias for 'set_param' for backward compatibility.
259  """
260  return set_param(*args, **kws)
261 
262 def get_param(name):
263  """Return the value of a Z3 global (or module) parameter
264 
265  >>> get_param('nlsat.reorder')
266  'true'
267  """
268  ptr = (ctypes.c_char_p * 1)()
269  if Z3_global_param_get(str(name), ptr):
270  r = z3core._to_pystr(ptr[0])
271  return r
272  raise Z3Exception("failed to retrieve value for '%s'" % name)
273 
274 
279 
280 # Mark objects that use pretty printer
282  """Superclass for all Z3 objects that have support for pretty printing."""
283  def use_pp(self):
284  return True
285 
287  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
288  def __init__(self, ast, ctx=None):
289  self.ast = ast
290  self.ctx = _get_ctx(ctx)
291  Z3_inc_ref(self.ctx.ref(), self.as_ast())
292 
293  def __del__(self):
294  if self.ctx.ref() is not None:
295  Z3_dec_ref(self.ctx.ref(), self.as_ast())
296 
297  def __deepcopy__(self, memo={}):
298  return _to_ast_ref(self.ast, self.ctx)
299 
300  def __str__(self):
301  return obj_to_string(self)
302 
303  def __repr__(self):
304  return obj_to_string(self)
305 
306  def __eq__(self, other):
307  return self.eq(other)
308 
309  def __hash__(self):
310  return self.hash()
311 
312  def __nonzero__(self):
313  return self.__bool__()
314 
315  def __bool__(self):
316  if is_true(self):
317  return True
318  elif is_false(self):
319  return False
320  elif is_eq(self) and self.num_args() == 2:
321  return self.arg(0).eq(self.arg(1))
322  else:
323  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
324 
325  def sexpr(self):
326  """Return a string representing the AST node in s-expression notation.
327 
328  >>> x = Int('x')
329  >>> ((x + 1)*x).sexpr()
330  '(* (+ x 1) x)'
331  """
332  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
333 
334  def as_ast(self):
335  """Return a pointer to the corresponding C Z3_ast object."""
336  return self.ast
337 
338  def get_id(self):
339  """Return unique identifier for object. It can be used for hash-tables and maps."""
340  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
341 
342  def ctx_ref(self):
343  """Return a reference to the C context where this AST node is stored."""
344  return self.ctx.ref()
345 
346  def eq(self, other):
347  """Return `True` if `self` and `other` are structurally identical.
348 
349  >>> x = Int('x')
350  >>> n1 = x + 1
351  >>> n2 = 1 + x
352  >>> n1.eq(n2)
353  False
354  >>> n1 = simplify(n1)
355  >>> n2 = simplify(n2)
356  >>> n1.eq(n2)
357  True
358  """
359  if __debug__:
360  _z3_assert(is_ast(other), "Z3 AST expected")
361  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
362 
363  def translate(self, target):
364  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
365 
366  >>> c1 = Context()
367  >>> c2 = Context()
368  >>> x = Int('x', c1)
369  >>> y = Int('y', c2)
370  >>> # Nodes in different contexts can't be mixed.
371  >>> # However, we can translate nodes from one context to another.
372  >>> x.translate(c2) + y
373  x + y
374  """
375  if __debug__:
376  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
377  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
378 
379  def __copy__(self):
380  return self.translate(self.ctx)
381 
382  def hash(self):
383  """Return a hashcode for the `self`.
384 
385  >>> n1 = simplify(Int('x') + 1)
386  >>> n2 = simplify(2 + Int('x') - 1)
387  >>> n1.hash() == n2.hash()
388  True
389  """
390  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
391 
392 def is_ast(a):
393  """Return `True` if `a` is an AST node.
394 
395  >>> is_ast(10)
396  False
397  >>> is_ast(IntVal(10))
398  True
399  >>> is_ast(Int('x'))
400  True
401  >>> is_ast(BoolSort())
402  True
403  >>> is_ast(Function('f', IntSort(), IntSort()))
404  True
405  >>> is_ast("x")
406  False
407  >>> is_ast(Solver())
408  False
409  """
410  return isinstance(a, AstRef)
411 
412 def eq(a, b):
413  """Return `True` if `a` and `b` are structurally identical AST nodes.
414 
415  >>> x = Int('x')
416  >>> y = Int('y')
417  >>> eq(x, y)
418  False
419  >>> eq(x + 1, x + 1)
420  True
421  >>> eq(x + 1, 1 + x)
422  False
423  >>> eq(simplify(x + 1), simplify(1 + x))
424  True
425  """
426  if __debug__:
427  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
428  return a.eq(b)
429 
430 def _ast_kind(ctx, a):
431  if is_ast(a):
432  a = a.as_ast()
433  return Z3_get_ast_kind(ctx.ref(), a)
434 
435 def _ctx_from_ast_arg_list(args, default_ctx=None):
436  ctx = None
437  for a in args:
438  if is_ast(a) or is_probe(a):
439  if ctx is None:
440  ctx = a.ctx
441  else:
442  if __debug__:
443  _z3_assert(ctx == a.ctx, "Context mismatch")
444  if ctx is None:
445  ctx = default_ctx
446  return ctx
447 
448 def _ctx_from_ast_args(*args):
449  return _ctx_from_ast_arg_list(args)
450 
451 def _to_func_decl_array(args):
452  sz = len(args)
453  _args = (FuncDecl * sz)()
454  for i in range(sz):
455  _args[i] = args[i].as_func_decl()
456  return _args, sz
457 
458 def _to_ast_array(args):
459  sz = len(args)
460  _args = (Ast * sz)()
461  for i in range(sz):
462  _args[i] = args[i].as_ast()
463  return _args, sz
464 
465 def _to_ref_array(ref, args):
466  sz = len(args)
467  _args = (ref * sz)()
468  for i in range(sz):
469  _args[i] = args[i].as_ast()
470  return _args, sz
471 
472 def _to_ast_ref(a, ctx):
473  k = _ast_kind(ctx, a)
474  if k == Z3_SORT_AST:
475  return _to_sort_ref(a, ctx)
476  elif k == Z3_FUNC_DECL_AST:
477  return _to_func_decl_ref(a, ctx)
478  else:
479  return _to_expr_ref(a, ctx)
480 
481 
486 
487 def _sort_kind(ctx, s):
488  return Z3_get_sort_kind(ctx.ref(), s)
489 
491  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
492  def as_ast(self):
493  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
494 
495  def get_id(self):
496  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
497 
498  def kind(self):
499  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
500 
501  >>> b = BoolSort()
502  >>> b.kind() == Z3_BOOL_SORT
503  True
504  >>> b.kind() == Z3_INT_SORT
505  False
506  >>> A = ArraySort(IntSort(), IntSort())
507  >>> A.kind() == Z3_ARRAY_SORT
508  True
509  >>> A.kind() == Z3_INT_SORT
510  False
511  """
512  return _sort_kind(self.ctx, self.ast)
513 
514  def subsort(self, other):
515  """Return `True` if `self` is a subsort of `other`.
516 
517  >>> IntSort().subsort(RealSort())
518  True
519  """
520  return False
521 
522  def cast(self, val):
523  """Try to cast `val` as an element of sort `self`.
524 
525  This method is used in Z3Py to convert Python objects such as integers,
526  floats, longs and strings into Z3 expressions.
527 
528  >>> x = Int('x')
529  >>> RealSort().cast(x)
530  ToReal(x)
531  """
532  if __debug__:
533  _z3_assert(is_expr(val), "Z3 expression expected")
534  _z3_assert(self.eq(val.sort()), "Sort mismatch")
535  return val
536 
537  def name(self):
538  """Return the name (string) of sort `self`.
539 
540  >>> BoolSort().name()
541  'Bool'
542  >>> ArraySort(IntSort(), IntSort()).name()
543  'Array'
544  """
545  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
546 
547  def __eq__(self, other):
548  """Return `True` if `self` and `other` are the same Z3 sort.
549 
550  >>> p = Bool('p')
551  >>> p.sort() == BoolSort()
552  True
553  >>> p.sort() == IntSort()
554  False
555  """
556  if other is None:
557  return False
558  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
559 
560  def __ne__(self, other):
561  """Return `True` if `self` and `other` are not the same Z3 sort.
562 
563  >>> p = Bool('p')
564  >>> p.sort() != BoolSort()
565  False
566  >>> p.sort() != IntSort()
567  True
568  """
569  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
570 
571  def __hash__(self):
572  """ Hash code. """
573  return AstRef.__hash__(self)
574 
575 def is_sort(s):
576  """Return `True` if `s` is a Z3 sort.
577 
578  >>> is_sort(IntSort())
579  True
580  >>> is_sort(Int('x'))
581  False
582  >>> is_expr(Int('x'))
583  True
584  """
585  return isinstance(s, SortRef)
586 
587 def _to_sort_ref(s, ctx):
588  if __debug__:
589  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
590  k = _sort_kind(ctx, s)
591  if k == Z3_BOOL_SORT:
592  return BoolSortRef(s, ctx)
593  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
594  return ArithSortRef(s, ctx)
595  elif k == Z3_BV_SORT:
596  return BitVecSortRef(s, ctx)
597  elif k == Z3_ARRAY_SORT:
598  return ArraySortRef(s, ctx)
599  elif k == Z3_DATATYPE_SORT:
600  return DatatypeSortRef(s, ctx)
601  elif k == Z3_FINITE_DOMAIN_SORT:
602  return FiniteDomainSortRef(s, ctx)
603  elif k == Z3_FLOATING_POINT_SORT:
604  return FPSortRef(s, ctx)
605  elif k == Z3_ROUNDING_MODE_SORT:
606  return FPRMSortRef(s, ctx)
607  return SortRef(s, ctx)
608 
609 def _sort(ctx, a):
610  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
611 
612 def DeclareSort(name, ctx=None):
613  """Create a new uninterpreted sort named `name`.
614 
615  If `ctx=None`, then the new sort is declared in the global Z3Py context.
616 
617  >>> A = DeclareSort('A')
618  >>> a = Const('a', A)
619  >>> b = Const('b', A)
620  >>> a.sort() == A
621  True
622  >>> b.sort() == A
623  True
624  >>> a == b
625  a == b
626  """
627  ctx = _get_ctx(ctx)
628  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
629 
630 
635 
637  """Function declaration. Every constant and function have an associated declaration.
638 
639  The declaration assigns a name, a sort (i.e., type), and for function
640  the sort (i.e., type) of each of its arguments. Note that, in Z3,
641  a constant is a function with 0 arguments.
642  """
643  def as_ast(self):
644  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
645 
646  def get_id(self):
647  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
648 
649  def as_func_decl(self):
650  return self.ast
651 
652  def name(self):
653  """Return the name of the function declaration `self`.
654 
655  >>> f = Function('f', IntSort(), IntSort())
656  >>> f.name()
657  'f'
658  >>> isinstance(f.name(), str)
659  True
660  """
661  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
662 
663  def arity(self):
664  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
665 
666  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
667  >>> f.arity()
668  2
669  """
670  return int(Z3_get_arity(self.ctx_ref(), self.ast))
671 
672  def domain(self, i):
673  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
674 
675  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
676  >>> f.domain(0)
677  Int
678  >>> f.domain(1)
679  Real
680  """
681  if __debug__:
682  _z3_assert(i < self.arity(), "Index out of bounds")
683  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
684 
685  def range(self):
686  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
687 
688  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
689  >>> f.range()
690  Bool
691  """
692  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
693 
694  def kind(self):
695  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
696 
697  >>> x = Int('x')
698  >>> d = (x + 1).decl()
699  >>> d.kind() == Z3_OP_ADD
700  True
701  >>> d.kind() == Z3_OP_MUL
702  False
703  """
704  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
705 
706  def params(self):
707  ctx = self.ctx
708  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
709  result = [ None for i in range(n) ]
710  for i in range(n):
711  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
712  if k == Z3_PARAMETER_INT:
713  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
714  elif k == Z3_PARAMETER_DOUBLE:
715  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
716  elif k == Z3_PARAMETER_RATIONAL:
717  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
718  elif k == Z3_PARAMETER_SYMBOL:
719  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
720  elif k == Z3_PARAMETER_SORT:
721  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
722  elif k == Z3_PARAMETER_AST:
723  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
724  elif k == Z3_PARAMETER_FUNC_DECL:
725  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
726  else:
727  assert(False)
728  return result
729 
730  def __call__(self, *args):
731  """Create a Z3 application expression using the function `self`, and the given arguments.
732 
733  The arguments must be Z3 expressions. This method assumes that
734  the sorts of the elements in `args` match the sorts of the
735  domain. Limited coercion is supported. For example, if
736  args[0] is a Python integer, and the function expects a Z3
737  integer, then the argument is automatically converted into a
738  Z3 integer.
739 
740  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
741  >>> x = Int('x')
742  >>> y = Real('y')
743  >>> f(x, y)
744  f(x, y)
745  >>> f(x, x)
746  f(x, ToReal(x))
747  """
748  args = _get_args(args)
749  num = len(args)
750  if __debug__:
751  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
752  _args = (Ast * num)()
753  saved = []
754  for i in range(num):
755  # self.domain(i).cast(args[i]) may create a new Z3 expression,
756  # then we must save in 'saved' to prevent it from being garbage collected.
757  tmp = self.domain(i).cast(args[i])
758  saved.append(tmp)
759  _args[i] = tmp.as_ast()
760  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
761 
763  """Return `True` if `a` is a Z3 function declaration.
764 
765  >>> f = Function('f', IntSort(), IntSort())
766  >>> is_func_decl(f)
767  True
768  >>> x = Real('x')
769  >>> is_func_decl(x)
770  False
771  """
772  return isinstance(a, FuncDeclRef)
773 
774 def Function(name, *sig):
775  """Create a new Z3 uninterpreted function with the given sorts.
776 
777  >>> f = Function('f', IntSort(), IntSort())
778  >>> f(f(0))
779  f(f(0))
780  """
781  sig = _get_args(sig)
782  if __debug__:
783  _z3_assert(len(sig) > 0, "At least two arguments expected")
784  arity = len(sig) - 1
785  rng = sig[arity]
786  if __debug__:
787  _z3_assert(is_sort(rng), "Z3 sort expected")
788  dom = (Sort * arity)()
789  for i in range(arity):
790  if __debug__:
791  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
792  dom[i] = sig[i].ast
793  ctx = rng.ctx
794  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
795 
796 def _to_func_decl_ref(a, ctx):
797  return FuncDeclRef(a, ctx)
798 
799 
804 
806  """Constraints, formulas and terms are expressions in Z3.
807 
808  Expressions are ASTs. Every expression has a sort.
809  There are three main kinds of expressions:
810  function applications, quantifiers and bounded variables.
811  A constant is a function application with 0 arguments.
812  For quantifier free problems, all expressions are
813  function applications.
814  """
815  def as_ast(self):
816  return self.ast
817 
818  def get_id(self):
819  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
820 
821  def sort(self):
822  """Return the sort of expression `self`.
823 
824  >>> x = Int('x')
825  >>> (x + 1).sort()
826  Int
827  >>> y = Real('y')
828  >>> (x + y).sort()
829  Real
830  """
831  return _sort(self.ctx, self.as_ast())
832 
833  def sort_kind(self):
834  """Shorthand for `self.sort().kind()`.
835 
836  >>> a = Array('a', IntSort(), IntSort())
837  >>> a.sort_kind() == Z3_ARRAY_SORT
838  True
839  >>> a.sort_kind() == Z3_INT_SORT
840  False
841  """
842  return self.sort().kind()
843 
844  def __eq__(self, other):
845  """Return a Z3 expression that represents the constraint `self == other`.
846 
847  If `other` is `None`, then this method simply returns `False`.
848 
849  >>> a = Int('a')
850  >>> b = Int('b')
851  >>> a == b
852  a == b
853  >>> a is None
854  False
855  """
856  if other is None:
857  return False
858  a, b = _coerce_exprs(self, other)
859  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
860 
861  def __hash__(self):
862  """ Hash code. """
863  return AstRef.__hash__(self)
864 
865  def __ne__(self, other):
866  """Return a Z3 expression that represents the constraint `self != other`.
867 
868  If `other` is `None`, then this method simply returns `True`.
869 
870  >>> a = Int('a')
871  >>> b = Int('b')
872  >>> a != b
873  a != b
874  >>> a is not None
875  True
876  """
877  if other is None:
878  return True
879  a, b = _coerce_exprs(self, other)
880  _args, sz = _to_ast_array((a, b))
881  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
882 
883  def params(self):
884  return self.decl().params()
885 
886  def decl(self):
887  """Return the Z3 function declaration associated with a Z3 application.
888 
889  >>> f = Function('f', IntSort(), IntSort())
890  >>> a = Int('a')
891  >>> t = f(a)
892  >>> eq(t.decl(), f)
893  True
894  >>> (a + 1).decl()
895  +
896  """
897  if __debug__:
898  _z3_assert(is_app(self), "Z3 application expected")
899  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
900 
901  def num_args(self):
902  """Return the number of arguments of a Z3 application.
903 
904  >>> a = Int('a')
905  >>> b = Int('b')
906  >>> (a + b).num_args()
907  2
908  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
909  >>> t = f(a, b, 0)
910  >>> t.num_args()
911  3
912  """
913  if __debug__:
914  _z3_assert(is_app(self), "Z3 application expected")
915  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
916 
917  def arg(self, idx):
918  """Return argument `idx` of the application `self`.
919 
920  This method assumes that `self` is a function application with at least `idx+1` arguments.
921 
922  >>> a = Int('a')
923  >>> b = Int('b')
924  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
925  >>> t = f(a, b, 0)
926  >>> t.arg(0)
927  a
928  >>> t.arg(1)
929  b
930  >>> t.arg(2)
931  0
932  """
933  if __debug__:
934  _z3_assert(is_app(self), "Z3 application expected")
935  _z3_assert(idx < self.num_args(), "Invalid argument index")
936  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
937 
938  def children(self):
939  """Return a list containing the children of the given expression
940 
941  >>> a = Int('a')
942  >>> b = Int('b')
943  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
944  >>> t = f(a, b, 0)
945  >>> t.children()
946  [a, b, 0]
947  """
948  if is_app(self):
949  return [self.arg(i) for i in range(self.num_args())]
950  else:
951  return []
952 
953 def _to_expr_ref(a, ctx):
954  if isinstance(a, Pattern):
955  return PatternRef(a, ctx)
956  ctx_ref = ctx.ref()
957  k = Z3_get_ast_kind(ctx_ref, a)
958  if k == Z3_QUANTIFIER_AST:
959  return QuantifierRef(a, ctx)
960  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
961  if sk == Z3_BOOL_SORT:
962  return BoolRef(a, ctx)
963  if sk == Z3_INT_SORT:
964  if k == Z3_NUMERAL_AST:
965  return IntNumRef(a, ctx)
966  return ArithRef(a, ctx)
967  if sk == Z3_REAL_SORT:
968  if k == Z3_NUMERAL_AST:
969  return RatNumRef(a, ctx)
970  if _is_algebraic(ctx, a):
971  return AlgebraicNumRef(a, ctx)
972  return ArithRef(a, ctx)
973  if sk == Z3_BV_SORT:
974  if k == Z3_NUMERAL_AST:
975  return BitVecNumRef(a, ctx)
976  else:
977  return BitVecRef(a, ctx)
978  if sk == Z3_ARRAY_SORT:
979  return ArrayRef(a, ctx)
980  if sk == Z3_DATATYPE_SORT:
981  return DatatypeRef(a, ctx)
982  if sk == Z3_FLOATING_POINT_SORT:
983  if k == Z3_APP_AST and _is_numeral(ctx, a):
984  return FPNumRef(a, ctx)
985  else:
986  return FPRef(a, ctx)
987  if sk == Z3_FINITE_DOMAIN_SORT:
988  if k == Z3_NUMERAL_AST:
989  return FiniteDomainNumRef(a, ctx)
990  else:
991  return FiniteDomainRef(a, ctx)
992  if sk == Z3_ROUNDING_MODE_SORT:
993  return FPRMRef(a, ctx)
994  if sk == Z3_SEQ_SORT:
995  return SeqRef(a, ctx)
996  if sk == Z3_RE_SORT:
997  return ReRef(a, ctx)
998  return ExprRef(a, ctx)
999 
1000 def _coerce_expr_merge(s, a):
1001  if is_expr(a):
1002  s1 = a.sort()
1003  if s is None:
1004  return s1
1005  if s1.eq(s):
1006  return s
1007  elif s.subsort(s1):
1008  return s1
1009  elif s1.subsort(s):
1010  return s
1011  else:
1012  if __debug__:
1013  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1014  _z3_assert(False, "sort mismatch")
1015  else:
1016  return s
1017 
1018 def _coerce_exprs(a, b, ctx=None):
1019  if not is_expr(a) and not is_expr(b):
1020  a = _py2expr(a, ctx)
1021  b = _py2expr(b, ctx)
1022  s = None
1023  s = _coerce_expr_merge(s, a)
1024  s = _coerce_expr_merge(s, b)
1025  a = s.cast(a)
1026  b = s.cast(b)
1027  return (a, b)
1028 
1029 
1030 def _reduce(f, l, a):
1031  r = a
1032  for e in l:
1033  r = f(r, e)
1034  return r
1035 
1036 def _coerce_expr_list(alist, ctx=None):
1037  has_expr = False
1038  for a in alist:
1039  if is_expr(a):
1040  has_expr = True
1041  break
1042  if not has_expr:
1043  alist = [ _py2expr(a, ctx) for a in alist ]
1044  s = _reduce(_coerce_expr_merge, alist, None)
1045  return [ s.cast(a) for a in alist ]
1046 
1047 def is_expr(a):
1048  """Return `True` if `a` is a Z3 expression.
1049 
1050  >>> a = Int('a')
1051  >>> is_expr(a)
1052  True
1053  >>> is_expr(a + 1)
1054  True
1055  >>> is_expr(IntSort())
1056  False
1057  >>> is_expr(1)
1058  False
1059  >>> is_expr(IntVal(1))
1060  True
1061  >>> x = Int('x')
1062  >>> is_expr(ForAll(x, x >= 0))
1063  True
1064  >>> is_expr(FPVal(1.0))
1065  True
1066  """
1067  return isinstance(a, ExprRef)
1068 
1069 def is_app(a):
1070  """Return `True` if `a` is a Z3 function application.
1071 
1072  Note that, constants are function applications with 0 arguments.
1073 
1074  >>> a = Int('a')
1075  >>> is_app(a)
1076  True
1077  >>> is_app(a + 1)
1078  True
1079  >>> is_app(IntSort())
1080  False
1081  >>> is_app(1)
1082  False
1083  >>> is_app(IntVal(1))
1084  True
1085  >>> x = Int('x')
1086  >>> is_app(ForAll(x, x >= 0))
1087  False
1088  """
1089  if not isinstance(a, ExprRef):
1090  return False
1091  k = _ast_kind(a.ctx, a)
1092  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1093 
1094 def is_const(a):
1095  """Return `True` if `a` is Z3 constant/variable expression.
1096 
1097  >>> a = Int('a')
1098  >>> is_const(a)
1099  True
1100  >>> is_const(a + 1)
1101  False
1102  >>> is_const(1)
1103  False
1104  >>> is_const(IntVal(1))
1105  True
1106  >>> x = Int('x')
1107  >>> is_const(ForAll(x, x >= 0))
1108  False
1109  """
1110  return is_app(a) and a.num_args() == 0
1111 
1112 def is_var(a):
1113  """Return `True` if `a` is variable.
1114 
1115  Z3 uses de-Bruijn indices for representing bound variables in
1116  quantifiers.
1117 
1118  >>> x = Int('x')
1119  >>> is_var(x)
1120  False
1121  >>> is_const(x)
1122  True
1123  >>> f = Function('f', IntSort(), IntSort())
1124  >>> # Z3 replaces x with bound variables when ForAll is executed.
1125  >>> q = ForAll(x, f(x) == x)
1126  >>> b = q.body()
1127  >>> b
1128  f(Var(0)) == Var(0)
1129  >>> b.arg(1)
1130  Var(0)
1131  >>> is_var(b.arg(1))
1132  True
1133  """
1134  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1135 
1137  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1138 
1139  >>> x = Int('x')
1140  >>> y = Int('y')
1141  >>> is_var(x)
1142  False
1143  >>> is_const(x)
1144  True
1145  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1146  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1147  >>> q = ForAll([x, y], f(x, y) == x + y)
1148  >>> q.body()
1149  f(Var(1), Var(0)) == Var(1) + Var(0)
1150  >>> b = q.body()
1151  >>> b.arg(0)
1152  f(Var(1), Var(0))
1153  >>> v1 = b.arg(0).arg(0)
1154  >>> v2 = b.arg(0).arg(1)
1155  >>> v1
1156  Var(1)
1157  >>> v2
1158  Var(0)
1159  >>> get_var_index(v1)
1160  1
1161  >>> get_var_index(v2)
1162  0
1163  """
1164  if __debug__:
1165  _z3_assert(is_var(a), "Z3 bound variable expected")
1166  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1167 
1168 def is_app_of(a, k):
1169  """Return `True` if `a` is an application of the given kind `k`.
1170 
1171  >>> x = Int('x')
1172  >>> n = x + 1
1173  >>> is_app_of(n, Z3_OP_ADD)
1174  True
1175  >>> is_app_of(n, Z3_OP_MUL)
1176  False
1177  """
1178  return is_app(a) and a.decl().kind() == k
1179 
1180 def If(a, b, c, ctx=None):
1181  """Create a Z3 if-then-else expression.
1182 
1183  >>> x = Int('x')
1184  >>> y = Int('y')
1185  >>> max = If(x > y, x, y)
1186  >>> max
1187  If(x > y, x, y)
1188  >>> simplify(max)
1189  If(x <= y, y, x)
1190  """
1191  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1192  return Cond(a, b, c, ctx)
1193  else:
1194  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1195  s = BoolSort(ctx)
1196  a = s.cast(a)
1197  b, c = _coerce_exprs(b, c, ctx)
1198  if __debug__:
1199  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1200  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1201 
1202 def Distinct(*args):
1203  """Create a Z3 distinct expression.
1204 
1205  >>> x = Int('x')
1206  >>> y = Int('y')
1207  >>> Distinct(x, y)
1208  x != y
1209  >>> z = Int('z')
1210  >>> Distinct(x, y, z)
1211  Distinct(x, y, z)
1212  >>> simplify(Distinct(x, y, z))
1213  Distinct(x, y, z)
1214  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1215  And(Not(x == y), Not(x == z), Not(y == z))
1216  """
1217  args = _get_args(args)
1218  ctx = _ctx_from_ast_arg_list(args)
1219  if __debug__:
1220  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1221  args = _coerce_expr_list(args, ctx)
1222  _args, sz = _to_ast_array(args)
1223  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1224 
1225 def _mk_bin(f, a, b):
1226  args = (Ast * 2)()
1227  if __debug__:
1228  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1229  args[0] = a.as_ast()
1230  args[1] = b.as_ast()
1231  return f(a.ctx.ref(), 2, args)
1232 
1233 def Const(name, sort):
1234  """Create a constant of the given sort.
1235 
1236  >>> Const('x', IntSort())
1237  x
1238  """
1239  if __debug__:
1240  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1241  ctx = sort.ctx
1242  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1243 
1244 def Consts(names, sort):
1245  """Create a several constants of the given sort.
1246 
1247  `names` is a string containing the names of all constants to be created.
1248  Blank spaces separate the names of different constants.
1249 
1250  >>> x, y, z = Consts('x y z', IntSort())
1251  >>> x + y + z
1252  x + y + z
1253  """
1254  if isinstance(names, str):
1255  names = names.split(" ")
1256  return [Const(name, sort) for name in names]
1257 
1258 def Var(idx, s):
1259  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1260 
1261  >>> Var(0, IntSort())
1262  Var(0)
1263  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1264  False
1265  """
1266  if __debug__:
1267  _z3_assert(is_sort(s), "Z3 sort expected")
1268  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1269 
1270 def RealVar(idx, ctx=None):
1271  """
1272  Create a real free variable. Free variables are used to create quantified formulas.
1273  They are also used to create polynomials.
1274 
1275  >>> RealVar(0)
1276  Var(0)
1277  """
1278  return Var(idx, RealSort(ctx))
1279 
1280 def RealVarVector(n, ctx=None):
1281  """
1282  Create a list of Real free variables.
1283  The variables have ids: 0, 1, ..., n-1
1284 
1285  >>> x0, x1, x2, x3 = RealVarVector(4)
1286  >>> x2
1287  Var(2)
1288  """
1289  return [ RealVar(i, ctx) for i in range(n) ]
1290 
1291 
1296 
1298  """Boolean sort."""
1299  def cast(self, val):
1300  """Try to cast `val` as a Boolean.
1301 
1302  >>> x = BoolSort().cast(True)
1303  >>> x
1304  True
1305  >>> is_expr(x)
1306  True
1307  >>> is_expr(True)
1308  False
1309  >>> x.sort()
1310  Bool
1311  """
1312  if isinstance(val, bool):
1313  return BoolVal(val, self.ctx)
1314  if __debug__:
1315  if not is_expr(val):
1316  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1317  if not self.eq(val.sort()):
1318  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1319  return val
1320 
1321  def subsort(self, other):
1322  return isinstance(other, ArithSortRef)
1323 
1324  def is_int(self):
1325  return True
1326 
1327  def is_bool(self):
1328  return True
1329 
1330 
1332  """All Boolean expressions are instances of this class."""
1333  def sort(self):
1334  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1335 
1336  def __rmul__(self, other):
1337  return self * other
1338 
1339  def __mul__(self, other):
1340  """Create the Z3 expression `self * other`.
1341  """
1342  if other == 1:
1343  return self
1344  if other == 0:
1345  return 0
1346  return If(self, other, 0)
1347 
1348 
1349 def is_bool(a):
1350  """Return `True` if `a` is a Z3 Boolean expression.
1351 
1352  >>> p = Bool('p')
1353  >>> is_bool(p)
1354  True
1355  >>> q = Bool('q')
1356  >>> is_bool(And(p, q))
1357  True
1358  >>> x = Real('x')
1359  >>> is_bool(x)
1360  False
1361  >>> is_bool(x == 0)
1362  True
1363  """
1364  return isinstance(a, BoolRef)
1365 
1366 def is_true(a):
1367  """Return `True` if `a` is the Z3 true expression.
1368 
1369  >>> p = Bool('p')
1370  >>> is_true(p)
1371  False
1372  >>> is_true(simplify(p == p))
1373  True
1374  >>> x = Real('x')
1375  >>> is_true(x == 0)
1376  False
1377  >>> # True is a Python Boolean expression
1378  >>> is_true(True)
1379  False
1380  """
1381  return is_app_of(a, Z3_OP_TRUE)
1382 
1383 def is_false(a):
1384  """Return `True` if `a` is the Z3 false expression.
1385 
1386  >>> p = Bool('p')
1387  >>> is_false(p)
1388  False
1389  >>> is_false(False)
1390  False
1391  >>> is_false(BoolVal(False))
1392  True
1393  """
1394  return is_app_of(a, Z3_OP_FALSE)
1395 
1396 def is_and(a):
1397  """Return `True` if `a` is a Z3 and expression.
1398 
1399  >>> p, q = Bools('p q')
1400  >>> is_and(And(p, q))
1401  True
1402  >>> is_and(Or(p, q))
1403  False
1404  """
1405  return is_app_of(a, Z3_OP_AND)
1406 
1407 def is_or(a):
1408  """Return `True` if `a` is a Z3 or expression.
1409 
1410  >>> p, q = Bools('p q')
1411  >>> is_or(Or(p, q))
1412  True
1413  >>> is_or(And(p, q))
1414  False
1415  """
1416  return is_app_of(a, Z3_OP_OR)
1417 
1418 def is_not(a):
1419  """Return `True` if `a` is a Z3 not expression.
1420 
1421  >>> p = Bool('p')
1422  >>> is_not(p)
1423  False
1424  >>> is_not(Not(p))
1425  True
1426  """
1427  return is_app_of(a, Z3_OP_NOT)
1428 
1429 def is_eq(a):
1430  """Return `True` if `a` is a Z3 equality expression.
1431 
1432  >>> x, y = Ints('x y')
1433  >>> is_eq(x == y)
1434  True
1435  """
1436  return is_app_of(a, Z3_OP_EQ)
1437 
1439  """Return `True` if `a` is a Z3 distinct expression.
1440 
1441  >>> x, y, z = Ints('x y z')
1442  >>> is_distinct(x == y)
1443  False
1444  >>> is_distinct(Distinct(x, y, z))
1445  True
1446  """
1447  return is_app_of(a, Z3_OP_DISTINCT)
1448 
1449 def BoolSort(ctx=None):
1450  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1451 
1452  >>> BoolSort()
1453  Bool
1454  >>> p = Const('p', BoolSort())
1455  >>> is_bool(p)
1456  True
1457  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1458  >>> r(0, 1)
1459  r(0, 1)
1460  >>> is_bool(r(0, 1))
1461  True
1462  """
1463  ctx = _get_ctx(ctx)
1464  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1465 
1466 def BoolVal(val, ctx=None):
1467  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1468 
1469  >>> BoolVal(True)
1470  True
1471  >>> is_true(BoolVal(True))
1472  True
1473  >>> is_true(True)
1474  False
1475  >>> is_false(BoolVal(False))
1476  True
1477  """
1478  ctx = _get_ctx(ctx)
1479  if val == False:
1480  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1481  else:
1482  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1483 
1484 def Bool(name, ctx=None):
1485  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1486 
1487  >>> p = Bool('p')
1488  >>> q = Bool('q')
1489  >>> And(p, q)
1490  And(p, q)
1491  """
1492  ctx = _get_ctx(ctx)
1493  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1494 
1495 def Bools(names, ctx=None):
1496  """Return a tuple of Boolean constants.
1497 
1498  `names` is a single string containing all names separated by blank spaces.
1499  If `ctx=None`, then the global context is used.
1500 
1501  >>> p, q, r = Bools('p q r')
1502  >>> And(p, Or(q, r))
1503  And(p, Or(q, r))
1504  """
1505  ctx = _get_ctx(ctx)
1506  if isinstance(names, str):
1507  names = names.split(" ")
1508  return [Bool(name, ctx) for name in names]
1509 
1510 def BoolVector(prefix, sz, ctx=None):
1511  """Return a list of Boolean constants of size `sz`.
1512 
1513  The constants are named using the given prefix.
1514  If `ctx=None`, then the global context is used.
1515 
1516  >>> P = BoolVector('p', 3)
1517  >>> P
1518  [p__0, p__1, p__2]
1519  >>> And(P)
1520  And(p__0, p__1, p__2)
1521  """
1522  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1523 
1524 def FreshBool(prefix='b', ctx=None):
1525  """Return a fresh Boolean constant in the given context using the given prefix.
1526 
1527  If `ctx=None`, then the global context is used.
1528 
1529  >>> b1 = FreshBool()
1530  >>> b2 = FreshBool()
1531  >>> eq(b1, b2)
1532  False
1533  """
1534  ctx = _get_ctx(ctx)
1535  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1536 
1537 def Implies(a, b, ctx=None):
1538  """Create a Z3 implies expression.
1539 
1540  >>> p, q = Bools('p q')
1541  >>> Implies(p, q)
1542  Implies(p, q)
1543  >>> simplify(Implies(p, q))
1544  Or(Not(p), q)
1545  """
1546  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1547  s = BoolSort(ctx)
1548  a = s.cast(a)
1549  b = s.cast(b)
1550  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1551 
1552 def Xor(a, b, ctx=None):
1553  """Create a Z3 Xor expression.
1554 
1555  >>> p, q = Bools('p q')
1556  >>> Xor(p, q)
1557  Xor(p, q)
1558  >>> simplify(Xor(p, q))
1559  Not(p) == q
1560  """
1561  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1562  s = BoolSort(ctx)
1563  a = s.cast(a)
1564  b = s.cast(b)
1565  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1566 
1567 def Not(a, ctx=None):
1568  """Create a Z3 not expression or probe.
1569 
1570  >>> p = Bool('p')
1571  >>> Not(Not(p))
1572  Not(Not(p))
1573  >>> simplify(Not(Not(p)))
1574  p
1575  """
1576  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1577  if is_probe(a):
1578  # Not is also used to build probes
1579  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1580  else:
1581  s = BoolSort(ctx)
1582  a = s.cast(a)
1583  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1584 
1585 def _has_probe(args):
1586  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1587  for arg in args:
1588  if is_probe(arg):
1589  return True
1590  return False
1591 
1592 def And(*args):
1593  """Create a Z3 and-expression or and-probe.
1594 
1595  >>> p, q, r = Bools('p q r')
1596  >>> And(p, q, r)
1597  And(p, q, r)
1598  >>> P = BoolVector('p', 5)
1599  >>> And(P)
1600  And(p__0, p__1, p__2, p__3, p__4)
1601  """
1602  last_arg = None
1603  if len(args) > 0:
1604  last_arg = args[len(args)-1]
1605  if isinstance(last_arg, Context):
1606  ctx = args[len(args)-1]
1607  args = args[:len(args)-1]
1608  elif len(args) == 1 and isinstance(args[0], AstVector):
1609  ctx = args[0].ctx
1610  args = [a for a in args[0]]
1611  else:
1612  ctx = main_ctx()
1613  args = _get_args(args)
1614  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1615  if __debug__:
1616  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1617  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1618  if _has_probe(args):
1619  return _probe_and(args, ctx)
1620  else:
1621  args = _coerce_expr_list(args, ctx)
1622  _args, sz = _to_ast_array(args)
1623  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1624 
1625 def Or(*args):
1626  """Create a Z3 or-expression or or-probe.
1627 
1628  >>> p, q, r = Bools('p q r')
1629  >>> Or(p, q, r)
1630  Or(p, q, r)
1631  >>> P = BoolVector('p', 5)
1632  >>> Or(P)
1633  Or(p__0, p__1, p__2, p__3, p__4)
1634  """
1635  last_arg = None
1636  if len(args) > 0:
1637  last_arg = args[len(args)-1]
1638  if isinstance(last_arg, Context):
1639  ctx = args[len(args)-1]
1640  args = args[:len(args)-1]
1641  else:
1642  ctx = main_ctx()
1643  args = _get_args(args)
1644  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1645  if __debug__:
1646  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1647  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1648  if _has_probe(args):
1649  return _probe_or(args, ctx)
1650  else:
1651  args = _coerce_expr_list(args, ctx)
1652  _args, sz = _to_ast_array(args)
1653  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1654 
1655 #########################################
1656 #
1657 # Patterns
1658 #
1659 #########################################
1660 
1661 class PatternRef(ExprRef):
1662  """Patterns are hints for quantifier instantiation.
1663 
1664  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1665  """
1666  def as_ast(self):
1667  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1668 
1669  def get_id(self):
1670  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1671 
1672 def is_pattern(a):
1673  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1674 
1675  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1676 
1677  >>> f = Function('f', IntSort(), IntSort())
1678  >>> x = Int('x')
1679  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1680  >>> q
1681  ForAll(x, f(x) == 0)
1682  >>> q.num_patterns()
1683  1
1684  >>> is_pattern(q.pattern(0))
1685  True
1686  >>> q.pattern(0)
1687  f(Var(0))
1688  """
1689  return isinstance(a, PatternRef)
1690 
1691 def MultiPattern(*args):
1692  """Create a Z3 multi-pattern using the given expressions `*args`
1693 
1694  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1695 
1696  >>> f = Function('f', IntSort(), IntSort())
1697  >>> g = Function('g', IntSort(), IntSort())
1698  >>> x = Int('x')
1699  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1700  >>> q
1701  ForAll(x, f(x) != g(x))
1702  >>> q.num_patterns()
1703  1
1704  >>> is_pattern(q.pattern(0))
1705  True
1706  >>> q.pattern(0)
1707  MultiPattern(f(Var(0)), g(Var(0)))
1708  """
1709  if __debug__:
1710  _z3_assert(len(args) > 0, "At least one argument expected")
1711  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1712  ctx = args[0].ctx
1713  args, sz = _to_ast_array(args)
1714  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1715 
1716 def _to_pattern(arg):
1717  if is_pattern(arg):
1718  return arg
1719  else:
1720  return MultiPattern(arg)
1721 
1722 #########################################
1723 #
1724 # Quantifiers
1725 #
1726 #########################################
1727 
1728 class QuantifierRef(BoolRef):
1729  """Universally and Existentially quantified formulas."""
1730 
1731  def as_ast(self):
1732  return self.ast
1733 
1734  def get_id(self):
1735  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1736 
1737  def sort(self):
1738  """Return the Boolean sort."""
1739  return BoolSort(self.ctx)
1740 
1741  def is_forall(self):
1742  """Return `True` if `self` is a universal quantifier.
1743 
1744  >>> f = Function('f', IntSort(), IntSort())
1745  >>> x = Int('x')
1746  >>> q = ForAll(x, f(x) == 0)
1747  >>> q.is_forall()
1748  True
1749  >>> q = Exists(x, f(x) != 0)
1750  >>> q.is_forall()
1751  False
1752  """
1753  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1754 
1755  def weight(self):
1756  """Return the weight annotation of `self`.
1757 
1758  >>> f = Function('f', IntSort(), IntSort())
1759  >>> x = Int('x')
1760  >>> q = ForAll(x, f(x) == 0)
1761  >>> q.weight()
1762  1
1763  >>> q = ForAll(x, f(x) == 0, weight=10)
1764  >>> q.weight()
1765  10
1766  """
1767  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1768 
1769  def num_patterns(self):
1770  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1771 
1772  >>> f = Function('f', IntSort(), IntSort())
1773  >>> g = Function('g', IntSort(), IntSort())
1774  >>> x = Int('x')
1775  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1776  >>> q.num_patterns()
1777  2
1778  """
1779  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1780 
1781  def pattern(self, idx):
1782  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1783 
1784  >>> f = Function('f', IntSort(), IntSort())
1785  >>> g = Function('g', IntSort(), IntSort())
1786  >>> x = Int('x')
1787  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1788  >>> q.num_patterns()
1789  2
1790  >>> q.pattern(0)
1791  f(Var(0))
1792  >>> q.pattern(1)
1793  g(Var(0))
1794  """
1795  if __debug__:
1796  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1797  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1798 
1799  def num_no_patterns(self):
1800  """Return the number of no-patterns."""
1801  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1802 
1803  def no_pattern(self, idx):
1804  """Return a no-pattern."""
1805  if __debug__:
1806  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1807  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1808 
1809  def body(self):
1810  """Return the expression being quantified.
1811 
1812  >>> f = Function('f', IntSort(), IntSort())
1813  >>> x = Int('x')
1814  >>> q = ForAll(x, f(x) == 0)
1815  >>> q.body()
1816  f(Var(0)) == 0
1817  """
1818  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1819 
1820  def num_vars(self):
1821  """Return the number of variables bounded by this quantifier.
1822 
1823  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1824  >>> x = Int('x')
1825  >>> y = Int('y')
1826  >>> q = ForAll([x, y], f(x, y) >= x)
1827  >>> q.num_vars()
1828  2
1829  """
1830  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1831 
1832  def var_name(self, idx):
1833  """Return a string representing a name used when displaying the quantifier.
1834 
1835  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1836  >>> x = Int('x')
1837  >>> y = Int('y')
1838  >>> q = ForAll([x, y], f(x, y) >= x)
1839  >>> q.var_name(0)
1840  'x'
1841  >>> q.var_name(1)
1842  'y'
1843  """
1844  if __debug__:
1845  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1846  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1847 
1848  def var_sort(self, idx):
1849  """Return the sort of a bound variable.
1850 
1851  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1852  >>> x = Int('x')
1853  >>> y = Real('y')
1854  >>> q = ForAll([x, y], f(x, y) >= x)
1855  >>> q.var_sort(0)
1856  Int
1857  >>> q.var_sort(1)
1858  Real
1859  """
1860  if __debug__:
1861  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1862  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1863 
1864  def children(self):
1865  """Return a list containing a single element self.body()
1866 
1867  >>> f = Function('f', IntSort(), IntSort())
1868  >>> x = Int('x')
1869  >>> q = ForAll(x, f(x) == 0)
1870  >>> q.children()
1871  [f(Var(0)) == 0]
1872  """
1873  return [ self.body() ]
1874 
1875 def is_quantifier(a):
1876  """Return `True` if `a` is a Z3 quantifier.
1877 
1878  >>> f = Function('f', IntSort(), IntSort())
1879  >>> x = Int('x')
1880  >>> q = ForAll(x, f(x) == 0)
1881  >>> is_quantifier(q)
1882  True
1883  >>> is_quantifier(f(x))
1884  False
1885  """
1886  return isinstance(a, QuantifierRef)
1887 
1888 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1889  if __debug__:
1890  _z3_assert(is_bool(body), "Z3 expression expected")
1891  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1892  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1893  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1894  ctx = body.ctx
1895  if is_app(vs):
1896  vs = [vs]
1897  num_vars = len(vs)
1898  if num_vars == 0:
1899  return body
1900  _vs = (Ast * num_vars)()
1901  for i in range(num_vars):
1902  ## TODO: Check if is constant
1903  _vs[i] = vs[i].as_ast()
1904  patterns = [ _to_pattern(p) for p in patterns ]
1905  num_pats = len(patterns)
1906  _pats = (Pattern * num_pats)()
1907  for i in range(num_pats):
1908  _pats[i] = patterns[i].ast
1909  _no_pats, num_no_pats = _to_ast_array(no_patterns)
1910  qid = to_symbol(qid, ctx)
1911  skid = to_symbol(skid, ctx)
1912  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
1913  num_vars, _vs,
1914  num_pats, _pats,
1915  num_no_pats, _no_pats,
1916  body.as_ast()), ctx)
1917 
1918 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1919  """Create a Z3 forall formula.
1920 
1921  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1922 
1923  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1924 
1925  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1926  >>> x = Int('x')
1927  >>> y = Int('y')
1928  >>> ForAll([x, y], f(x, y) >= x)
1929  ForAll([x, y], f(x, y) >= x)
1930  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
1931  ForAll([x, y], f(x, y) >= x)
1932  >>> ForAll([x, y], f(x, y) >= x, weight=10)
1933  ForAll([x, y], f(x, y) >= x)
1934  """
1935  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
1936 
1937 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1938  """Create a Z3 exists formula.
1939 
1940  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1941 
1942  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1943 
1944  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1945  >>> x = Int('x')
1946  >>> y = Int('y')
1947  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
1948  >>> q
1949  Exists([x, y], f(x, y) >= x)
1950  >>> is_quantifier(q)
1951  True
1952  >>> r = Tactic('nnf')(q).as_expr()
1953  >>> is_quantifier(r)
1954  False
1955  """
1956  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
1957 
1958 #########################################
1959 #
1960 # Arithmetic
1961 #
1962 #########################################
1963 
1964 class ArithSortRef(SortRef):
1965  """Real and Integer sorts."""
1966 
1967  def is_real(self):
1968  """Return `True` if `self` is of the sort Real.
1969 
1970  >>> x = Real('x')
1971  >>> x.is_real()
1972  True
1973  >>> (x + 1).is_real()
1974  True
1975  >>> x = Int('x')
1976  >>> x.is_real()
1977  False
1978  """
1979  return self.kind() == Z3_REAL_SORT
1980 
1981  def is_int(self):
1982  """Return `True` if `self` is of the sort Integer.
1983 
1984  >>> x = Int('x')
1985  >>> x.is_int()
1986  True
1987  >>> (x + 1).is_int()
1988  True
1989  >>> x = Real('x')
1990  >>> x.is_int()
1991  False
1992  """
1993  return self.kind() == Z3_INT_SORT
1994 
1995  def subsort(self, other):
1996  """Return `True` if `self` is a subsort of `other`."""
1997  return self.is_int() and is_arith_sort(other) and other.is_real()
1998 
1999  def cast(self, val):
2000  """Try to cast `val` as an Integer or Real.
2001 
2002  >>> IntSort().cast(10)
2003  10
2004  >>> is_int(IntSort().cast(10))
2005  True
2006  >>> is_int(10)
2007  False
2008  >>> RealSort().cast(10)
2009  10
2010  >>> is_real(RealSort().cast(10))
2011  True
2012  """
2013  if is_expr(val):
2014  if __debug__:
2015  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2016  val_s = val.sort()
2017  if self.eq(val_s):
2018  return val
2019  if val_s.is_int() and self.is_real():
2020  return ToReal(val)
2021  if val_s.is_bool() and self.is_int():
2022  return If(val, 1, 0)
2023  if val_s.is_bool() and self.is_real():
2024  return ToReal(If(val, 1, 0))
2025  if __debug__:
2026  _z3_assert(False, "Z3 Integer/Real expression expected" )
2027  else:
2028  if self.is_int():
2029  return IntVal(val, self.ctx)
2030  if self.is_real():
2031  return RealVal(val, self.ctx)
2032  if __debug__:
2033  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2034 
2035 def is_arith_sort(s):
2036  """Return `True` if s is an arithmetical sort (type).
2037 
2038  >>> is_arith_sort(IntSort())
2039  True
2040  >>> is_arith_sort(RealSort())
2041  True
2042  >>> is_arith_sort(BoolSort())
2043  False
2044  >>> n = Int('x') + 1
2045  >>> is_arith_sort(n.sort())
2046  True
2047  """
2048  return isinstance(s, ArithSortRef)
2049 
2050 class ArithRef(ExprRef):
2051  """Integer and Real expressions."""
2052 
2053  def sort(self):
2054  """Return the sort (type) of the arithmetical expression `self`.
2055 
2056  >>> Int('x').sort()
2057  Int
2058  >>> (Real('x') + 1).sort()
2059  Real
2060  """
2061  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2062 
2063  def is_int(self):
2064  """Return `True` if `self` is an integer expression.
2065 
2066  >>> x = Int('x')
2067  >>> x.is_int()
2068  True
2069  >>> (x + 1).is_int()
2070  True
2071  >>> y = Real('y')
2072  >>> (x + y).is_int()
2073  False
2074  """
2075  return self.sort().is_int()
2076 
2077  def is_real(self):
2078  """Return `True` if `self` is an real expression.
2079 
2080  >>> x = Real('x')
2081  >>> x.is_real()
2082  True
2083  >>> (x + 1).is_real()
2084  True
2085  """
2086  return self.sort().is_real()
2087 
2088  def __add__(self, other):
2089  """Create the Z3 expression `self + other`.
2090 
2091  >>> x = Int('x')
2092  >>> y = Int('y')
2093  >>> x + y
2094  x + y
2095  >>> (x + y).sort()
2096  Int
2097  """
2098  a, b = _coerce_exprs(self, other)
2099  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2100 
2101  def __radd__(self, other):
2102  """Create the Z3 expression `other + self`.
2103 
2104  >>> x = Int('x')
2105  >>> 10 + x
2106  10 + x
2107  """
2108  a, b = _coerce_exprs(self, other)
2109  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2110 
2111  def __mul__(self, other):
2112  """Create the Z3 expression `self * other`.
2113 
2114  >>> x = Real('x')
2115  >>> y = Real('y')
2116  >>> x * y
2117  x*y
2118  >>> (x * y).sort()
2119  Real
2120  """
2121  a, b = _coerce_exprs(self, other)
2122  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2123 
2124  def __rmul__(self, other):
2125  """Create the Z3 expression `other * self`.
2126 
2127  >>> x = Real('x')
2128  >>> 10 * x
2129  10*x
2130  """
2131  a, b = _coerce_exprs(self, other)
2132  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2133 
2134  def __sub__(self, other):
2135  """Create the Z3 expression `self - other`.
2136 
2137  >>> x = Int('x')
2138  >>> y = Int('y')
2139  >>> x - y
2140  x - y
2141  >>> (x - y).sort()
2142  Int
2143  """
2144  a, b = _coerce_exprs(self, other)
2145  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2146 
2147  def __rsub__(self, other):
2148  """Create the Z3 expression `other - self`.
2149 
2150  >>> x = Int('x')
2151  >>> 10 - x
2152  10 - x
2153  """
2154  a, b = _coerce_exprs(self, other)
2155  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2156 
2157  def __pow__(self, other):
2158  """Create the Z3 expression `self**other` (** is the power operator).
2159 
2160  >>> x = Real('x')
2161  >>> x**3
2162  x**3
2163  >>> (x**3).sort()
2164  Real
2165  >>> simplify(IntVal(2)**8)
2166  256
2167  """
2168  a, b = _coerce_exprs(self, other)
2169  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2170 
2171  def __rpow__(self, other):
2172  """Create the Z3 expression `other**self` (** is the power operator).
2173 
2174  >>> x = Real('x')
2175  >>> 2**x
2176  2**x
2177  >>> (2**x).sort()
2178  Real
2179  >>> simplify(2**IntVal(8))
2180  256
2181  """
2182  a, b = _coerce_exprs(self, other)
2183  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2184 
2185  def __div__(self, other):
2186  """Create the Z3 expression `other/self`.
2187 
2188  >>> x = Int('x')
2189  >>> y = Int('y')
2190  >>> x/y
2191  x/y
2192  >>> (x/y).sort()
2193  Int
2194  >>> (x/y).sexpr()
2195  '(div x y)'
2196  >>> x = Real('x')
2197  >>> y = Real('y')
2198  >>> x/y
2199  x/y
2200  >>> (x/y).sort()
2201  Real
2202  >>> (x/y).sexpr()
2203  '(/ x y)'
2204  """
2205  a, b = _coerce_exprs(self, other)
2206  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2207 
2208  def __truediv__(self, other):
2209  """Create the Z3 expression `other/self`."""
2210  return self.__div__(other)
2211 
2212  def __rdiv__(self, other):
2213  """Create the Z3 expression `other/self`.
2214 
2215  >>> x = Int('x')
2216  >>> 10/x
2217  10/x
2218  >>> (10/x).sexpr()
2219  '(div 10 x)'
2220  >>> x = Real('x')
2221  >>> 10/x
2222  10/x
2223  >>> (10/x).sexpr()
2224  '(/ 10.0 x)'
2225  """
2226  a, b = _coerce_exprs(self, other)
2227  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2228 
2229  def __rtruediv__(self, other):
2230  """Create the Z3 expression `other/self`."""
2231  return self.__rdiv__(other)
2232 
2233  def __mod__(self, other):
2234  """Create the Z3 expression `other%self`.
2235 
2236  >>> x = Int('x')
2237  >>> y = Int('y')
2238  >>> x % y
2239  x%y
2240  >>> simplify(IntVal(10) % IntVal(3))
2241  1
2242  """
2243  a, b = _coerce_exprs(self, other)
2244  if __debug__:
2245  _z3_assert(a.is_int(), "Z3 integer expression expected")
2246  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2247 
2248  def __rmod__(self, other):
2249  """Create the Z3 expression `other%self`.
2250 
2251  >>> x = Int('x')
2252  >>> 10 % x
2253  10%x
2254  """
2255  a, b = _coerce_exprs(self, other)
2256  if __debug__:
2257  _z3_assert(a.is_int(), "Z3 integer expression expected")
2258  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2259 
2260  def __neg__(self):
2261  """Return an expression representing `-self`.
2262 
2263  >>> x = Int('x')
2264  >>> -x
2265  -x
2266  >>> simplify(-(-x))
2267  x
2268  """
2269  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2270 
2271  def __pos__(self):
2272  """Return `self`.
2273 
2274  >>> x = Int('x')
2275  >>> +x
2276  x
2277  """
2278  return self
2279 
2280  def __le__(self, other):
2281  """Create the Z3 expression `other <= self`.
2282 
2283  >>> x, y = Ints('x y')
2284  >>> x <= y
2285  x <= y
2286  >>> y = Real('y')
2287  >>> x <= y
2288  ToReal(x) <= y
2289  """
2290  a, b = _coerce_exprs(self, other)
2291  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2292 
2293  def __lt__(self, other):
2294  """Create the Z3 expression `other < self`.
2295 
2296  >>> x, y = Ints('x y')
2297  >>> x < y
2298  x < y
2299  >>> y = Real('y')
2300  >>> x < y
2301  ToReal(x) < y
2302  """
2303  a, b = _coerce_exprs(self, other)
2304  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2305 
2306  def __gt__(self, other):
2307  """Create the Z3 expression `other > self`.
2308 
2309  >>> x, y = Ints('x y')
2310  >>> x > y
2311  x > y
2312  >>> y = Real('y')
2313  >>> x > y
2314  ToReal(x) > y
2315  """
2316  a, b = _coerce_exprs(self, other)
2317  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2318 
2319  def __ge__(self, other):
2320  """Create the Z3 expression `other >= self`.
2321 
2322  >>> x, y = Ints('x y')
2323  >>> x >= y
2324  x >= y
2325  >>> y = Real('y')
2326  >>> x >= y
2327  ToReal(x) >= y
2328  """
2329  a, b = _coerce_exprs(self, other)
2330  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2331 
2332 def is_arith(a):
2333  """Return `True` if `a` is an arithmetical expression.
2334 
2335  >>> x = Int('x')
2336  >>> is_arith(x)
2337  True
2338  >>> is_arith(x + 1)
2339  True
2340  >>> is_arith(1)
2341  False
2342  >>> is_arith(IntVal(1))
2343  True
2344  >>> y = Real('y')
2345  >>> is_arith(y)
2346  True
2347  >>> is_arith(y + 1)
2348  True
2349  """
2350  return isinstance(a, ArithRef)
2351 
2352 def is_int(a):
2353  """Return `True` if `a` is an integer expression.
2354 
2355  >>> x = Int('x')
2356  >>> is_int(x + 1)
2357  True
2358  >>> is_int(1)
2359  False
2360  >>> is_int(IntVal(1))
2361  True
2362  >>> y = Real('y')
2363  >>> is_int(y)
2364  False
2365  >>> is_int(y + 1)
2366  False
2367  """
2368  return is_arith(a) and a.is_int()
2369 
2370 def is_real(a):
2371  """Return `True` if `a` is a real expression.
2372 
2373  >>> x = Int('x')
2374  >>> is_real(x + 1)
2375  False
2376  >>> y = Real('y')
2377  >>> is_real(y)
2378  True
2379  >>> is_real(y + 1)
2380  True
2381  >>> is_real(1)
2382  False
2383  >>> is_real(RealVal(1))
2384  True
2385  """
2386  return is_arith(a) and a.is_real()
2387 
2388 def _is_numeral(ctx, a):
2389  return Z3_is_numeral_ast(ctx.ref(), a)
2390 
2391 def _is_algebraic(ctx, a):
2392  return Z3_is_algebraic_number(ctx.ref(), a)
2393 
2394 def is_int_value(a):
2395  """Return `True` if `a` is an integer value of sort Int.
2396 
2397  >>> is_int_value(IntVal(1))
2398  True
2399  >>> is_int_value(1)
2400  False
2401  >>> is_int_value(Int('x'))
2402  False
2403  >>> n = Int('x') + 1
2404  >>> n
2405  x + 1
2406  >>> n.arg(1)
2407  1
2408  >>> is_int_value(n.arg(1))
2409  True
2410  >>> is_int_value(RealVal("1/3"))
2411  False
2412  >>> is_int_value(RealVal(1))
2413  False
2414  """
2415  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2416 
2417 def is_rational_value(a):
2418  """Return `True` if `a` is rational value of sort Real.
2419 
2420  >>> is_rational_value(RealVal(1))
2421  True
2422  >>> is_rational_value(RealVal("3/5"))
2423  True
2424  >>> is_rational_value(IntVal(1))
2425  False
2426  >>> is_rational_value(1)
2427  False
2428  >>> n = Real('x') + 1
2429  >>> n.arg(1)
2430  1
2431  >>> is_rational_value(n.arg(1))
2432  True
2433  >>> is_rational_value(Real('x'))
2434  False
2435  """
2436  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2437 
2438 def is_algebraic_value(a):
2439  """Return `True` if `a` is an algebraic value of sort Real.
2440 
2441  >>> is_algebraic_value(RealVal("3/5"))
2442  False
2443  >>> n = simplify(Sqrt(2))
2444  >>> n
2445  1.4142135623?
2446  >>> is_algebraic_value(n)
2447  True
2448  """
2449  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2450 
2451 def is_add(a):
2452  """Return `True` if `a` is an expression of the form b + c.
2453 
2454  >>> x, y = Ints('x y')
2455  >>> is_add(x + y)
2456  True
2457  >>> is_add(x - y)
2458  False
2459  """
2460  return is_app_of(a, Z3_OP_ADD)
2461 
2462 def is_mul(a):
2463  """Return `True` if `a` is an expression of the form b * c.
2464 
2465  >>> x, y = Ints('x y')
2466  >>> is_mul(x * y)
2467  True
2468  >>> is_mul(x - y)
2469  False
2470  """
2471  return is_app_of(a, Z3_OP_MUL)
2472 
2473 def is_sub(a):
2474  """Return `True` if `a` is an expression of the form b - c.
2475 
2476  >>> x, y = Ints('x y')
2477  >>> is_sub(x - y)
2478  True
2479  >>> is_sub(x + y)
2480  False
2481  """
2482  return is_app_of(a, Z3_OP_SUB)
2483 
2484 def is_div(a):
2485  """Return `True` if `a` is an expression of the form b / c.
2486 
2487  >>> x, y = Reals('x y')
2488  >>> is_div(x / y)
2489  True
2490  >>> is_div(x + y)
2491  False
2492  >>> x, y = Ints('x y')
2493  >>> is_div(x / y)
2494  False
2495  >>> is_idiv(x / y)
2496  True
2497  """
2498  return is_app_of(a, Z3_OP_DIV)
2499 
2500 def is_idiv(a):
2501  """Return `True` if `a` is an expression of the form b div c.
2502 
2503  >>> x, y = Ints('x y')
2504  >>> is_idiv(x / y)
2505  True
2506  >>> is_idiv(x + y)
2507  False
2508  """
2509  return is_app_of(a, Z3_OP_IDIV)
2510 
2511 def is_mod(a):
2512  """Return `True` if `a` is an expression of the form b % c.
2513 
2514  >>> x, y = Ints('x y')
2515  >>> is_mod(x % y)
2516  True
2517  >>> is_mod(x + y)
2518  False
2519  """
2520  return is_app_of(a, Z3_OP_MOD)
2521 
2522 def is_le(a):
2523  """Return `True` if `a` is an expression of the form b <= c.
2524 
2525  >>> x, y = Ints('x y')
2526  >>> is_le(x <= y)
2527  True
2528  >>> is_le(x < y)
2529  False
2530  """
2531  return is_app_of(a, Z3_OP_LE)
2532 
2533 def is_lt(a):
2534  """Return `True` if `a` is an expression of the form b < c.
2535 
2536  >>> x, y = Ints('x y')
2537  >>> is_lt(x < y)
2538  True
2539  >>> is_lt(x == y)
2540  False
2541  """
2542  return is_app_of(a, Z3_OP_LT)
2543 
2544 def is_ge(a):
2545  """Return `True` if `a` is an expression of the form b >= c.
2546 
2547  >>> x, y = Ints('x y')
2548  >>> is_ge(x >= y)
2549  True
2550  >>> is_ge(x == y)
2551  False
2552  """
2553  return is_app_of(a, Z3_OP_GE)
2554 
2555 def is_gt(a):
2556  """Return `True` if `a` is an expression of the form b > c.
2557 
2558  >>> x, y = Ints('x y')
2559  >>> is_gt(x > y)
2560  True
2561  >>> is_gt(x == y)
2562  False
2563  """
2564  return is_app_of(a, Z3_OP_GT)
2565 
2566 def is_is_int(a):
2567  """Return `True` if `a` is an expression of the form IsInt(b).
2568 
2569  >>> x = Real('x')
2570  >>> is_is_int(IsInt(x))
2571  True
2572  >>> is_is_int(x)
2573  False
2574  """
2575  return is_app_of(a, Z3_OP_IS_INT)
2576 
2577 def is_to_real(a):
2578  """Return `True` if `a` is an expression of the form ToReal(b).
2579 
2580  >>> x = Int('x')
2581  >>> n = ToReal(x)
2582  >>> n
2583  ToReal(x)
2584  >>> is_to_real(n)
2585  True
2586  >>> is_to_real(x)
2587  False
2588  """
2589  return is_app_of(a, Z3_OP_TO_REAL)
2590 
2591 def is_to_int(a):
2592  """Return `True` if `a` is an expression of the form ToInt(b).
2593 
2594  >>> x = Real('x')
2595  >>> n = ToInt(x)
2596  >>> n
2597  ToInt(x)
2598  >>> is_to_int(n)
2599  True
2600  >>> is_to_int(x)
2601  False
2602  """
2603  return is_app_of(a, Z3_OP_TO_INT)
2604 
2605 class IntNumRef(ArithRef):
2606  """Integer values."""
2607 
2608  def as_long(self):
2609  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2610 
2611  >>> v = IntVal(1)
2612  >>> v + 1
2613  1 + 1
2614  >>> v.as_long() + 1
2615  2
2616  """
2617  if __debug__:
2618  _z3_assert(self.is_int(), "Integer value expected")
2619  return int(self.as_string())
2620 
2621  def as_string(self):
2622  """Return a Z3 integer numeral as a Python string.
2623  >>> v = IntVal(100)
2624  >>> v.as_string()
2625  '100'
2626  """
2627  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2628 
2629 class RatNumRef(ArithRef):
2630  """Rational values."""
2631 
2632  def numerator(self):
2633  """ Return the numerator of a Z3 rational numeral.
2634 
2635  >>> is_rational_value(RealVal("3/5"))
2636  True
2637  >>> n = RealVal("3/5")
2638  >>> n.numerator()
2639  3
2640  >>> is_rational_value(Q(3,5))
2641  True
2642  >>> Q(3,5).numerator()
2643  3
2644  """
2645  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2646 
2647  def denominator(self):
2648  """ Return the denominator of a Z3 rational numeral.
2649 
2650  >>> is_rational_value(Q(3,5))
2651  True
2652  >>> n = Q(3,5)
2653  >>> n.denominator()
2654  5
2655  """
2656  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2657 
2658  def numerator_as_long(self):
2659  """ Return the numerator as a Python long.
2660 
2661  >>> v = RealVal(10000000000)
2662  >>> v
2663  10000000000
2664  >>> v + 1
2665  10000000000 + 1
2666  >>> v.numerator_as_long() + 1 == 10000000001
2667  True
2668  """
2669  return self.numerator().as_long()
2670 
2671  def denominator_as_long(self):
2672  """ Return the denominator as a Python long.
2673 
2674  >>> v = RealVal("1/3")
2675  >>> v
2676  1/3
2677  >>> v.denominator_as_long()
2678  3
2679  """
2680  return self.denominator().as_long()
2681 
2682  def is_int(self):
2683  return False
2684 
2685  def is_real(self):
2686  return True
2687 
2688  def is_int_value(self):
2689  return self.denominator().is_int() and self.denominator_as_long() == 1
2690 
2691  def as_long(self):
2692  _z3_assert(self.is_int(), "Expected integer fraction")
2693  return self.numerator_as_long()
2694 
2695  def as_decimal(self, prec):
2696  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2697 
2698  >>> v = RealVal("1/5")
2699  >>> v.as_decimal(3)
2700  '0.2'
2701  >>> v = RealVal("1/3")
2702  >>> v.as_decimal(3)
2703  '0.333?'
2704  """
2705  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2706 
2707  def as_string(self):
2708  """Return a Z3 rational numeral as a Python string.
2709 
2710  >>> v = Q(3,6)
2711  >>> v.as_string()
2712  '1/2'
2713  """
2714  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2715 
2716  def as_fraction(self):
2717  """Return a Z3 rational as a Python Fraction object.
2718 
2719  >>> v = RealVal("1/5")
2720  >>> v.as_fraction()
2721  Fraction(1, 5)
2722  """
2723  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2724 
2725 class AlgebraicNumRef(ArithRef):
2726  """Algebraic irrational values."""
2727 
2728  def approx(self, precision=10):
2729  """Return a Z3 rational number that approximates the algebraic number `self`.
2730  The result `r` is such that |r - self| <= 1/10^precision
2731 
2732  >>> x = simplify(Sqrt(2))
2733  >>> x.approx(20)
2734  6838717160008073720548335/4835703278458516698824704
2735  >>> x.approx(5)
2736  2965821/2097152
2737  """
2738  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2739  def as_decimal(self, prec):
2740  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2741 
2742  >>> x = simplify(Sqrt(2))
2743  >>> x.as_decimal(10)
2744  '1.4142135623?'
2745  >>> x.as_decimal(20)
2746  '1.41421356237309504880?'
2747  """
2748  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2749 
2750 def _py2expr(a, ctx=None):
2751  if isinstance(a, bool):
2752  return BoolVal(a, ctx)
2753  if _is_int(a):
2754  return IntVal(a, ctx)
2755  if isinstance(a, float):
2756  return RealVal(a, ctx)
2757  if __debug__:
2758  _z3_assert(False, "Python bool, int, long or float expected")
2759 
2760 def IntSort(ctx=None):
2761  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2762 
2763  >>> IntSort()
2764  Int
2765  >>> x = Const('x', IntSort())
2766  >>> is_int(x)
2767  True
2768  >>> x.sort() == IntSort()
2769  True
2770  >>> x.sort() == BoolSort()
2771  False
2772  """
2773  ctx = _get_ctx(ctx)
2774  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2775 
2776 def RealSort(ctx=None):
2777  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2778 
2779  >>> RealSort()
2780  Real
2781  >>> x = Const('x', RealSort())
2782  >>> is_real(x)
2783  True
2784  >>> is_int(x)
2785  False
2786  >>> x.sort() == RealSort()
2787  True
2788  """
2789  ctx = _get_ctx(ctx)
2790  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2791 
2792 def _to_int_str(val):
2793  if isinstance(val, float):
2794  return str(int(val))
2795  elif isinstance(val, bool):
2796  if val:
2797  return "1"
2798  else:
2799  return "0"
2800  elif _is_int(val):
2801  return str(val)
2802  elif isinstance(val, str):
2803  return val
2804  if __debug__:
2805  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2806 
2807 def IntVal(val, ctx=None):
2808  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2809 
2810  >>> IntVal(1)
2811  1
2812  >>> IntVal("100")
2813  100
2814  """
2815  ctx = _get_ctx(ctx)
2816  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2817 
2818 def RealVal(val, ctx=None):
2819  """Return a Z3 real value.
2820 
2821  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2822  If `ctx=None`, then the global context is used.
2823 
2824  >>> RealVal(1)
2825  1
2826  >>> RealVal(1).sort()
2827  Real
2828  >>> RealVal("3/5")
2829  3/5
2830  >>> RealVal("1.5")
2831  3/2
2832  """
2833  ctx = _get_ctx(ctx)
2834  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2835 
2836 def RatVal(a, b, ctx=None):
2837  """Return a Z3 rational a/b.
2838 
2839  If `ctx=None`, then the global context is used.
2840 
2841  >>> RatVal(3,5)
2842  3/5
2843  >>> RatVal(3,5).sort()
2844  Real
2845  """
2846  if __debug__:
2847  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2848  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2849  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2850 
2851 def Q(a, b, ctx=None):
2852  """Return a Z3 rational a/b.
2853 
2854  If `ctx=None`, then the global context is used.
2855 
2856  >>> Q(3,5)
2857  3/5
2858  >>> Q(3,5).sort()
2859  Real
2860  """
2861  return simplify(RatVal(a, b))
2862 
2863 def Int(name, ctx=None):
2864  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2865 
2866  >>> x = Int('x')
2867  >>> is_int(x)
2868  True
2869  >>> is_int(x + 1)
2870  True
2871  """
2872  ctx = _get_ctx(ctx)
2873  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2874 
2875 def Ints(names, ctx=None):
2876  """Return a tuple of Integer constants.
2877 
2878  >>> x, y, z = Ints('x y z')
2879  >>> Sum(x, y, z)
2880  x + y + z
2881  """
2882  ctx = _get_ctx(ctx)
2883  if isinstance(names, str):
2884  names = names.split(" ")
2885  return [Int(name, ctx) for name in names]
2886 
2887 def IntVector(prefix, sz, ctx=None):
2888  """Return a list of integer constants of size `sz`.
2889 
2890  >>> X = IntVector('x', 3)
2891  >>> X
2892  [x__0, x__1, x__2]
2893  >>> Sum(X)
2894  x__0 + x__1 + x__2
2895  """
2896  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
2897 
2898 def FreshInt(prefix='x', ctx=None):
2899  """Return a fresh integer constant in the given context using the given prefix.
2900 
2901  >>> x = FreshInt()
2902  >>> y = FreshInt()
2903  >>> eq(x, y)
2904  False
2905  >>> x.sort()
2906  Int
2907  """
2908  ctx = _get_ctx(ctx)
2909  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
2910 
2911 def Real(name, ctx=None):
2912  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
2913 
2914  >>> x = Real('x')
2915  >>> is_real(x)
2916  True
2917  >>> is_real(x + 1)
2918  True
2919  """
2920  ctx = _get_ctx(ctx)
2921  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
2922 
2923 def Reals(names, ctx=None):
2924  """Return a tuple of real constants.
2925 
2926  >>> x, y, z = Reals('x y z')
2927  >>> Sum(x, y, z)
2928  x + y + z
2929  >>> Sum(x, y, z).sort()
2930  Real
2931  """
2932  ctx = _get_ctx(ctx)
2933  if isinstance(names, str):
2934  names = names.split(" ")
2935  return [Real(name, ctx) for name in names]
2936 
2937 def RealVector(prefix, sz, ctx=None):
2938  """Return a list of real constants of size `sz`.
2939 
2940  >>> X = RealVector('x', 3)
2941  >>> X
2942  [x__0, x__1, x__2]
2943  >>> Sum(X)
2944  x__0 + x__1 + x__2
2945  >>> Sum(X).sort()
2946  Real
2947  """
2948  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
2949 
2950 def FreshReal(prefix='b', ctx=None):
2951  """Return a fresh real constant in the given context using the given prefix.
2952 
2953  >>> x = FreshReal()
2954  >>> y = FreshReal()
2955  >>> eq(x, y)
2956  False
2957  >>> x.sort()
2958  Real
2959  """
2960  ctx = _get_ctx(ctx)
2961  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
2962 
2963 def ToReal(a):
2964  """ Return the Z3 expression ToReal(a).
2965 
2966  >>> x = Int('x')
2967  >>> x.sort()
2968  Int
2969  >>> n = ToReal(x)
2970  >>> n
2971  ToReal(x)
2972  >>> n.sort()
2973  Real
2974  """
2975  if __debug__:
2976  _z3_assert(a.is_int(), "Z3 integer expression expected.")
2977  ctx = a.ctx
2978  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
2979 
2980 def ToInt(a):
2981  """ Return the Z3 expression ToInt(a).
2982 
2983  >>> x = Real('x')
2984  >>> x.sort()
2985  Real
2986  >>> n = ToInt(x)
2987  >>> n
2988  ToInt(x)
2989  >>> n.sort()
2990  Int
2991  """
2992  if __debug__:
2993  _z3_assert(a.is_real(), "Z3 real expression expected.")
2994  ctx = a.ctx
2995  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
2996 
2997 def IsInt(a):
2998  """ Return the Z3 predicate IsInt(a).
2999 
3000  >>> x = Real('x')
3001  >>> IsInt(x + "1/2")
3002  IsInt(x + 1/2)
3003  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3004  [x = 1/2]
3005  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3006  no solution
3007  """
3008  if __debug__:
3009  _z3_assert(a.is_real(), "Z3 real expression expected.")
3010  ctx = a.ctx
3011  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3012 
3013 def Sqrt(a, ctx=None):
3014  """ Return a Z3 expression which represents the square root of a.
3015 
3016  >>> x = Real('x')
3017  >>> Sqrt(x)
3018  x**(1/2)
3019  """
3020  if not is_expr(a):
3021  ctx = _get_ctx(ctx)
3022  a = RealVal(a, ctx)
3023  return a ** "1/2"
3024 
3025 def Cbrt(a, ctx=None):
3026  """ Return a Z3 expression which represents the cubic root of a.
3027 
3028  >>> x = Real('x')
3029  >>> Cbrt(x)
3030  x**(1/3)
3031  """
3032  if not is_expr(a):
3033  ctx = _get_ctx(ctx)
3034  a = RealVal(a, ctx)
3035  return a ** "1/3"
3036 
3037 #########################################
3038 #
3039 # Bit-Vectors
3040 #
3041 #########################################
3042 
3043 class BitVecSortRef(SortRef):
3044  """Bit-vector sort."""
3045 
3046  def size(self):
3047  """Return the size (number of bits) of the bit-vector sort `self`.
3048 
3049  >>> b = BitVecSort(32)
3050  >>> b.size()
3051  32
3052  """
3053  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3054 
3055  def subsort(self, other):
3056  return is_bv_sort(other) and self.size() < other.size()
3057 
3058  def cast(self, val):
3059  """Try to cast `val` as a Bit-Vector.
3060 
3061  >>> b = BitVecSort(32)
3062  >>> b.cast(10)
3063  10
3064  >>> b.cast(10).sexpr()
3065  '#x0000000a'
3066  """
3067  if is_expr(val):
3068  if __debug__:
3069  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3070  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3071  return val
3072  else:
3073  return BitVecVal(val, self)
3074 
3075 def is_bv_sort(s):
3076  """Return True if `s` is a Z3 bit-vector sort.
3077 
3078  >>> is_bv_sort(BitVecSort(32))
3079  True
3080  >>> is_bv_sort(IntSort())
3081  False
3082  """
3083  return isinstance(s, BitVecSortRef)
3084 
3085 class BitVecRef(ExprRef):
3086  """Bit-vector expressions."""
3087 
3088  def sort(self):
3089  """Return the sort of the bit-vector expression `self`.
3090 
3091  >>> x = BitVec('x', 32)
3092  >>> x.sort()
3093  BitVec(32)
3094  >>> x.sort() == BitVecSort(32)
3095  True
3096  """
3097  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3098 
3099  def size(self):
3100  """Return the number of bits of the bit-vector expression `self`.
3101 
3102  >>> x = BitVec('x', 32)
3103  >>> (x + 1).size()
3104  32
3105  >>> Concat(x, x).size()
3106  64
3107  """
3108  return self.sort().size()
3109 
3110  def __add__(self, other):
3111  """Create the Z3 expression `self + other`.
3112 
3113  >>> x = BitVec('x', 32)
3114  >>> y = BitVec('y', 32)
3115  >>> x + y
3116  x + y
3117  >>> (x + y).sort()
3118  BitVec(32)
3119  """
3120  a, b = _coerce_exprs(self, other)
3121  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3122 
3123  def __radd__(self, other):
3124  """Create the Z3 expression `other + self`.
3125 
3126  >>> x = BitVec('x', 32)
3127  >>> 10 + x
3128  10 + x
3129  """
3130  a, b = _coerce_exprs(self, other)
3131  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3132 
3133  def __mul__(self, other):
3134  """Create the Z3 expression `self * other`.
3135 
3136  >>> x = BitVec('x', 32)
3137  >>> y = BitVec('y', 32)
3138  >>> x * y
3139  x*y
3140  >>> (x * y).sort()
3141  BitVec(32)
3142  """
3143  a, b = _coerce_exprs(self, other)
3144  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3145 
3146  def __rmul__(self, other):
3147  """Create the Z3 expression `other * self`.
3148 
3149  >>> x = BitVec('x', 32)
3150  >>> 10 * x
3151  10*x
3152  """
3153  a, b = _coerce_exprs(self, other)
3154  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3155 
3156  def __sub__(self, other):
3157  """Create the Z3 expression `self - other`.
3158 
3159  >>> x = BitVec('x', 32)
3160  >>> y = BitVec('y', 32)
3161  >>> x - y
3162  x - y
3163  >>> (x - y).sort()
3164  BitVec(32)
3165  """
3166  a, b = _coerce_exprs(self, other)
3167  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3168 
3169  def __rsub__(self, other):
3170  """Create the Z3 expression `other - self`.
3171 
3172  >>> x = BitVec('x', 32)
3173  >>> 10 - x
3174  10 - x
3175  """
3176  a, b = _coerce_exprs(self, other)
3177  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3178 
3179  def __or__(self, other):
3180  """Create the Z3 expression bitwise-or `self | other`.
3181 
3182  >>> x = BitVec('x', 32)
3183  >>> y = BitVec('y', 32)
3184  >>> x | y
3185  x | y
3186  >>> (x | y).sort()
3187  BitVec(32)
3188  """
3189  a, b = _coerce_exprs(self, other)
3190  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3191 
3192  def __ror__(self, other):
3193  """Create the Z3 expression bitwise-or `other | self`.
3194 
3195  >>> x = BitVec('x', 32)
3196  >>> 10 | x
3197  10 | x
3198  """
3199  a, b = _coerce_exprs(self, other)
3200  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3201 
3202  def __and__(self, other):
3203  """Create the Z3 expression bitwise-and `self & other`.
3204 
3205  >>> x = BitVec('x', 32)
3206  >>> y = BitVec('y', 32)
3207  >>> x & y
3208  x & y
3209  >>> (x & y).sort()
3210  BitVec(32)
3211  """
3212  a, b = _coerce_exprs(self, other)
3213  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3214 
3215  def __rand__(self, other):
3216  """Create the Z3 expression bitwise-or `other & self`.
3217 
3218  >>> x = BitVec('x', 32)
3219  >>> 10 & x
3220  10 & x
3221  """
3222  a, b = _coerce_exprs(self, other)
3223  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3224 
3225  def __xor__(self, other):
3226  """Create the Z3 expression bitwise-xor `self ^ other`.
3227 
3228  >>> x = BitVec('x', 32)
3229  >>> y = BitVec('y', 32)
3230  >>> x ^ y
3231  x ^ y
3232  >>> (x ^ y).sort()
3233  BitVec(32)
3234  """
3235  a, b = _coerce_exprs(self, other)
3236  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3237 
3238  def __rxor__(self, other):
3239  """Create the Z3 expression bitwise-xor `other ^ self`.
3240 
3241  >>> x = BitVec('x', 32)
3242  >>> 10 ^ x
3243  10 ^ x
3244  """
3245  a, b = _coerce_exprs(self, other)
3246  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3247 
3248  def __pos__(self):
3249  """Return `self`.
3250 
3251  >>> x = BitVec('x', 32)
3252  >>> +x
3253  x
3254  """
3255  return self
3256 
3257  def __neg__(self):
3258  """Return an expression representing `-self`.
3259 
3260  >>> x = BitVec('x', 32)
3261  >>> -x
3262  -x
3263  >>> simplify(-(-x))
3264  x
3265  """
3266  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3267 
3268  def __invert__(self):
3269  """Create the Z3 expression bitwise-not `~self`.
3270 
3271  >>> x = BitVec('x', 32)
3272  >>> ~x
3273  ~x
3274  >>> simplify(~(~x))
3275  x
3276  """
3277  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3278 
3279  def __div__(self, other):
3280  """Create the Z3 expression (signed) division `self / other`.
3281 
3282  Use the function UDiv() for unsigned division.
3283 
3284  >>> x = BitVec('x', 32)
3285  >>> y = BitVec('y', 32)
3286  >>> x / y
3287  x/y
3288  >>> (x / y).sort()
3289  BitVec(32)
3290  >>> (x / y).sexpr()
3291  '(bvsdiv x y)'
3292  >>> UDiv(x, y).sexpr()
3293  '(bvudiv x y)'
3294  """
3295  a, b = _coerce_exprs(self, other)
3296  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3297 
3298  def __truediv__(self, other):
3299  """Create the Z3 expression (signed) division `self / other`."""
3300  return self.__div__(other)
3301 
3302  def __rdiv__(self, other):
3303  """Create the Z3 expression (signed) division `other / self`.
3304 
3305  Use the function UDiv() for unsigned division.
3306 
3307  >>> x = BitVec('x', 32)
3308  >>> 10 / x
3309  10/x
3310  >>> (10 / x).sexpr()
3311  '(bvsdiv #x0000000a x)'
3312  >>> UDiv(10, x).sexpr()
3313  '(bvudiv #x0000000a x)'
3314  """
3315  a, b = _coerce_exprs(self, other)
3316  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3317 
3318  def __rtruediv__(self, other):
3319  """Create the Z3 expression (signed) division `other / self`."""
3320  return self.__rdiv__(other)
3321 
3322  def __mod__(self, other):
3323  """Create the Z3 expression (signed) mod `self % other`.
3324 
3325  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3326 
3327  >>> x = BitVec('x', 32)
3328  >>> y = BitVec('y', 32)
3329  >>> x % y
3330  x%y
3331  >>> (x % y).sort()
3332  BitVec(32)
3333  >>> (x % y).sexpr()
3334  '(bvsmod x y)'
3335  >>> URem(x, y).sexpr()
3336  '(bvurem x y)'
3337  >>> SRem(x, y).sexpr()
3338  '(bvsrem x y)'
3339  """
3340  a, b = _coerce_exprs(self, other)
3341  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3342 
3343  def __rmod__(self, other):
3344  """Create the Z3 expression (signed) mod `other % self`.
3345 
3346  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3347 
3348  >>> x = BitVec('x', 32)
3349  >>> 10 % x
3350  10%x
3351  >>> (10 % x).sexpr()
3352  '(bvsmod #x0000000a x)'
3353  >>> URem(10, x).sexpr()
3354  '(bvurem #x0000000a x)'
3355  >>> SRem(10, x).sexpr()
3356  '(bvsrem #x0000000a x)'
3357  """
3358  a, b = _coerce_exprs(self, other)
3359  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3360 
3361  def __le__(self, other):
3362  """Create the Z3 expression (signed) `other <= self`.
3363 
3364  Use the function ULE() for unsigned less than or equal to.
3365 
3366  >>> x, y = BitVecs('x y', 32)
3367  >>> x <= y
3368  x <= y
3369  >>> (x <= y).sexpr()
3370  '(bvsle x y)'
3371  >>> ULE(x, y).sexpr()
3372  '(bvule x y)'
3373  """
3374  a, b = _coerce_exprs(self, other)
3375  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3376 
3377  def __lt__(self, other):
3378  """Create the Z3 expression (signed) `other < self`.
3379 
3380  Use the function ULT() for unsigned less than.
3381 
3382  >>> x, y = BitVecs('x y', 32)
3383  >>> x < y
3384  x < y
3385  >>> (x < y).sexpr()
3386  '(bvslt x y)'
3387  >>> ULT(x, y).sexpr()
3388  '(bvult x y)'
3389  """
3390  a, b = _coerce_exprs(self, other)
3391  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3392 
3393  def __gt__(self, other):
3394  """Create the Z3 expression (signed) `other > self`.
3395 
3396  Use the function UGT() for unsigned greater than.
3397 
3398  >>> x, y = BitVecs('x y', 32)
3399  >>> x > y
3400  x > y
3401  >>> (x > y).sexpr()
3402  '(bvsgt x y)'
3403  >>> UGT(x, y).sexpr()
3404  '(bvugt x y)'
3405  """
3406  a, b = _coerce_exprs(self, other)
3407  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3408 
3409  def __ge__(self, other):
3410  """Create the Z3 expression (signed) `other >= self`.
3411 
3412  Use the function UGE() for unsigned greater than or equal to.
3413 
3414  >>> x, y = BitVecs('x y', 32)
3415  >>> x >= y
3416  x >= y
3417  >>> (x >= y).sexpr()
3418  '(bvsge x y)'
3419  >>> UGE(x, y).sexpr()
3420  '(bvuge x y)'
3421  """
3422  a, b = _coerce_exprs(self, other)
3423  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3424 
3425  def __rshift__(self, other):
3426  """Create the Z3 expression (arithmetical) right shift `self >> other`
3427 
3428  Use the function LShR() for the right logical shift
3429 
3430  >>> x, y = BitVecs('x y', 32)
3431  >>> x >> y
3432  x >> y
3433  >>> (x >> y).sexpr()
3434  '(bvashr x y)'
3435  >>> LShR(x, y).sexpr()
3436  '(bvlshr x y)'
3437  >>> BitVecVal(4, 3)
3438  4
3439  >>> BitVecVal(4, 3).as_signed_long()
3440  -4
3441  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3442  -2
3443  >>> simplify(BitVecVal(4, 3) >> 1)
3444  6
3445  >>> simplify(LShR(BitVecVal(4, 3), 1))
3446  2
3447  >>> simplify(BitVecVal(2, 3) >> 1)
3448  1
3449  >>> simplify(LShR(BitVecVal(2, 3), 1))
3450  1
3451  """
3452  a, b = _coerce_exprs(self, other)
3453  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3454 
3455  def __lshift__(self, other):
3456  """Create the Z3 expression left shift `self << other`
3457 
3458  >>> x, y = BitVecs('x y', 32)
3459  >>> x << y
3460  x << y
3461  >>> (x << y).sexpr()
3462  '(bvshl x y)'
3463  >>> simplify(BitVecVal(2, 3) << 1)
3464  4
3465  """
3466  a, b = _coerce_exprs(self, other)
3467  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3468 
3469  def __rrshift__(self, other):
3470  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3471 
3472  Use the function LShR() for the right logical shift
3473 
3474  >>> x = BitVec('x', 32)
3475  >>> 10 >> x
3476  10 >> x
3477  >>> (10 >> x).sexpr()
3478  '(bvashr #x0000000a x)'
3479  """
3480  a, b = _coerce_exprs(self, other)
3481  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3482 
3483  def __rlshift__(self, other):
3484  """Create the Z3 expression left shift `other << self`.
3485 
3486  Use the function LShR() for the right logical shift
3487 
3488  >>> x = BitVec('x', 32)
3489  >>> 10 << x
3490  10 << x
3491  >>> (10 << x).sexpr()
3492  '(bvshl #x0000000a x)'
3493  """
3494  a, b = _coerce_exprs(self, other)
3495  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3496 
3497 class BitVecNumRef(BitVecRef):
3498  """Bit-vector values."""
3499 
3500  def as_long(self):
3501  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3502 
3503  >>> v = BitVecVal(0xbadc0de, 32)
3504  >>> v
3505  195936478
3506  >>> print("0x%.8x" % v.as_long())
3507  0x0badc0de
3508  """
3509  return int(self.as_string())
3510 
3511  def as_signed_long(self):
3512  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3513 
3514  >>> BitVecVal(4, 3).as_signed_long()
3515  -4
3516  >>> BitVecVal(7, 3).as_signed_long()
3517  -1
3518  >>> BitVecVal(3, 3).as_signed_long()
3519  3
3520  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3521  -1
3522  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3523  -1
3524  """
3525  sz = self.size()
3526  val = self.as_long()
3527  if val >= 2**(sz - 1):
3528  val = val - 2**sz
3529  if val < -2**(sz - 1):
3530  val = val + 2**sz
3531  return int(val)
3532 
3533  def as_string(self):
3534  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3535 
3536 def is_bv(a):
3537  """Return `True` if `a` is a Z3 bit-vector expression.
3538 
3539  >>> b = BitVec('b', 32)
3540  >>> is_bv(b)
3541  True
3542  >>> is_bv(b + 10)
3543  True
3544  >>> is_bv(Int('x'))
3545  False
3546  """
3547  return isinstance(a, BitVecRef)
3548 
3549 def is_bv_value(a):
3550  """Return `True` if `a` is a Z3 bit-vector numeral value.
3551 
3552  >>> b = BitVec('b', 32)
3553  >>> is_bv_value(b)
3554  False
3555  >>> b = BitVecVal(10, 32)
3556  >>> b
3557  10
3558  >>> is_bv_value(b)
3559  True
3560  """
3561  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3562 
3563 def BV2Int(a, is_signed=False):
3564  """Return the Z3 expression BV2Int(a).
3565 
3566  >>> b = BitVec('b', 3)
3567  >>> BV2Int(b).sort()
3568  Int
3569  >>> x = Int('x')
3570  >>> x > BV2Int(b)
3571  x > BV2Int(b)
3572  >>> x > BV2Int(b, is_signed=False)
3573  x > BV2Int(b)
3574  >>> x > BV2Int(b, is_signed=True)
3575  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3576  >>> solve(x > BV2Int(b), b == 1, x < 3)
3577  [b = 1, x = 2]
3578  """
3579  if __debug__:
3580  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3581  ctx = a.ctx
3582  ## investigate problem with bv2int
3583  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3584 
3585 def Int2BV(a, num_bits):
3586  """Return the z3 expression Int2BV(a, num_bits).
3587  It is a bit-vector of width num_bits and represents the
3588  modulo of a by 2^num_bits
3589  """
3590  ctx = a.ctx
3591  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3592 
3593 def BitVecSort(sz, ctx=None):
3594  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3595 
3596  >>> Byte = BitVecSort(8)
3597  >>> Word = BitVecSort(16)
3598  >>> Byte
3599  BitVec(8)
3600  >>> x = Const('x', Byte)
3601  >>> eq(x, BitVec('x', 8))
3602  True
3603  """
3604  ctx = _get_ctx(ctx)
3605  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3606 
3607 def BitVecVal(val, bv, ctx=None):
3608  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3609 
3610  >>> v = BitVecVal(10, 32)
3611  >>> v
3612  10
3613  >>> print("0x%.8x" % v.as_long())
3614  0x0000000a
3615  """
3616  if is_bv_sort(bv):
3617  ctx = bv.ctx
3618  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3619  else:
3620  ctx = _get_ctx(ctx)
3621  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3622 
3623 def BitVec(name, bv, ctx=None):
3624  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3625  If `ctx=None`, then the global context is used.
3626 
3627  >>> x = BitVec('x', 16)
3628  >>> is_bv(x)
3629  True
3630  >>> x.size()
3631  16
3632  >>> x.sort()
3633  BitVec(16)
3634  >>> word = BitVecSort(16)
3635  >>> x2 = BitVec('x', word)
3636  >>> eq(x, x2)
3637  True
3638  """
3639  if isinstance(bv, BitVecSortRef):
3640  ctx = bv.ctx
3641  else:
3642  ctx = _get_ctx(ctx)
3643  bv = BitVecSort(bv, ctx)
3644  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3645 
3646 def BitVecs(names, bv, ctx=None):
3647  """Return a tuple of bit-vector constants of size bv.
3648 
3649  >>> x, y, z = BitVecs('x y z', 16)
3650  >>> x.size()
3651  16
3652  >>> x.sort()
3653  BitVec(16)
3654  >>> Sum(x, y, z)
3655  0 + x + y + z
3656  >>> Product(x, y, z)
3657  1*x*y*z
3658  >>> simplify(Product(x, y, z))
3659  x*y*z
3660  """
3661  ctx = _get_ctx(ctx)
3662  if isinstance(names, str):
3663  names = names.split(" ")
3664  return [BitVec(name, bv, ctx) for name in names]
3665 
3666 def Concat(*args):
3667  """Create a Z3 bit-vector concatenation expression.
3668 
3669  >>> v = BitVecVal(1, 4)
3670  >>> Concat(v, v+1, v)
3671  Concat(Concat(1, 1 + 1), 1)
3672  >>> simplify(Concat(v, v+1, v))
3673  289
3674  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3675  121
3676  """
3677  args = _get_args(args)
3678  sz = len(args)
3679  if __debug__:
3680  _z3_assert(sz >= 2, "At least two arguments expected.")
3681 
3682  ctx = None
3683  for a in args:
3684  if is_expr(a):
3685  ctx = a.ctx
3686  break
3687  if is_seq(args[0]) or isinstance(args[0], str):
3688  args = [_coerce_seq(s, ctx) for s in args]
3689  if __debug__:
3690  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3691  v = (Ast * sz)()
3692  for i in range(sz):
3693  v[i] = args[i].as_ast()
3694  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3695 
3696  if is_re(args[0]):
3697  if __debug__:
3698  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3699  v = (Ast * sz)()
3700  for i in range(sz):
3701  v[i] = args[i].as_ast()
3702  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3703 
3704  if __debug__:
3705  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3706  r = args[0]
3707  for i in range(sz - 1):
3708  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3709  return r
3710 
3711 def Extract(high, low, a):
3712  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3713 
3714  >>> x = BitVec('x', 8)
3715  >>> Extract(6, 2, x)
3716  Extract(6, 2, x)
3717  >>> Extract(6, 2, x).sort()
3718  BitVec(5)
3719  >>> simplify(Extract(StringVal("abcd"),2,1))
3720  "c"
3721  """
3722  if isinstance(high, str):
3723  high = StringVal(high)
3724  if is_seq(high):
3725  s = high
3726  offset, length = _coerce_exprs(low, a, s.ctx)
3727  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3728  if __debug__:
3729  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3730  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3731  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3732  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3733 
3734 def _check_bv_args(a, b):
3735  if __debug__:
3736  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3737 
3738 def ULE(a, b):
3739  """Create the Z3 expression (unsigned) `other <= self`.
3740 
3741  Use the operator <= for signed less than or equal to.
3742 
3743  >>> x, y = BitVecs('x y', 32)
3744  >>> ULE(x, y)
3745  ULE(x, y)
3746  >>> (x <= y).sexpr()
3747  '(bvsle x y)'
3748  >>> ULE(x, y).sexpr()
3749  '(bvule x y)'
3750  """
3751  _check_bv_args(a, b)
3752  a, b = _coerce_exprs(a, b)
3753  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3754 
3755 def ULT(a, b):
3756  """Create the Z3 expression (unsigned) `other < self`.
3757 
3758  Use the operator < for signed less than.
3759 
3760  >>> x, y = BitVecs('x y', 32)
3761  >>> ULT(x, y)
3762  ULT(x, y)
3763  >>> (x < y).sexpr()
3764  '(bvslt x y)'
3765  >>> ULT(x, y).sexpr()
3766  '(bvult x y)'
3767  """
3768  _check_bv_args(a, b)
3769  a, b = _coerce_exprs(a, b)
3770  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3771 
3772 def UGE(a, b):
3773  """Create the Z3 expression (unsigned) `other >= self`.
3774 
3775  Use the operator >= for signed greater than or equal to.
3776 
3777  >>> x, y = BitVecs('x y', 32)
3778  >>> UGE(x, y)
3779  UGE(x, y)
3780  >>> (x >= y).sexpr()
3781  '(bvsge x y)'
3782  >>> UGE(x, y).sexpr()
3783  '(bvuge x y)'
3784  """
3785  _check_bv_args(a, b)
3786  a, b = _coerce_exprs(a, b)
3787  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3788 
3789 def UGT(a, b):
3790  """Create the Z3 expression (unsigned) `other > self`.
3791 
3792  Use the operator > for signed greater than.
3793 
3794  >>> x, y = BitVecs('x y', 32)
3795  >>> UGT(x, y)
3796  UGT(x, y)
3797  >>> (x > y).sexpr()
3798  '(bvsgt x y)'
3799  >>> UGT(x, y).sexpr()
3800  '(bvugt x y)'
3801  """
3802  _check_bv_args(a, b)
3803  a, b = _coerce_exprs(a, b)
3804  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3805 
3806 def UDiv(a, b):
3807  """Create the Z3 expression (unsigned) division `self / other`.
3808 
3809  Use the operator / for signed division.
3810 
3811  >>> x = BitVec('x', 32)
3812  >>> y = BitVec('y', 32)
3813  >>> UDiv(x, y)
3814  UDiv(x, y)
3815  >>> UDiv(x, y).sort()
3816  BitVec(32)
3817  >>> (x / y).sexpr()
3818  '(bvsdiv x y)'
3819  >>> UDiv(x, y).sexpr()
3820  '(bvudiv x y)'
3821  """
3822  _check_bv_args(a, b)
3823  a, b = _coerce_exprs(a, b)
3824  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3825 
3826 def URem(a, b):
3827  """Create the Z3 expression (unsigned) remainder `self % other`.
3828 
3829  Use the operator % for signed modulus, and SRem() for signed remainder.
3830 
3831  >>> x = BitVec('x', 32)
3832  >>> y = BitVec('y', 32)
3833  >>> URem(x, y)
3834  URem(x, y)
3835  >>> URem(x, y).sort()
3836  BitVec(32)
3837  >>> (x % y).sexpr()
3838  '(bvsmod x y)'
3839  >>> URem(x, y).sexpr()
3840  '(bvurem x y)'
3841  """
3842  _check_bv_args(a, b)
3843  a, b = _coerce_exprs(a, b)
3844  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3845 
3846 def SRem(a, b):
3847  """Create the Z3 expression signed remainder.
3848 
3849  Use the operator % for signed modulus, and URem() for unsigned remainder.
3850 
3851  >>> x = BitVec('x', 32)
3852  >>> y = BitVec('y', 32)
3853  >>> SRem(x, y)
3854  SRem(x, y)
3855  >>> SRem(x, y).sort()
3856  BitVec(32)
3857  >>> (x % y).sexpr()
3858  '(bvsmod x y)'
3859  >>> SRem(x, y).sexpr()
3860  '(bvsrem x y)'
3861  """
3862  _check_bv_args(a, b)
3863  a, b = _coerce_exprs(a, b)
3864  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3865 
3866 def LShR(a, b):
3867  """Create the Z3 expression logical right shift.
3868 
3869  Use the operator >> for the arithmetical right shift.
3870 
3871  >>> x, y = BitVecs('x y', 32)
3872  >>> LShR(x, y)
3873  LShR(x, y)
3874  >>> (x >> y).sexpr()
3875  '(bvashr x y)'
3876  >>> LShR(x, y).sexpr()
3877  '(bvlshr x y)'
3878  >>> BitVecVal(4, 3)
3879  4
3880  >>> BitVecVal(4, 3).as_signed_long()
3881  -4
3882  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3883  -2
3884  >>> simplify(BitVecVal(4, 3) >> 1)
3885  6
3886  >>> simplify(LShR(BitVecVal(4, 3), 1))
3887  2
3888  >>> simplify(BitVecVal(2, 3) >> 1)
3889  1
3890  >>> simplify(LShR(BitVecVal(2, 3), 1))
3891  1
3892  """
3893  _check_bv_args(a, b)
3894  a, b = _coerce_exprs(a, b)
3895  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3896 
3897 def RotateLeft(a, b):
3898  """Return an expression representing `a` rotated to the left `b` times.
3899 
3900  >>> a, b = BitVecs('a b', 16)
3901  >>> RotateLeft(a, b)
3902  RotateLeft(a, b)
3903  >>> simplify(RotateLeft(a, 0))
3904  a
3905  >>> simplify(RotateLeft(a, 16))
3906  a
3907  """
3908  _check_bv_args(a, b)
3909  a, b = _coerce_exprs(a, b)
3910  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3911 
3912 def RotateRight(a, b):
3913  """Return an expression representing `a` rotated to the right `b` times.
3914 
3915  >>> a, b = BitVecs('a b', 16)
3916  >>> RotateRight(a, b)
3917  RotateRight(a, b)
3918  >>> simplify(RotateRight(a, 0))
3919  a
3920  >>> simplify(RotateRight(a, 16))
3921  a
3922  """
3923  _check_bv_args(a, b)
3924  a, b = _coerce_exprs(a, b)
3925  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3926 
3927 def SignExt(n, a):
3928  """Return a bit-vector expression with `n` extra sign-bits.
3929 
3930  >>> x = BitVec('x', 16)
3931  >>> n = SignExt(8, x)
3932  >>> n.size()
3933  24
3934  >>> n
3935  SignExt(8, x)
3936  >>> n.sort()
3937  BitVec(24)
3938  >>> v0 = BitVecVal(2, 2)
3939  >>> v0
3940  2
3941  >>> v0.size()
3942  2
3943  >>> v = simplify(SignExt(6, v0))
3944  >>> v
3945  254
3946  >>> v.size()
3947  8
3948  >>> print("%.x" % v.as_long())
3949  fe
3950  """
3951  if __debug__:
3952  _z3_assert(_is_int(n), "First argument must be an integer")
3953  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3954  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3955 
3956 def ZeroExt(n, a):
3957  """Return a bit-vector expression with `n` extra zero-bits.
3958 
3959  >>> x = BitVec('x', 16)
3960  >>> n = ZeroExt(8, x)
3961  >>> n.size()
3962  24
3963  >>> n
3964  ZeroExt(8, x)
3965  >>> n.sort()
3966  BitVec(24)
3967  >>> v0 = BitVecVal(2, 2)
3968  >>> v0
3969  2
3970  >>> v0.size()
3971  2
3972  >>> v = simplify(ZeroExt(6, v0))
3973  >>> v
3974  2
3975  >>> v.size()
3976  8
3977  """
3978  if __debug__:
3979  _z3_assert(_is_int(n), "First argument must be an integer")
3980  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3981  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3982 
3983 def RepeatBitVec(n, a):
3984  """Return an expression representing `n` copies of `a`.
3985 
3986  >>> x = BitVec('x', 8)
3987  >>> n = RepeatBitVec(4, x)
3988  >>> n
3989  RepeatBitVec(4, x)
3990  >>> n.size()
3991  32
3992  >>> v0 = BitVecVal(10, 4)
3993  >>> print("%.x" % v0.as_long())
3994  a
3995  >>> v = simplify(RepeatBitVec(4, v0))
3996  >>> v.size()
3997  16
3998  >>> print("%.x" % v.as_long())
3999  aaaa
4000  """
4001  if __debug__:
4002  _z3_assert(_is_int(n), "First argument must be an integer")
4003  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4004  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4005 
4006 def BVRedAnd(a):
4007  """Return the reduction-and expression of `a`."""
4008  if __debug__:
4009  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4010  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4011 
4012 def BVRedOr(a):
4013  """Return the reduction-or expression of `a`."""
4014  if __debug__:
4015  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4016  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4017 
4018 def BVAddNoOverflow(a, b, signed):
4019  """A predicate the determines that bit-vector addition does not overflow"""
4020  _check_bv_args(a, b)
4021  a, b = _coerce_exprs(a, b)
4022  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4023 
4024 def BVAddNoUnderflow(a, b):
4025  """A predicate the determines that signed bit-vector addition does not underflow"""
4026  _check_bv_args(a, b)
4027  a, b = _coerce_exprs(a, b)
4028  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4029 
4030 def BVSubNoOverflow(a, b):
4031  """A predicate the determines that bit-vector subtraction does not overflow"""
4032  _check_bv_args(a, b)
4033  a, b = _coerce_exprs(a, b)
4034  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4035 
4036 
4037 def BVSubNoUnderflow(a, b, signed):
4038  """A predicate the determines that bit-vector subtraction does not underflow"""
4039  _check_bv_args(a, b)
4040  a, b = _coerce_exprs(a, b)
4041  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4042 
4043 def BVSDivNoOverflow(a, b):
4044  """A predicate the determines that bit-vector signed division does not overflow"""
4045  _check_bv_args(a, b)
4046  a, b = _coerce_exprs(a, b)
4047  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4048 
4049 def BVSNegNoOverflow(a):
4050  """A predicate the determines that bit-vector unary negation does not overflow"""
4051  if __debug__:
4052  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4053  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4054 
4055 def BVMulNoOverflow(a, b, signed):
4056  """A predicate the determines that bit-vector multiplication does not overflow"""
4057  _check_bv_args(a, b)
4058  a, b = _coerce_exprs(a, b)
4059  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4060 
4061 
4062 def BVMulNoUnderflow(a, b):
4063  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4064  _check_bv_args(a, b)
4065  a, b = _coerce_exprs(a, b)
4066  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4067 
4068 
4069 
4070 #########################################
4071 #
4072 # Arrays
4073 #
4074 #########################################
4075 
4076 class ArraySortRef(SortRef):
4077  """Array sorts."""
4078 
4079  def domain(self):
4080  """Return the domain of the array sort `self`.
4081 
4082  >>> A = ArraySort(IntSort(), BoolSort())
4083  >>> A.domain()
4084  Int
4085  """
4086  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4087 
4088  def range(self):
4089  """Return the range of the array sort `self`.
4090 
4091  >>> A = ArraySort(IntSort(), BoolSort())
4092  >>> A.range()
4093  Bool
4094  """
4095  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4096 
4097 class ArrayRef(ExprRef):
4098  """Array expressions. """
4099 
4100  def sort(self):
4101  """Return the array sort of the array expression `self`.
4102 
4103  >>> a = Array('a', IntSort(), BoolSort())
4104  >>> a.sort()
4105  Array(Int, Bool)
4106  """
4107  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4108 
4109  def domain(self):
4110  """Shorthand for `self.sort().domain()`.
4111 
4112  >>> a = Array('a', IntSort(), BoolSort())
4113  >>> a.domain()
4114  Int
4115  """
4116  return self.sort().domain()
4117 
4118  def range(self):
4119  """Shorthand for `self.sort().range()`.
4120 
4121  >>> a = Array('a', IntSort(), BoolSort())
4122  >>> a.range()
4123  Bool
4124  """
4125  return self.sort().range()
4126 
4127  def __getitem__(self, arg):
4128  """Return the Z3 expression `self[arg]`.
4129 
4130  >>> a = Array('a', IntSort(), BoolSort())
4131  >>> i = Int('i')
4132  >>> a[i]
4133  a[i]
4134  >>> a[i].sexpr()
4135  '(select a i)'
4136  """
4137  arg = self.domain().cast(arg)
4138  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4139 
4140  def default(self):
4141  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4142 
4143 
4144 def is_array(a):
4145  """Return `True` if `a` is a Z3 array expression.
4146 
4147  >>> a = Array('a', IntSort(), IntSort())
4148  >>> is_array(a)
4149  True
4150  >>> is_array(Store(a, 0, 1))
4151  True
4152  >>> is_array(a[0])
4153  False
4154  """
4155  return isinstance(a, ArrayRef)
4156 
4157 def is_const_array(a):
4158  """Return `True` if `a` is a Z3 constant array.
4159 
4160  >>> a = K(IntSort(), 10)
4161  >>> is_const_array(a)
4162  True
4163  >>> a = Array('a', IntSort(), IntSort())
4164  >>> is_const_array(a)
4165  False
4166  """
4167  return is_app_of(a, Z3_OP_CONST_ARRAY)
4168 
4169 def is_K(a):
4170  """Return `True` if `a` is a Z3 constant array.
4171 
4172  >>> a = K(IntSort(), 10)
4173  >>> is_K(a)
4174  True
4175  >>> a = Array('a', IntSort(), IntSort())
4176  >>> is_K(a)
4177  False
4178  """
4179  return is_app_of(a, Z3_OP_CONST_ARRAY)
4180 
4181 def is_map(a):
4182  """Return `True` if `a` is a Z3 map array expression.
4183 
4184  >>> f = Function('f', IntSort(), IntSort())
4185  >>> b = Array('b', IntSort(), IntSort())
4186  >>> a = Map(f, b)
4187  >>> a
4188  Map(f, b)
4189  >>> is_map(a)
4190  True
4191  >>> is_map(b)
4192  False
4193  """
4194  return is_app_of(a, Z3_OP_ARRAY_MAP)
4195 
4196 def is_default(a):
4197  """Return `True` if `a` is a Z3 default array expression.
4198  >>> d = Default(K(IntSort(), 10))
4199  >>> is_default(d)
4200  True
4201  """
4202  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4203 
4204 def get_map_func(a):
4205  """Return the function declaration associated with a Z3 map array expression.
4206 
4207  >>> f = Function('f', IntSort(), IntSort())
4208  >>> b = Array('b', IntSort(), IntSort())
4209  >>> a = Map(f, b)
4210  >>> eq(f, get_map_func(a))
4211  True
4212  >>> get_map_func(a)
4213  f
4214  >>> get_map_func(a)(0)
4215  f(0)
4216  """
4217  if __debug__:
4218  _z3_assert(is_map(a), "Z3 array map expression expected.")
4219  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4220 
4221 def ArraySort(d, r):
4222  """Return the Z3 array sort with the given domain and range sorts.
4223 
4224  >>> A = ArraySort(IntSort(), BoolSort())
4225  >>> A
4226  Array(Int, Bool)
4227  >>> A.domain()
4228  Int
4229  >>> A.range()
4230  Bool
4231  >>> AA = ArraySort(IntSort(), A)
4232  >>> AA
4233  Array(Int, Array(Int, Bool))
4234  """
4235  if __debug__:
4236  _z3_assert(is_sort(d), "Z3 sort expected")
4237  _z3_assert(is_sort(r), "Z3 sort expected")
4238  _z3_assert(d.ctx == r.ctx, "Context mismatch")
4239  ctx = d.ctx
4240  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4241 
4242 def Array(name, dom, rng):
4243  """Return an array constant named `name` with the given domain and range sorts.
4244 
4245  >>> a = Array('a', IntSort(), IntSort())
4246  >>> a.sort()
4247  Array(Int, Int)
4248  >>> a[0]
4249  a[0]
4250  """
4251  s = ArraySort(dom, rng)
4252  ctx = s.ctx
4253  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4254 
4255 def Update(a, i, v):
4256  """Return a Z3 store array expression.
4257 
4258  >>> a = Array('a', IntSort(), IntSort())
4259  >>> i, v = Ints('i v')
4260  >>> s = Update(a, i, v)
4261  >>> s.sort()
4262  Array(Int, Int)
4263  >>> prove(s[i] == v)
4264  proved
4265  >>> j = Int('j')
4266  >>> prove(Implies(i != j, s[j] == a[j]))
4267  proved
4268  """
4269  if __debug__:
4270  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4271  i = a.domain().cast(i)
4272  v = a.range().cast(v)
4273  ctx = a.ctx
4274  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4275 
4276 def Default(a):
4277  """ Return a default value for array expression.
4278  >>> b = K(IntSort(), 1)
4279  >>> prove(Default(b) == 1)
4280  proved
4281  """
4282  if __debug__:
4283  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4284  return a.default()
4285 
4286 
4287 def Store(a, i, v):
4288  """Return a Z3 store array expression.
4289 
4290  >>> a = Array('a', IntSort(), IntSort())
4291  >>> i, v = Ints('i v')
4292  >>> s = Store(a, i, v)
4293  >>> s.sort()
4294  Array(Int, Int)
4295  >>> prove(s[i] == v)
4296  proved
4297  >>> j = Int('j')
4298  >>> prove(Implies(i != j, s[j] == a[j]))
4299  proved
4300  """
4301  return Update(a, i, v)
4302 
4303 def Select(a, i):
4304  """Return a Z3 select array expression.
4305 
4306  >>> a = Array('a', IntSort(), IntSort())
4307  >>> i = Int('i')
4308  >>> Select(a, i)
4309  a[i]
4310  >>> eq(Select(a, i), a[i])
4311  True
4312  """
4313  if __debug__:
4314  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4315  return a[i]
4316 
4317 
4318 def Map(f, *args):
4319  """Return a Z3 map array expression.
4320 
4321  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4322  >>> a1 = Array('a1', IntSort(), IntSort())
4323  >>> a2 = Array('a2', IntSort(), IntSort())
4324  >>> b = Map(f, a1, a2)
4325  >>> b
4326  Map(f, a1, a2)
4327  >>> prove(b[0] == f(a1[0], a2[0]))
4328  proved
4329  """
4330  args = _get_args(args)
4331  if __debug__:
4332  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4333  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4334  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4335  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4336  _args, sz = _to_ast_array(args)
4337  ctx = f.ctx
4338  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4339 
4340 def K(dom, v):
4341  """Return a Z3 constant array expression.
4342 
4343  >>> a = K(IntSort(), 10)
4344  >>> a
4345  K(Int, 10)
4346  >>> a.sort()
4347  Array(Int, Int)
4348  >>> i = Int('i')
4349  >>> a[i]
4350  K(Int, 10)[i]
4351  >>> simplify(a[i])
4352  10
4353  """
4354  if __debug__:
4355  _z3_assert(is_sort(dom), "Z3 sort expected")
4356  ctx = dom.ctx
4357  if not is_expr(v):
4358  v = _py2expr(v, ctx)
4359  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4360 
4361 def Ext(a, b):
4362  """Return extensionality index for arrays.
4363  """
4364  if __debug__:
4365  _z3_assert(is_array(a) and is_array(b))
4366  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
4367 
4368 def is_select(a):
4369  """Return `True` if `a` is a Z3 array select application.
4370 
4371  >>> a = Array('a', IntSort(), IntSort())
4372  >>> is_select(a)
4373  False
4374  >>> i = Int('i')
4375  >>> is_select(a[i])
4376  True
4377  """
4378  return is_app_of(a, Z3_OP_SELECT)
4379 
4380 def is_store(a):
4381  """Return `True` if `a` is a Z3 array store application.
4382 
4383  >>> a = Array('a', IntSort(), IntSort())
4384  >>> is_store(a)
4385  False
4386  >>> is_store(Store(a, 0, 1))
4387  True
4388  """
4389  return is_app_of(a, Z3_OP_STORE)
4390 
4391 #########################################
4392 #
4393 # Datatypes
4394 #
4395 #########################################
4396 
4397 def _valid_accessor(acc):
4398  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4399  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4400 
4401 class Datatype:
4402  """Helper class for declaring Z3 datatypes.
4403 
4404  >>> List = Datatype('List')
4405  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4406  >>> List.declare('nil')
4407  >>> List = List.create()
4408  >>> # List is now a Z3 declaration
4409  >>> List.nil
4410  nil
4411  >>> List.cons(10, List.nil)
4412  cons(10, nil)
4413  >>> List.cons(10, List.nil).sort()
4414  List
4415  >>> cons = List.cons
4416  >>> nil = List.nil
4417  >>> car = List.car
4418  >>> cdr = List.cdr
4419  >>> n = cons(1, cons(0, nil))
4420  >>> n
4421  cons(1, cons(0, nil))
4422  >>> simplify(cdr(n))
4423  cons(0, nil)
4424  >>> simplify(car(n))
4425  1
4426  """
4427  def __init__(self, name, ctx=None):
4428  self.ctx = _get_ctx(ctx)
4429  self.name = name
4430  self.constructors = []
4431 
4432  def __deepcopy__(self, memo={}):
4433  r = Datatype(self.name, self.ctx)
4434  r.constructors = copy.deepcopy(self.constructors)
4435  return r
4436 
4437  def declare_core(self, name, rec_name, *args):
4438  if __debug__:
4439  _z3_assert(isinstance(name, str), "String expected")
4440  _z3_assert(isinstance(rec_name, str), "String expected")
4441  _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)")
4442  self.constructors.append((name, rec_name, args))
4443 
4444  def declare(self, name, *args):
4445  """Declare constructor named `name` with the given accessors `args`.
4446  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.
4447 
4448  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4449  declares the constructor named `cons` that builds a new List using an integer and a List.
4450  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4451  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4452  the actual datatype in Z3.
4453 
4454  >>> List = Datatype('List')
4455  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4456  >>> List.declare('nil')
4457  >>> List = List.create()
4458  """
4459  if __debug__:
4460  _z3_assert(isinstance(name, str), "String expected")
4461  _z3_assert(name != "", "Constructor name cannot be empty")
4462  return self.declare_core(name, "is-" + name, *args)
4463 
4464  def __repr__(self):
4465  return "Datatype(%s, %s)" % (self.name, self.constructors)
4466 
4467  def create(self):
4468  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4469 
4470  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4471 
4472  >>> List = Datatype('List')
4473  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4474  >>> List.declare('nil')
4475  >>> List = List.create()
4476  >>> List.nil
4477  nil
4478  >>> List.cons(10, List.nil)
4479  cons(10, nil)
4480  """
4481  return CreateDatatypes([self])[0]
4482 
4483 class ScopedConstructor:
4484  """Auxiliary object used to create Z3 datatypes."""
4485  def __init__(self, c, ctx):
4486  self.c = c
4487  self.ctx = ctx
4488  def __del__(self):
4489  if self.ctx.ref() is not None:
4490  Z3_del_constructor(self.ctx.ref(), self.c)
4491 
4492 class ScopedConstructorList:
4493  """Auxiliary object used to create Z3 datatypes."""
4494  def __init__(self, c, ctx):
4495  self.c = c
4496  self.ctx = ctx
4497  def __del__(self):
4498  if self.ctx.ref() is not None:
4499  Z3_del_constructor_list(self.ctx.ref(), self.c)
4500 
4501 def CreateDatatypes(*ds):
4502  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4503 
4504  In the following example we define a Tree-List using two mutually recursive datatypes.
4505 
4506  >>> TreeList = Datatype('TreeList')
4507  >>> Tree = Datatype('Tree')
4508  >>> # Tree has two constructors: leaf and node
4509  >>> Tree.declare('leaf', ('val', IntSort()))
4510  >>> # a node contains a list of trees
4511  >>> Tree.declare('node', ('children', TreeList))
4512  >>> TreeList.declare('nil')
4513  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4514  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4515  >>> Tree.val(Tree.leaf(10))
4516  val(leaf(10))
4517  >>> simplify(Tree.val(Tree.leaf(10)))
4518  10
4519  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4520  >>> n1
4521  node(cons(leaf(10), cons(leaf(20), nil)))
4522  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4523  >>> simplify(n2 == n1)
4524  False
4525  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4526  True
4527  """
4528  ds = _get_args(ds)
4529  if __debug__:
4530  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4531  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4532  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4533  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4534  ctx = ds[0].ctx
4535  num = len(ds)
4536  names = (Symbol * num)()
4537  out = (Sort * num)()
4538  clists = (ConstructorList * num)()
4539  to_delete = []
4540  for i in range(num):
4541  d = ds[i]
4542  names[i] = to_symbol(d.name, ctx)
4543  num_cs = len(d.constructors)
4544  cs = (Constructor * num_cs)()
4545  for j in range(num_cs):
4546  c = d.constructors[j]
4547  cname = to_symbol(c[0], ctx)
4548  rname = to_symbol(c[1], ctx)
4549  fs = c[2]
4550  num_fs = len(fs)
4551  fnames = (Symbol * num_fs)()
4552  sorts = (Sort * num_fs)()
4553  refs = (ctypes.c_uint * num_fs)()
4554  for k in range(num_fs):
4555  fname = fs[k][0]
4556  ftype = fs[k][1]
4557  fnames[k] = to_symbol(fname, ctx)
4558  if isinstance(ftype, Datatype):
4559  if __debug__:
4560  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4561  sorts[k] = None
4562  refs[k] = ds.index(ftype)
4563  else:
4564  if __debug__:
4565  _z3_assert(is_sort(ftype), "Z3 sort expected")
4566  sorts[k] = ftype.ast
4567  refs[k] = 0
4568  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4569  to_delete.append(ScopedConstructor(cs[j], ctx))
4570  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4571  to_delete.append(ScopedConstructorList(clists[i], ctx))
4572  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4573  result = []
4574  ## Create a field for every constructor, recognizer and accessor
4575  for i in range(num):
4576  dref = DatatypeSortRef(out[i], ctx)
4577  num_cs = dref.num_constructors()
4578  for j in range(num_cs):
4579  cref = dref.constructor(j)
4580  cref_name = cref.name()
4581  cref_arity = cref.arity()
4582  if cref.arity() == 0:
4583  cref = cref()
4584  setattr(dref, cref_name, cref)
4585  rref = dref.recognizer(j)
4586  setattr(dref, "is_" + cref_name, rref)
4587  for k in range(cref_arity):
4588  aref = dref.accessor(j, k)
4589  setattr(dref, aref.name(), aref)
4590  result.append(dref)
4591  return tuple(result)
4592 
4593 class DatatypeSortRef(SortRef):
4594  """Datatype sorts."""
4595  def num_constructors(self):
4596  """Return the number of constructors in the given Z3 datatype.
4597 
4598  >>> List = Datatype('List')
4599  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4600  >>> List.declare('nil')
4601  >>> List = List.create()
4602  >>> # List is now a Z3 declaration
4603  >>> List.num_constructors()
4604  2
4605  """
4606  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4607 
4608  def constructor(self, idx):
4609  """Return a constructor of the datatype `self`.
4610 
4611  >>> List = Datatype('List')
4612  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4613  >>> List.declare('nil')
4614  >>> List = List.create()
4615  >>> # List is now a Z3 declaration
4616  >>> List.num_constructors()
4617  2
4618  >>> List.constructor(0)
4619  cons
4620  >>> List.constructor(1)
4621  nil
4622  """
4623  if __debug__:
4624  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4625  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4626 
4627  def recognizer(self, idx):
4628  """In Z3, each constructor has an associated recognizer predicate.
4629 
4630  If the constructor is named `name`, then the recognizer `is_name`.
4631 
4632  >>> List = Datatype('List')
4633  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4634  >>> List.declare('nil')
4635  >>> List = List.create()
4636  >>> # List is now a Z3 declaration
4637  >>> List.num_constructors()
4638  2
4639  >>> List.recognizer(0)
4640  is(cons)
4641  >>> List.recognizer(1)
4642  is(nil)
4643  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4644  False
4645  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4646  True
4647  >>> l = Const('l', List)
4648  >>> simplify(List.is_cons(l))
4649  is(cons, l)
4650  """
4651  if __debug__:
4652  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4653  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4654 
4655  def accessor(self, i, j):
4656  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4657 
4658  >>> List = Datatype('List')
4659  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4660  >>> List.declare('nil')
4661  >>> List = List.create()
4662  >>> List.num_constructors()
4663  2
4664  >>> List.constructor(0)
4665  cons
4666  >>> num_accs = List.constructor(0).arity()
4667  >>> num_accs
4668  2
4669  >>> List.accessor(0, 0)
4670  car
4671  >>> List.accessor(0, 1)
4672  cdr
4673  >>> List.constructor(1)
4674  nil
4675  >>> num_accs = List.constructor(1).arity()
4676  >>> num_accs
4677  0
4678  """
4679  if __debug__:
4680  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4681  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4682  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4683 
4684 class DatatypeRef(ExprRef):
4685  """Datatype expressions."""
4686  def sort(self):
4687  """Return the datatype sort of the datatype expression `self`."""
4688  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4689 
4690 def EnumSort(name, values, ctx=None):
4691  """Return a new enumeration sort named `name` containing the given values.
4692 
4693  The result is a pair (sort, list of constants).
4694  Example:
4695  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4696  """
4697  if __debug__:
4698  _z3_assert(isinstance(name, str), "Name must be a string")
4699  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4700  _z3_assert(len(values) > 0, "At least one value expected")
4701  ctx = _get_ctx(ctx)
4702  num = len(values)
4703  _val_names = (Symbol * num)()
4704  for i in range(num):
4705  _val_names[i] = to_symbol(values[i])
4706  _values = (FuncDecl * num)()
4707  _testers = (FuncDecl * num)()
4708  name = to_symbol(name)
4709  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4710  V = []
4711  for i in range(num):
4712  V.append(FuncDeclRef(_values[i], ctx))
4713  V = [a() for a in V]
4714  return S, V
4715 
4716 #########################################
4717 #
4718 # Parameter Sets
4719 #
4720 #########################################
4721 
4722 class ParamsRef:
4723  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4724 
4725  Consider using the function `args2params` to create instances of this object.
4726  """
4727  def __init__(self, ctx=None, params=None):
4728  self.ctx = _get_ctx(ctx)
4729  if params is None:
4730  self.params = Z3_mk_params(self.ctx.ref())
4731  else:
4732  self.params = params
4733  Z3_params_inc_ref(self.ctx.ref(), self.params)
4734 
4735  def __deepcopy__(self, memo={}):
4736  return ParamsRef(self.ctx, self.params)
4737 
4738  def __del__(self):
4739  if self.ctx.ref() is not None:
4740  Z3_params_dec_ref(self.ctx.ref(), self.params)
4741 
4742  def set(self, name, val):
4743  """Set parameter name with value val."""
4744  if __debug__:
4745  _z3_assert(isinstance(name, str), "parameter name must be a string")
4746  name_sym = to_symbol(name, self.ctx)
4747  if isinstance(val, bool):
4748  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4749  elif _is_int(val):
4750  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4751  elif isinstance(val, float):
4752  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4753  elif isinstance(val, str):
4754  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4755  else:
4756  if __debug__:
4757  _z3_assert(False, "invalid parameter value")
4758 
4759  def __repr__(self):
4760  return Z3_params_to_string(self.ctx.ref(), self.params)
4761 
4762  def validate(self, ds):
4763  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
4764  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
4765 
4766 def args2params(arguments, keywords, ctx=None):
4767  """Convert python arguments into a Z3_params object.
4768  A ':' is added to the keywords, and '_' is replaced with '-'
4769 
4770  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
4771  (params model true relevancy 2 elim_and true)
4772  """
4773  if __debug__:
4774  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
4775  prev = None
4776  r = ParamsRef(ctx)
4777  for a in arguments:
4778  if prev is None:
4779  prev = a
4780  else:
4781  r.set(prev, a)
4782  prev = None
4783  for k in keywords:
4784  v = keywords[k]
4785  r.set(k, v)
4786  return r
4787 
4788 class ParamDescrsRef:
4789  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
4790  """
4791  def __init__(self, descr, ctx=None):
4792  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
4793  self.ctx = _get_ctx(ctx)
4794  self.descr = descr
4795  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
4796 
4797  def __deepcopy__(self, memo={}):
4798  return ParamsDescrsRef(self.descr, self.ctx)
4799 
4800  def __del__(self):
4801  if self.ctx.ref() is not None:
4802  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
4803 
4804  def size(self):
4805  """Return the size of in the parameter description `self`.
4806  """
4807  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
4808 
4809  def __len__(self):
4810  """Return the size of in the parameter description `self`.
4811  """
4812  return self.size()
4813 
4814  def get_name(self, i):
4815  """Return the i-th parameter name in the parameter description `self`.
4816  """
4817  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
4818 
4819  def get_kind(self, n):
4820  """Return the kind of the parameter named `n`.
4821  """
4822  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4823 
4824  def get_documentation(self, n):
4825  """Return the documentation string of the parameter named `n`.
4826  """
4827  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4828 
4829  def __getitem__(self, arg):
4830  if _is_int(arg):
4831  return self.get_name(arg)
4832  else:
4833  return self.get_kind(arg)
4834 
4835  def __repr__(self):
4836  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
4837 
4838 #########################################
4839 #
4840 # Goals
4841 #
4842 #########################################
4843 
4844 class Goal(Z3PPObject):
4845  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
4846 
4847  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
4848  A goal has a solution if one of its subgoals has a solution.
4849  A goal is unsatisfiable if all subgoals are unsatisfiable.
4850  """
4851 
4852  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
4853  if __debug__:
4854  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
4855  self.ctx = _get_ctx(ctx)
4856  self.goal = goal
4857  if self.goal is None:
4858  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
4859  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
4860 
4861  def __deepcopy__(self, memo={}):
4862  return Goal(False, False, False, self.ctx, self.goal)
4863 
4864  def __del__(self):
4865  if self.goal is not None and self.ctx.ref() is not None:
4866  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
4867 
4868  def depth(self):
4869  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
4870 
4871  >>> x, y = Ints('x y')
4872  >>> g = Goal()
4873  >>> g.add(x == 0, y >= x + 1)
4874  >>> g.depth()
4875  0
4876  >>> r = Then('simplify', 'solve-eqs')(g)
4877  >>> # r has 1 subgoal
4878  >>> len(r)
4879  1
4880  >>> r[0].depth()
4881  2
4882  """
4883  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
4884 
4885  def inconsistent(self):
4886  """Return `True` if `self` contains the `False` constraints.
4887 
4888  >>> x, y = Ints('x y')
4889  >>> g = Goal()
4890  >>> g.inconsistent()
4891  False
4892  >>> g.add(x == 0, x == 1)
4893  >>> g
4894  [x == 0, x == 1]
4895  >>> g.inconsistent()
4896  False
4897  >>> g2 = Tactic('propagate-values')(g)[0]
4898  >>> g2.inconsistent()
4899  True
4900  """
4901  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
4902 
4903  def prec(self):
4904  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
4905 
4906  >>> g = Goal()
4907  >>> g.prec() == Z3_GOAL_PRECISE
4908  True
4909  >>> x, y = Ints('x y')
4910  >>> g.add(x == y + 1)
4911  >>> g.prec() == Z3_GOAL_PRECISE
4912  True
4913  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
4914  >>> g2 = t(g)[0]
4915  >>> g2
4916  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
4917  >>> g2.prec() == Z3_GOAL_PRECISE
4918  False
4919  >>> g2.prec() == Z3_GOAL_UNDER
4920  True
4921  """
4922  return Z3_goal_precision(self.ctx.ref(), self.goal)
4923 
4924  def precision(self):
4925  """Alias for `prec()`.
4926 
4927  >>> g = Goal()
4928  >>> g.precision() == Z3_GOAL_PRECISE
4929  True
4930  """
4931  return self.prec()
4932 
4933  def size(self):
4934  """Return the number of constraints in the goal `self`.
4935 
4936  >>> g = Goal()
4937  >>> g.size()
4938  0
4939  >>> x, y = Ints('x y')
4940  >>> g.add(x == 0, y > x)
4941  >>> g.size()
4942  2
4943  """
4944  return int(Z3_goal_size(self.ctx.ref(), self.goal))
4945 
4946  def __len__(self):
4947  """Return the number of constraints in the goal `self`.
4948 
4949  >>> g = Goal()
4950  >>> len(g)
4951  0
4952  >>> x, y = Ints('x y')
4953  >>> g.add(x == 0, y > x)
4954  >>> len(g)
4955  2
4956  """
4957  return self.size()
4958 
4959  def get(self, i):
4960  """Return a constraint in the goal `self`.
4961 
4962  >>> g = Goal()
4963  >>> x, y = Ints('x y')
4964  >>> g.add(x == 0, y > x)
4965  >>> g.get(0)
4966  x == 0
4967  >>> g.get(1)
4968  y > x
4969  """
4970  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
4971 
4972  def __getitem__(self, arg):
4973  """Return a constraint in the goal `self`.
4974 
4975  >>> g = Goal()
4976  >>> x, y = Ints('x y')
4977  >>> g.add(x == 0, y > x)
4978  >>> g[0]
4979  x == 0
4980  >>> g[1]
4981  y > x
4982  """
4983  if arg >= len(self):
4984  raise IndexError
4985  return self.get(arg)
4986 
4987  def assert_exprs(self, *args):
4988  """Assert constraints into the goal.
4989 
4990  >>> x = Int('x')
4991  >>> g = Goal()
4992  >>> g.assert_exprs(x > 0, x < 2)
4993  >>> g
4994  [x > 0, x < 2]
4995  """
4996  args = _get_args(args)
4997  s = BoolSort(self.ctx)
4998  for arg in args:
4999  arg = s.cast(arg)
5000  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5001 
5002  def append(self, *args):
5003  """Add constraints.
5004 
5005  >>> x = Int('x')
5006  >>> g = Goal()
5007  >>> g.append(x > 0, x < 2)
5008  >>> g
5009  [x > 0, x < 2]
5010  """
5011  self.assert_exprs(*args)
5012 
5013  def insert(self, *args):
5014  """Add constraints.
5015 
5016  >>> x = Int('x')
5017  >>> g = Goal()
5018  >>> g.insert(x > 0, x < 2)
5019  >>> g
5020  [x > 0, x < 2]
5021  """
5022  self.assert_exprs(*args)
5023 
5024  def add(self, *args):
5025  """Add constraints.
5026 
5027  >>> x = Int('x')
5028  >>> g = Goal()
5029  >>> g.add(x > 0, x < 2)
5030  >>> g
5031  [x > 0, x < 2]
5032  """
5033  self.assert_exprs(*args)
5034 
5035  def __repr__(self):
5036  return obj_to_string(self)
5037 
5038  def sexpr(self):
5039  """Return a textual representation of the s-expression representing the goal."""
5040  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5041 
5042  def translate(self, target):
5043  """Copy goal `self` to context `target`.
5044 
5045  >>> x = Int('x')
5046  >>> g = Goal()
5047  >>> g.add(x > 10)
5048  >>> g
5049  [x > 10]
5050  >>> c2 = Context()
5051  >>> g2 = g.translate(c2)
5052  >>> g2
5053  [x > 10]
5054  >>> g.ctx == main_ctx()
5055  True
5056  >>> g2.ctx == c2
5057  True
5058  >>> g2.ctx == main_ctx()
5059  False
5060  """
5061  if __debug__:
5062  _z3_assert(isinstance(target, Context), "target must be a context")
5063  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5064 
5065  def __copy__(self):
5066  return self.translate(self.ctx)
5067 
5068  def __deepcopy__(self):
5069  return self.translate(self.ctx)
5070 
5071  def simplify(self, *arguments, **keywords):
5072  """Return a new simplified goal.
5073 
5074  This method is essentially invoking the simplify tactic.
5075 
5076  >>> g = Goal()
5077  >>> x = Int('x')
5078  >>> g.add(x + 1 >= 2)
5079  >>> g
5080  [x + 1 >= 2]
5081  >>> g2 = g.simplify()
5082  >>> g2
5083  [x >= 1]
5084  >>> # g was not modified
5085  >>> g
5086  [x + 1 >= 2]
5087  """
5088  t = Tactic('simplify')
5089  return t.apply(self, *arguments, **keywords)[0]
5090 
5091  def as_expr(self):
5092  """Return goal `self` as a single Z3 expression.
5093 
5094  >>> x = Int('x')
5095  >>> g = Goal()
5096  >>> g.as_expr()
5097  True
5098  >>> g.add(x > 1)
5099  >>> g.as_expr()
5100  x > 1
5101  >>> g.add(x < 10)
5102  >>> g.as_expr()
5103  And(x > 1, x < 10)
5104  """
5105  sz = len(self)
5106  if sz == 0:
5107  return BoolVal(True, self.ctx)
5108  elif sz == 1:
5109  return self.get(0)
5110  else:
5111  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5112 
5113 #########################################
5114 #
5115 # AST Vector
5116 #
5117 #########################################
5118 class AstVector(Z3PPObject):
5119  """A collection (vector) of ASTs."""
5120 
5121  def __init__(self, v=None, ctx=None):
5122  self.vector = None
5123  if v is None:
5124  self.ctx = _get_ctx(ctx)
5125  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5126  else:
5127  self.vector = v
5128  assert ctx is not None
5129  self.ctx = ctx
5130  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5131 
5132  def __deepcopy__(self, memo={}):
5133  return AstVector(self.vector, self.ctx)
5134 
5135  def __del__(self):
5136  if self.vector is not None and self.ctx.ref() is not None:
5137  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5138 
5139  def __len__(self):
5140  """Return the size of the vector `self`.
5141 
5142  >>> A = AstVector()
5143  >>> len(A)
5144  0
5145  >>> A.push(Int('x'))
5146  >>> A.push(Int('x'))
5147  >>> len(A)
5148  2
5149  """
5150  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5151 
5152  def __getitem__(self, i):
5153  """Return the AST at position `i`.
5154 
5155  >>> A = AstVector()
5156  >>> A.push(Int('x') + 1)
5157  >>> A.push(Int('y'))
5158  >>> A[0]
5159  x + 1
5160  >>> A[1]
5161  y
5162  """
5163 
5164  if isinstance(i, int):
5165  if i < 0:
5166  i += self.__len__()
5167 
5168  if i >= self.__len__():
5169  raise IndexError
5170  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5171 
5172  elif isinstance(i, slice):
5173  return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5174 
5175 
5176  def __setitem__(self, i, v):
5177  """Update AST at position `i`.
5178 
5179  >>> A = AstVector()
5180  >>> A.push(Int('x') + 1)
5181  >>> A.push(Int('y'))
5182  >>> A[0]
5183  x + 1
5184  >>> A[0] = Int('x')
5185  >>> A[0]
5186  x
5187  """
5188  if i >= self.__len__():
5189  raise IndexError
5190  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5191 
5192  def push(self, v):
5193  """Add `v` in the end of the vector.
5194 
5195  >>> A = AstVector()
5196  >>> len(A)
5197  0
5198  >>> A.push(Int('x'))
5199  >>> len(A)
5200  1
5201  """
5202  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5203 
5204  def resize(self, sz):
5205  """Resize the vector to `sz` elements.
5206 
5207  >>> A = AstVector()
5208  >>> A.resize(10)
5209  >>> len(A)
5210  10
5211  >>> for i in range(10): A[i] = Int('x')
5212  >>> A[5]
5213  x
5214  """
5215  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5216 
5217  def __contains__(self, item):
5218  """Return `True` if the vector contains `item`.
5219 
5220  >>> x = Int('x')
5221  >>> A = AstVector()
5222  >>> x in A
5223  False
5224  >>> A.push(x)
5225  >>> x in A
5226  True
5227  >>> (x+1) in A
5228  False
5229  >>> A.push(x+1)
5230  >>> (x+1) in A
5231  True
5232  >>> A
5233  [x, x + 1]
5234  """
5235  for elem in self:
5236  if elem.eq(item):
5237  return True
5238  return False
5239 
5240  def translate(self, other_ctx):
5241  """Copy vector `self` to context `other_ctx`.
5242 
5243  >>> x = Int('x')
5244  >>> A = AstVector()
5245  >>> A.push(x)
5246  >>> c2 = Context()
5247  >>> B = A.translate(c2)
5248  >>> B
5249  [x]
5250  """
5251  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5252 
5253  def __copy__(self):
5254  return self.translate(self.ctx)
5255 
5256  def __deepcopy__(self):
5257  return self.translate(self.ctx)
5258 
5259  def __repr__(self):
5260  return obj_to_string(self)
5261 
5262  def sexpr(self):
5263  """Return a textual representation of the s-expression representing the vector."""
5264  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5265 
5266 #########################################
5267 #
5268 # AST Map
5269 #
5270 #########################################
5271 class AstMap:
5272  """A mapping from ASTs to ASTs."""
5273 
5274  def __init__(self, m=None, ctx=None):
5275  self.map = None
5276  if m is None:
5277  self.ctx = _get_ctx(ctx)
5278  self.map = Z3_mk_ast_map(self.ctx.ref())
5279  else:
5280  self.map = m
5281  assert ctx is not None
5282  self.ctx = ctx
5283  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5284 
5285  def __deepcopy__(self, memo={}):
5286  return AstMap(self.map, self.ctx)
5287 
5288  def __del__(self):
5289  if self.map is not None and self.ctx.ref() is not None:
5290  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5291 
5292  def __len__(self):
5293  """Return the size of the map.
5294 
5295  >>> M = AstMap()
5296  >>> len(M)
5297  0
5298  >>> x = Int('x')
5299  >>> M[x] = IntVal(1)
5300  >>> len(M)
5301  1
5302  """
5303  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5304 
5305  def __contains__(self, key):
5306  """Return `True` if the map contains key `key`.
5307 
5308  >>> M = AstMap()
5309  >>> x = Int('x')
5310  >>> M[x] = x + 1
5311  >>> x in M
5312  True
5313  >>> x+1 in M
5314  False
5315  """
5316  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5317 
5318  def __getitem__(self, key):
5319  """Retrieve the value associated with key `key`.
5320 
5321  >>> M = AstMap()
5322  >>> x = Int('x')
5323  >>> M[x] = x + 1
5324  >>> M[x]
5325  x + 1
5326  """
5327  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5328 
5329  def __setitem__(self, k, v):
5330  """Add/Update key `k` with value `v`.
5331 
5332  >>> M = AstMap()
5333  >>> x = Int('x')
5334  >>> M[x] = x + 1
5335  >>> len(M)
5336  1
5337  >>> M[x]
5338  x + 1
5339  >>> M[x] = IntVal(1)
5340  >>> M[x]
5341  1
5342  """
5343  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5344 
5345  def __repr__(self):
5346  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5347 
5348  def erase(self, k):
5349  """Remove the entry associated with key `k`.
5350 
5351  >>> M = AstMap()
5352  >>> x = Int('x')
5353  >>> M[x] = x + 1
5354  >>> len(M)
5355  1
5356  >>> M.erase(x)
5357  >>> len(M)
5358  0
5359  """
5360  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5361 
5362  def reset(self):
5363  """Remove all entries from the map.
5364 
5365  >>> M = AstMap()
5366  >>> x = Int('x')
5367  >>> M[x] = x + 1
5368  >>> M[x+x] = IntVal(1)
5369  >>> len(M)
5370  2
5371  >>> M.reset()
5372  >>> len(M)
5373  0
5374  """
5375  Z3_ast_map_reset(self.ctx.ref(), self.map)
5376 
5377  def keys(self):
5378  """Return an AstVector containing all keys in the map.
5379 
5380  >>> M = AstMap()
5381  >>> x = Int('x')
5382  >>> M[x] = x + 1
5383  >>> M[x+x] = IntVal(1)
5384  >>> M.keys()
5385  [x, x + x]
5386  """
5387  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5388 
5389 #########################################
5390 #
5391 # Model
5392 #
5393 #########################################
5394 
5395 class FuncEntry:
5396  """Store the value of the interpretation of a function in a particular point."""
5397 
5398  def __init__(self, entry, ctx):
5399  self.entry = entry
5400  self.ctx = ctx
5401  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5402 
5403  def __deepcopy__(self, memo={}):
5404  return FuncEntry(self.entry, self.ctx)
5405 
5406  def __del__(self):
5407  if self.ctx.ref() is not None:
5408  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5409 
5410  def num_args(self):
5411  """Return the number of arguments in the given entry.
5412 
5413  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5414  >>> s = Solver()
5415  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5416  >>> s.check()
5417  sat
5418  >>> m = s.model()
5419  >>> f_i = m[f]
5420  >>> f_i.num_entries()
5421  3
5422  >>> e = f_i.entry(0)
5423  >>> e.num_args()
5424  2
5425  """
5426  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5427 
5428  def arg_value(self, idx):
5429  """Return the value of argument `idx`.
5430 
5431  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5432  >>> s = Solver()
5433  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5434  >>> s.check()
5435  sat
5436  >>> m = s.model()
5437  >>> f_i = m[f]
5438  >>> f_i.num_entries()
5439  3
5440  >>> e = f_i.entry(0)
5441  >>> e
5442  [0, 1, 10]
5443  >>> e.num_args()
5444  2
5445  >>> e.arg_value(0)
5446  0
5447  >>> e.arg_value(1)
5448  1
5449  >>> try:
5450  ... e.arg_value(2)
5451  ... except IndexError:
5452  ... print("index error")
5453  index error
5454  """
5455  if idx >= self.num_args():
5456  raise IndexError
5457  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5458 
5459  def value(self):
5460  """Return the value of the function at point `self`.
5461 
5462  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5463  >>> s = Solver()
5464  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5465  >>> s.check()
5466  sat
5467  >>> m = s.model()
5468  >>> f_i = m[f]
5469  >>> f_i.num_entries()
5470  3
5471  >>> e = f_i.entry(0)
5472  >>> e
5473  [0, 1, 10]
5474  >>> e.num_args()
5475  2
5476  >>> e.value()
5477  10
5478  """
5479  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5480 
5481  def as_list(self):
5482  """Return entry `self` as a Python list.
5483  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5484  >>> s = Solver()
5485  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5486  >>> s.check()
5487  sat
5488  >>> m = s.model()
5489  >>> f_i = m[f]
5490  >>> f_i.num_entries()
5491  3
5492  >>> e = f_i.entry(0)
5493  >>> e.as_list()
5494  [0, 1, 10]
5495  """
5496  args = [ self.arg_value(i) for i in range(self.num_args())]
5497  args.append(self.value())
5498  return args
5499 
5500  def __repr__(self):
5501  return repr(self.as_list())
5502 
5503 class FuncInterp(Z3PPObject):
5504  """Stores the interpretation of a function in a Z3 model."""
5505 
5506  def __init__(self, f, ctx):
5507  self.f = f
5508  self.ctx = ctx
5509  if self.f is not None:
5510  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5511 
5512  def __deepcopy__(self, memo={}):
5513  return FuncInterp(self.f, self.ctx)
5514 
5515  def __del__(self):
5516  if self.f is not None and self.ctx.ref() is not None:
5517  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5518 
5519  def else_value(self):
5520  """
5521  Return the `else` value for a function interpretation.
5522  Return None if Z3 did not specify the `else` value for
5523  this object.
5524 
5525  >>> f = Function('f', IntSort(), IntSort())
5526  >>> s = Solver()
5527  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5528  >>> s.check()
5529  sat
5530  >>> m = s.model()
5531  >>> m[f]
5532  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5533  >>> m[f].else_value()
5534  1
5535  """
5536  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5537  if r:
5538  return _to_expr_ref(r, self.ctx)
5539  else:
5540  return None
5541 
5542  def num_entries(self):
5543  """Return the number of entries/points in the function interpretation `self`.
5544 
5545  >>> f = Function('f', IntSort(), IntSort())
5546  >>> s = Solver()
5547  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5548  >>> s.check()
5549  sat
5550  >>> m = s.model()
5551  >>> m[f]
5552  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5553  >>> m[f].num_entries()
5554  3
5555  """
5556  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5557 
5558  def arity(self):
5559  """Return the number of arguments for each entry in the function interpretation `self`.
5560 
5561  >>> f = Function('f', IntSort(), IntSort())
5562  >>> s = Solver()
5563  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5564  >>> s.check()
5565  sat
5566  >>> m = s.model()
5567  >>> m[f].arity()
5568  1
5569  """
5570  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5571 
5572  def entry(self, idx):
5573  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5574 
5575  >>> f = Function('f', IntSort(), IntSort())
5576  >>> s = Solver()
5577  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5578  >>> s.check()
5579  sat
5580  >>> m = s.model()
5581  >>> m[f]
5582  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5583  >>> m[f].num_entries()
5584  3
5585  >>> m[f].entry(0)
5586  [0, 1]
5587  >>> m[f].entry(1)
5588  [1, 1]
5589  >>> m[f].entry(2)
5590  [2, 0]
5591  """
5592  if idx >= self.num_entries():
5593  raise IndexError
5594  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5595 
5596  def translate(self, other_ctx):
5597  """Copy model 'self' to context 'other_ctx'.
5598  """
5599  return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5600 
5601  def __copy__(self):
5602  return self.translate(self.ctx)
5603 
5604  def __deepcopy__(self):
5605  return self.translate(self.ctx)
5606 
5607  def as_list(self):
5608  """Return the function interpretation as a Python list.
5609  >>> f = Function('f', IntSort(), IntSort())
5610  >>> s = Solver()
5611  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5612  >>> s.check()
5613  sat
5614  >>> m = s.model()
5615  >>> m[f]
5616  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5617  >>> m[f].as_list()
5618  [[0, 1], [1, 1], [2, 0], 1]
5619  """
5620  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5621  r.append(self.else_value())
5622  return r
5623 
5624  def __repr__(self):
5625  return obj_to_string(self)
5626 
5627 class ModelRef(Z3PPObject):
5628  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5629 
5630  def __init__(self, m, ctx):
5631  assert ctx is not None
5632  self.model = m
5633  self.ctx = ctx
5634  Z3_model_inc_ref(self.ctx.ref(), self.model)
5635 
5636  def __del__(self):
5637  if self.ctx.ref() is not None:
5638  Z3_model_dec_ref(self.ctx.ref(), self.model)
5639 
5640  def __repr__(self):
5641  return obj_to_string(self)
5642 
5643  def sexpr(self):
5644  """Return a textual representation of the s-expression representing the model."""
5645  return Z3_model_to_string(self.ctx.ref(), self.model)
5646 
5647  def eval(self, t, model_completion=False):
5648  """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`.
5649 
5650  >>> x = Int('x')
5651  >>> s = Solver()
5652  >>> s.add(x > 0, x < 2)
5653  >>> s.check()
5654  sat
5655  >>> m = s.model()
5656  >>> m.eval(x + 1)
5657  2
5658  >>> m.eval(x == 1)
5659  True
5660  >>> y = Int('y')
5661  >>> m.eval(y + x)
5662  1 + y
5663  >>> m.eval(y)
5664  y
5665  >>> m.eval(y, model_completion=True)
5666  0
5667  >>> # Now, m contains an interpretation for y
5668  >>> m.eval(y + x)
5669  1
5670  """
5671  r = (Ast * 1)()
5672  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5673  return _to_expr_ref(r[0], self.ctx)
5674  raise Z3Exception("failed to evaluate expression in the model")
5675 
5676  def evaluate(self, t, model_completion=False):
5677  """Alias for `eval`.
5678 
5679  >>> x = Int('x')
5680  >>> s = Solver()
5681  >>> s.add(x > 0, x < 2)
5682  >>> s.check()
5683  sat
5684  >>> m = s.model()
5685  >>> m.evaluate(x + 1)
5686  2
5687  >>> m.evaluate(x == 1)
5688  True
5689  >>> y = Int('y')
5690  >>> m.evaluate(y + x)
5691  1 + y
5692  >>> m.evaluate(y)
5693  y
5694  >>> m.evaluate(y, model_completion=True)
5695  0
5696  >>> # Now, m contains an interpretation for y
5697  >>> m.evaluate(y + x)
5698  1
5699  """
5700  return self.eval(t, model_completion)
5701 
5702  def __len__(self):
5703  """Return the number of constant and function declarations in the model `self`.
5704 
5705  >>> f = Function('f', IntSort(), IntSort())
5706  >>> x = Int('x')
5707  >>> s = Solver()
5708  >>> s.add(x > 0, f(x) != x)
5709  >>> s.check()
5710  sat
5711  >>> m = s.model()
5712  >>> len(m)
5713  2
5714  """
5715  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5716 
5717  def get_interp(self, decl):
5718  """Return the interpretation for a given declaration or constant.
5719 
5720  >>> f = Function('f', IntSort(), IntSort())
5721  >>> x = Int('x')
5722  >>> s = Solver()
5723  >>> s.add(x > 0, x < 2, f(x) == 0)
5724  >>> s.check()
5725  sat
5726  >>> m = s.model()
5727  >>> m[x]
5728  1
5729  >>> m[f]
5730  [1 -> 0, else -> 0]
5731  """
5732  if __debug__:
5733  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
5734  if is_const(decl):
5735  decl = decl.decl()
5736  try:
5737  if decl.arity() == 0:
5738  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
5739  if _r.value is None:
5740  return None
5741  r = _to_expr_ref(_r, self.ctx)
5742  if is_as_array(r):
5743  return self.get_interp(get_as_array_func(r))
5744  else:
5745  return r
5746  else:
5747  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
5748  except Z3Exception:
5749  return None
5750 
5751  def num_sorts(self):
5752  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
5753 
5754  >>> A = DeclareSort('A')
5755  >>> a, b = Consts('a b', A)
5756  >>> s = Solver()
5757  >>> s.add(a != b)
5758  >>> s.check()
5759  sat
5760  >>> m = s.model()
5761  >>> m.num_sorts()
5762  1
5763  """
5764  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
5765 
5766  def get_sort(self, idx):
5767  """Return the uninterpreted sort at position `idx` < self.num_sorts().
5768 
5769  >>> A = DeclareSort('A')
5770  >>> B = DeclareSort('B')
5771  >>> a1, a2 = Consts('a1 a2', A)
5772  >>> b1, b2 = Consts('b1 b2', B)
5773  >>> s = Solver()
5774  >>> s.add(a1 != a2, b1 != b2)
5775  >>> s.check()
5776  sat
5777  >>> m = s.model()
5778  >>> m.num_sorts()
5779  2
5780  >>> m.get_sort(0)
5781  A
5782  >>> m.get_sort(1)
5783  B
5784  """
5785  if idx >= self.num_sorts():
5786  raise IndexError
5787  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
5788 
5789  def sorts(self):
5790  """Return all uninterpreted sorts that have an interpretation in the model `self`.
5791 
5792  >>> A = DeclareSort('A')
5793  >>> B = DeclareSort('B')
5794  >>> a1, a2 = Consts('a1 a2', A)
5795  >>> b1, b2 = Consts('b1 b2', B)
5796  >>> s = Solver()
5797  >>> s.add(a1 != a2, b1 != b2)
5798  >>> s.check()
5799  sat
5800  >>> m = s.model()
5801  >>> m.sorts()
5802  [A, B]
5803  """
5804  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
5805 
5806  def get_universe(self, s):
5807  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
5808 
5809  >>> A = DeclareSort('A')
5810  >>> a, b = Consts('a b', A)
5811  >>> s = Solver()
5812  >>> s.add(a != b)
5813  >>> s.check()
5814  sat
5815  >>> m = s.model()
5816  >>> m.get_universe(A)
5817  [A!val!0, A!val!1]
5818  """
5819  if __debug__:
5820  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
5821  try:
5822  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
5823  except Z3Exception:
5824  return None
5825 
5826  def __getitem__(self, idx):
5827  """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.
5828 
5829  The elements can be retrieved using position or the actual declaration.
5830 
5831  >>> f = Function('f', IntSort(), IntSort())
5832  >>> x = Int('x')
5833  >>> s = Solver()
5834  >>> s.add(x > 0, x < 2, f(x) == 0)
5835  >>> s.check()
5836  sat
5837  >>> m = s.model()
5838  >>> len(m)
5839  2
5840  >>> m[0]
5841  x
5842  >>> m[1]
5843  f
5844  >>> m[x]
5845  1
5846  >>> m[f]
5847  [1 -> 0, else -> 0]
5848  >>> for d in m: print("%s -> %s" % (d, m[d]))
5849  x -> 1
5850  f -> [1 -> 0, else -> 0]
5851  """
5852  if _is_int(idx):
5853  if idx >= len(self):
5854  raise IndexError
5855  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
5856  if (idx < num_consts):
5857  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
5858  else:
5859  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
5860  if isinstance(idx, FuncDeclRef):
5861  return self.get_interp(idx)
5862  if is_const(idx):
5863  return self.get_interp(idx.decl())
5864  if isinstance(idx, SortRef):
5865  return self.get_universe(idx)
5866  if __debug__:
5867  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
5868  return None
5869 
5870  def decls(self):
5871  """Return a list with all symbols that have an interpretation in the model `self`.
5872  >>> f = Function('f', IntSort(), IntSort())
5873  >>> x = Int('x')
5874  >>> s = Solver()
5875  >>> s.add(x > 0, x < 2, f(x) == 0)
5876  >>> s.check()
5877  sat
5878  >>> m = s.model()
5879  >>> m.decls()
5880  [x, f]
5881  """
5882  r = []
5883  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
5884  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
5885  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
5886  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
5887  return r
5888 
5889  def translate(self, target):
5890  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
5891  """
5892  if __debug__:
5893  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
5894  model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
5895  return Model(model, target)
5896 
5897  def __copy__(self):
5898  return self.translate(self.ctx)
5899 
5900  def __deepcopy__(self):
5901  return self.translate(self.ctx)
5902 
5903 def is_as_array(n):
5904  """Return true if n is a Z3 expression of the form (_ as-array f)."""
5905  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
5906 
5907 def get_as_array_func(n):
5908  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
5909  if __debug__:
5910  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
5911  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
5912 
5913 #########################################
5914 #
5915 # Statistics
5916 #
5917 #########################################
5918 class Statistics:
5919  """Statistics for `Solver.check()`."""
5920 
5921  def __init__(self, stats, ctx):
5922  self.stats = stats
5923  self.ctx = ctx
5924  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
5925 
5926  def __deepcopy__(self, memo={}):
5927  return Statistics(self.stats, self.ctx)
5928 
5929  def __del__(self):
5930  if self.ctx.ref() is not None:
5931  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
5932 
5933  def __repr__(self):
5934  if in_html_mode():
5935  out = io.StringIO()
5936  even = True
5937  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
5938  for k, v in self:
5939  if even:
5940  out.write(u('<tr style="background-color:#CFCFCF">'))
5941  even = False
5942  else:
5943  out.write(u('<tr>'))
5944  even = True
5945  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
5946  out.write(u('</table>'))
5947  return out.getvalue()
5948  else:
5949  return Z3_stats_to_string(self.ctx.ref(), self.stats)
5950 
5951  def __len__(self):
5952  """Return the number of statistical counters.
5953 
5954  >>> x = Int('x')
5955  >>> s = Then('simplify', 'nlsat').solver()
5956  >>> s.add(x > 0)
5957  >>> s.check()
5958  sat
5959  >>> st = s.statistics()
5960  >>> len(st)
5961  6
5962  """
5963  return int(Z3_stats_size(self.ctx.ref(), self.stats))
5964 
5965  def __getitem__(self, idx):
5966  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
5967 
5968  >>> x = Int('x')
5969  >>> s = Then('simplify', 'nlsat').solver()
5970  >>> s.add(x > 0)
5971  >>> s.check()
5972  sat
5973  >>> st = s.statistics()
5974  >>> len(st)
5975  6
5976  >>> st[0]
5977  ('nlsat propagations', 2)
5978  >>> st[1]
5979  ('nlsat stages', 2)
5980  """
5981  if idx >= len(self):
5982  raise IndexError
5983  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5984  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5985  else:
5986  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5987  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
5988 
5989  def keys(self):
5990  """Return the list of statistical counters.
5991 
5992  >>> x = Int('x')
5993  >>> s = Then('simplify', 'nlsat').solver()
5994  >>> s.add(x > 0)
5995  >>> s.check()
5996  sat
5997  >>> st = s.statistics()
5998  """
5999  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6000 
6001  def get_key_value(self, key):
6002  """Return the value of a particular statistical counter.
6003 
6004  >>> x = Int('x')
6005  >>> s = Then('simplify', 'nlsat').solver()
6006  >>> s.add(x > 0)
6007  >>> s.check()
6008  sat
6009  >>> st = s.statistics()
6010  >>> st.get_key_value('nlsat propagations')
6011  2
6012  """
6013  for idx in range(len(self)):
6014  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6015  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6016  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6017  else:
6018  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6019  raise Z3Exception("unknown key")
6020 
6021  def __getattr__(self, name):
6022  """Access the value of statistical using attributes.
6023 
6024  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6025  we should use '_' (e.g., 'nlsat_propagations').
6026 
6027  >>> x = Int('x')
6028  >>> s = Then('simplify', 'nlsat').solver()
6029  >>> s.add(x > 0)
6030  >>> s.check()
6031  sat
6032  >>> st = s.statistics()
6033  >>> st.nlsat_propagations
6034  2
6035  >>> st.nlsat_stages
6036  2
6037  """
6038  key = name.replace('_', ' ')
6039  try:
6040  return self.get_key_value(key)
6041  except Z3Exception:
6042  raise AttributeError
6043 
6044 #########################################
6045 #
6046 # Solver
6047 #
6048 #########################################
6049 class CheckSatResult:
6050  """Represents the result of a satisfiability check: sat, unsat, unknown.
6051 
6052  >>> s = Solver()
6053  >>> s.check()
6054  sat
6055  >>> r = s.check()
6056  >>> isinstance(r, CheckSatResult)
6057  True
6058  """
6059 
6060  def __init__(self, r):
6061  self.r = r
6062 
6063  def __deepcopy__(self, memo={}):
6064  return CheckSatResult(self.r)
6065 
6066  def __eq__(self, other):
6067  return isinstance(other, CheckSatResult) and self.r == other.r
6068 
6069  def __ne__(self, other):
6070  return not self.__eq__(other)
6071 
6072  def __repr__(self):
6073  if in_html_mode():
6074  if self.r == Z3_L_TRUE:
6075  return "<b>sat</b>"
6076  elif self.r == Z3_L_FALSE:
6077  return "<b>unsat</b>"
6078  else:
6079  return "<b>unknown</b>"
6080  else:
6081  if self.r == Z3_L_TRUE:
6082  return "sat"
6083  elif self.r == Z3_L_FALSE:
6084  return "unsat"
6085  else:
6086  return "unknown"
6087 
6088 sat = CheckSatResult(Z3_L_TRUE)
6089 unsat = CheckSatResult(Z3_L_FALSE)
6090 unknown = CheckSatResult(Z3_L_UNDEF)
6091 
6092 class Solver(Z3PPObject):
6093  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6094 
6095  def __init__(self, solver=None, ctx=None):
6096  assert solver is None or ctx is not None
6097  self.ctx = _get_ctx(ctx)
6098  self.solver = None
6099  if solver is None:
6100  self.solver = Z3_mk_solver(self.ctx.ref())
6101  else:
6102  self.solver = solver
6103  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6104 
6105  def __del__(self):
6106  if self.solver is not None and self.ctx.ref() is not None:
6107  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6108 
6109  def set(self, *args, **keys):
6110  """Set a configuration option. The method `help()` return a string containing all available options.
6111 
6112  >>> s = Solver()
6113  >>> # The option MBQI can be set using three different approaches.
6114  >>> s.set(mbqi=True)
6115  >>> s.set('MBQI', True)
6116  >>> s.set(':mbqi', True)
6117  """
6118  p = args2params(args, keys, self.ctx)
6119  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6120 
6121  def push(self):
6122  """Create a backtracking point.
6123 
6124  >>> x = Int('x')
6125  >>> s = Solver()
6126  >>> s.add(x > 0)
6127  >>> s
6128  [x > 0]
6129  >>> s.push()
6130  >>> s.add(x < 1)
6131  >>> s
6132  [x > 0, x < 1]
6133  >>> s.check()
6134  unsat
6135  >>> s.pop()
6136  >>> s.check()
6137  sat
6138  >>> s
6139  [x > 0]
6140  """
6141  Z3_solver_push(self.ctx.ref(), self.solver)
6142 
6143  def pop(self, num=1):
6144  """Backtrack \c num backtracking points.
6145 
6146  >>> x = Int('x')
6147  >>> s = Solver()
6148  >>> s.add(x > 0)
6149  >>> s
6150  [x > 0]
6151  >>> s.push()
6152  >>> s.add(x < 1)
6153  >>> s
6154  [x > 0, x < 1]
6155  >>> s.check()
6156  unsat
6157  >>> s.pop()
6158  >>> s.check()
6159  sat
6160  >>> s
6161  [x > 0]
6162  """
6163  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6164 
6165  def num_scopes(self):
6166  """Return the current number of backtracking points.
6167 
6168  >>> s = Solver()
6169  >>> s.num_scopes()
6170  0L
6171  >>> s.push()
6172  >>> s.num_scopes()
6173  1L
6174  >>> s.push()
6175  >>> s.num_scopes()
6176  2L
6177  >>> s.pop()
6178  >>> s.num_scopes()
6179  1L
6180  """
6181  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6182 
6183  def reset(self):
6184  """Remove all asserted constraints and backtracking points created using `push()`.
6185 
6186  >>> x = Int('x')
6187  >>> s = Solver()
6188  >>> s.add(x > 0)
6189  >>> s
6190  [x > 0]
6191  >>> s.reset()
6192  >>> s
6193  []
6194  """
6195  Z3_solver_reset(self.ctx.ref(), self.solver)
6196 
6197  def assert_exprs(self, *args):
6198  """Assert constraints into the solver.
6199 
6200  >>> x = Int('x')
6201  >>> s = Solver()
6202  >>> s.assert_exprs(x > 0, x < 2)
6203  >>> s
6204  [x > 0, x < 2]
6205  """
6206  args = _get_args(args)
6207  s = BoolSort(self.ctx)
6208  for arg in args:
6209  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6210  for f in arg:
6211  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6212  else:
6213  arg = s.cast(arg)
6214  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6215 
6216  def add(self, *args):
6217  """Assert constraints into the solver.
6218 
6219  >>> x = Int('x')
6220  >>> s = Solver()
6221  >>> s.add(x > 0, x < 2)
6222  >>> s
6223  [x > 0, x < 2]
6224  """
6225  self.assert_exprs(*args)
6226 
6227  def __iadd__(self, fml):
6228  self.add(fml)
6229  return self
6230 
6231  def append(self, *args):
6232  """Assert constraints into the solver.
6233 
6234  >>> x = Int('x')
6235  >>> s = Solver()
6236  >>> s.append(x > 0, x < 2)
6237  >>> s
6238  [x > 0, x < 2]
6239  """
6240  self.assert_exprs(*args)
6241 
6242  def insert(self, *args):
6243  """Assert constraints into the solver.
6244 
6245  >>> x = Int('x')
6246  >>> s = Solver()
6247  >>> s.insert(x > 0, x < 2)
6248  >>> s
6249  [x > 0, x < 2]
6250  """
6251  self.assert_exprs(*args)
6252 
6253  def assert_and_track(self, a, p):
6254  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6255 
6256  If `p` is a string, it will be automatically converted into a Boolean constant.
6257 
6258  >>> x = Int('x')
6259  >>> p3 = Bool('p3')
6260  >>> s = Solver()
6261  >>> s.set(unsat_core=True)
6262  >>> s.assert_and_track(x > 0, 'p1')
6263  >>> s.assert_and_track(x != 1, 'p2')
6264  >>> s.assert_and_track(x < 0, p3)
6265  >>> print(s.check())
6266  unsat
6267  >>> c = s.unsat_core()
6268  >>> len(c)
6269  2
6270  >>> Bool('p1') in c
6271  True
6272  >>> Bool('p2') in c
6273  False
6274  >>> p3 in c
6275  True
6276  """
6277  if isinstance(p, str):
6278  p = Bool(p, self.ctx)
6279  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6280  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6281  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6282 
6283  def check(self, *assumptions):
6284  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6285 
6286  >>> x = Int('x')
6287  >>> s = Solver()
6288  >>> s.check()
6289  sat
6290  >>> s.add(x > 0, x < 2)
6291  >>> s.check()
6292  sat
6293  >>> s.model()
6294  [x = 1]
6295  >>> s.add(x < 1)
6296  >>> s.check()
6297  unsat
6298  >>> s.reset()
6299  >>> s.add(2**x == 4)
6300  >>> s.check()
6301  unknown
6302  """
6303  assumptions = _get_args(assumptions)
6304  num = len(assumptions)
6305  _assumptions = (Ast * num)()
6306  for i in range(num):
6307  _assumptions[i] = assumptions[i].as_ast()
6308  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6309  return CheckSatResult(r)
6310 
6311  def model(self):
6312  """Return a model for the last `check()`.
6313 
6314  This function raises an exception if
6315  a model is not available (e.g., last `check()` returned unsat).
6316 
6317  >>> s = Solver()
6318  >>> a = Int('a')
6319  >>> s.add(a + 2 == 0)
6320  >>> s.check()
6321  sat
6322  >>> s.model()
6323  [a = -2]
6324  """
6325  try:
6326  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6327  except Z3Exception:
6328  raise Z3Exception("model is not available")
6329 
6330  def unsat_core(self):
6331  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6332 
6333  These are the assumptions Z3 used in the unsatisfiability proof.
6334  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6335  They may be also used to "retract" assumptions. Note that, assumptions are not really
6336  "soft constraints", but they can be used to implement them.
6337 
6338  >>> p1, p2, p3 = Bools('p1 p2 p3')
6339  >>> x, y = Ints('x y')
6340  >>> s = Solver()
6341  >>> s.add(Implies(p1, x > 0))
6342  >>> s.add(Implies(p2, y > x))
6343  >>> s.add(Implies(p2, y < 1))
6344  >>> s.add(Implies(p3, y > -3))
6345  >>> s.check(p1, p2, p3)
6346  unsat
6347  >>> core = s.unsat_core()
6348  >>> len(core)
6349  2
6350  >>> p1 in core
6351  True
6352  >>> p2 in core
6353  True
6354  >>> p3 in core
6355  False
6356  >>> # "Retracting" p2
6357  >>> s.check(p1, p3)
6358  sat
6359  """
6360  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6361 
6362  def consequences(self, assumptions, variables):
6363  """Determine fixed values for the variables based on the solver state and assumptions.
6364  >>> s = Solver()
6365  >>> a, b, c, d = Bools('a b c d')
6366  >>> s.add(Implies(a,b), Implies(b, c))
6367  >>> s.consequences([a],[b,c,d])
6368  (sat, [Implies(a, b), Implies(a, c)])
6369  >>> s.consequences([Not(c),d],[a,b,c,d])
6370  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6371  """
6372  if isinstance(assumptions, list):
6373  _asms = AstVector(None, self.ctx)
6374  for a in assumptions:
6375  _asms.push(a)
6376  assumptions = _asms
6377  if isinstance(variables, list):
6378  _vars = AstVector(None, self.ctx)
6379  for a in variables:
6380  _vars.push(a)
6381  variables = _vars
6382  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6383  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6384  consequences = AstVector(None, self.ctx)
6385  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6386  sz = len(consequences)
6387  consequences = [ consequences[i] for i in range(sz) ]
6388  return CheckSatResult(r), consequences
6389 
6390  def from_file(self, filename):
6391  """Parse assertions from a file"""
6392  try:
6393  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6394  except Z3Exception as e:
6395  _handle_parse_error(e, self.ctx)
6396 
6397  def from_string(self, s):
6398  """Parse assertions from a string"""
6399  try:
6400  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6401  except Z3Exception as e:
6402  _handle_parse_error(e, self.ctx)
6403 
6404  def proof(self):
6405  """Return a proof for the last `check()`. Proof construction must be enabled."""
6406  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6407 
6408  def assertions(self):
6409  """Return an AST vector containing all added constraints.
6410 
6411  >>> s = Solver()
6412  >>> s.assertions()
6413  []
6414  >>> a = Int('a')
6415  >>> s.add(a > 0)
6416  >>> s.add(a < 10)
6417  >>> s.assertions()
6418  [a > 0, a < 10]
6419  """
6420  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6421 
6422  def statistics(self):
6423  """Return statistics for the last `check()`.
6424 
6425  >>> s = SimpleSolver()
6426  >>> x = Int('x')
6427  >>> s.add(x > 0)
6428  >>> s.check()
6429  sat
6430  >>> st = s.statistics()
6431  >>> st.get_key_value('final checks')
6432  1
6433  >>> len(st) > 0
6434  True
6435  >>> st[0] != 0
6436  True
6437  """
6438  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6439 
6440  def reason_unknown(self):
6441  """Return a string describing why the last `check()` returned `unknown`.
6442 
6443  >>> x = Int('x')
6444  >>> s = SimpleSolver()
6445  >>> s.add(2**x == 4)
6446  >>> s.check()
6447  unknown
6448  >>> s.reason_unknown()
6449  '(incomplete (theory arithmetic))'
6450  """
6451  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6452 
6453  def help(self):
6454  """Display a string describing all available options."""
6455  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6456 
6457  def param_descrs(self):
6458  """Return the parameter description set."""
6459  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6460 
6461  def __repr__(self):
6462  """Return a formatted string with all added constraints."""
6463  return obj_to_string(self)
6464 
6465  def translate(self, target):
6466  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6467 
6468  >>> c1 = Context()
6469  >>> c2 = Context()
6470  >>> s1 = Solver(ctx=c1)
6471  >>> s2 = s1.translate(c2)
6472  """
6473  if __debug__:
6474  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6475  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6476  return Solver(solver, target)
6477 
6478  def __copy__(self):
6479  return self.translate(self.ctx)
6480 
6481  def __deepcopy__(self):
6482  return self.translate(self.ctx)
6483 
6484  def sexpr(self):
6485  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6486 
6487  >>> x = Int('x')
6488  >>> s = Solver()
6489  >>> s.add(x > 0)
6490  >>> s.add(x < 2)
6491  >>> r = s.sexpr()
6492  """
6493  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6494 
6495  def to_smt2(self):
6496  """return SMTLIB2 formatted benchmark for solver's assertions"""
6497  es = self.assertions()
6498  sz = len(es)
6499  sz1 = sz
6500  if sz1 > 0:
6501  sz1 -= 1
6502  v = (Ast * sz1)()
6503  for i in range(sz1):
6504  v[i] = es[i].as_ast()
6505  if sz > 0:
6506  e = es[sz1].as_ast()
6507  else:
6508  e = BoolVal(True, self.ctx).as_ast()
6509  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6510 
6511 def SolverFor(logic, ctx=None):
6512  """Create a solver customized for the given logic.
6513 
6514  The parameter `logic` is a string. It should be contains
6515  the name of a SMT-LIB logic.
6516  See http://www.smtlib.org/ for the name of all available logics.
6517 
6518  >>> s = SolverFor("QF_LIA")
6519  >>> x = Int('x')
6520  >>> s.add(x > 0)
6521  >>> s.add(x < 2)
6522  >>> s.check()
6523  sat
6524  >>> s.model()
6525  [x = 1]
6526  """
6527  ctx = _get_ctx(ctx)
6528  logic = to_symbol(logic)
6529  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6530 
6531 def SimpleSolver(ctx=None):
6532  """Return a simple general purpose solver with limited amount of preprocessing.
6533 
6534  >>> s = SimpleSolver()
6535  >>> x = Int('x')
6536  >>> s.add(x > 0)
6537  >>> s.check()
6538  sat
6539  """
6540  ctx = _get_ctx(ctx)
6541  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6542 
6543 
6548 
6550  """Fixedpoint API provides methods for solving with recursive predicates"""
6551 
6552  def __init__(self, fixedpoint=None, ctx=None):
6553  assert fixedpoint is None or ctx is not None
6554  self.ctx = _get_ctx(ctx)
6555  self.fixedpoint = None
6556  if fixedpoint is None:
6557  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6558  else:
6559  self.fixedpoint = fixedpoint
6560  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6561  self.vars = []
6562 
6563  def __deepcopy__(self, memo={}):
6564  return FixedPoint(self.fixedpoint, self.ctx)
6565 
6566  def __del__(self):
6567  if self.fixedpoint is not None and self.ctx.ref() is not None:
6568  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6569 
6570  def set(self, *args, **keys):
6571  """Set a configuration option. The method `help()` return a string containing all available options.
6572  """
6573  p = args2params(args, keys, self.ctx)
6574  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6575 
6576  def help(self):
6577  """Display a string describing all available options."""
6578  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6579 
6580  def param_descrs(self):
6581  """Return the parameter description set."""
6582  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6583 
6584  def assert_exprs(self, *args):
6585  """Assert constraints as background axioms for the fixedpoint solver."""
6586  args = _get_args(args)
6587  s = BoolSort(self.ctx)
6588  for arg in args:
6589  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6590  for f in arg:
6591  f = self.abstract(f)
6592  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6593  else:
6594  arg = s.cast(arg)
6595  arg = self.abstract(arg)
6596  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6597 
6598  def add(self, *args):
6599  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6600  self.assert_exprs(*args)
6601 
6602  def __iadd__(self, fml):
6603  self.add(fml)
6604  return self
6605 
6606  def append(self, *args):
6607  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6608  self.assert_exprs(*args)
6609 
6610  def insert(self, *args):
6611  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6612  self.assert_exprs(*args)
6613 
6614  def add_rule(self, head, body = None, name = None):
6615  """Assert rules defining recursive predicates to the fixedpoint solver.
6616  >>> a = Bool('a')
6617  >>> b = Bool('b')
6618  >>> s = Fixedpoint()
6619  >>> s.register_relation(a.decl())
6620  >>> s.register_relation(b.decl())
6621  >>> s.fact(a)
6622  >>> s.rule(b, a)
6623  >>> s.query(b)
6624  sat
6625  """
6626  if name is None:
6627  name = ""
6628  name = to_symbol(name, self.ctx)
6629  if body is None:
6630  head = self.abstract(head)
6631  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6632  else:
6633  body = _get_args(body)
6634  f = self.abstract(Implies(And(body, self.ctx),head))
6635  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6636 
6637  def rule(self, head, body = None, name = None):
6638  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6639  self.add_rule(head, body, name)
6640 
6641  def fact(self, head, name = None):
6642  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6643  self.add_rule(head, None, name)
6644 
6645  def query(self, *query):
6646  """Query the fixedpoint engine whether formula is derivable.
6647  You can also pass an tuple or list of recursive predicates.
6648  """
6649  query = _get_args(query)
6650  sz = len(query)
6651  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6652  _decls = (FuncDecl * sz)()
6653  i = 0
6654  for q in query:
6655  _decls[i] = q.ast
6656  i = i + 1
6657  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6658  else:
6659  if sz == 1:
6660  query = query[0]
6661  else:
6662  query = And(query, self.ctx)
6663  query = self.abstract(query, False)
6664  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6665  return CheckSatResult(r)
6666 
6667  def query_from_lvl (self, lvl, *query):
6668  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
6669  """
6670  query = _get_args(query)
6671  sz = len(query)
6672  if sz >= 1 and isinstance(query[0], FuncDecl):
6673  _z3_assert (False, "unsupported")
6674  else:
6675  if sz == 1:
6676  query = query[0]
6677  else:
6678  query = And(query)
6679  query = self.abstract(query, False)
6680  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
6681  return CheckSatResult(r)
6682 
6683  def push(self):
6684  """create a backtracking point for added rules, facts and assertions"""
6685  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6686 
6687  def pop(self):
6688  """restore to previously created backtracking point"""
6689  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
6690 
6691  def update_rule(self, head, body, name):
6692  """update rule"""
6693  if name is None:
6694  name = ""
6695  name = to_symbol(name, self.ctx)
6696  body = _get_args(body)
6697  f = self.abstract(Implies(And(body, self.ctx),head))
6698  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6699 
6700  def get_answer(self):
6701  """Retrieve answer from last query call."""
6702  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
6703  return _to_expr_ref(r, self.ctx)
6704 
6706  """Retrieve a ground cex from last query call."""
6707  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
6708  return _to_expr_ref(r, self.ctx)
6709 
6711  """retrieve rules along the counterexample trace"""
6712  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
6713 
6715  """retrieve rule names along the counterexample trace"""
6716  # this is a hack as I don't know how to return a list of symbols from C++;
6717  # obtain names as a single string separated by semicolons
6718  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
6719  # split into individual names
6720  return names.split (';')
6721 
6722  def get_num_levels(self, predicate):
6723  """Retrieve number of levels used for predicate in PDR engine"""
6724  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
6725 
6726  def get_cover_delta(self, level, predicate):
6727  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
6728  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
6729  return _to_expr_ref(r, self.ctx)
6730 
6731  def add_cover(self, level, predicate, property):
6732  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
6733  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
6734 
6735  def register_relation(self, *relations):
6736  """Register relation as recursive"""
6737  relations = _get_args(relations)
6738  for f in relations:
6739  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
6740 
6741  def set_predicate_representation(self, f, *representations):
6742  """Control how relation is represented"""
6743  representations = _get_args(representations)
6744  representations = [to_symbol(s) for s in representations]
6745  sz = len(representations)
6746  args = (Symbol * sz)()
6747  for i in range(sz):
6748  args[i] = representations[i]
6749  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
6750 
6751  def parse_string(self, s):
6752  """Parse rules and queries from a string"""
6753  try:
6754  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
6755  except Z3Exception as e:
6756  _handle_parse_error(e, self.ctx)
6757 
6758  def parse_file(self, f):
6759  """Parse rules and queries from a file"""
6760  try:
6761  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
6762  except Z3Exception as e:
6763  _handle_parse_error(e, self.ctx)
6764 
6765  def get_rules(self):
6766  """retrieve rules that have been added to fixedpoint context"""
6767  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
6768 
6769  def get_assertions(self):
6770  """retrieve assertions that have been added to fixedpoint context"""
6771  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
6772 
6773  def __repr__(self):
6774  """Return a formatted string with all added rules and constraints."""
6775  return self.sexpr()
6776 
6777  def sexpr(self):
6778  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6779  """
6780  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
6781 
6782  def to_string(self, queries):
6783  """Return a formatted string (in Lisp-like format) with all added constraints.
6784  We say the string is in s-expression format.
6785  Include also queries.
6786  """
6787  args, len = _to_ast_array(queries)
6788  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
6789 
6790  def statistics(self):
6791  """Return statistics for the last `query()`.
6792  """
6793  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
6794 
6795  def reason_unknown(self):
6796  """Return a string describing why the last `query()` returned `unknown`.
6797  """
6798  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
6799 
6800  def declare_var(self, *vars):
6801  """Add variable or several variables.
6802  The added variable or variables will be bound in the rules
6803  and queries
6804  """
6805  vars = _get_args(vars)
6806  for v in vars:
6807  self.vars += [v]
6808 
6809  def abstract(self, fml, is_forall=True):
6810  if self.vars == []:
6811  return fml
6812  if is_forall:
6813  return ForAll(self.vars, fml)
6814  else:
6815  return Exists(self.vars, fml)
6816 
6817 
6818 
6823 
6825  """Finite domain sort."""
6826 
6827  def size(self):
6828  """Return the size of the finite domain sort"""
6829  r = (ctypes.c_ulonglong * 1)()
6830  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
6831  return r[0]
6832  else:
6833  raise Z3Exception("Failed to retrieve finite domain sort size")
6834 
6835 def FiniteDomainSort(name, sz, ctx=None):
6836  """Create a named finite domain sort of a given size sz"""
6837  if not isinstance(name, Symbol):
6838  name = to_symbol(name)
6839  ctx = _get_ctx(ctx)
6840  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
6841 
6843  """Return True if `s` is a Z3 finite-domain sort.
6844 
6845  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
6846  True
6847  >>> is_finite_domain_sort(IntSort())
6848  False
6849  """
6850  return isinstance(s, FiniteDomainSortRef)
6851 
6852 
6854  """Finite-domain expressions."""
6855 
6856  def sort(self):
6857  """Return the sort of the finite-domain expression `self`."""
6858  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
6859 
6860  def as_string(self):
6861  """Return a Z3 floating point expression as a Python string."""
6862  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
6863 
6865  """Return `True` if `a` is a Z3 finite-domain expression.
6866 
6867  >>> s = FiniteDomainSort('S', 100)
6868  >>> b = Const('b', s)
6869  >>> is_finite_domain(b)
6870  True
6871  >>> is_finite_domain(Int('x'))
6872  False
6873  """
6874  return isinstance(a, FiniteDomainRef)
6875 
6876 
6878  """Integer values."""
6879 
6880  def as_long(self):
6881  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
6882 
6883  >>> s = FiniteDomainSort('S', 100)
6884  >>> v = FiniteDomainVal(3, s)
6885  >>> v
6886  3
6887  >>> v.as_long() + 1
6888  4
6889  """
6890  return int(self.as_string())
6891 
6892  def as_string(self):
6893  """Return a Z3 finite-domain numeral as a Python string.
6894 
6895  >>> s = FiniteDomainSort('S', 100)
6896  >>> v = FiniteDomainVal(42, s)
6897  >>> v.as_string()
6898  '42'
6899  """
6900  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
6901 
6902 
6903 def FiniteDomainVal(val, sort, ctx=None):
6904  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
6905 
6906  >>> s = FiniteDomainSort('S', 256)
6907  >>> FiniteDomainVal(255, s)
6908  255
6909  >>> FiniteDomainVal('100', s)
6910  100
6911  """
6912  if __debug__:
6913  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
6914  ctx = sort.ctx
6915  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
6916 
6918  """Return `True` if `a` is a Z3 finite-domain value.
6919 
6920  >>> s = FiniteDomainSort('S', 100)
6921  >>> b = Const('b', s)
6922  >>> is_finite_domain_value(b)
6923  False
6924  >>> b = FiniteDomainVal(10, s)
6925  >>> b
6926  10
6927  >>> is_finite_domain_value(b)
6928  True
6929  """
6930  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
6931 
6932 
6933 
6938 
6940  def __init__(self, opt, value, is_max):
6941  self._opt = opt
6942  self._value = value
6943  self._is_max = is_max
6944 
6945  def lower(self):
6946  opt = self._opt
6947  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6948 
6949  def upper(self):
6950  opt = self._opt
6951  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6952 
6953  def lower_values(self):
6954  opt = self._opt
6955  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6956 
6957  def upper_values(self):
6958  opt = self._opt
6959  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6960 
6961  def value(self):
6962  if self._is_max:
6963  return self.upper()
6964  else:
6965  return self.lower()
6966 
6967  def __str__(self):
6968  return "%s:%s" % (self._value, self._is_max)
6969 
6970 
6972  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
6973 
6974  def __init__(self, ctx=None):
6975  self.ctx = _get_ctx(ctx)
6976  self.optimize = Z3_mk_optimize(self.ctx.ref())
6977  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
6978 
6979  def __deepcopy__(self, memo={}):
6980  return Optimize(self.optimize, self.ctx)
6981 
6982  def __del__(self):
6983  if self.optimize is not None and self.ctx.ref() is not None:
6984  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
6985 
6986  def set(self, *args, **keys):
6987  """Set a configuration option. The method `help()` return a string containing all available options.
6988  """
6989  p = args2params(args, keys, self.ctx)
6990  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
6991 
6992  def help(self):
6993  """Display a string describing all available options."""
6994  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
6995 
6996  def param_descrs(self):
6997  """Return the parameter description set."""
6998  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
6999 
7000  def assert_exprs(self, *args):
7001  """Assert constraints as background axioms for the optimize solver."""
7002  args = _get_args(args)
7003  for arg in args:
7004  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7005  for f in arg:
7006  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7007  else:
7008  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7009 
7010  def add(self, *args):
7011  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7012  self.assert_exprs(*args)
7013 
7014  def __iadd__(self, fml):
7015  self.add(fml)
7016  return self
7017 
7018  def add_soft(self, arg, weight = "1", id = None):
7019  """Add soft constraint with optional weight and optional identifier.
7020  If no weight is supplied, then the penalty for violating the soft constraint
7021  is 1.
7022  Soft constraints are grouped by identifiers. Soft constraints that are
7023  added without identifiers are grouped by default.
7024  """
7025  if _is_int(weight):
7026  weight = "%d" % weight
7027  elif isinstance(weight, float):
7028  weight = "%f" % weight
7029  if not isinstance(weight, str):
7030  raise Z3Exception("weight should be a string or an integer")
7031  if id is None:
7032  id = ""
7033  id = to_symbol(id, self.ctx)
7034  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7035  return OptimizeObjective(self, v, False)
7036 
7037  def maximize(self, arg):
7038  """Add objective function to maximize."""
7039  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7040 
7041  def minimize(self, arg):
7042  """Add objective function to minimize."""
7043  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7044 
7045  def push(self):
7046  """create a backtracking point for added rules, facts and assertions"""
7047  Z3_optimize_push(self.ctx.ref(), self.optimize)
7048 
7049  def pop(self):
7050  """restore to previously created backtracking point"""
7051  Z3_optimize_pop(self.ctx.ref(), self.optimize)
7052 
7053  def check(self):
7054  """Check satisfiability while optimizing objective functions."""
7055  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize))
7056 
7057  def reason_unknown(self):
7058  """Return a string that describes why the last `check()` returned `unknown`."""
7059  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7060 
7061  def model(self):
7062  """Return a model for the last check()."""
7063  try:
7064  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7065  except Z3Exception:
7066  raise Z3Exception("model is not available")
7067 
7068  def lower(self, obj):
7069  if not isinstance(obj, OptimizeObjective):
7070  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7071  return obj.lower()
7072 
7073  def upper(self, obj):
7074  if not isinstance(obj, OptimizeObjective):
7075  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7076  return obj.upper()
7077 
7078  def lower_values(self, obj):
7079  if not isinstance(obj, OptimizeObjective):
7080  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7081  return obj.lower_values()
7082 
7083  def upper_values(self, obj):
7084  if not isinstance(obj, OptimizeObjective):
7085  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7086  return obj.upper_values()
7087 
7088  def from_file(self, filename):
7089  """Parse assertions and objectives from a file"""
7090  try:
7091  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7092  except Z3Exception as e:
7093  _handle_parse_error(e, self.ctx)
7094 
7095  def from_string(self, s):
7096  """Parse assertions and objectives from a string"""
7097  try:
7098  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7099  except Z3Exception as e:
7100  _handle_parse_error(e, self.ctx)
7101 
7102  def assertions(self):
7103  """Return an AST vector containing all added constraints."""
7104  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7105 
7106  def objectives(self):
7107  """returns set of objective functions"""
7108  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7109 
7110  def __repr__(self):
7111  """Return a formatted string with all added rules and constraints."""
7112  return self.sexpr()
7113 
7114  def sexpr(self):
7115  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7116  """
7117  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7118 
7119  def statistics(self):
7120  """Return statistics for the last check`.
7121  """
7122  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7123 
7124 
7125 
7126 
7127 
7133  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7134 
7135  def __init__(self, result, ctx):
7136  self.result = result
7137  self.ctx = ctx
7138  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7139 
7140  def __deepcopy__(self, memo={}):
7141  return ApplyResult(self.result, self.ctx)
7142 
7143  def __del__(self):
7144  if self.ctx.ref() is not None:
7145  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7146 
7147  def __len__(self):
7148  """Return the number of subgoals in `self`.
7149 
7150  >>> a, b = Ints('a b')
7151  >>> g = Goal()
7152  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7153  >>> t = Tactic('split-clause')
7154  >>> r = t(g)
7155  >>> len(r)
7156  2
7157  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7158  >>> len(t(g))
7159  4
7160  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7161  >>> len(t(g))
7162  1
7163  """
7164  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7165 
7166  def __getitem__(self, idx):
7167  """Return one of the subgoals stored in ApplyResult object `self`.
7168 
7169  >>> a, b = Ints('a b')
7170  >>> g = Goal()
7171  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7172  >>> t = Tactic('split-clause')
7173  >>> r = t(g)
7174  >>> r[0]
7175  [a == 0, Or(b == 0, b == 1), a > b]
7176  >>> r[1]
7177  [a == 1, Or(b == 0, b == 1), a > b]
7178  """
7179  if idx >= len(self):
7180  raise IndexError
7181  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7182 
7183  def __repr__(self):
7184  return obj_to_string(self)
7185 
7186  def sexpr(self):
7187  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7188  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7189 
7190  def convert_model(self, model, idx=0):
7191  """Convert a model for a subgoal into a model for the original goal.
7192 
7193  >>> a, b = Ints('a b')
7194  >>> g = Goal()
7195  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7196  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
7197  >>> r = t(g)
7198  >>> r[0]
7199  [Or(b == 0, b == 1), Not(0 <= b)]
7200  >>> r[1]
7201  [Or(b == 0, b == 1), Not(1 <= b)]
7202  >>> # Remark: the subgoal r[0] is unsatisfiable
7203  >>> # Creating a solver for solving the second subgoal
7204  >>> s = Solver()
7205  >>> s.add(r[1])
7206  >>> s.check()
7207  sat
7208  >>> s.model()
7209  [b = 0]
7210  >>> # Model s.model() does not assign a value to `a`
7211  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
7212  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
7213  >>> r.convert_model(s.model(), 1)
7214  [b = 0, a = 1]
7215  """
7216  if __debug__:
7217  _z3_assert(idx < len(self), "index out of bounds")
7218  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
7219  return ModelRef(Z3_apply_result_convert_model(self.ctx.ref(), self.result, idx, model.model), self.ctx)
7220 
7221  def as_expr(self):
7222  """Return a Z3 expression consisting of all subgoals.
7223 
7224  >>> x = Int('x')
7225  >>> g = Goal()
7226  >>> g.add(x > 1)
7227  >>> g.add(Or(x == 2, x == 3))
7228  >>> r = Tactic('simplify')(g)
7229  >>> r
7230  [[Not(x <= 1), Or(x == 2, x == 3)]]
7231  >>> r.as_expr()
7232  And(Not(x <= 1), Or(x == 2, x == 3))
7233  >>> r = Tactic('split-clause')(g)
7234  >>> r
7235  [[x > 1, x == 2], [x > 1, x == 3]]
7236  >>> r.as_expr()
7237  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7238  """
7239  sz = len(self)
7240  if sz == 0:
7241  return BoolVal(False, self.ctx)
7242  elif sz == 1:
7243  return self[0].as_expr()
7244  else:
7245  return Or([ self[i].as_expr() for i in range(len(self)) ])
7246 
7247 
7252 class Tactic:
7253  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7254 
7255  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7256  """
7257  def __init__(self, tactic, ctx=None):
7258  self.ctx = _get_ctx(ctx)
7259  self.tactic = None
7260  if isinstance(tactic, TacticObj):
7261  self.tactic = tactic
7262  else:
7263  if __debug__:
7264  _z3_assert(isinstance(tactic, str), "tactic name expected")
7265  try:
7266  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7267  except Z3Exception:
7268  raise Z3Exception("unknown tactic '%s'" % tactic)
7269  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7270 
7271  def __deepcopy__(self, memo={}):
7272  return Tactic(self.tactic, self.ctx)
7273 
7274  def __del__(self):
7275  if self.tactic is not None and self.ctx.ref() is not None:
7276  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7277 
7278  def solver(self):
7279  """Create a solver using the tactic `self`.
7280 
7281  The solver supports the methods `push()` and `pop()`, but it
7282  will always solve each `check()` from scratch.
7283 
7284  >>> t = Then('simplify', 'nlsat')
7285  >>> s = t.solver()
7286  >>> x = Real('x')
7287  >>> s.add(x**2 == 2, x > 0)
7288  >>> s.check()
7289  sat
7290  >>> s.model()
7291  [x = 1.4142135623?]
7292  """
7293  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7294 
7295  def apply(self, goal, *arguments, **keywords):
7296  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7297 
7298  >>> x, y = Ints('x y')
7299  >>> t = Tactic('solve-eqs')
7300  >>> t.apply(And(x == 0, y >= x + 1))
7301  [[y >= 1]]
7302  """
7303  if __debug__:
7304  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7305  goal = _to_goal(goal)
7306  if len(arguments) > 0 or len(keywords) > 0:
7307  p = args2params(arguments, keywords, self.ctx)
7308  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7309  else:
7310  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7311 
7312  def __call__(self, goal, *arguments, **keywords):
7313  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7314 
7315  >>> x, y = Ints('x y')
7316  >>> t = Tactic('solve-eqs')
7317  >>> t(And(x == 0, y >= x + 1))
7318  [[y >= 1]]
7319  """
7320  return self.apply(goal, *arguments, **keywords)
7321 
7322  def help(self):
7323  """Display a string containing a description of the available options for the `self` tactic."""
7324  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7325 
7326  def param_descrs(self):
7327  """Return the parameter description set."""
7328  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7329 
7330 def _to_goal(a):
7331  if isinstance(a, BoolRef):
7332  goal = Goal(ctx = a.ctx)
7333  goal.add(a)
7334  return goal
7335  else:
7336  return a
7337 
7338 def _to_tactic(t, ctx=None):
7339  if isinstance(t, Tactic):
7340  return t
7341  else:
7342  return Tactic(t, ctx)
7343 
7344 def _and_then(t1, t2, ctx=None):
7345  t1 = _to_tactic(t1, ctx)
7346  t2 = _to_tactic(t2, ctx)
7347  if __debug__:
7348  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7349  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7350 
7351 def _or_else(t1, t2, ctx=None):
7352  t1 = _to_tactic(t1, ctx)
7353  t2 = _to_tactic(t2, ctx)
7354  if __debug__:
7355  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7356  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7357 
7358 def AndThen(*ts, **ks):
7359  """Return a tactic that applies the tactics in `*ts` in sequence.
7360 
7361  >>> x, y = Ints('x y')
7362  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7363  >>> t(And(x == 0, y > x + 1))
7364  [[Not(y <= 1)]]
7365  >>> t(And(x == 0, y > x + 1)).as_expr()
7366  Not(y <= 1)
7367  """
7368  if __debug__:
7369  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7370  ctx = ks.get('ctx', None)
7371  num = len(ts)
7372  r = ts[0]
7373  for i in range(num - 1):
7374  r = _and_then(r, ts[i+1], ctx)
7375  return r
7376 
7377 def Then(*ts, **ks):
7378  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7379 
7380  >>> x, y = Ints('x y')
7381  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7382  >>> t(And(x == 0, y > x + 1))
7383  [[Not(y <= 1)]]
7384  >>> t(And(x == 0, y > x + 1)).as_expr()
7385  Not(y <= 1)
7386  """
7387  return AndThen(*ts, **ks)
7388 
7389 def OrElse(*ts, **ks):
7390  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7391 
7392  >>> x = Int('x')
7393  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7394  >>> # Tactic split-clause fails if there is no clause in the given goal.
7395  >>> t(x == 0)
7396  [[x == 0]]
7397  >>> t(Or(x == 0, x == 1))
7398  [[x == 0], [x == 1]]
7399  """
7400  if __debug__:
7401  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7402  ctx = ks.get('ctx', None)
7403  num = len(ts)
7404  r = ts[0]
7405  for i in range(num - 1):
7406  r = _or_else(r, ts[i+1], ctx)
7407  return r
7408 
7409 def ParOr(*ts, **ks):
7410  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7411 
7412  >>> x = Int('x')
7413  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7414  >>> t(x + 1 == 2)
7415  [[x == 1]]
7416  """
7417  if __debug__:
7418  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7419  ctx = _get_ctx(ks.get('ctx', None))
7420  ts = [ _to_tactic(t, ctx) for t in ts ]
7421  sz = len(ts)
7422  _args = (TacticObj * sz)()
7423  for i in range(sz):
7424  _args[i] = ts[i].tactic
7425  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7426 
7427 def ParThen(t1, t2, ctx=None):
7428  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7429 
7430  >>> x, y = Ints('x y')
7431  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7432  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7433  [[x == 1, y == 2], [x == 2, y == 3]]
7434  """
7435  t1 = _to_tactic(t1, ctx)
7436  t2 = _to_tactic(t2, ctx)
7437  if __debug__:
7438  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7439  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7440 
7441 def ParAndThen(t1, t2, ctx=None):
7442  """Alias for ParThen(t1, t2, ctx)."""
7443  return ParThen(t1, t2, ctx)
7444 
7445 def With(t, *args, **keys):
7446  """Return a tactic that applies tactic `t` using the given configuration options.
7447 
7448  >>> x, y = Ints('x y')
7449  >>> t = With(Tactic('simplify'), som=True)
7450  >>> t((x + 1)*(y + 2) == 0)
7451  [[2*x + y + x*y == -2]]
7452  """
7453  ctx = keys.pop('ctx', None)
7454  t = _to_tactic(t, ctx)
7455  p = args2params(args, keys, t.ctx)
7456  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7457 
7458 def WithParams(t, p):
7459  """Return a tactic that applies tactic `t` using the given configuration options.
7460 
7461  >>> x, y = Ints('x y')
7462  >>> p = ParamsRef()
7463  >>> p.set("som", True)
7464  >>> t = WithParams(Tactic('simplify'), p)
7465  >>> t((x + 1)*(y + 2) == 0)
7466  [[2*x + y + x*y == -2]]
7467  """
7468  t = _to_tactic(t, None)
7469  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7470 
7471 def Repeat(t, max=4294967295, ctx=None):
7472  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7473 
7474  >>> x, y = Ints('x y')
7475  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7476  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7477  >>> r = t(c)
7478  >>> for subgoal in r: print(subgoal)
7479  [x == 0, y == 0, x > y]
7480  [x == 0, y == 1, x > y]
7481  [x == 1, y == 0, x > y]
7482  [x == 1, y == 1, x > y]
7483  >>> t = Then(t, Tactic('propagate-values'))
7484  >>> t(c)
7485  [[x == 1, y == 0]]
7486  """
7487  t = _to_tactic(t, ctx)
7488  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7489 
7490 def TryFor(t, ms, ctx=None):
7491  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7492 
7493  If `t` does not terminate in `ms` milliseconds, then it fails.
7494  """
7495  t = _to_tactic(t, ctx)
7496  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7497 
7498 def tactics(ctx=None):
7499  """Return a list of all available tactics in Z3.
7500 
7501  >>> l = tactics()
7502  >>> l.count('simplify') == 1
7503  True
7504  """
7505  ctx = _get_ctx(ctx)
7506  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7507 
7508 def tactic_description(name, ctx=None):
7509  """Return a short description for the tactic named `name`.
7510 
7511  >>> d = tactic_description('simplify')
7512  """
7513  ctx = _get_ctx(ctx)
7514  return Z3_tactic_get_descr(ctx.ref(), name)
7515 
7517  """Display a (tabular) description of all available tactics in Z3."""
7518  if in_html_mode():
7519  even = True
7520  print('<table border="1" cellpadding="2" cellspacing="0">')
7521  for t in tactics():
7522  if even:
7523  print('<tr style="background-color:#CFCFCF">')
7524  even = False
7525  else:
7526  print('<tr>')
7527  even = True
7528  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7529  print('</table>')
7530  else:
7531  for t in tactics():
7532  print('%s : %s' % (t, tactic_description(t)))
7533 
7534 class Probe:
7535  """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."""
7536  def __init__(self, probe, ctx=None):
7537  self.ctx = _get_ctx(ctx)
7538  self.probe = None
7539  if isinstance(probe, ProbeObj):
7540  self.probe = probe
7541  elif isinstance(probe, float):
7542  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7543  elif _is_int(probe):
7544  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7545  elif isinstance(probe, bool):
7546  if probe:
7547  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7548  else:
7549  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7550  else:
7551  if __debug__:
7552  _z3_assert(isinstance(probe, str), "probe name expected")
7553  try:
7554  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7555  except Z3Exception:
7556  raise Z3Exception("unknown probe '%s'" % probe)
7557  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7558 
7559  def __deepcopy__(self, memo={}):
7560  return Probe(self.probe, self.ctx)
7561 
7562  def __del__(self):
7563  if self.probe is not None and self.ctx.ref() is not None:
7564  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7565 
7566  def __lt__(self, other):
7567  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7568 
7569  >>> p = Probe('size') < 10
7570  >>> x = Int('x')
7571  >>> g = Goal()
7572  >>> g.add(x > 0)
7573  >>> g.add(x < 10)
7574  >>> p(g)
7575  1.0
7576  """
7577  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7578 
7579  def __gt__(self, other):
7580  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7581 
7582  >>> p = Probe('size') > 10
7583  >>> x = Int('x')
7584  >>> g = Goal()
7585  >>> g.add(x > 0)
7586  >>> g.add(x < 10)
7587  >>> p(g)
7588  0.0
7589  """
7590  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7591 
7592  def __le__(self, other):
7593  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7594 
7595  >>> p = Probe('size') <= 2
7596  >>> x = Int('x')
7597  >>> g = Goal()
7598  >>> g.add(x > 0)
7599  >>> g.add(x < 10)
7600  >>> p(g)
7601  1.0
7602  """
7603  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7604 
7605  def __ge__(self, other):
7606  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7607 
7608  >>> p = Probe('size') >= 2
7609  >>> x = Int('x')
7610  >>> g = Goal()
7611  >>> g.add(x > 0)
7612  >>> g.add(x < 10)
7613  >>> p(g)
7614  1.0
7615  """
7616  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7617 
7618  def __eq__(self, other):
7619  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7620 
7621  >>> p = Probe('size') == 2
7622  >>> x = Int('x')
7623  >>> g = Goal()
7624  >>> g.add(x > 0)
7625  >>> g.add(x < 10)
7626  >>> p(g)
7627  1.0
7628  """
7629  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7630 
7631  def __ne__(self, other):
7632  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7633 
7634  >>> p = Probe('size') != 2
7635  >>> x = Int('x')
7636  >>> g = Goal()
7637  >>> g.add(x > 0)
7638  >>> g.add(x < 10)
7639  >>> p(g)
7640  0.0
7641  """
7642  p = self.__eq__(other)
7643  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
7644 
7645  def __call__(self, goal):
7646  """Evaluate the probe `self` in the given goal.
7647 
7648  >>> p = Probe('size')
7649  >>> x = Int('x')
7650  >>> g = Goal()
7651  >>> g.add(x > 0)
7652  >>> g.add(x < 10)
7653  >>> p(g)
7654  2.0
7655  >>> g.add(x < 20)
7656  >>> p(g)
7657  3.0
7658  >>> p = Probe('num-consts')
7659  >>> p(g)
7660  1.0
7661  >>> p = Probe('is-propositional')
7662  >>> p(g)
7663  0.0
7664  >>> p = Probe('is-qflia')
7665  >>> p(g)
7666  1.0
7667  """
7668  if __debug__:
7669  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
7670  goal = _to_goal(goal)
7671  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
7672 
7673 def is_probe(p):
7674  """Return `True` if `p` is a Z3 probe.
7675 
7676  >>> is_probe(Int('x'))
7677  False
7678  >>> is_probe(Probe('memory'))
7679  True
7680  """
7681  return isinstance(p, Probe)
7682 
7683 def _to_probe(p, ctx=None):
7684  if is_probe(p):
7685  return p
7686  else:
7687  return Probe(p, ctx)
7688 
7689 def probes(ctx=None):
7690  """Return a list of all available probes in Z3.
7691 
7692  >>> l = probes()
7693  >>> l.count('memory') == 1
7694  True
7695  """
7696  ctx = _get_ctx(ctx)
7697  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
7698 
7699 def probe_description(name, ctx=None):
7700  """Return a short description for the probe named `name`.
7701 
7702  >>> d = probe_description('memory')
7703  """
7704  ctx = _get_ctx(ctx)
7705  return Z3_probe_get_descr(ctx.ref(), name)
7706 
7708  """Display a (tabular) description of all available probes in Z3."""
7709  if in_html_mode():
7710  even = True
7711  print('<table border="1" cellpadding="2" cellspacing="0">')
7712  for p in probes():
7713  if even:
7714  print('<tr style="background-color:#CFCFCF">')
7715  even = False
7716  else:
7717  print('<tr>')
7718  even = True
7719  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
7720  print('</table>')
7721  else:
7722  for p in probes():
7723  print('%s : %s' % (p, probe_description(p)))
7724 
7725 def _probe_nary(f, args, ctx):
7726  if __debug__:
7727  _z3_assert(len(args) > 0, "At least one argument expected")
7728  num = len(args)
7729  r = _to_probe(args[0], ctx)
7730  for i in range(num - 1):
7731  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
7732  return r
7733 
7734 def _probe_and(args, ctx):
7735  return _probe_nary(Z3_probe_and, args, ctx)
7736 
7737 def _probe_or(args, ctx):
7738  return _probe_nary(Z3_probe_or, args, ctx)
7739 
7740 def FailIf(p, ctx=None):
7741  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7742 
7743  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
7744 
7745  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
7746  >>> x, y = Ints('x y')
7747  >>> g = Goal()
7748  >>> g.add(x > 0)
7749  >>> g.add(y > 0)
7750  >>> t(g)
7751  [[x > 0, y > 0]]
7752  >>> g.add(x == y + 1)
7753  >>> t(g)
7754  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7755  """
7756  p = _to_probe(p, ctx)
7757  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
7758 
7759 def When(p, t, ctx=None):
7760  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7761 
7762  >>> t = When(Probe('size') > 2, Tactic('simplify'))
7763  >>> x, y = Ints('x y')
7764  >>> g = Goal()
7765  >>> g.add(x > 0)
7766  >>> g.add(y > 0)
7767  >>> t(g)
7768  [[x > 0, y > 0]]
7769  >>> g.add(x == y + 1)
7770  >>> t(g)
7771  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7772  """
7773  p = _to_probe(p, ctx)
7774  t = _to_tactic(t, ctx)
7775  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
7776 
7777 def Cond(p, t1, t2, ctx=None):
7778  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
7779 
7780  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
7781  """
7782  p = _to_probe(p, ctx)
7783  t1 = _to_tactic(t1, ctx)
7784  t2 = _to_tactic(t2, ctx)
7785  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
7786 
7787 
7792 
7793 def simplify(a, *arguments, **keywords):
7794  """Simplify the expression `a` using the given options.
7795 
7796  This function has many options. Use `help_simplify` to obtain the complete list.
7797 
7798  >>> x = Int('x')
7799  >>> y = Int('y')
7800  >>> simplify(x + 1 + y + x + 1)
7801  2 + 2*x + y
7802  >>> simplify((x + 1)*(y + 1), som=True)
7803  1 + x + y + x*y
7804  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
7805  And(Not(x == y), Not(x == 1), Not(y == 1))
7806  >>> simplify(And(x == 0, y == 1), elim_and=True)
7807  Not(Or(Not(x == 0), Not(y == 1)))
7808  """
7809  if __debug__:
7810  _z3_assert(is_expr(a), "Z3 expression expected")
7811  if len(arguments) > 0 or len(keywords) > 0:
7812  p = args2params(arguments, keywords, a.ctx)
7813  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
7814  else:
7815  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
7816 
7818  """Return a string describing all options available for Z3 `simplify` procedure."""
7819  print(Z3_simplify_get_help(main_ctx().ref()))
7820 
7822  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
7824 
7825 def substitute(t, *m):
7826  """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.
7827 
7828  >>> x = Int('x')
7829  >>> y = Int('y')
7830  >>> substitute(x + 1, (x, y + 1))
7831  y + 1 + 1
7832  >>> f = Function('f', IntSort(), IntSort())
7833  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
7834  1 + 1
7835  """
7836  if isinstance(m, tuple):
7837  m1 = _get_args(m)
7838  if isinstance(m1, list):
7839  m = m1
7840  if __debug__:
7841  _z3_assert(is_expr(t), "Z3 expression expected")
7842  _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.")
7843  num = len(m)
7844  _from = (Ast * num)()
7845  _to = (Ast * num)()
7846  for i in range(num):
7847  _from[i] = m[i][0].as_ast()
7848  _to[i] = m[i][1].as_ast()
7849  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
7850 
7851 def substitute_vars(t, *m):
7852  """Substitute the free variables in t with the expression in m.
7853 
7854  >>> v0 = Var(0, IntSort())
7855  >>> v1 = Var(1, IntSort())
7856  >>> x = Int('x')
7857  >>> f = Function('f', IntSort(), IntSort(), IntSort())
7858  >>> # replace v0 with x+1 and v1 with x
7859  >>> substitute_vars(f(v0, v1), x + 1, x)
7860  f(x + 1, x)
7861  """
7862  if __debug__:
7863  _z3_assert(is_expr(t), "Z3 expression expected")
7864  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
7865  num = len(m)
7866  _to = (Ast * num)()
7867  for i in range(num):
7868  _to[i] = m[i].as_ast()
7869  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
7870 
7871 def Sum(*args):
7872  """Create the sum of the Z3 expressions.
7873 
7874  >>> a, b, c = Ints('a b c')
7875  >>> Sum(a, b, c)
7876  a + b + c
7877  >>> Sum([a, b, c])
7878  a + b + c
7879  >>> A = IntVector('a', 5)
7880  >>> Sum(A)
7881  a__0 + a__1 + a__2 + a__3 + a__4
7882  """
7883  args = _get_args(args)
7884  if len(args) == 0:
7885  return 0
7886  ctx = _ctx_from_ast_arg_list(args)
7887  if ctx is None:
7888  return _reduce(lambda a, b: a + b, args, 0)
7889  args = _coerce_expr_list(args, ctx)
7890  if is_bv(args[0]):
7891  return _reduce(lambda a, b: a + b, args, 0)
7892  else:
7893  _args, sz = _to_ast_array(args)
7894  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
7895 
7896 
7897 def Product(*args):
7898  """Create the product of the Z3 expressions.
7899 
7900  >>> a, b, c = Ints('a b c')
7901  >>> Product(a, b, c)
7902  a*b*c
7903  >>> Product([a, b, c])
7904  a*b*c
7905  >>> A = IntVector('a', 5)
7906  >>> Product(A)
7907  a__0*a__1*a__2*a__3*a__4
7908  """
7909  args = _get_args(args)
7910  if len(args) == 0:
7911  return 1
7912  ctx = _ctx_from_ast_arg_list(args)
7913  if ctx is None:
7914  return _reduce(lambda a, b: a * b, args, 1)
7915  args = _coerce_expr_list(args, ctx)
7916  if is_bv(args[0]):
7917  return _reduce(lambda a, b: a * b, args, 1)
7918  else:
7919  _args, sz = _to_ast_array(args)
7920  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
7921 
7922 def AtMost(*args):
7923  """Create an at-most Pseudo-Boolean k constraint.
7924 
7925  >>> a, b, c = Bools('a b c')
7926  >>> f = AtMost(a, b, c, 2)
7927  """
7928  args = _get_args(args)
7929  if __debug__:
7930  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7931  ctx = _ctx_from_ast_arg_list(args)
7932  if __debug__:
7933  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7934  args1 = _coerce_expr_list(args[:-1], ctx)
7935  k = args[-1]
7936  _args, sz = _to_ast_array(args1)
7937  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
7938 
7939 def AtLeast(*args):
7940  """Create an at-most Pseudo-Boolean k constraint.
7941 
7942  >>> a, b, c = Bools('a b c')
7943  >>> f = AtLeast(a, b, c, 2)
7944  """
7945  args = _get_args(args)
7946  if __debug__:
7947  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7948  ctx = _ctx_from_ast_arg_list(args)
7949  if __debug__:
7950  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7951  args1 = _coerce_expr_list(args[:-1], ctx)
7952  k = args[-1]
7953  _args, sz = _to_ast_array(args1)
7954  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
7955 
7956 
7957 def _pb_args_coeffs(args, default_ctx = None):
7958  args = _get_args_ast_list(args)
7959  if len(args) == 0:
7960  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
7961  args, coeffs = zip(*args)
7962  if __debug__:
7963  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7964  ctx = _ctx_from_ast_arg_list(args)
7965  if __debug__:
7966  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7967  args = _coerce_expr_list(args, ctx)
7968  _args, sz = _to_ast_array(args)
7969  _coeffs = (ctypes.c_int * len(coeffs))()
7970  for i in range(len(coeffs)):
7971  _coeffs[i] = coeffs[i]
7972  return ctx, sz, _args, _coeffs
7973 
7974 def PbLe(args, k):
7975  """Create a Pseudo-Boolean inequality k constraint.
7976 
7977  >>> a, b, c = Bools('a b c')
7978  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
7979  """
7980  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7981  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
7982 
7983 def PbGe(args, k):
7984  """Create a Pseudo-Boolean inequality k constraint.
7985 
7986  >>> a, b, c = Bools('a b c')
7987  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
7988  """
7989  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7990  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
7991 
7992 def PbEq(args, k, ctx = None):
7993  """Create a Pseudo-Boolean inequality k constraint.
7994 
7995  >>> a, b, c = Bools('a b c')
7996  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
7997  """
7998  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7999  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8000 
8001 
8002 def solve(*args, **keywords):
8003  """Solve the constraints `*args`.
8004 
8005  This is a simple function for creating demonstrations. It creates a solver,
8006  configure it using the options in `keywords`, adds the constraints
8007  in `args`, and invokes check.
8008 
8009  >>> a = Int('a')
8010  >>> solve(a > 0, a < 2)
8011  [a = 1]
8012  """
8013  s = Solver()
8014  s.set(**keywords)
8015  s.add(*args)
8016  if keywords.get('show', False):
8017  print(s)
8018  r = s.check()
8019  if r == unsat:
8020  print("no solution")
8021  elif r == unknown:
8022  print("failed to solve")
8023  try:
8024  print(s.model())
8025  except Z3Exception:
8026  return
8027  else:
8028  print(s.model())
8029 
8030 def solve_using(s, *args, **keywords):
8031  """Solve the constraints `*args` using solver `s`.
8032 
8033  This is a simple function for creating demonstrations. It is similar to `solve`,
8034  but it uses the given solver `s`.
8035  It configures solver `s` using the options in `keywords`, adds the constraints
8036  in `args`, and invokes check.
8037  """
8038  if __debug__:
8039  _z3_assert(isinstance(s, Solver), "Solver object expected")
8040  s.set(**keywords)
8041  s.add(*args)
8042  if keywords.get('show', False):
8043  print("Problem:")
8044  print(s)
8045  r = s.check()
8046  if r == unsat:
8047  print("no solution")
8048  elif r == unknown:
8049  print("failed to solve")
8050  try:
8051  print(s.model())
8052  except Z3Exception:
8053  return
8054  else:
8055  if keywords.get('show', False):
8056  print("Solution:")
8057  print(s.model())
8058 
8059 def prove(claim, **keywords):
8060  """Try to prove the given claim.
8061 
8062  This is a simple function for creating demonstrations. It tries to prove
8063  `claim` by showing the negation is unsatisfiable.
8064 
8065  >>> p, q = Bools('p q')
8066  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8067  proved
8068  """
8069  if __debug__:
8070  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8071  s = Solver()
8072  s.set(**keywords)
8073  s.add(Not(claim))
8074  if keywords.get('show', False):
8075  print(s)
8076  r = s.check()
8077  if r == unsat:
8078  print("proved")
8079  elif r == unknown:
8080  print("failed to prove")
8081  print(s.model())
8082  else:
8083  print("counterexample")
8084  print(s.model())
8085 
8086 def _solve_html(*args, **keywords):
8087  """Version of funcion `solve` used in RiSE4Fun."""
8088  s = Solver()
8089  s.set(**keywords)
8090  s.add(*args)
8091  if keywords.get('show', False):
8092  print("<b>Problem:</b>")
8093  print(s)
8094  r = s.check()
8095  if r == unsat:
8096  print("<b>no solution</b>")
8097  elif r == unknown:
8098  print("<b>failed to solve</b>")
8099  try:
8100  print(s.model())
8101  except Z3Exception:
8102  return
8103  else:
8104  if keywords.get('show', False):
8105  print("<b>Solution:</b>")
8106  print(s.model())
8107 
8108 def _solve_using_html(s, *args, **keywords):
8109  """Version of funcion `solve_using` used in RiSE4Fun."""
8110  if __debug__:
8111  _z3_assert(isinstance(s, Solver), "Solver object expected")
8112  s.set(**keywords)
8113  s.add(*args)
8114  if keywords.get('show', False):
8115  print("<b>Problem:</b>")
8116  print(s)
8117  r = s.check()
8118  if r == unsat:
8119  print("<b>no solution</b>")
8120  elif r == unknown:
8121  print("<b>failed to solve</b>")
8122  try:
8123  print(s.model())
8124  except Z3Exception:
8125  return
8126  else:
8127  if keywords.get('show', False):
8128  print("<b>Solution:</b>")
8129  print(s.model())
8130 
8131 def _prove_html(claim, **keywords):
8132  """Version of funcion `prove` used in RiSE4Fun."""
8133  if __debug__:
8134  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8135  s = Solver()
8136  s.set(**keywords)
8137  s.add(Not(claim))
8138  if keywords.get('show', False):
8139  print(s)
8140  r = s.check()
8141  if r == unsat:
8142  print("<b>proved</b>")
8143  elif r == unknown:
8144  print("<b>failed to prove</b>")
8145  print(s.model())
8146  else:
8147  print("<b>counterexample</b>")
8148  print(s.model())
8149 
8150 def _dict2sarray(sorts, ctx):
8151  sz = len(sorts)
8152  _names = (Symbol * sz)()
8153  _sorts = (Sort * sz) ()
8154  i = 0
8155  for k in sorts:
8156  v = sorts[k]
8157  if __debug__:
8158  _z3_assert(isinstance(k, str), "String expected")
8159  _z3_assert(is_sort(v), "Z3 sort expected")
8160  _names[i] = to_symbol(k, ctx)
8161  _sorts[i] = v.ast
8162  i = i + 1
8163  return sz, _names, _sorts
8164 
8165 def _dict2darray(decls, ctx):
8166  sz = len(decls)
8167  _names = (Symbol * sz)()
8168  _decls = (FuncDecl * sz) ()
8169  i = 0
8170  for k in decls:
8171  v = decls[k]
8172  if __debug__:
8173  _z3_assert(isinstance(k, str), "String expected")
8174  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8175  _names[i] = to_symbol(k, ctx)
8176  if is_const(v):
8177  _decls[i] = v.decl().ast
8178  else:
8179  _decls[i] = v.ast
8180  i = i + 1
8181  return sz, _names, _decls
8182 
8183 def _handle_parse_error(ex, ctx):
8184  msg = Z3_get_parser_error(ctx.ref())
8185  if msg != "":
8186  raise Z3Exception(msg)
8187  raise ex
8188 
8189 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8190  """Parse a string in SMT 2.0 format using the given sorts and decls.
8191 
8192  The arguments sorts and decls are Python dictionaries used to initialize
8193  the symbol table used for the SMT 2.0 parser.
8194 
8195  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8196  And(x > 0, x < 10)
8197  >>> x, y = Ints('x y')
8198  >>> f = Function('f', IntSort(), IntSort())
8199  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8200  x + f(y) > 0
8201  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8202  a > 0
8203  """
8204  ctx = _get_ctx(ctx)
8205  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8206  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8207  try:
8208  return _to_expr_ref(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8209  except Z3Exception as e:
8210  _handle_parse_error(e, ctx)
8211 
8212 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8213  """Parse a file in SMT 2.0 format using the given sorts and decls.
8214 
8215  This function is similar to parse_smt2_string().
8216  """
8217  ctx = _get_ctx(ctx)
8218  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8219  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8220  try:
8221  return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8222  except Z3Exception as e:
8223  _handle_parse_error(e, ctx)
8224 
8225 def Interpolant(a,ctx=None):
8226  """Create an interpolation operator.
8227 
8228  The argument is an interpolation pattern (see tree_interpolant).
8229 
8230  >>> x = Int('x')
8231  >>> print(Interpolant(x>0))
8232  interp(x > 0)
8233  """
8234  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
8235  s = BoolSort(ctx)
8236  a = s.cast(a)
8237  return BoolRef(Z3_mk_interpolant(ctx.ref(), a.as_ast()), ctx)
8238 
8239 def tree_interpolant(pat,p=None,ctx=None):
8240  """Compute interpolant for a tree of formulas.
8241 
8242  The input is an interpolation pattern over a set of formulas C.
8243  The pattern pat is a formula combining the formulas in C using
8244  logical conjunction and the "interp" operator (see Interp). This
8245  interp operator is logically the identity operator. It marks the
8246  sub-formulas of the pattern for which interpolants should be
8247  computed. The interpolant is a map sigma from marked subformulas
8248  to formulas, such that, for each marked subformula phi of pat
8249  (where phi sigma is phi with sigma(psi) substituted for each
8250  subformula psi of phi such that psi in dom(sigma)):
8251 
8252  1) phi sigma implies sigma(phi), and
8253 
8254  2) sigma(phi) is in the common uninterpreted vocabulary between
8255  the formulas of C occurring in phi and those not occurring in
8256  phi
8257 
8258  and moreover pat sigma implies false. In the simplest case
8259  an interpolant for the pattern "(and (interp A) B)" maps A
8260  to an interpolant for A /\ B.
8261 
8262  The return value is a vector of formulas representing sigma. This
8263  vector contains sigma(phi) for each marked subformula of pat, in
8264  pre-order traversal. This means that subformulas of phi occur before phi
8265  in the vector. Also, subformulas that occur multiply in pat will
8266  occur multiply in the result vector.
8267 
8268  If pat is satisfiable, raises an object of class ModelRef
8269  that represents a model of pat.
8270 
8271  If neither a proof of unsatisfiability nor a model is obtained
8272  (for example, because of a timeout, or because models are disabled)
8273  then None is returned.
8274 
8275  If parameters p are supplied, these are used in creating the
8276  solver that determines satisfiability.
8277 
8278  >>> x = Int('x')
8279  >>> y = Int('y')
8280  >>> print(tree_interpolant(And(Interpolant(x < 0), Interpolant(y > 2), x == y)))
8281  [Not(x >= 0), Not(y <= 2)]
8282 
8283  # >>> g = And(Interpolant(x<0),x<2)
8284  # >>> try:
8285  # ... print tree_interpolant(g).sexpr()
8286  # ... except ModelRef as m:
8287  # ... print m.sexpr()
8288  (define-fun x () Int
8289  (- 1))
8290  """
8291  f = pat
8292  ctx = _get_ctx(_ctx_from_ast_arg_list([f], ctx))
8293  ptr = (AstVectorObj * 1)()
8294  mptr = (Model * 1)()
8295  if p is None:
8296  p = ParamsRef(ctx)
8297  res = Z3_compute_interpolant(ctx.ref(),f.as_ast(),p.params,ptr,mptr)
8298  if res == Z3_L_FALSE:
8299  return AstVector(ptr[0],ctx)
8300  if mptr[0]:
8301  raise ModelRef(mptr[0], ctx)
8302  return None
8303 
8304 def binary_interpolant(a,b,p=None,ctx=None):
8305  """Compute an interpolant for a binary conjunction.
8306 
8307  If a & b is unsatisfiable, returns an interpolant for a & b.
8308  This is a formula phi such that
8309 
8310  1) a implies phi
8311  2) b implies not phi
8312  3) All the uninterpreted symbols of phi occur in both a and b.
8313 
8314  If a & b is satisfiable, raises an object of class ModelRef
8315  that represents a model of a &b.
8316 
8317  If neither a proof of unsatisfiability nor a model is obtained
8318  (for example, because of a timeout, or because models are disabled)
8319  then None is returned.
8320 
8321  If parameters p are supplied, these are used in creating the
8322  solver that determines satisfiability.
8323 
8324  x = Int('x')
8325  print(binary_interpolant(x<0,x>2))
8326  Not(x >= 0)
8327  """
8328  f = And(Interpolant(a),b)
8329  ti = tree_interpolant(f,p,ctx)
8330  return ti[0] if ti is not None else None
8331 
8332 def sequence_interpolant(v,p=None,ctx=None):
8333  """Compute interpolant for a sequence of formulas.
8334 
8335  If len(v) == N, and if the conjunction of the formulas in v is
8336  unsatisfiable, the interpolant is a sequence of formulas w
8337  such that len(w) = N-1 and v[0] implies w[0] and for i in 0..N-1:
8338 
8339  1) w[i] & v[i+1] implies w[i+1] (or false if i+1 = N)
8340  2) All uninterpreted symbols in w[i] occur in both v[0]..v[i]
8341  and v[i+1]..v[n]
8342 
8343  Requires len(v) >= 1.
8344 
8345  If a & b is satisfiable, raises an object of class ModelRef
8346  that represents a model of a & b.
8347 
8348  If neither a proof of unsatisfiability nor a model is obtained
8349  (for example, because of a timeout, or because models are disabled)
8350  then None is returned.
8351 
8352  If parameters p are supplied, these are used in creating the
8353  solver that determines satisfiability.
8354 
8355  x = Int('x')
8356  y = Int('y')
8357  print(sequence_interpolant([x < 0, y == x , y > 2]))
8358  [Not(x >= 0), Not(y >= 0)]
8359  """
8360  f = v[0]
8361  for i in range(1,len(v)):
8362  f = And(Interpolant(f),v[i])
8363  return tree_interpolant(f,p,ctx)
8364 
8365 
8366 #########################################
8367 #
8368 # Floating-Point Arithmetic
8369 #
8370 #########################################
8371 
8372 
8373 # Global default rounding mode
8374 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8375 _dflt_fpsort_ebits = 11
8376 _dflt_fpsort_sbits = 53
8377 
8378 def get_default_rounding_mode(ctx=None):
8379  """Retrieves the global default rounding mode."""
8380  global _dflt_rounding_mode
8381  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8382  return RTZ(ctx)
8383  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8384  return RTN(ctx)
8385  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8386  return RTP(ctx)
8387  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8388  return RNE(ctx)
8389  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8390  return RNA(ctx)
8391 
8392 def set_default_rounding_mode(rm, ctx=None):
8393  global _dflt_rounding_mode
8394  if is_fprm_value(rm):
8395  _dflt_rounding_mode = rm.decl().kind()
8396  else:
8397  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8398  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8399  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8400  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8401  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8402  "illegal rounding mode")
8403  _dflt_rounding_mode = rm
8404 
8405 def get_default_fp_sort(ctx=None):
8406  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8407 
8408 def set_default_fp_sort(ebits, sbits, ctx=None):
8409  global _dflt_fpsort_ebits
8410  global _dflt_fpsort_sbits
8411  _dflt_fpsort_ebits = ebits
8412  _dflt_fpsort_sbits = sbits
8413 
8414 def _dflt_rm(ctx=None):
8415  return get_default_rounding_mode(ctx)
8416 
8417 def _dflt_fps(ctx=None):
8418  return get_default_fp_sort(ctx)
8419 
8420 def _coerce_fp_expr_list(alist, ctx):
8421  first_fp_sort = None
8422  for a in alist:
8423  if is_fp(a):
8424  if first_fp_sort is None:
8425  first_fp_sort = a.sort()
8426  elif first_fp_sort == a.sort():
8427  pass # OK, same as before
8428  else:
8429  # we saw at least 2 different float sorts; something will
8430  # throw a sort mismatch later, for now assume None.
8431  first_fp_sort = None
8432  break
8433 
8434  r = []
8435  for i in range(len(alist)):
8436  a = alist[i]
8437  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8438  r.append(FPVal(a, None, first_fp_sort, ctx))
8439  else:
8440  r.append(a)
8441  return _coerce_expr_list(r, ctx)
8442 
8443 
8444 ### FP Sorts
8445 
8446 class FPSortRef(SortRef):
8447  """Floating-point sort."""
8448 
8449  def ebits(self):
8450  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8451  >>> b = FPSort(8, 24)
8452  >>> b.ebits()
8453  8
8454  """
8455  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8456 
8457  def sbits(self):
8458  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8459  >>> b = FPSort(8, 24)
8460  >>> b.sbits()
8461  24
8462  """
8463  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8464 
8465  def cast(self, val):
8466  """Try to cast `val` as a floating-point expression.
8467  >>> b = FPSort(8, 24)
8468  >>> b.cast(1.0)
8469  1
8470  >>> b.cast(1.0).sexpr()
8471  '(fp #b0 #x7f #b00000000000000000000000)'
8472  """
8473  if is_expr(val):
8474  if __debug__:
8475  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8476  return val
8477  else:
8478  return FPVal(val, None, self, self.ctx)
8479 
8480 
8481 def Float16(ctx=None):
8482  """Floating-point 16-bit (half) sort."""
8483  ctx = _get_ctx(ctx)
8484  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8485 
8486 def FloatHalf(ctx=None):
8487  """Floating-point 16-bit (half) sort."""
8488  ctx = _get_ctx(ctx)
8489  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8490 
8491 def Float32(ctx=None):
8492  """Floating-point 32-bit (single) sort."""
8493  ctx = _get_ctx(ctx)
8494  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8495 
8496 def FloatSingle(ctx=None):
8497  """Floating-point 32-bit (single) sort."""
8498  ctx = _get_ctx(ctx)
8499  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8500 
8501 def Float64(ctx=None):
8502  """Floating-point 64-bit (double) sort."""
8503  ctx = _get_ctx(ctx)
8504  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8505 
8506 def FloatDouble(ctx=None):
8507  """Floating-point 64-bit (double) sort."""
8508  ctx = _get_ctx(ctx)
8509  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8510 
8511 def Float128(ctx=None):
8512  """Floating-point 128-bit (quadruple) sort."""
8513  ctx = _get_ctx(ctx)
8514  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8515 
8516 def FloatQuadruple(ctx=None):
8517  """Floating-point 128-bit (quadruple) sort."""
8518  ctx = _get_ctx(ctx)
8519  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8520 
8521 class FPRMSortRef(SortRef):
8522  """"Floating-point rounding mode sort."""
8523 
8524 
8525 def is_fp_sort(s):
8526  """Return True if `s` is a Z3 floating-point sort.
8527 
8528  >>> is_fp_sort(FPSort(8, 24))
8529  True
8530  >>> is_fp_sort(IntSort())
8531  False
8532  """
8533  return isinstance(s, FPSortRef)
8534 
8535 def is_fprm_sort(s):
8536  """Return True if `s` is a Z3 floating-point rounding mode sort.
8537 
8538  >>> is_fprm_sort(FPSort(8, 24))
8539  False
8540  >>> is_fprm_sort(RNE().sort())
8541  True
8542  """
8543  return isinstance(s, FPRMSortRef)
8544 
8545 ### FP Expressions
8546 
8547 class FPRef(ExprRef):
8548  """Floating-point expressions."""
8549 
8550  def sort(self):
8551  """Return the sort of the floating-point expression `self`.
8552 
8553  >>> x = FP('1.0', FPSort(8, 24))
8554  >>> x.sort()
8555  FPSort(8, 24)
8556  >>> x.sort() == FPSort(8, 24)
8557  True
8558  """
8559  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8560 
8561  def ebits(self):
8562  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8563  >>> b = FPSort(8, 24)
8564  >>> b.ebits()
8565  8
8566  """
8567  return self.sort().ebits();
8568 
8569  def sbits(self):
8570  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8571  >>> b = FPSort(8, 24)
8572  >>> b.sbits()
8573  24
8574  """
8575  return self.sort().sbits();
8576 
8577  def as_string(self):
8578  """Return a Z3 floating point expression as a Python string."""
8579  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8580 
8581  def __le__(self, other):
8582  return fpLEQ(self, other, self.ctx)
8583 
8584  def __lt__(self, other):
8585  return fpLT(self, other, self.ctx)
8586 
8587  def __ge__(self, other):
8588  return fpGEQ(self, other, self.ctx)
8589 
8590  def __gt__(self, other):
8591  return fpGT(self, other, self.ctx)
8592 
8593  def __add__(self, other):
8594  """Create the Z3 expression `self + other`.
8595 
8596  >>> x = FP('x', FPSort(8, 24))
8597  >>> y = FP('y', FPSort(8, 24))
8598  >>> x + y
8599  x + y
8600  >>> (x + y).sort()
8601  FPSort(8, 24)
8602  """
8603  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8604  return fpAdd(_dflt_rm(), a, b, self.ctx)
8605 
8606  def __radd__(self, other):
8607  """Create the Z3 expression `other + self`.
8608 
8609  >>> x = FP('x', FPSort(8, 24))
8610  >>> 10 + x
8611  1.25*(2**3) + x
8612  """
8613  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8614  return fpAdd(_dflt_rm(), a, b, self.ctx)
8615 
8616  def __sub__(self, other):
8617  """Create the Z3 expression `self - other`.
8618 
8619  >>> x = FP('x', FPSort(8, 24))
8620  >>> y = FP('y', FPSort(8, 24))
8621  >>> x - y
8622  x - y
8623  >>> (x - y).sort()
8624  FPSort(8, 24)
8625  """
8626  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8627  return fpSub(_dflt_rm(), a, b, self.ctx)
8628 
8629  def __rsub__(self, other):
8630  """Create the Z3 expression `other - self`.
8631 
8632  >>> x = FP('x', FPSort(8, 24))
8633  >>> 10 - x
8634  1.25*(2**3) - x
8635  """
8636  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8637  return fpSub(_dflt_rm(), a, b, self.ctx)
8638 
8639  def __mul__(self, other):
8640  """Create the Z3 expression `self * other`.
8641 
8642  >>> x = FP('x', FPSort(8, 24))
8643  >>> y = FP('y', FPSort(8, 24))
8644  >>> x * y
8645  x * y
8646  >>> (x * y).sort()
8647  FPSort(8, 24)
8648  >>> 10 * y
8649  1.25*(2**3) * y
8650  """
8651  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8652  return fpMul(_dflt_rm(), a, b, self.ctx)
8653 
8654  def __rmul__(self, other):
8655  """Create the Z3 expression `other * self`.
8656 
8657  >>> x = FP('x', FPSort(8, 24))
8658  >>> y = FP('y', FPSort(8, 24))
8659  >>> x * y
8660  x * y
8661  >>> x * 10
8662  x * 1.25*(2**3)
8663  """
8664  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8665  return fpMul(_dflt_rm(), a, b, self.ctx)
8666 
8667  def __pos__(self):
8668  """Create the Z3 expression `+self`."""
8669  return self
8670 
8671  def __neg__(self):
8672  """Create the Z3 expression `-self`.
8673 
8674  >>> x = FP('x', Float32())
8675  >>> -x
8676  -x
8677  """
8678  return fpNeg(self)
8679 
8680  def __div__(self, other):
8681  """Create the Z3 expression `self / other`.
8682 
8683  >>> x = FP('x', FPSort(8, 24))
8684  >>> y = FP('y', FPSort(8, 24))
8685  >>> x / y
8686  x / y
8687  >>> (x / y).sort()
8688  FPSort(8, 24)
8689  >>> 10 / y
8690  1.25*(2**3) / y
8691  """
8692  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8693  return fpDiv(_dflt_rm(), a, b, self.ctx)
8694 
8695  def __rdiv__(self, other):
8696  """Create the Z3 expression `other / self`.
8697 
8698  >>> x = FP('x', FPSort(8, 24))
8699  >>> y = FP('y', FPSort(8, 24))
8700  >>> x / y
8701  x / y
8702  >>> x / 10
8703  x / 1.25*(2**3)
8704  """
8705  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8706  return fpDiv(_dflt_rm(), a, b, self.ctx)
8707 
8708  if not sys.version < '3':
8709  def __truediv__(self, other):
8710  """Create the Z3 expression division `self / other`."""
8711  return self.__div__(other)
8712 
8713  def __rtruediv__(self, other):
8714  """Create the Z3 expression division `other / self`."""
8715  return self.__rdiv__(other)
8716 
8717  def __mod__(self, other):
8718  """Create the Z3 expression mod `self % other`."""
8719  return fpRem(self, other)
8720 
8721  def __rmod__(self, other):
8722  """Create the Z3 expression mod `other % self`."""
8723  return fpRem(other, self)
8724 
8725 class FPRMRef(ExprRef):
8726  """Floating-point rounding mode expressions"""
8727 
8728  def as_string(self):
8729  """Return a Z3 floating point expression as a Python string."""
8730  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8731 
8732 
8733 def RoundNearestTiesToEven(ctx=None):
8734  ctx = _get_ctx(ctx)
8735  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8736 
8737 def RNE (ctx=None):
8738  ctx = _get_ctx(ctx)
8739  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8740 
8741 def RoundNearestTiesToAway(ctx=None):
8742  ctx = _get_ctx(ctx)
8743  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8744 
8745 def RNA (ctx=None):
8746  ctx = _get_ctx(ctx)
8747  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8748 
8749 def RoundTowardPositive(ctx=None):
8750  ctx = _get_ctx(ctx)
8751  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8752 
8753 def RTP(ctx=None):
8754  ctx = _get_ctx(ctx)
8755  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8756 
8757 def RoundTowardNegative(ctx=None):
8758  ctx = _get_ctx(ctx)
8759  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8760 
8761 def RTN(ctx=None):
8762  ctx = _get_ctx(ctx)
8763  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8764 
8765 def RoundTowardZero(ctx=None):
8766  ctx = _get_ctx(ctx)
8767  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8768 
8769 def RTZ(ctx=None):
8770  ctx = _get_ctx(ctx)
8771  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8772 
8773 def is_fprm(a):
8774  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8775 
8776  >>> rm = RNE()
8777  >>> is_fprm(rm)
8778  True
8779  >>> rm = 1.0
8780  >>> is_fprm(rm)
8781  False
8782  """
8783  return isinstance(a, FPRMRef)
8784 
8785 def is_fprm_value(a):
8786  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8787  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8788 
8789 ### FP Numerals
8790 
8791 class FPNumRef(FPRef):
8792  """The sign of the numeral.
8793 
8794  >>> x = FPVal(+1.0, FPSort(8, 24))
8795  >>> x.sign()
8796  False
8797  >>> x = FPVal(-1.0, FPSort(8, 24))
8798  >>> x.sign()
8799  True
8800  """
8801  def sign(self):
8802  l = (ctypes.c_int)()
8803  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
8804  raise Z3Exception("error retrieving the sign of a numeral.")
8805  return l.value != 0
8806 
8807  """The sign of a floating-point numeral as a bit-vector expression.
8808 
8809  Remark: NaN's are invalid arguments.
8810  """
8811  def sign_as_bv(self):
8812  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8813 
8814  """The significand of the numeral.
8815 
8816  >>> x = FPVal(2.5, FPSort(8, 24))
8817  >>> x.significand()
8818  1.25
8819  """
8820  def significand(self):
8821  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
8822 
8823  """The significand of the numeral as a long.
8824 
8825  >>> x = FPVal(2.5, FPSort(8, 24))
8826  >>> x.significand_as_long()
8827  1.25
8828  """
8829  def significand_as_long(self):
8830  return Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast())
8831 
8832  """The significand of the numeral as a bit-vector expression.
8833 
8834  Remark: NaN are invalid arguments.
8835  """
8836  def significand_as_bv(self):
8837  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8838 
8839  """The exponent of the numeral.
8840 
8841  >>> x = FPVal(2.5, FPSort(8, 24))
8842  >>> x.exponent()
8843  1
8844  """
8845  def exponent(self, biased=True):
8846  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
8847 
8848  """The exponent of the numeral as a long.
8849 
8850  >>> x = FPVal(2.5, FPSort(8, 24))
8851  >>> x.exponent_as_long()
8852  1
8853  """
8854  def exponent_as_long(self, biased=True):
8855  ptr = (ctypes.c_longlong * 1)()
8856  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
8857  raise Z3Exception("error retrieving the exponent of a numeral.")
8858  return ptr[0]
8859 
8860  """The exponent of the numeral as a bit-vector expression.
8861 
8862  Remark: NaNs are invalid arguments.
8863  """
8864  def exponent_as_bv(self, biased=True):
8865  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
8866 
8867  """Indicates whether the numeral is a NaN."""
8868  def isNaN(self):
8869  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
8870 
8871  """Indicates whether the numeral is +oo or -oo."""
8872  def isInf(self):
8873  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
8874 
8875  """Indicates whether the numeral is +zero or -zero."""
8876  def isZero(self):
8877  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
8878 
8879  """Indicates whether the numeral is normal."""
8880  def isNormal(self):
8881  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
8882 
8883  """Indicates whether the numeral is subnormal."""
8884  def isSubnormal(self):
8885  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
8886 
8887  """Indicates whether the numeral is positive."""
8888  def isPositive(self):
8889  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
8890 
8891  """Indicates whether the numeral is negative."""
8892  def isNegative(self):
8893  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
8894 
8895  """
8896  The string representation of the numeral.
8897 
8898  >>> x = FPVal(20, FPSort(8, 24))
8899  >>> x.as_string()
8900  1.25*(2**4)
8901  """
8902  def as_string(self):
8903  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
8904  return ("FPVal(%s, %s)" % (s, self.sort()))
8905 
8906 def is_fp(a):
8907  """Return `True` if `a` is a Z3 floating-point expression.
8908 
8909  >>> b = FP('b', FPSort(8, 24))
8910  >>> is_fp(b)
8911  True
8912  >>> is_fp(b + 1.0)
8913  True
8914  >>> is_fp(Int('x'))
8915  False
8916  """
8917  return isinstance(a, FPRef)
8918 
8919 def is_fp_value(a):
8920  """Return `True` if `a` is a Z3 floating-point numeral value.
8921 
8922  >>> b = FP('b', FPSort(8, 24))
8923  >>> is_fp_value(b)
8924  False
8925  >>> b = FPVal(1.0, FPSort(8, 24))
8926  >>> b
8927  1
8928  >>> is_fp_value(b)
8929  True
8930  """
8931  return is_fp(a) and _is_numeral(a.ctx, a.ast)
8932 
8933 def FPSort(ebits, sbits, ctx=None):
8934  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
8935 
8936  >>> Single = FPSort(8, 24)
8937  >>> Double = FPSort(11, 53)
8938  >>> Single
8939  FPSort(8, 24)
8940  >>> x = Const('x', Single)
8941  >>> eq(x, FP('x', FPSort(8, 24)))
8942  True
8943  """
8944  ctx = _get_ctx(ctx)
8945  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
8946 
8947 def _to_float_str(val, exp=0):
8948  if isinstance(val, float):
8949  if math.isnan(val):
8950  res = "NaN"
8951  elif val == 0.0:
8952  sone = math.copysign(1.0, val)
8953  if sone < 0.0:
8954  return "-0.0"
8955  else:
8956  return "+0.0"
8957  elif val == float("+inf"):
8958  res = "+oo"
8959  elif val == float("-inf"):
8960  res = "-oo"
8961  else:
8962  v = val.as_integer_ratio()
8963  num = v[0]
8964  den = v[1]
8965  rvs = str(num) + '/' + str(den)
8966  res = rvs + 'p' + _to_int_str(exp)
8967  elif isinstance(val, bool):
8968  if val:
8969  res = "1.0"
8970  else:
8971  res = "0.0"
8972  elif _is_int(val):
8973  res = str(val)
8974  elif isinstance(val, str):
8975  inx = val.find('*(2**')
8976  if inx == -1:
8977  res = val
8978  elif val[-1] == ')':
8979  res = val[0:inx]
8980  exp = str(int(val[inx+5:-1]) + int(exp))
8981  else:
8982  _z3_assert(False, "String does not have floating-point numeral form.")
8983  elif __debug__:
8984  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
8985  if exp == 0:
8986  return res
8987  else:
8988  return res + 'p' + exp
8989 
8990 
8991 def fpNaN(s):
8992  """Create a Z3 floating-point NaN term.
8993 
8994  >>> s = FPSort(8, 24)
8995  >>> set_fpa_pretty(True)
8996  >>> fpNaN(s)
8997  NaN
8998  >>> pb = get_fpa_pretty()
8999  >>> set_fpa_pretty(False)
9000  >>> fpNaN(s)
9001  fpNaN(FPSort(8, 24))
9002  >>> set_fpa_pretty(pb)
9003  """
9004  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9005  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9006 
9007 def fpPlusInfinity(s):
9008  """Create a Z3 floating-point +oo term.
9009 
9010  >>> s = FPSort(8, 24)
9011  >>> pb = get_fpa_pretty()
9012  >>> set_fpa_pretty(True)
9013  >>> fpPlusInfinity(s)
9014  +oo
9015  >>> set_fpa_pretty(False)
9016  >>> fpPlusInfinity(s)
9017  fpPlusInfinity(FPSort(8, 24))
9018  >>> set_fpa_pretty(pb)
9019  """
9020  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9021  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9022 
9023 def fpMinusInfinity(s):
9024  """Create a Z3 floating-point -oo term."""
9025  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9026  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9027 
9028 def fpInfinity(s, negative):
9029  """Create a Z3 floating-point +oo or -oo term."""
9030  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9031  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9032  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9033 
9034 def fpPlusZero(s):
9035  """Create a Z3 floating-point +0.0 term."""
9036  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9037  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9038 
9039 def fpMinusZero(s):
9040  """Create a Z3 floating-point -0.0 term."""
9041  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9042  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9043 
9044 def fpZero(s, negative):
9045  """Create a Z3 floating-point +0.0 or -0.0 term."""
9046  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9047  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9048  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9049 
9050 def FPVal(sig, exp=None, fps=None, ctx=None):
9051  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9052 
9053  >>> v = FPVal(20.0, FPSort(8, 24))
9054  >>> v
9055  1.25*(2**4)
9056  >>> print("0x%.8x" % v.exponent_as_long(False))
9057  0x00000004
9058  >>> v = FPVal(2.25, FPSort(8, 24))
9059  >>> v
9060  1.125*(2**1)
9061  >>> v = FPVal(-2.25, FPSort(8, 24))
9062  >>> v
9063  -1.125*(2**1)
9064  >>> FPVal(-0.0, FPSort(8, 24))
9065  -0.0
9066  >>> FPVal(0.0, FPSort(8, 24))
9067  +0.0
9068  >>> FPVal(+0.0, FPSort(8, 24))
9069  +0.0
9070  """
9071  ctx = _get_ctx(ctx)
9072  if is_fp_sort(exp):
9073  fps = exp
9074  exp = None
9075  elif fps is None:
9076  fps = _dflt_fps(ctx)
9077  _z3_assert(is_fp_sort(fps), "sort mismatch")
9078  if exp is None:
9079  exp = 0
9080  val = _to_float_str(sig)
9081  if val == "NaN" or val == "nan":
9082  return fpNaN(fps)
9083  elif val == "-0.0":
9084  return fpMinusZero(fps)
9085  elif val == "0.0" or val == "+0.0":
9086  return fpPlusZero(fps)
9087  elif val == "+oo" or val == "+inf" or val == "+Inf":
9088  return fpPlusInfinity(fps)
9089  elif val == "-oo" or val == "-inf" or val == "-Inf":
9090  return fpMinusInfinity(fps)
9091  else:
9092  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9093 
9094 def FP(name, fpsort, ctx=None):
9095  """Return a floating-point constant named `name`.
9096  `fpsort` is the floating-point sort.
9097  If `ctx=None`, then the global context is used.
9098 
9099  >>> x = FP('x', FPSort(8, 24))
9100  >>> is_fp(x)
9101  True
9102  >>> x.ebits()
9103  8
9104  >>> x.sort()
9105  FPSort(8, 24)
9106  >>> word = FPSort(8, 24)
9107  >>> x2 = FP('x', word)
9108  >>> eq(x, x2)
9109  True
9110  """
9111  if isinstance(fpsort, FPSortRef) and ctx is None:
9112  ctx = fpsort.ctx
9113  else:
9114  ctx = _get_ctx(ctx)
9115  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9116 
9117 def FPs(names, fpsort, ctx=None):
9118  """Return an array of floating-point constants.
9119 
9120  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9121  >>> x.sort()
9122  FPSort(8, 24)
9123  >>> x.sbits()
9124  24
9125  >>> x.ebits()
9126  8
9127  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9128  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9129  """
9130  ctx = _get_ctx(ctx)
9131  if isinstance(names, str):
9132  names = names.split(" ")
9133  return [FP(name, fpsort, ctx) for name in names]
9134 
9135 def fpAbs(a, ctx=None):
9136  """Create a Z3 floating-point absolute value expression.
9137 
9138  >>> s = FPSort(8, 24)
9139  >>> rm = RNE()
9140  >>> x = FPVal(1.0, s)
9141  >>> fpAbs(x)
9142  fpAbs(1)
9143  >>> y = FPVal(-20.0, s)
9144  >>> y
9145  -1.25*(2**4)
9146  >>> fpAbs(y)
9147  fpAbs(-1.25*(2**4))
9148  >>> fpAbs(-1.25*(2**4))
9149  fpAbs(-1.25*(2**4))
9150  >>> fpAbs(x).sort()
9151  FPSort(8, 24)
9152  """
9153  ctx = _get_ctx(ctx)
9154  [a] = _coerce_fp_expr_list([a], ctx)
9155  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9156 
9157 def fpNeg(a, ctx=None):
9158  """Create a Z3 floating-point addition expression.
9159 
9160  >>> s = FPSort(8, 24)
9161  >>> rm = RNE()
9162  >>> x = FP('x', s)
9163  >>> fpNeg(x)
9164  -x
9165  >>> fpNeg(x).sort()
9166  FPSort(8, 24)
9167  """
9168  ctx = _get_ctx(ctx)
9169  [a] = _coerce_fp_expr_list([a], ctx)
9170  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9171 
9172 def _mk_fp_unary(f, rm, a, ctx):
9173  ctx = _get_ctx(ctx)
9174  [a] = _coerce_fp_expr_list([a], ctx)
9175  if __debug__:
9176  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9177  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9178  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9179 
9180 def _mk_fp_unary_norm(f, a, ctx):
9181  ctx = _get_ctx(ctx)
9182  [a] = _coerce_fp_expr_list([a], ctx)
9183  if __debug__:
9184  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9185  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
9186 
9187 def _mk_fp_unary_pred(f, a, ctx):
9188  ctx = _get_ctx(ctx)
9189  [a] = _coerce_fp_expr_list([a], ctx)
9190  if __debug__:
9191  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9192  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9193 
9194 def _mk_fp_bin(f, rm, a, b, ctx):
9195  ctx = _get_ctx(ctx)
9196  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9197  if __debug__:
9198  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9199  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9200  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9201 
9202 def _mk_fp_bin_norm(f, a, b, ctx):
9203  ctx = _get_ctx(ctx)
9204  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9205  if __debug__:
9206  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9207  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9208 
9209 def _mk_fp_bin_pred(f, a, b, ctx):
9210  ctx = _get_ctx(ctx)
9211  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9212  if __debug__:
9213  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9214  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9215 
9216 def _mk_fp_tern(f, rm, a, b, c, ctx):
9217  ctx = _get_ctx(ctx)
9218  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9219  if __debug__:
9220  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9221  _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")
9222  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9223 
9224 def fpAdd(rm, a, b, ctx=None):
9225  """Create a Z3 floating-point addition expression.
9226 
9227  >>> s = FPSort(8, 24)
9228  >>> rm = RNE()
9229  >>> x = FP('x', s)
9230  >>> y = FP('y', s)
9231  >>> fpAdd(rm, x, y)
9232  fpAdd(RNE(), x, y)
9233  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9234  x + y
9235  >>> fpAdd(rm, x, y).sort()
9236  FPSort(8, 24)
9237  """
9238  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9239 
9240 def fpSub(rm, a, b, ctx=None):
9241  """Create a Z3 floating-point subtraction expression.
9242 
9243  >>> s = FPSort(8, 24)
9244  >>> rm = RNE()
9245  >>> x = FP('x', s)
9246  >>> y = FP('y', s)
9247  >>> fpSub(rm, x, y)
9248  fpSub(RNE(), x, y)
9249  >>> fpSub(rm, x, y).sort()
9250  FPSort(8, 24)
9251  """
9252  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9253 
9254 def fpMul(rm, a, b, ctx=None):
9255  """Create a Z3 floating-point multiplication expression.
9256 
9257  >>> s = FPSort(8, 24)
9258  >>> rm = RNE()
9259  >>> x = FP('x', s)
9260  >>> y = FP('y', s)
9261  >>> fpMul(rm, x, y)
9262  fpMul(RNE(), x, y)
9263  >>> fpMul(rm, x, y).sort()
9264  FPSort(8, 24)
9265  """
9266  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9267 
9268 def fpDiv(rm, a, b, ctx=None):
9269  """Create a Z3 floating-point division expression.
9270 
9271  >>> s = FPSort(8, 24)
9272  >>> rm = RNE()
9273  >>> x = FP('x', s)
9274  >>> y = FP('y', s)
9275  >>> fpDiv(rm, x, y)
9276  fpDiv(RNE(), x, y)
9277  >>> fpDiv(rm, x, y).sort()
9278  FPSort(8, 24)
9279  """
9280  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9281 
9282 def fpRem(a, b, ctx=None):
9283  """Create a Z3 floating-point remainder expression.
9284 
9285  >>> s = FPSort(8, 24)
9286  >>> x = FP('x', s)
9287  >>> y = FP('y', s)
9288  >>> fpRem(x, y)
9289  fpRem(x, y)
9290  >>> fpRem(x, y).sort()
9291  FPSort(8, 24)
9292  """
9293  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9294 
9295 def fpMin(a, b, ctx=None):
9296  """Create a Z3 floating-point minimum expression.
9297 
9298  >>> s = FPSort(8, 24)
9299  >>> rm = RNE()
9300  >>> x = FP('x', s)
9301  >>> y = FP('y', s)
9302  >>> fpMin(x, y)
9303  fpMin(x, y)
9304  >>> fpMin(x, y).sort()
9305  FPSort(8, 24)
9306  """
9307  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9308 
9309 def fpMax(a, b, ctx=None):
9310  """Create a Z3 floating-point maximum expression.
9311 
9312  >>> s = FPSort(8, 24)
9313  >>> rm = RNE()
9314  >>> x = FP('x', s)
9315  >>> y = FP('y', s)
9316  >>> fpMax(x, y)
9317  fpMax(x, y)
9318  >>> fpMax(x, y).sort()
9319  FPSort(8, 24)
9320  """
9321  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9322 
9323 def fpFMA(rm, a, b, c, ctx=None):
9324  """Create a Z3 floating-point fused multiply-add expression.
9325  """
9326  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9327 
9328 def fpSqrt(rm, a, ctx=None):
9329  """Create a Z3 floating-point square root expression.
9330  """
9331  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9332 
9333 def fpRoundToIntegral(rm, a, ctx=None):
9334  """Create a Z3 floating-point roundToIntegral expression.
9335  """
9336  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9337 
9338 def fpIsNaN(a, ctx=None):
9339  """Create a Z3 floating-point isNaN expression.
9340 
9341  >>> s = FPSort(8, 24)
9342  >>> x = FP('x', s)
9343  >>> y = FP('y', s)
9344  >>> fpIsNaN(x)
9345  fpIsNaN(x)
9346  """
9347  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
9348 
9349 def fpIsInf(a, ctx=None):
9350  """Create a Z3 floating-point isInfinite expression.
9351 
9352  >>> s = FPSort(8, 24)
9353  >>> x = FP('x', s)
9354  >>> fpIsInf(x)
9355  fpIsInf(x)
9356  """
9357  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
9358 
9359 def fpIsZero(a, ctx=None):
9360  """Create a Z3 floating-point isZero expression.
9361  """
9362  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
9363 
9364 def fpIsNormal(a, ctx=None):
9365  """Create a Z3 floating-point isNormal expression.
9366  """
9367  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
9368 
9369 def fpIsSubnormal(a, ctx=None):
9370  """Create a Z3 floating-point isSubnormal expression.
9371  """
9372  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
9373 
9374 def fpIsNegative(a, ctx=None):
9375  """Create a Z3 floating-point isNegative expression.
9376  """
9377  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9378 
9379 def fpIsPositive(a, ctx=None):
9380  """Create a Z3 floating-point isPositive expression.
9381  """
9382  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9383  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9384 
9385 def _check_fp_args(a, b):
9386  if __debug__:
9387  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9388 
9389 def fpLT(a, b, ctx=None):
9390  """Create the Z3 floating-point expression `other < self`.
9391 
9392  >>> x, y = FPs('x y', FPSort(8, 24))
9393  >>> fpLT(x, y)
9394  x < y
9395  >>> (x < y).sexpr()
9396  '(fp.lt x y)'
9397  """
9398  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9399 
9400 def fpLEQ(a, b, ctx=None):
9401  """Create the Z3 floating-point expression `other <= self`.
9402 
9403  >>> x, y = FPs('x y', FPSort(8, 24))
9404  >>> fpLEQ(x, y)
9405  x <= y
9406  >>> (x <= y).sexpr()
9407  '(fp.leq x y)'
9408  """
9409  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9410 
9411 def fpGT(a, b, ctx=None):
9412  """Create the Z3 floating-point expression `other > self`.
9413 
9414  >>> x, y = FPs('x y', FPSort(8, 24))
9415  >>> fpGT(x, y)
9416  x > y
9417  >>> (x > y).sexpr()
9418  '(fp.gt x y)'
9419  """
9420  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9421 
9422 def fpGEQ(a, b, ctx=None):
9423  """Create the Z3 floating-point expression `other >= self`.
9424 
9425  >>> x, y = FPs('x y', FPSort(8, 24))
9426  >>> fpGEQ(x, y)
9427  x >= y
9428  >>> (x >= y).sexpr()
9429  '(fp.geq x y)'
9430  """
9431  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9432 
9433 def fpEQ(a, b, ctx=None):
9434  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9435 
9436  >>> x, y = FPs('x y', FPSort(8, 24))
9437  >>> fpEQ(x, y)
9438  fpEQ(x, y)
9439  >>> fpEQ(x, y).sexpr()
9440  '(fp.eq x y)'
9441  """
9442  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9443 
9444 def fpNEQ(a, b, ctx=None):
9445  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9446 
9447  >>> x, y = FPs('x y', FPSort(8, 24))
9448  >>> fpNEQ(x, y)
9449  Not(fpEQ(x, y))
9450  >>> (x != y).sexpr()
9451  '(distinct x y)'
9452  """
9453  return Not(fpEQ(a, b, ctx))
9454 
9455 def fpFP(sgn, exp, sig, ctx=None):
9456  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9457 
9458  >>> s = FPSort(8, 24)
9459  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9460  >>> print(x)
9461  fpFP(1, 127, 4194304)
9462  >>> xv = FPVal(-1.5, s)
9463  >>> print(xv)
9464  -1.5
9465  >>> slvr = Solver()
9466  >>> slvr.add(fpEQ(x, xv))
9467  >>> slvr.check()
9468  sat
9469  >>> xv = FPVal(+1.5, s)
9470  >>> print(xv)
9471  1.5
9472  >>> slvr = Solver()
9473  >>> slvr.add(fpEQ(x, xv))
9474  >>> slvr.check()
9475  unsat
9476  """
9477  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9478  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9479  ctx = _get_ctx(ctx)
9480  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9481  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9482 
9483 def fpToFP(a1, a2=None, a3=None, ctx=None):
9484  """Create a Z3 floating-point conversion expression from other term sorts
9485  to floating-point.
9486 
9487  From a bit-vector term in IEEE 754-2008 format:
9488  >>> x = FPVal(1.0, Float32())
9489  >>> x_bv = fpToIEEEBV(x)
9490  >>> simplify(fpToFP(x_bv, Float32()))
9491  1
9492 
9493  From a floating-point term with different precision:
9494  >>> x = FPVal(1.0, Float32())
9495  >>> x_db = fpToFP(RNE(), x, Float64())
9496  >>> x_db.sort()
9497  FPSort(11, 53)
9498 
9499  From a real term:
9500  >>> x_r = RealVal(1.5)
9501  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9502  1.5
9503 
9504  From a signed bit-vector term:
9505  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9506  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9507  -1.25*(2**2)
9508  """
9509  ctx = _get_ctx(ctx)
9510  if is_bv(a1) and is_fp_sort(a2):
9511  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9512  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9513  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9514  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9515  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9516  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9517  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9518  else:
9519  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9520 
9521 def fpBVToFP(v, sort, ctx=None):
9522  """Create a Z3 floating-point conversion expression that represents the
9523  conversion from a bit-vector term to a floating-point term.
9524 
9525  >>> x_bv = BitVecVal(0x3F800000, 32)
9526  >>> x_fp = fpBVToFP(x_bv, Float32())
9527  >>> x_fp
9528  fpToFP(1065353216)
9529  >>> simplify(x_fp)
9530  1
9531  """
9532  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9533  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9534  ctx = _get_ctx(ctx)
9535  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9536 
9537 def fpFPToFP(rm, v, sort, ctx=None):
9538  """Create a Z3 floating-point conversion expression that represents the
9539  conversion from a floating-point term to a floating-point term of different precision.
9540 
9541  >>> x_sgl = FPVal(1.0, Float32())
9542  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9543  >>> x_dbl
9544  fpToFP(RNE(), 1)
9545  >>> simplify(x_dbl)
9546  1
9547  >>> x_dbl.sort()
9548  FPSort(11, 53)
9549  """
9550  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9551  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9552  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9553  ctx = _get_ctx(ctx)
9554  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9555 
9556 def fpRealToFP(rm, v, sort, ctx=None):
9557  """Create a Z3 floating-point conversion expression that represents the
9558  conversion from a real term to a floating-point term.
9559 
9560  >>> x_r = RealVal(1.5)
9561  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9562  >>> x_fp
9563  fpToFP(RNE(), 3/2)
9564  >>> simplify(x_fp)
9565  1.5
9566  """
9567  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9568  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9569  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9570  ctx = _get_ctx(ctx)
9571  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9572 
9573 def fpSignedToFP(rm, v, sort, ctx=None):
9574  """Create a Z3 floating-point conversion expression that represents the
9575  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9576 
9577  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9578  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9579  >>> x_fp
9580  fpToFP(RNE(), 4294967291)
9581  >>> simplify(x_fp)
9582  -1.25*(2**2)
9583  """
9584  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9585  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9586  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9587  ctx = _get_ctx(ctx)
9588  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9589 
9590 def fpUnsignedToFP(rm, v, sort, ctx=None):
9591  """Create a Z3 floating-point conversion expression that represents the
9592  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9593 
9594  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9595  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9596  >>> x_fp
9597  fpToFPUnsigned(RNE(), 4294967291)
9598  >>> simplify(x_fp)
9599  1*(2**32)
9600  """
9601  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9602  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9603  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9604  ctx = _get_ctx(ctx)
9605  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9606 
9607 def fpToFPUnsigned(rm, x, s, ctx=None):
9608  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9609  if __debug__:
9610  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9611  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9612  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9613  ctx = _get_ctx(ctx)
9614  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9615 
9616 def fpToSBV(rm, x, s, ctx=None):
9617  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9618 
9619  >>> x = FP('x', FPSort(8, 24))
9620  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9621  >>> print(is_fp(x))
9622  True
9623  >>> print(is_bv(y))
9624  True
9625  >>> print(is_fp(y))
9626  False
9627  >>> print(is_bv(x))
9628  False
9629  """
9630  if __debug__:
9631  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9632  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9633  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9634  ctx = _get_ctx(ctx)
9635  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9636 
9637 def fpToUBV(rm, x, s, ctx=None):
9638  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9639 
9640  >>> x = FP('x', FPSort(8, 24))
9641  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9642  >>> print(is_fp(x))
9643  True
9644  >>> print(is_bv(y))
9645  True
9646  >>> print(is_fp(y))
9647  False
9648  >>> print(is_bv(x))
9649  False
9650  """
9651  if __debug__:
9652  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9653  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9654  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9655  ctx = _get_ctx(ctx)
9656  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9657 
9658 def fpToReal(x, ctx=None):
9659  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9660 
9661  >>> x = FP('x', FPSort(8, 24))
9662  >>> y = fpToReal(x)
9663  >>> print(is_fp(x))
9664  True
9665  >>> print(is_real(y))
9666  True
9667  >>> print(is_fp(y))
9668  False
9669  >>> print(is_real(x))
9670  False
9671  """
9672  if __debug__:
9673  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9674  ctx = _get_ctx(ctx)
9675  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9676 
9677 def fpToIEEEBV(x, ctx=None):
9678  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9679 
9680  The size of the resulting bit-vector is automatically determined.
9681 
9682  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9683  knows only one NaN and it will always produce the same bit-vector representation of
9684  that NaN.
9685 
9686  >>> x = FP('x', FPSort(8, 24))
9687  >>> y = fpToIEEEBV(x)
9688  >>> print(is_fp(x))
9689  True
9690  >>> print(is_bv(y))
9691  True
9692  >>> print(is_fp(y))
9693  False
9694  >>> print(is_bv(x))
9695  False
9696  """
9697  if __debug__:
9698  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9699  ctx = _get_ctx(ctx)
9700  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9701 
9702 
9703 
9704 #########################################
9705 #
9706 # Strings, Sequences and Regular expressions
9707 #
9708 #########################################
9709 
9710 class SeqSortRef(SortRef):
9711  """Sequence sort."""
9712 
9713  def is_string(self):
9714  """Determine if sort is a string
9715  >>> s = StringSort()
9716  >>> s.is_string()
9717  True
9718  >>> s = SeqSort(IntSort())
9719  >>> s.is_string()
9720  False
9721  """
9722  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9723 
9724 
9725 def StringSort(ctx=None):
9726  """Create a string sort
9727  >>> s = StringSort()
9728  >>> print(s)
9729  String
9730  """
9731  ctx = _get_ctx(ctx)
9732  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9733 
9734 
9735 def SeqSort(s):
9736  """Create a sequence sort over elements provided in the argument
9737  >>> s = SeqSort(IntSort())
9738  >>> s == Unit(IntVal(1)).sort()
9739  True
9740  """
9741  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9742 
9743 class SeqRef(ExprRef):
9744  """Sequence expression."""
9745 
9746  def sort(self):
9747  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9748 
9749  def __add__(self, other):
9750  return Concat(self, other)
9751 
9752  def __radd__(self, other):
9753  return Concat(other, self)
9754 
9755  def __getitem__(self, i):
9756  if _is_int(i):
9757  i = IntVal(i, self.ctx)
9758  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9759 
9760  def is_string(self):
9761  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9762 
9763  def is_string_value(self):
9764  return Z3_is_string(self.ctx_ref(), self.as_ast())
9765 
9766  def as_string(self):
9767  """Return a string representation of sequence expression."""
9768  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9769 
9770 
9771 def _coerce_seq(s, ctx=None):
9772  if isinstance(s, str):
9773  ctx = _get_ctx(ctx)
9774  s = StringVal(s, ctx)
9775  if not is_expr(s):
9776  raise Z3Exception("Non-expression passed as a sequence")
9777  if not is_seq(s):
9778  raise Z3Exception("Non-sequence passed as a sequence")
9779  return s
9780 
9781 def _get_ctx2(a, b, ctx=None):
9782  if is_expr(a):
9783  return a.ctx
9784  if is_expr(b):
9785  return b.ctx
9786  if ctx is None:
9787  ctx = main_ctx()
9788  return ctx
9789 
9790 def is_seq(a):
9791  """Return `True` if `a` is a Z3 sequence expression.
9792  >>> print (is_seq(Unit(IntVal(0))))
9793  True
9794  >>> print (is_seq(StringVal("abc")))
9795  True
9796  """
9797  return isinstance(a, SeqRef)
9798 
9799 def is_string(a):
9800  """Return `True` if `a` is a Z3 string expression.
9801  >>> print (is_string(StringVal("ab")))
9802  True
9803  """
9804  return isinstance(a, SeqRef) and a.is_string()
9805 
9806 def is_string_value(a):
9807  """return 'True' if 'a' is a Z3 string constant expression.
9808  >>> print (is_string_value(StringVal("a")))
9809  True
9810  >>> print (is_string_value(StringVal("a") + StringVal("b")))
9811  False
9812  """
9813  return isinstance(a, SeqRef) and a.is_string_value()
9814 
9815 
9816 def StringVal(s, ctx=None):
9817  """create a string expression"""
9818  ctx = _get_ctx(ctx)
9819  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
9820 
9821 def String(name, ctx=None):
9822  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
9823 
9824  >>> x = String('x')
9825  """
9826  ctx = _get_ctx(ctx)
9827  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
9828 
9829 def SubString(s, offset, length):
9830  """Extract substring or subsequence starting at offset"""
9831  return Extract(s, offset, length)
9832 
9833 def SubSeq(s, offset, length):
9834  """Extract substring or subsequence starting at offset"""
9835  return Extract(s, offset, length)
9836 
9837 def Strings(names, ctx=None):
9838  """Return a tuple of String constants. """
9839  ctx = _get_ctx(ctx)
9840  if isinstance(names, str):
9841  names = names.split(" ")
9842  return [String(name, ctx) for name in names]
9843 
9844 def Empty(s):
9845  """Create the empty sequence of the given sort
9846  >>> e = Empty(StringSort())
9847  >>> print(e)
9848  ""
9849  >>> e2 = StringVal("")
9850  >>> print(e.eq(e2))
9851  True
9852  >>> e3 = Empty(SeqSort(IntSort()))
9853  >>> print(e3)
9854  seq.empty
9855  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
9856  >>> print(e4)
9857  re.empty
9858  """
9859  if isinstance(s, SeqSortRef):
9860  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
9861  if isinstance(s, ReSortRef):
9862  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
9863  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
9864 
9865 def Full(s):
9866  """Create the regular expression that accepts the universal language
9867  >>> e = Full(ReSort(SeqSort(IntSort())))
9868  >>> print(e)
9869  re.all
9870  >>> e1 = Full(ReSort(StringSort()))
9871  >>> print(e1)
9872  re.all
9873  """
9874  if isinstance(s, ReSortRef):
9875  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
9876  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
9877 
9878 
9879 def Unit(a):
9880  """Create a singleton sequence"""
9881  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
9882 
9883 def PrefixOf(a, b):
9884  """Check if 'a' is a prefix of 'b'
9885  >>> s1 = PrefixOf("ab", "abc")
9886  >>> simplify(s1)
9887  True
9888  >>> s2 = PrefixOf("bc", "abc")
9889  >>> simplify(s2)
9890  False
9891  """
9892  ctx = _get_ctx2(a, b)
9893  a = _coerce_seq(a, ctx)
9894  b = _coerce_seq(b, ctx)
9895  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9896 
9897 def SuffixOf(a, b):
9898  """Check if 'a' is a suffix of 'b'
9899  >>> s1 = SuffixOf("ab", "abc")
9900  >>> simplify(s1)
9901  False
9902  >>> s2 = SuffixOf("bc", "abc")
9903  >>> simplify(s2)
9904  True
9905  """
9906  ctx = _get_ctx2(a, b)
9907  a = _coerce_seq(a, ctx)
9908  b = _coerce_seq(b, ctx)
9909  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9910 
9911 def Contains(a, b):
9912  """Check if 'a' contains 'b'
9913  >>> s1 = Contains("abc", "ab")
9914  >>> simplify(s1)
9915  True
9916  >>> s2 = Contains("abc", "bc")
9917  >>> simplify(s2)
9918  True
9919  >>> x, y, z = Strings('x y z')
9920  >>> s3 = Contains(Concat(x,y,z), y)
9921  >>> simplify(s3)
9922  True
9923  """
9924  ctx = _get_ctx2(a, b)
9925  a = _coerce_seq(a, ctx)
9926  b = _coerce_seq(b, ctx)
9927  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9928 
9929 
9930 def Replace(s, src, dst):
9931  """Replace the first occurrence of 'src' by 'dst' in 's'
9932  >>> r = Replace("aaa", "a", "b")
9933  >>> simplify(r)
9934  "baa"
9935  """
9936  ctx = _get_ctx2(dst, s)
9937  if ctx is None and is_expr(src):
9938  ctx = src.ctx
9939  src = _coerce_seq(src, ctx)
9940  dst = _coerce_seq(dst, ctx)
9941  s = _coerce_seq(s, ctx)
9942  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
9943 
9944 def IndexOf(s, substr):
9945  return IndexOf(s, substr, IntVal(0))
9946 
9947 def IndexOf(s, substr, offset):
9948  """Retrieve the index of substring within a string starting at a specified offset.
9949  >>> simplify(IndexOf("abcabc", "bc", 0))
9950  1
9951  >>> simplify(IndexOf("abcabc", "bc", 2))
9952  4
9953  """
9954  ctx = None
9955  if is_expr(offset):
9956  ctx = offset.ctx
9957  ctx = _get_ctx2(s, substr, ctx)
9958  s = _coerce_seq(s, ctx)
9959  substr = _coerce_seq(substr, ctx)
9960  if _is_int(offset):
9961  offset = IntVal(offset, ctx)
9962  return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
9963 
9964 def Length(s):
9965  """Obtain the length of a sequence 's'
9966  >>> l = Length(StringVal("abc"))
9967  >>> simplify(l)
9968  3
9969  """
9970  s = _coerce_seq(s)
9971  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
9972 
9973 def StrToInt(s):
9974  """Convert string expression to integer
9975  >>> a = StrToInt("1")
9976  >>> simplify(1 == a)
9977  True
9978  >>> b = StrToInt("2")
9979  >>> simplify(1 == b)
9980  False
9981  >>> c = StrToInt(IntToStr(2))
9982  >>> simplify(1 == c)
9983  False
9984  """
9985  s = _coerce_seq(s)
9986  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
9987 
9988 
9989 def IntToStr(s):
9990  """Convert integer expression to string"""
9991  if not is_expr(s):
9992  s = _py2expr(s)
9993  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
9994 
9995 
9996 def Re(s, ctx=None):
9997  """The regular expression that accepts sequence 's'
9998  >>> s1 = Re("ab")
9999  >>> s2 = Re(StringVal("ab"))
10000  >>> s3 = Re(Unit(BoolVal(True)))
10001  """
10002  s = _coerce_seq(s, ctx)
10003  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10004 
10005 
10006 
10007 
10008 ## Regular expressions
10009 
10010 class ReSortRef(SortRef):
10011  """Regular expression sort."""
10012 
10013 
10014 def ReSort(s):
10015  if is_ast(s):
10016  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10017  if s is None or isinstance(s, Context):
10018  ctx = _get_ctx(s)
10019  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10020  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10021 
10022 
10023 class ReRef(ExprRef):
10024  """Regular expressions."""
10025 
10026  def __add__(self, other):
10027  return Union(self, other)
10028 
10029 
10030 def is_re(s):
10031  return isinstance(s, ReRef)
10032 
10033 
10034 def InRe(s, re):
10035  """Create regular expression membership test
10036  >>> re = Union(Re("a"),Re("b"))
10037  >>> print (simplify(InRe("a", re)))
10038  True
10039  >>> print (simplify(InRe("b", re)))
10040  True
10041  >>> print (simplify(InRe("c", re)))
10042  False
10043  """
10044  s = _coerce_seq(s, re.ctx)
10045  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10046 
10047 def Union(*args):
10048  """Create union of regular expressions.
10049  >>> re = Union(Re("a"), Re("b"), Re("c"))
10050  >>> print (simplify(InRe("d", re)))
10051  False
10052  """
10053  args = _get_args(args)
10054  sz = len(args)
10055  if __debug__:
10056  _z3_assert(sz > 0, "At least one argument expected.")
10057  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10058  if sz == 1:
10059  return args[0]
10060  ctx = args[0].ctx
10061  v = (Ast * sz)()
10062  for i in range(sz):
10063  v[i] = args[i].as_ast()
10064  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10065 
10066 def Plus(re):
10067  """Create the regular expression accepting one or more repetitions of argument.
10068  >>> re = Plus(Re("a"))
10069  >>> print(simplify(InRe("aa", re)))
10070  True
10071  >>> print(simplify(InRe("ab", re)))
10072  False
10073  >>> print(simplify(InRe("", re)))
10074  False
10075  """
10076  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10077 
10078 def Option(re):
10079  """Create the regular expression that optionally accepts the argument.
10080  >>> re = Option(Re("a"))
10081  >>> print(simplify(InRe("a", re)))
10082  True
10083  >>> print(simplify(InRe("", re)))
10084  True
10085  >>> print(simplify(InRe("aa", re)))
10086  False
10087  """
10088  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10089 
10090 def Complement(re):
10091  """Create the complement regular expression."""
10092  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10093 
10094 def Star(re):
10095  """Create the regular expression accepting zero or more repetitions of argument.
10096  >>> re = Star(Re("a"))
10097  >>> print(simplify(InRe("aa", re)))
10098  True
10099  >>> print(simplify(InRe("ab", re)))
10100  False
10101  >>> print(simplify(InRe("", re)))
10102  True
10103  """
10104  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10105 
10106 def Loop(re, lo, hi=0):
10107  """Create the regular expression accepting between a lower and upper bound repetitions
10108  >>> re = Loop(Re("a"), 1, 3)
10109  >>> print(simplify(InRe("aa", re)))
10110  True
10111  >>> print(simplify(InRe("aaaa", re)))
10112  False
10113  >>> print(simplify(InRe("", re)))
10114  False
10115  """
10116  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
def param_descrs(self)
Definition: z3py.py:6996
def value(self)
Definition: z3py.py:6961
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:7068
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:652
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:9677
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:2533
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:7793
def __ge__(self, other)
Definition: z3py.py:7605
Z3_bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:2950
def is_distinct(a)
Definition: z3py.py:1438
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:7579
def Then(ts, ks)
Definition: z3py.py:7377
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:3927
def update_rule(self, head, body, name)
Definition: z3py.py:6691
def SeqSort(s)
Definition: z3py.py:9735
Fixedpoint.
Definition: z3py.py:6549
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:6949
def OrElse(ts, ks)
Definition: z3py.py:7389
def is_fprm_sort(s)
Definition: z3py.py:8535
def get_version_string()
Definition: z3py.py:68
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:1728
def AtLeast(args)
Definition: z3py.py:7939
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:4766
def entry(self, idx)
Definition: z3py.py:5572
def get_cover_delta(self, level, predicate)
Definition: z3py.py:6726
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:7083
def RatVal(a, b, ctx=None)
Definition: z3py.py:2836
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:7010
def __getitem__(self, idx)
Definition: z3py.py:7166
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:636
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:2937
Booleans.
Definition: z3py.py:1297
def Product(args)
Definition: z3py.py:7897
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:4903
def IsInt(a)
Definition: z3py.py:2997
def Sum(args)
Definition: z3py.py:7871
def __repr__(self)
Definition: z3py.py:303
def is_arith_sort(s)
Definition: z3py.py:2035
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...
Z3_bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def ReSort(s)
Definition: z3py.py:10014
def push(self)
Definition: z3py.py:6683
def Function(name, sig)
Definition: z3py.py:774
def RTZ(ctx=None)
Definition: z3py.py:8769
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:815
def __iadd__(self, fml)
Definition: z3py.py:7014
def RealSort(ctx=None)
Definition: z3py.py:2776
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:2868
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9521
Z3_model Z3_API Z3_apply_result_convert_model(Z3_context c, Z3_apply_result r, unsigned i, Z3_model m)
Convert a model for the subgoal Z3_apply_result_get_subgoal(c, r, i) into a model for the original go...
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o)
Check consistency and produce optimal values.
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9117
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9050
def get_rules(self)
Definition: z3py.py:6765
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:1280
def sort(self)
Definition: z3py.py:6856
def AndThen(ts, ks)
Definition: z3py.py:7358
def ZeroExt(n, a)
Definition: z3py.py:3956
def assertions(self)
Definition: z3py.py:7102
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:7851
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:1981
def Var(idx, s)
Definition: z3py.py:1258
def __del__(self)
Definition: z3py.py:7562
def is_bool(self)
Definition: z3py.py:1327
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:7689
def to_symbol(s, ctx=None)
Definition: z3py.py:101
def help(self)
Definition: z3py.py:6453
def reset_params()
Definition: z3py.py:252
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:4444
def is_string_value(a)
Definition: z3py.py:9806
def as_ast(self)
Definition: z3py.py:334
def assert_exprs(self, args)
Definition: z3py.py:7000
def LShR(a, b)
Definition: z3py.py:3866
def is_default(a)
Definition: z3py.py:4196
def set_option(args, kws)
Definition: z3py.py:257
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:3043
def Consts(names, sort)
Definition: z3py.py:1244
def use_pp(self)
Definition: z3py.py:283
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:2807
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:312
def is_and(a)
Definition: z3py.py:1396
def ref(self)
Definition: z3py.py:188
def push(self)
Definition: z3py.py:6121
def fpGT(a, b, ctx=None)
Definition: z3py.py:9411
def sort(self)
Definition: z3py.py:1333
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8189
def ULT(a, b)
Definition: z3py.py:3755
def fpIsInf(a, ctx=None)
Definition: z3py.py:9349
Arithmetic.
Definition: z3py.py:1964
FP Expressions.
Definition: z3py.py:8547
def __init__(self, ctx=None)
Definition: z3py.py:6974
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
def minimize(self, arg)
Definition: z3py.py:7041
def help(self)
Definition: z3py.py:6992
def sort(self)
Definition: z3py.py:2053
Z3_bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
def is_to_real(a)
Definition: z3py.py:2577
def as_ast(self)
Definition: z3py.py:492
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9483
def assert_exprs(self, args)
Definition: z3py.py:6584
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:8501
def param_descrs(self)
Definition: z3py.py:6580
def is_select(a)
Definition: z3py.py:4368
def is_real(self)
Definition: z3py.py:2077
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:2063
ASTs base class.
Definition: z3py.py:281
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:865
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:9590
def is_gt(a)
Definition: z3py.py:2555
def lower_values(self, obj)
Definition: z3py.py:7078
def pop(self)
Definition: z3py.py:7049
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:7186
def set_param(args, kws)
Definition: z3py.py:229
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:844
def domain(self, i)
Definition: z3py.py:672
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:6860
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:1937
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:10106
def AtMost(args)
Definition: z3py.py:7922
def __deepcopy__(self, memo={})
Definition: z3py.py:7140
def register_relation(self, relations)
Definition: z3py.py:6735
def IndexOf(s, substr)
Definition: z3py.py:9944
def is_app(a)
Definition: z3py.py:1069
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9637
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:7147
def StringSort(ctx=None)
Definition: z3py.py:9725
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:1592
def open_log(fname)
Definition: z3py.py:93
def __deepcopy__(self, memo={})
Definition: z3py.py:7271
def solver(self)
Definition: z3py.py:7278
def PrefixOf(a, b)
Definition: z3py.py:9883
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9422
def PbEq(args, k, ctx=None)
Definition: z3py.py:7992
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:6637
def range(self)
Definition: z3py.py:4118
def __repr__(self)
Definition: z3py.py:7183
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:9282
def Cbrt(a, ctx=None)
Definition: z3py.py:3025
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def disable_trace(msg)
Definition: z3py.py:65
def RotateRight(a, b)
Definition: z3py.py:3912
def sort(self)
Definition: z3py.py:3088
def is_ge(a)
Definition: z3py.py:2544
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
def is_K(a)
Definition: z3py.py:4169
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:833
def tactics(ctx=None)
Definition: z3py.py:7498
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:1094
def Star(re)
Definition: z3py.py:10094
def InRe(s, re)
Definition: z3py.py:10034
def is_finite_domain_sort(s)
Definition: z3py.py:6842
def push(self)
Definition: z3py.py:7045
def z3_error_handler(c, e)
Definition: z3py.py:148
def RotateLeft(a, b)
Definition: z3py.py:3897
def Const(name, sort)
Definition: z3py.py:1233
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:1510
def substitute(t, m)
Definition: z3py.py:7825
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:4242
def main_ctx()
Definition: z3py.py:203
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:1180
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3607
def get_id(self)
Definition: z3py.py:646
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:4144
def is_pattern(a)
Definition: z3py.py:1672
Statistics.
Definition: z3py.py:5918
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:7777
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:8919
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
def help_simplify()
Definition: z3py.py:7817
def fpMax(a, b, ctx=None)
Definition: z3py.py:9309
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:7073
def get_rule_names_along_trace(self)
Definition: z3py.py:6714
def Int(name, ctx=None)
Definition: z3py.py:2863
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6552
def __repr__(self)
Definition: z3py.py:7110
def __repr__(self)
Definition: z3py.py:6773
Arrays.
Definition: z3py.py:4076
def simplify_param_descrs()
Definition: z3py.py:7821
def is_map(a)
Definition: z3py.py:4181
def is_or(a)
Definition: z3py.py:1407
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9607
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9254
Patterns.
Definition: z3py.py:1661
def fpAbs(a, ctx=None)
Definition: z3py.py:9135
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9433
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3623
def is_int_value(a)
Definition: z3py.py:2394
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:571
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:4276
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:6835
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:4501
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def URem(a, b)
Definition: z3py.py:3826
def PbGe(args, k)
Definition: z3py.py:7983
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def binary_interpolant(a, b, p=None, ctx=None)
Definition: z3py.py:8304
def Union(args)
Definition: z3py.py:10047
def SuffixOf(a, b)
Definition: z3py.py:9897
def __eq__(self, other)
Definition: z3py.py:306
def __mul__(self, other)
Definition: z3py.py:1339
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9573
def is_mod(a)
Definition: z3py.py:2511
def fact(self, head, name=None)
Definition: z3py.py:6641
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
def UGE(a, b)
Definition: z3py.py:3772
def Replace(s, src, dst)
Definition: z3py.py:9930
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:2911
def __init__(self, args, kws)
Definition: z3py.py:164
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:6953
def cast(self, val)
Definition: z3py.py:522
def Length(s)
Definition: z3py.py:9964
def decl(self)
Definition: z3py.py:886
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7441
def Bools(names, ctx=None)
Definition: z3py.py:1495
def is_eq(a)
Definition: z3py.py:1429
def __del__(self)
Definition: z3py.py:183
def Float32(ctx=None)
Definition: z3py.py:8491
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9338
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:7119
def depth(self)
Definition: z3py.py:4868
def __str__(self)
Definition: z3py.py:6967
def sort(self)
Definition: z3py.py:821
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:2370
def RealVal(val, ctx=None)
Definition: z3py.py:2818
def PbLe(args, k)
Definition: z3py.py:7974
def get_id(self)
Definition: z3py.py:818
def Extract(high, low, a)
Definition: z3py.py:3711
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:1270
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:1918
def solve_using(s, args, keywords)
Definition: z3py.py:8030
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:6741
def maximize(self, arg)
Definition: z3py.py:7037
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:412
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def help(self)
Definition: z3py.py:7322
def __bool__(self)
Definition: z3py.py:315
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7018
def sexpr(self)
Definition: z3py.py:7114
def is_le(a)
Definition: z3py.py:2522
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:297
def is_not(a)
Definition: z3py.py:1418
def get_map_func(a)
Definition: z3py.py:4204
def Implies(a, b, ctx=None)
Definition: z3py.py:1537
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7257
def __deepcopy__(self, memo={})
Definition: z3py.py:6979
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:7295
def solve(args, keywords)
Definition: z3py.py:8002
def is_arith(a)
Definition: z3py.py:2332
def __del__(self)
Definition: z3py.py:7274
def is_sort(s)
Definition: z3py.py:575
def objectives(self)
Definition: z3py.py:7106
def Or(args)
Definition: z3py.py:1625
def __init__(self, opt, value, is_max)
Definition: z3py.py:6940
def num_sorts(self)
Definition: z3py.py:5751
def add(self, args)
Definition: z3py.py:6598
def hash(self)
Definition: z3py.py:382
def is_int(a)
Definition: z3py.py:2352
def check(self, assumptions)
Definition: z3py.py:6283
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:9007
def insert(self, args)
Definition: z3py.py:6610
def is_quantifier(a)
Definition: z3py.py:1875
def as_string(self)
Definition: z3py.py:6892
def is_string(a)
Definition: z3py.py:9799
def StringVal(s, ctx=None)
Definition: z3py.py:9816
def Plus(re)
Definition: z3py.py:10066
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:9973
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:7312
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:6903
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:883
def num_args(self)
Definition: z3py.py:901
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:8933
def __del__(self)
Definition: z3py.py:7143
def prove(claim, keywords)
Definition: z3py.py:8059
def DeclareSort(name, ctx=None)
Definition: z3py.py:612
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:2875
def parse_file(self, f)
Definition: z3py.py:6758
def Interpolant(a, ctx=None)
Definition: z3py.py:8225
def pop(self)
Definition: z3py.py:6687
def is_true(a)
Definition: z3py.py:1366
def Int2BV(a, num_bits)
Definition: z3py.py:3585
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:9911
def is_finite_domain_value(a)
Definition: z3py.py:6917
def is_real(self)
Definition: z3py.py:1967
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:1524
def Bool(name, ctx=None)
Definition: z3py.py:1484
def probe_description(name, ctx=None)
Definition: z3py.py:7699
def get_rules_along_trace(self)
Definition: z3py.py:6710
def __deepcopy__(self, memo={})
Definition: z3py.py:6563
def __del__(self)
Definition: z3py.py:6982
def tactic_description(name, ctx=None)
Definition: z3py.py:7508
def param_descrs(self)
Definition: z3py.py:7326
def RNE(ctx=None)
Definition: z3py.py:8737
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:4380
def get_version()
Definition: z3py.py:76
def from_string(self, s)
Definition: z3py.py:7095
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:3846
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9094
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:9616
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9268
def eq(self, other)
Definition: z3py.py:346
def get_id(self)
Definition: z3py.py:495
def ToReal(a)
Definition: z3py.py:2963
def is_bv_value(a)
Definition: z3py.py:3549
def range(self)
Definition: z3py.py:685
def is_idiv(a)
Definition: z3py.py:2500
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3646
def translate(self, target)
Definition: z3py.py:363
def from_file(self, filename)
Definition: z3py.py:7088
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 Z3_FALSE if the call failed. That is, Z3_get_sort_kind(s) == ...
def __init__(self, probe, ctx=None)
Definition: z3py.py:7536
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:6667
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:560
def __le__(self, other)
Definition: z3py.py:7592
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:1299
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:649
def size(self)
Definition: z3py.py:3099
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:6782
def assertions(self)
Definition: z3py.py:6408
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:9837
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:338
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9240
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9455
def __lt__(self, other)
Definition: z3py.py:7566
def ArraySort(d, r)
Definition: z3py.py:4221
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:4467
def Full(s)
Definition: z3py.py:9865
def is_const_array(a)
Definition: z3py.py:4157
def fpNaN(s)
Definition: z3py.py:8991
def cast(self, val)
Definition: z3py.py:1999
def as_long(self)
Definition: z3py.py:6880
def sexpr(self)
Definition: z3py.py:325
def reason_unknown(self)
Definition: z3py.py:7057
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:498
def IntSort(ctx=None)
Definition: z3py.py:2760
def Unit(a)
Definition: z3py.py:9879
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:6751
def is_rational_value(a)
Definition: z3py.py:2417
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def is_finite_domain(a)
Definition: z3py.py:6864
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:9157
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:9400
def get_ground_sat_answer(self)
Definition: z3py.py:6705
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4690
def sexpr(self)
Definition: z3py.py:6777
def __ne__(self, other)
Definition: z3py.py:7631
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:6800
def arg(self, idx)
Definition: z3py.py:917
def sort(self)
Definition: z3py.py:8550
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:9989
def Xor(a, b, ctx=None)
Definition: z3py.py:1552
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:4303
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:6614
def __rmul__(self, other)
Definition: z3py.py:1336
def params(self)
Definition: z3py.py:706
def query(self, query)
Definition: z3py.py:6645
def get_var_index(a)
Definition: z3py.py:1136
def Not(a, ctx=None)
Definition: z3py.py:1567
def MultiPattern(args)
Definition: z3py.py:1691
def BoolVal(val, ctx=None)
Definition: z3py.py:1466
def upper_values(self)
Definition: z3py.py:6957
def model(self)
Definition: z3py.py:7061
def is_div(a)
Definition: z3py.py:2484
FP Numerals.
Definition: z3py.py:8791
FP Sorts.
Definition: z3py.py:8446
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:342
def help(self)
Definition: z3py.py:6576
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:9996
def fpMin(a, b, ctx=None)
Definition: z3py.py:9295
def is_fp_sort(s)
Definition: z3py.py:8525
Expressions.
Definition: z3py.py:805
def is_app_of(a, k)
Definition: z3py.py:1168
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:7673
def is_mul(a)
Definition: z3py.py:2462
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:2898
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:514
def kind(self)
Definition: z3py.py:694
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:3075
def Update(a, i, v)
Definition: z3py.py:4255
def With(t, args, keys)
Definition: z3py.py:7445
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:97
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:6790
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:2451
def ParOr(ts, ks)
Definition: z3py.py:7409
def K(dom, v)
Definition: z3py.py:4340
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3593
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:861
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:2887
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9224
def get_assertions(self)
Definition: z3py.py:6769
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:6722
def UGT(a, b)
Definition: z3py.py:3789
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:6700
def children(self)
Definition: z3py.py:938
def BV2Int(a, is_signed=False)
Definition: z3py.py:3563
def arity(self)
Definition: z3py.py:5558
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:7458
def Store(a, i, v)
Definition: z3py.py:4287
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7490
def numerator(self)
Definition: z3py.py:2632
def __str__(self)
Definition: z3py.py:300
def is_int(self)
Definition: z3py.py:1324
def is_ast(a)
Definition: z3py.py:392
def sequence_interpolant(v, p=None, ctx=None)
Definition: z3py.py:8332
Z3_string Z3_API Z3_get_parser_error(Z3_context c)
Retrieve that last error message information generated from parsing.
def domain(self)
Definition: z3py.py:4109
def Empty(s)
Definition: z3py.py:9844
def __init__(self, ast, ctx=None)
Definition: z3py.py:288
def UDiv(a, b)
Definition: z3py.py:3806
def convert_model(self, model, idx=0)
Definition: z3py.py:7190
def is_expr(a)
Definition: z3py.py:1047
def __init__(self, result, ctx)
Definition: z3py.py:7135
def abstract(self, fml, is_forall=True)
Definition: z3py.py:6809
def set(self, args, keys)
Definition: z3py.py:6570
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:9658
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:4318
def __call__(self, args)
Definition: z3py.py:730
def else_value(self)
Definition: z3py.py:5519
def subsort(self, other)
Definition: z3py.py:1321
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:7707
def add_cover(self, level, predicate, property)
Definition: z3py.py:6731
def describe_tactics()
Definition: z3py.py:7516
def is_bool(a)
Definition: z3py.py:1349
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:1202
def __call__(self, goal)
Definition: z3py.py:7645
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 body(self)
Definition: z3py.py:1809
def as_list(self)
Definition: z3py.py:5607
def check(self)
Definition: z3py.py:7053
def arity(self)
Definition: z3py.py:663
def Reals(names, ctx=None)
Definition: z3py.py:2923
def is_bv(a)
Definition: z3py.py:3536
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def is_var(a)
Definition: z3py.py:1112
def as_expr(self)
Definition: z3py.py:7221
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:379
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9537
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9444
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:7471
def RepeatBitVec(n, a)
Definition: z3py.py:3983
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:6511
def get_full_version()
Definition: z3py.py:84
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7427
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:6945
def as_ast(self)
Definition: z3py.py:643
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:1383
def set(self, args, keys)
Definition: z3py.py:6986
def ULE(a, b)
Definition: z3py.py:3738
def is_is_int(a)
Definition: z3py.py:2566
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:62
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:537
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9556
def is_fprm(a)
Definition: z3py.py:8773
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:6602
def Option(re)
Definition: z3py.py:10078
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 as_signed_long(self)
Definition: z3py.py:3511
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:6566
def is_func_decl(a)
Definition: z3py.py:762
def interrupt(self)
Definition: z3py.py:192
def is_sub(a)
Definition: z3py.py:2473
def Concat(args)
Definition: z3py.py:3666
def FailIf(p, ctx=None)
Definition: z3py.py:7740
def __hash__(self)
Definition: z3py.py:309
def append(self, args)
Definition: z3py.py:6606
def When(p, t, ctx=None)
Definition: z3py.py:7759
def is_seq(a)
Definition: z3py.py:9790
def is_algebraic_value(a)
Definition: z3py.py:2438
def BoolSort(ctx=None)
Definition: z3py.py:1449
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:262
def is_to_int(a)
Definition: z3py.py:2591
def __eq__(self, other)
Definition: z3py.py:7618
def Q(a, b, ctx=None)
Definition: z3py.py:2851
def __deepcopy__(self, memo={})
Definition: z3py.py:7559
def String(name, ctx=None)
Definition: z3py.py:9821
def reason_unknown(self)
Definition: z3py.py:6795
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:2980
def num_entries(self)
Definition: z3py.py:5542
def tree_interpolant(pat, p=None, ctx=None)
Definition: z3py.py:8239
def __del__(self)
Definition: z3py.py:293
def is_fp(a)
Definition: z3py.py:8906
def __eq__(self, other)
Definition: z3py.py:547
def Sqrt(a, ctx=None)
Definition: z3py.py:3013
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:9389
def SimpleSolver(ctx=None)
Definition: z3py.py:6531