Z3
z3py.py
Go to the documentation of this file.
1 ############################################
2 # Copyright (c) 2012 Microsoft Corporation
3 #
4 # Z3 Python interface
5 #
6 # Author: Leonardo de Moura (leonardo)
7 ############################################
8 
9 """Z3 is a high performance theorem prover developed at Microsoft Research. 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.
10 
11 Several online tutorials for Z3Py are available at:
12 http://rise4fun.com/Z3Py/tutorial/guide
13 
14 Please send feedback, comments and/or corrections to leonardo@microsoft.com. Your comments are very valuable.
15 
16 Small example:
17 
18 >>> x = Int('x')
19 >>> y = Int('y')
20 >>> s = Solver()
21 >>> s.add(x > 0)
22 >>> s.add(x < 2)
23 >>> s.add(y == x + 1)
24 >>> s.check()
25 sat
26 >>> m = s.model()
27 >>> m[x]
28 1
29 >>> m[y]
30 2
31 
32 Z3 exceptions:
33 
34 >>> try:
35 ... x = Int('x')
36 ... y = Bool('y')
37 ... # the expression x + y is type incorrect
38 ... n = x + y
39 ... except Z3Exception as ex:
40 ... print("failed: %s" % ex)
41 failed: sort mismatch
42 """
43 from z3core import *
44 from z3types import *
45 from z3consts import *
46 from z3printer import *
47 from fractions import Fraction
48 import sys
49 import io
50 
51 if sys.version < '3':
52  def _is_int(v):
53  return isinstance(v, int) or isinstance(v, long)
54 else:
55  def _is_int(v):
56  return isinstance(v, int)
57 
58 def enable_trace(msg):
59  Z3_enable_trace(msg)
60 
61 def disable_trace(msg):
62  Z3_disable_trace(msg)
63 
65  major = ctypes.c_uint(0)
66  minor = ctypes.c_uint(0)
67  build = ctypes.c_uint(0)
68  rev = ctypes.c_uint(0)
69  Z3_get_version(major, minor, build, rev)
70  return "%s.%s.%s" % (major.value, minor.value, build.value)
71 
73  major = ctypes.c_uint(0)
74  minor = ctypes.c_uint(0)
75  build = ctypes.c_uint(0)
76  rev = ctypes.c_uint(0)
77  Z3_get_version(major, minor, build, rev)
78  return (major.value, minor.value, build.value, rev.value)
79 
80 # We use _z3_assert instead of the assert command because we want to
81 # produce nice error messages in Z3Py at rise4fun.com
82 def _z3_assert(cond, msg):
83  if not cond:
84  raise Z3Exception(msg)
85 
86 def open_log(fname):
87  """Log interaction to a file. This function must be invoked immediately after init(). """
88  Z3_open_log(fname)
89 
90 def append_log(s):
91  """Append user-defined string to interaction log. """
92  Z3_append_log(s)
93 
94 def to_symbol(s, ctx=None):
95  """Convert an integer or string into a Z3 symbol."""
96  if isinstance(s, int):
97  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
98  else:
99  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
100 
101 def _symbol2py(ctx, s):
102  """Convert a Z3 symbol back into a Python object. """
103  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
104  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
105  else:
106  return Z3_get_symbol_string(ctx.ref(), s)
107 
108 _error_handler_fptr = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint)
109 
110 # Hack for having nary functions that can receive one argument that is the
111 # list of arguments.
112 def _get_args(args):
113  try:
114  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
115  return args[0]
116  else:
117  return args
118  except: # len is not necessarily defined when args is not a sequence (use reflection?)
119  return args
120 
121 def _Z3python_error_handler_core(c, e):
122  # Do nothing error handler, just avoid exit(0)
123  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
124  return
125 
126 _Z3Python_error_handler = _error_handler_fptr(_Z3python_error_handler_core)
127 
128 def _to_param_value(val):
129  if isinstance(val, bool):
130  if val == True:
131  return "true"
132  else:
133  return "false"
134  else:
135  return str(val)
136 
137 class Context:
138  """A Context manages all other Z3 objects, global configuration options, etc.
139 
140  Z3Py uses a default global context. For most applications this is sufficient.
141  An application may use multiple Z3 contexts. Objects created in one context
142  cannot be used in another one. However, several objects may be "translated" from
143  one context to another. It is not safe to access Z3 objects from multiple threads.
144  The only exception is the method `interrupt()` that can be used to interrupt() a long
145  computation.
146  The initialization method receives global configuration options for the new context.
147  """
148  def __init__(self, *args, **kws):
149  if __debug__:
150  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
151  conf = Z3_mk_config()
152  for key in kws:
153  value = kws[key]
154  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
155  prev = None
156  for a in args:
157  if prev == None:
158  prev = a
159  else:
160  Z3_set_param_value(conf, str(prev), _to_param_value(a))
161  prev = None
162  self.lib = lib()
163  self.ctx = Z3_mk_context_rc(conf)
164  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
165  lib().Z3_set_error_handler.restype = None
166  lib().Z3_set_error_handler.argtypes = [ContextObj, _error_handler_fptr]
167  lib().Z3_set_error_handler(self.ctx, _Z3Python_error_handler)
168  Z3_del_config(conf)
169 
170  def __del__(self):
171  self.lib.Z3_del_context(self.ctx)
172 
173  def ref(self):
174  """Return a reference to the actual C pointer to the Z3 context."""
175  return self.ctx
176 
177  def interrupt(self):
178  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
179 
180  This method can be invoked from a thread different from the one executing the
181  interruptable procedure.
182  """
183  Z3_interrupt(self.ref())
184 
185 
186 # Global Z3 context
187 _main_ctx = None
188 def main_ctx():
189  """Return a reference to the global Z3 context.
190 
191  >>> x = Real('x')
192  >>> x.ctx == main_ctx()
193  True
194  >>> c = Context()
195  >>> c == main_ctx()
196  False
197  >>> x2 = Real('x', c)
198  >>> x2.ctx == c
199  True
200  >>> eq(x, x2)
201  False
202  """
203  global _main_ctx
204  if _main_ctx == None:
205  _main_ctx = Context()
206  return _main_ctx
207 
208 def _get_ctx(ctx):
209  if ctx == None:
210  return main_ctx()
211  else:
212  return ctx
213 
214 def set_param(*args, **kws):
215  """Set Z3 global (or module) parameters.
216 
217  >>> set_param(precision=10)
218  """
219  if __debug__:
220  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
221  new_kws = {}
222  for k in kws:
223  v = kws[k]
224  if not set_pp_option(k, v):
225  new_kws[k] = v
226  for key in new_kws:
227  value = new_kws[key]
228  Z3_global_param_set(str(key).upper(), _to_param_value(value))
229  prev = None
230  for a in args:
231  if prev == None:
232  prev = a
233  else:
234  Z3_global_param_set(str(prev), _to_param_value(a))
235  prev = None
236 
238  """Reset all global (or module) parameters.
239  """
241 
242 def set_option(*args, **kws):
243  """Alias for 'set_param' for backward compatibility.
244  """
245  return set_param(*args, **kws)
246 
247 def get_param(name):
248  """Return the value of a Z3 global (or module) parameter
249 
250  >>> get_param('nlsat.reorder')
251  'true'
252  """
253  ptr = (ctypes.c_char_p * 1)()
254  if Z3_global_param_get(str(name), ptr):
255  r = z3core._to_pystr(ptr[0])
256  return r
257  raise Z3Exception("failed to retrieve value for '%s'" % name)
258 
259 #########################################
260 #
261 # ASTs base class
262 #
263 #########################################
264 
265 # Mark objects that use pretty printer
267  """Superclass for all Z3 objects that have support for pretty printing."""
268  def use_pp(self):
269  return True
270 
272  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
273  def __init__(self, ast, ctx=None):
274  self.ast = ast
275  self.ctx = _get_ctx(ctx)
276  Z3_inc_ref(self.ctx.ref(), self.as_ast())
277 
278  def __del__(self):
279  Z3_dec_ref(self.ctx.ref(), self.as_ast())
280 
281  def __str__(self):
282  return obj_to_string(self)
283 
284  def __repr__(self):
285  return obj_to_string(self)
286 
287  def sexpr(self):
288  """Return an string representing the AST node in s-expression notation.
289 
290  >>> x = Int('x')
291  >>> ((x + 1)*x).sexpr()
292  '(* (+ x 1) x)'
293  """
294  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
295 
296  def as_ast(self):
297  """Return a pointer to the corresponding C Z3_ast object."""
298  return self.ast
299 
300  def get_id(self):
301  """Return unique identifier for object. It can be used for hash-tables and maps."""
302  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
303 
304 
305  def ctx_ref(self):
306  """Return a reference to the C context where this AST node is stored."""
307  return self.ctx.ref()
308 
309  def eq(self, other):
310  """Return `True` if `self` and `other` are structurally identical.
311 
312  >>> x = Int('x')
313  >>> n1 = x + 1
314  >>> n2 = 1 + x
315  >>> n1.eq(n2)
316  False
317  >>> n1 = simplify(n1)
318  >>> n2 = simplify(n2)
319  >>> n1.eq(n2)
320  True
321  """
322  if __debug__:
323  _z3_assert(is_ast(other), "Z3 AST expected")
324  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
325 
326  def translate(self, target):
327  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
328 
329  >>> c1 = Context()
330  >>> c2 = Context()
331  >>> x = Int('x', c1)
332  >>> y = Int('y', c2)
333  >>> # Nodes in different contexts can't be mixed.
334  >>> # However, we can translate nodes from one context to another.
335  >>> x.translate(c2) + y
336  x + y
337  """
338  if __debug__:
339  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
340  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
341 
342  def hash(self):
343  """Return a hashcode for the `self`.
344 
345  >>> n1 = simplify(Int('x') + 1)
346  >>> n2 = simplify(2 + Int('x') - 1)
347  >>> n1.hash() == n2.hash()
348  True
349  """
350  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
351 
352 def is_ast(a):
353  """Return `True` if `a` is an AST node.
354 
355  >>> is_ast(10)
356  False
357  >>> is_ast(IntVal(10))
358  True
359  >>> is_ast(Int('x'))
360  True
361  >>> is_ast(BoolSort())
362  True
363  >>> is_ast(Function('f', IntSort(), IntSort()))
364  True
365  >>> is_ast("x")
366  False
367  >>> is_ast(Solver())
368  False
369  """
370  return isinstance(a, AstRef)
371 
372 def eq(a, b):
373  """Return `True` if `a` and `b` are structurally identical AST nodes.
374 
375  >>> x = Int('x')
376  >>> y = Int('y')
377  >>> eq(x, y)
378  False
379  >>> eq(x + 1, x + 1)
380  True
381  >>> eq(x + 1, 1 + x)
382  False
383  >>> eq(simplify(x + 1), simplify(1 + x))
384  True
385  """
386  if __debug__:
387  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
388  return a.eq(b)
389 
390 def _ast_kind(ctx, a):
391  if is_ast(a):
392  a = a.as_ast()
393  return Z3_get_ast_kind(ctx.ref(), a)
394 
395 def _ctx_from_ast_arg_list(args, default_ctx=None):
396  ctx = None
397  for a in args:
398  if is_ast(a) or is_probe(a):
399  if ctx == None:
400  ctx = a.ctx
401  else:
402  if __debug__:
403  _z3_assert(ctx == a.ctx, "Context mismatch")
404  if ctx == None:
405  ctx = default_ctx
406  return ctx
407 
408 def _ctx_from_ast_args(*args):
409  return _ctx_from_ast_arg_list(args)
410 
411 def _to_func_decl_array(args):
412  sz = len(args)
413  _args = (FuncDecl * sz)()
414  for i in range(sz):
415  _args[i] = args[i].as_func_decl()
416  return _args, sz
417 
418 def _to_ast_array(args):
419  sz = len(args)
420  _args = (Ast * sz)()
421  for i in range(sz):
422  _args[i] = args[i].as_ast()
423  return _args, sz
424 
425 def _to_ref_array(ref, args):
426  sz = len(args)
427  _args = (ref * sz)()
428  for i in range(sz):
429  _args[i] = args[i].as_ast()
430  return _args, sz
431 
432 def _to_ast_ref(a, ctx):
433  k = _ast_kind(ctx, a)
434  if k == Z3_SORT_AST:
435  return _to_sort_ref(a, ctx)
436  elif k == Z3_FUNC_DECL_AST:
437  return _to_func_decl_ref(a, ctx)
438  else:
439  return _to_expr_ref(a, ctx)
440 
441 #########################################
442 #
443 # Sorts
444 #
445 #########################################
446 
447 def _sort_kind(ctx, s):
448  return Z3_get_sort_kind(ctx.ref(), s)
449 
451  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
452  def as_ast(self):
453  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
454 
455  def get_id(self):
456  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
457 
458 
459  def kind(self):
460  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
461 
462  >>> b = BoolSort()
463  >>> b.kind() == Z3_BOOL_SORT
464  True
465  >>> b.kind() == Z3_INT_SORT
466  False
467  >>> A = ArraySort(IntSort(), IntSort())
468  >>> A.kind() == Z3_ARRAY_SORT
469  True
470  >>> A.kind() == Z3_INT_SORT
471  False
472  """
473  return _sort_kind(self.ctx, self.ast)
474 
475  def subsort(self, other):
476  """Return `True` if `self` is a subsort of `other`.
477 
478  >>> IntSort().subsort(RealSort())
479  True
480  """
481  return False
482 
483  def cast(self, val):
484  """Try to cast `val` as an element of sort `self`.
485 
486  This method is used in Z3Py to convert Python objects such as integers,
487  floats, longs and strings into Z3 expressions.
488 
489  >>> x = Int('x')
490  >>> RealSort().cast(x)
491  ToReal(x)
492  """
493  if __debug__:
494  _z3_assert(is_expr(val), "Z3 expression expected")
495  _z3_assert(self.eq(val.sort()), "Sort mismatch")
496  return val
497 
498  def name(self):
499  """Return the name (string) of sort `self`.
500 
501  >>> BoolSort().name()
502  'Bool'
503  >>> ArraySort(IntSort(), IntSort()).name()
504  'Array'
505  """
506  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
507 
508  def __eq__(self, other):
509  """Return `True` if `self` and `other` are the same Z3 sort.
510 
511  >>> p = Bool('p')
512  >>> p.sort() == BoolSort()
513  True
514  >>> p.sort() == IntSort()
515  False
516  """
517  if other == None:
518  return False
519  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
520 
521  def __ne__(self, other):
522  """Return `True` if `self` and `other` are not the same Z3 sort.
523 
524  >>> p = Bool('p')
525  >>> p.sort() != BoolSort()
526  False
527  >>> p.sort() != IntSort()
528  True
529  """
530  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
531 
532 def is_sort(s):
533  """Return `True` if `s` is a Z3 sort.
534 
535  >>> is_sort(IntSort())
536  True
537  >>> is_sort(Int('x'))
538  False
539  >>> is_expr(Int('x'))
540  True
541  """
542  return isinstance(s, SortRef)
543 
544 def _to_sort_ref(s, ctx):
545  if __debug__:
546  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
547  k = _sort_kind(ctx, s)
548  if k == Z3_BOOL_SORT:
549  return BoolSortRef(s, ctx)
550  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
551  return ArithSortRef(s, ctx)
552  elif k == Z3_BV_SORT:
553  return BitVecSortRef(s, ctx)
554  elif k == Z3_ARRAY_SORT:
555  return ArraySortRef(s, ctx)
556  elif k == Z3_DATATYPE_SORT:
557  return DatatypeSortRef(s, ctx)
558  elif k == Z3_FLOATING_POINT_SORT:
559  return FPSortRef(s, ctx)
560  elif k == Z3_ROUNDING_MODE_SORT:
561  return FPRMSortRef(s, ctx)
562  return SortRef(s, ctx)
563 
564 def _sort(ctx, a):
565  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
566 
567 def DeclareSort(name, ctx=None):
568  """Create a new uninterpred sort named `name`.
569 
570  If `ctx=None`, then the new sort is declared in the global Z3Py context.
571 
572  >>> A = DeclareSort('A')
573  >>> a = Const('a', A)
574  >>> b = Const('b', A)
575  >>> a.sort() == A
576  True
577  >>> b.sort() == A
578  True
579  >>> a == b
580  a == b
581  """
582  ctx = _get_ctx(ctx)
583  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
584 
585 #########################################
586 #
587 # Function Declarations
588 #
589 #########################################
590 
592  """Function declaration. Every constant and function have an associated declaration.
593 
594  The declaration assigns a name, a sort (i.e., type), and for function
595  the sort (i.e., type) of each of its arguments. Note that, in Z3,
596  a constant is a function with 0 arguments.
597  """
598  def as_ast(self):
599  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
600 
601  def get_id(self):
602  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
603 
604  def as_func_decl(self):
605  return self.ast
606 
607  def name(self):
608  """Return the name of the function declaration `self`.
609 
610  >>> f = Function('f', IntSort(), IntSort())
611  >>> f.name()
612  'f'
613  >>> isinstance(f.name(), str)
614  True
615  """
616  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
617 
618  def arity(self):
619  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
620 
621  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
622  >>> f.arity()
623  2
624  """
625  return int(Z3_get_arity(self.ctx_ref(), self.ast))
626 
627  def domain(self, i):
628  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
629 
630  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
631  >>> f.domain(0)
632  Int
633  >>> f.domain(1)
634  Real
635  """
636  if __debug__:
637  _z3_assert(i < self.arity(), "Index out of bounds")
638  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
639 
640  def range(self):
641  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
642 
643  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
644  >>> f.range()
645  Bool
646  """
647  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
648 
649  def kind(self):
650  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
651 
652  >>> x = Int('x')
653  >>> d = (x + 1).decl()
654  >>> d.kind() == Z3_OP_ADD
655  True
656  >>> d.kind() == Z3_OP_MUL
657  False
658  """
659  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
660 
661  def __call__(self, *args):
662  """Create a Z3 application expression using the function `self`, and the given arguments.
663 
664  The arguments must be Z3 expressions. This method assumes that
665  the sorts of the elements in `args` match the sorts of the
666  domain. Limited coersion is supported. For example, if
667  args[0] is a Python integer, and the function expects a Z3
668  integer, then the argument is automatically converted into a
669  Z3 integer.
670 
671  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
672  >>> x = Int('x')
673  >>> y = Real('y')
674  >>> f(x, y)
675  f(x, y)
676  >>> f(x, x)
677  f(x, ToReal(x))
678  """
679  args = _get_args(args)
680  num = len(args)
681  if __debug__:
682  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
683  _args = (Ast * num)()
684  saved = []
685  for i in range(num):
686  # self.domain(i).cast(args[i]) may create a new Z3 expression,
687  # then we must save in 'saved' to prevent it from being garbage collected.
688  tmp = self.domain(i).cast(args[i])
689  saved.append(tmp)
690  _args[i] = tmp.as_ast()
691  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
692 
694  """Return `True` if `a` is a Z3 function declaration.
695 
696  >>> f = Function('f', IntSort(), IntSort())
697  >>> is_func_decl(f)
698  True
699  >>> x = Real('x')
700  >>> is_func_decl(x)
701  False
702  """
703  return isinstance(a, FuncDeclRef)
704 
705 def Function(name, *sig):
706  """Create a new Z3 uninterpreted function with the given sorts.
707 
708  >>> f = Function('f', IntSort(), IntSort())
709  >>> f(f(0))
710  f(f(0))
711  """
712  sig = _get_args(sig)
713  if __debug__:
714  _z3_assert(len(sig) > 0, "At least two arguments expected")
715  arity = len(sig) - 1
716  rng = sig[arity]
717  if __debug__:
718  _z3_assert(is_sort(rng), "Z3 sort expected")
719  dom = (Sort * arity)()
720  for i in range(arity):
721  if __debug__:
722  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
723  dom[i] = sig[i].ast
724  ctx = rng.ctx
725  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
726 
727 def _to_func_decl_ref(a, ctx):
728  return FuncDeclRef(a, ctx)
729 
730 #########################################
731 #
732 # Expressions
733 #
734 #########################################
735 
737  """Constraints, formulas and terms are expressions in Z3.
738 
739  Expressions are ASTs. Every expression has a sort.
740  There are three main kinds of expressions:
741  function applications, quantifiers and bounded variables.
742  A constant is a function application with 0 arguments.
743  For quantifier free problems, all expressions are
744  function applications.
745  """
746  def as_ast(self):
747  return self.ast
748 
749  def get_id(self):
750  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
751 
752  def sort(self):
753  """Return the sort of expression `self`.
754 
755  >>> x = Int('x')
756  >>> (x + 1).sort()
757  Int
758  >>> y = Real('y')
759  >>> (x + y).sort()
760  Real
761  """
762  return _sort(self.ctx, self.as_ast())
763 
764  def sort_kind(self):
765  """Shorthand for `self.sort().kind()`.
766 
767  >>> a = Array('a', IntSort(), IntSort())
768  >>> a.sort_kind() == Z3_ARRAY_SORT
769  True
770  >>> a.sort_kind() == Z3_INT_SORT
771  False
772  """
773  return self.sort().kind()
774 
775  def __eq__(self, other):
776  """Return a Z3 expression that represents the constraint `self == other`.
777 
778  If `other` is `None`, then this method simply returns `False`.
779 
780  >>> a = Int('a')
781  >>> b = Int('b')
782  >>> a == b
783  a == b
784  >>> a == None
785  False
786  """
787  if other == None:
788  return False
789  a, b = _coerce_exprs(self, other)
790  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
791 
792  def __ne__(self, other):
793  """Return a Z3 expression that represents the constraint `self != other`.
794 
795  If `other` is `None`, then this method simply returns `True`.
796 
797  >>> a = Int('a')
798  >>> b = Int('b')
799  >>> a != b
800  a != b
801  >>> a != None
802  True
803  """
804  if other == None:
805  return True
806  a, b = _coerce_exprs(self, other)
807  _args, sz = _to_ast_array((a, b))
808  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
809 
810  def decl(self):
811  """Return the Z3 function declaration associated with a Z3 application.
812 
813  >>> f = Function('f', IntSort(), IntSort())
814  >>> a = Int('a')
815  >>> t = f(a)
816  >>> eq(t.decl(), f)
817  True
818  >>> (a + 1).decl()
819  +
820  """
821  if __debug__:
822  _z3_assert(is_app(self), "Z3 application expected")
823  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
824 
825  def num_args(self):
826  """Return the number of arguments of a Z3 application.
827 
828  >>> a = Int('a')
829  >>> b = Int('b')
830  >>> (a + b).num_args()
831  2
832  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
833  >>> t = f(a, b, 0)
834  >>> t.num_args()
835  3
836  """
837  if __debug__:
838  _z3_assert(is_app(self), "Z3 application expected")
839  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
840 
841  def arg(self, idx):
842  """Return argument `idx` of the application `self`.
843 
844  This method assumes that `self` is a function application with at least `idx+1` arguments.
845 
846  >>> a = Int('a')
847  >>> b = Int('b')
848  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
849  >>> t = f(a, b, 0)
850  >>> t.arg(0)
851  a
852  >>> t.arg(1)
853  b
854  >>> t.arg(2)
855  0
856  """
857  if __debug__:
858  _z3_assert(is_app(self), "Z3 application expected")
859  _z3_assert(idx < self.num_args(), "Invalid argument index")
860  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
861 
862  def children(self):
863  """Return a list containing the children of the given expression
864 
865  >>> a = Int('a')
866  >>> b = Int('b')
867  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
868  >>> t = f(a, b, 0)
869  >>> t.children()
870  [a, b, 0]
871  """
872  if is_app(self):
873  return [self.arg(i) for i in range(self.num_args())]
874  else:
875  return []
876 
877 def _to_expr_ref(a, ctx):
878  if isinstance(a, Pattern):
879  return PatternRef(a, ctx)
880  ctx_ref = ctx.ref()
881  k = Z3_get_ast_kind(ctx_ref, a)
882  if k == Z3_QUANTIFIER_AST:
883  return QuantifierRef(a, ctx)
884  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
885  if sk == Z3_BOOL_SORT:
886  return BoolRef(a, ctx)
887  if sk == Z3_INT_SORT:
888  if k == Z3_NUMERAL_AST:
889  return IntNumRef(a, ctx)
890  return ArithRef(a, ctx)
891  if sk == Z3_REAL_SORT:
892  if k == Z3_NUMERAL_AST:
893  return RatNumRef(a, ctx)
894  if _is_algebraic(ctx, a):
895  return AlgebraicNumRef(a, ctx)
896  return ArithRef(a, ctx)
897  if sk == Z3_BV_SORT:
898  if k == Z3_NUMERAL_AST:
899  return BitVecNumRef(a, ctx)
900  else:
901  return BitVecRef(a, ctx)
902  if sk == Z3_ARRAY_SORT:
903  return ArrayRef(a, ctx)
904  if sk == Z3_DATATYPE_SORT:
905  return DatatypeRef(a, ctx)
906  if sk == Z3_FLOATING_POINT_SORT:
907  if k == Z3_APP_AST and _is_numeral(ctx, a):
908  return FPNumRef(a, ctx)
909  else:
910  return FPRef(a, ctx)
911  if sk == Z3_ROUNDING_MODE_SORT:
912  return FPRMRef(a, ctx)
913  return ExprRef(a, ctx)
914 
915 def _coerce_expr_merge(s, a):
916  if is_expr(a):
917  s1 = a.sort()
918  if s == None:
919  return s1
920  if s1.eq(s):
921  return s
922  elif s.subsort(s1):
923  return s1
924  elif s1.subsort(s):
925  return s
926  else:
927  if __debug__:
928  _z3_assert(s1.ctx == s.ctx, "context mismatch")
929  _z3_assert(False, "sort mismatch")
930  else:
931  return s
932 
933 def _coerce_exprs(a, b, ctx=None):
934  if not is_expr(a) and not is_expr(b):
935  a = _py2expr(a, ctx)
936  b = _py2expr(b, ctx)
937  s = None
938  s = _coerce_expr_merge(s, a)
939  s = _coerce_expr_merge(s, b)
940  a = s.cast(a)
941  b = s.cast(b)
942  return (a, b)
943 
944 def _reduce(f, l, a):
945  r = a
946  for e in l:
947  r = f(r, e)
948  return r
949 
950 def _coerce_expr_list(alist, ctx=None):
951  has_expr = False
952  for a in alist:
953  if is_expr(a):
954  has_expr = True
955  break
956  if not has_expr:
957  alist = [ _py2expr(a, ctx) for a in alist ]
958  s = _reduce(_coerce_expr_merge, alist, None)
959  return [ s.cast(a) for a in alist ]
960 
961 def is_expr(a):
962  """Return `True` if `a` is a Z3 expression.
963 
964  >>> a = Int('a')
965  >>> is_expr(a)
966  True
967  >>> is_expr(a + 1)
968  True
969  >>> is_expr(IntSort())
970  False
971  >>> is_expr(1)
972  False
973  >>> is_expr(IntVal(1))
974  True
975  >>> x = Int('x')
976  >>> is_expr(ForAll(x, x >= 0))
977  True
978  """
979  return isinstance(a, ExprRef)
980 
981 def is_app(a):
982  """Return `True` if `a` is a Z3 function application.
983 
984  Note that, constants are function applications with 0 arguments.
985 
986  >>> a = Int('a')
987  >>> is_app(a)
988  True
989  >>> is_app(a + 1)
990  True
991  >>> is_app(IntSort())
992  False
993  >>> is_app(1)
994  False
995  >>> is_app(IntVal(1))
996  True
997  >>> x = Int('x')
998  >>> is_app(ForAll(x, x >= 0))
999  False
1000  """
1001  if not isinstance(a, ExprRef):
1002  return False
1003  k = _ast_kind(a.ctx, a)
1004  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1005 
1006 def is_const(a):
1007  """Return `True` if `a` is Z3 constant/variable expression.
1008 
1009  >>> a = Int('a')
1010  >>> is_const(a)
1011  True
1012  >>> is_const(a + 1)
1013  False
1014  >>> is_const(1)
1015  False
1016  >>> is_const(IntVal(1))
1017  True
1018  >>> x = Int('x')
1019  >>> is_const(ForAll(x, x >= 0))
1020  False
1021  """
1022  return is_app(a) and a.num_args() == 0
1023 
1024 def is_var(a):
1025  """Return `True` if `a` is variable.
1026 
1027  Z3 uses de-Bruijn indices for representing bound variables in
1028  quantifiers.
1029 
1030  >>> x = Int('x')
1031  >>> is_var(x)
1032  False
1033  >>> is_const(x)
1034  True
1035  >>> f = Function('f', IntSort(), IntSort())
1036  >>> # Z3 replaces x with bound variables when ForAll is executed.
1037  >>> q = ForAll(x, f(x) == x)
1038  >>> b = q.body()
1039  >>> b
1040  f(Var(0)) == Var(0)
1041  >>> b.arg(1)
1042  Var(0)
1043  >>> is_var(b.arg(1))
1044  True
1045  """
1046  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1047 
1049  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1050 
1051  >>> x = Int('x')
1052  >>> y = Int('y')
1053  >>> is_var(x)
1054  False
1055  >>> is_const(x)
1056  True
1057  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1058  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1059  >>> q = ForAll([x, y], f(x, y) == x + y)
1060  >>> q.body()
1061  f(Var(1), Var(0)) == Var(1) + Var(0)
1062  >>> b = q.body()
1063  >>> b.arg(0)
1064  f(Var(1), Var(0))
1065  >>> v1 = b.arg(0).arg(0)
1066  >>> v2 = b.arg(0).arg(1)
1067  >>> v1
1068  Var(1)
1069  >>> v2
1070  Var(0)
1071  >>> get_var_index(v1)
1072  1
1073  >>> get_var_index(v2)
1074  0
1075  """
1076  if __debug__:
1077  _z3_assert(is_var(a), "Z3 bound variable expected")
1078  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1079 
1080 def is_app_of(a, k):
1081  """Return `True` if `a` is an application of the given kind `k`.
1082 
1083  >>> x = Int('x')
1084  >>> n = x + 1
1085  >>> is_app_of(n, Z3_OP_ADD)
1086  True
1087  >>> is_app_of(n, Z3_OP_MUL)
1088  False
1089  """
1090  return is_app(a) and a.decl().kind() == k
1091 
1092 def If(a, b, c, ctx=None):
1093  """Create a Z3 if-then-else expression.
1094 
1095  >>> x = Int('x')
1096  >>> y = Int('y')
1097  >>> max = If(x > y, x, y)
1098  >>> max
1099  If(x > y, x, y)
1100  >>> simplify(max)
1101  If(x <= y, y, x)
1102  """
1103  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1104  return Cond(a, b, c, ctx)
1105  else:
1106  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1107  s = BoolSort(ctx)
1108  a = s.cast(a)
1109  b, c = _coerce_exprs(b, c, ctx)
1110  if __debug__:
1111  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1112  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1113 
1114 def Distinct(*args):
1115  """Create a Z3 distinct expression.
1116 
1117  >>> x = Int('x')
1118  >>> y = Int('y')
1119  >>> Distinct(x, y)
1120  x != y
1121  >>> z = Int('z')
1122  >>> Distinct(x, y, z)
1123  Distinct(x, y, z)
1124  >>> simplify(Distinct(x, y, z))
1125  Distinct(x, y, z)
1126  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1127  And(Not(x == y), Not(x == z), Not(y == z))
1128  """
1129  args = _get_args(args)
1130  ctx = _ctx_from_ast_arg_list(args)
1131  if __debug__:
1132  _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression")
1133  args = _coerce_expr_list(args, ctx)
1134  _args, sz = _to_ast_array(args)
1135  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1136 
1137 def _mk_bin(f, a, b):
1138  args = (Ast * 2)()
1139  if __debug__:
1140  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1141  args[0] = a.as_ast()
1142  args[1] = b.as_ast()
1143  return f(a.ctx.ref(), 2, args)
1144 
1145 def Const(name, sort):
1146  """Create a constant of the given sort.
1147 
1148  >>> Const('x', IntSort())
1149  x
1150  """
1151  if __debug__:
1152  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1153  ctx = sort.ctx
1154  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1155 
1156 def Consts(names, sort):
1157  """Create a several constants of the given sort.
1158 
1159  `names` is a string containing the names of all constants to be created.
1160  Blank spaces separate the names of different constants.
1161 
1162  >>> x, y, z = Consts('x y z', IntSort())
1163  >>> x + y + z
1164  x + y + z
1165  """
1166  if isinstance(names, str):
1167  names = names.split(" ")
1168  return [Const(name, sort) for name in names]
1169 
1170 def Var(idx, s):
1171  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1172 
1173  >>> Var(0, IntSort())
1174  Var(0)
1175  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1176  False
1177  """
1178  if __debug__:
1179  _z3_assert(is_sort(s), "Z3 sort expected")
1180  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1181 
1182 def RealVar(idx, ctx=None):
1183  """
1184  Create a real free variable. Free variables are used to create quantified formulas.
1185  They are also used to create polynomials.
1186 
1187  >>> RealVar(0)
1188  Var(0)
1189  """
1190  return Var(idx, RealSort(ctx))
1191 
1192 def RealVarVector(n, ctx=None):
1193  """
1194  Create a list of Real free variables.
1195  The variables have ids: 0, 1, ..., n-1
1196 
1197  >>> x0, x1, x2, x3 = RealVarVector(4)
1198  >>> x2
1199  Var(2)
1200  """
1201  return [ RealVar(i, ctx) for i in range(n) ]
1202 
1203 #########################################
1204 #
1205 # Booleans
1206 #
1207 #########################################
1208 
1210  """Boolean sort."""
1211  def cast(self, val):
1212  """Try to cast `val` as a Boolean.
1213 
1214  >>> x = BoolSort().cast(True)
1215  >>> x
1216  True
1217  >>> is_expr(x)
1218  True
1219  >>> is_expr(True)
1220  False
1221  >>> x.sort()
1222  Bool
1223  """
1224  if isinstance(val, bool):
1225  return BoolVal(val, self.ctx)
1226  if __debug__:
1227  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected")
1228  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1229  return val
1230 
1232  """All Boolean expressions are instances of this class."""
1233  def sort(self):
1234  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1235 
1236 def is_bool(a):
1237  """Return `True` if `a` is a Z3 Boolean expression.
1238 
1239  >>> p = Bool('p')
1240  >>> is_bool(p)
1241  True
1242  >>> q = Bool('q')
1243  >>> is_bool(And(p, q))
1244  True
1245  >>> x = Real('x')
1246  >>> is_bool(x)
1247  False
1248  >>> is_bool(x == 0)
1249  True
1250  """
1251  return isinstance(a, BoolRef)
1252 
1253 def is_true(a):
1254  """Return `True` if `a` is the Z3 true expression.
1255 
1256  >>> p = Bool('p')
1257  >>> is_true(p)
1258  False
1259  >>> is_true(simplify(p == p))
1260  True
1261  >>> x = Real('x')
1262  >>> is_true(x == 0)
1263  False
1264  >>> # True is a Python Boolean expression
1265  >>> is_true(True)
1266  False
1267  """
1268  return is_app_of(a, Z3_OP_TRUE)
1269 
1270 def is_false(a):
1271  """Return `True` if `a` is the Z3 false expression.
1272 
1273  >>> p = Bool('p')
1274  >>> is_false(p)
1275  False
1276  >>> is_false(False)
1277  False
1278  >>> is_false(BoolVal(False))
1279  True
1280  """
1281  return is_app_of(a, Z3_OP_FALSE)
1282 
1283 def is_and(a):
1284  """Return `True` if `a` is a Z3 and expression.
1285 
1286  >>> p, q = Bools('p q')
1287  >>> is_and(And(p, q))
1288  True
1289  >>> is_and(Or(p, q))
1290  False
1291  """
1292  return is_app_of(a, Z3_OP_AND)
1293 
1294 def is_or(a):
1295  """Return `True` if `a` is a Z3 or expression.
1296 
1297  >>> p, q = Bools('p q')
1298  >>> is_or(Or(p, q))
1299  True
1300  >>> is_or(And(p, q))
1301  False
1302  """
1303  return is_app_of(a, Z3_OP_OR)
1304 
1305 def is_not(a):
1306  """Return `True` if `a` is a Z3 not expression.
1307 
1308  >>> p = Bool('p')
1309  >>> is_not(p)
1310  False
1311  >>> is_not(Not(p))
1312  True
1313  """
1314  return is_app_of(a, Z3_OP_NOT)
1315 
1316 def is_eq(a):
1317  """Return `True` if `a` is a Z3 equality expression.
1318 
1319  >>> x, y = Ints('x y')
1320  >>> is_eq(x == y)
1321  True
1322  """
1323  return is_app_of(a, Z3_OP_EQ)
1324 
1326  """Return `True` if `a` is a Z3 distinct expression.
1327 
1328  >>> x, y, z = Ints('x y z')
1329  >>> is_distinct(x == y)
1330  False
1331  >>> is_distinct(Distinct(x, y, z))
1332  True
1333  """
1334  return is_app_of(a, Z3_OP_DISTINCT)
1335 
1336 def BoolSort(ctx=None):
1337  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1338 
1339  >>> BoolSort()
1340  Bool
1341  >>> p = Const('p', BoolSort())
1342  >>> is_bool(p)
1343  True
1344  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1345  >>> r(0, 1)
1346  r(0, 1)
1347  >>> is_bool(r(0, 1))
1348  True
1349  """
1350  ctx = _get_ctx(ctx)
1351  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1352 
1353 def BoolVal(val, ctx=None):
1354  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1355 
1356  >>> BoolVal(True)
1357  True
1358  >>> is_true(BoolVal(True))
1359  True
1360  >>> is_true(True)
1361  False
1362  >>> is_false(BoolVal(False))
1363  True
1364  """
1365  ctx = _get_ctx(ctx)
1366  if val == False:
1367  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1368  else:
1369  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1370 
1371 def Bool(name, ctx=None):
1372  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1373 
1374  >>> p = Bool('p')
1375  >>> q = Bool('q')
1376  >>> And(p, q)
1377  And(p, q)
1378  """
1379  ctx = _get_ctx(ctx)
1380  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1381 
1382 def Bools(names, ctx=None):
1383  """Return a tuple of Boolean constants.
1384 
1385  `names` is a single string containing all names separated by blank spaces.
1386  If `ctx=None`, then the global context is used.
1387 
1388  >>> p, q, r = Bools('p q r')
1389  >>> And(p, Or(q, r))
1390  And(p, Or(q, r))
1391  """
1392  ctx = _get_ctx(ctx)
1393  if isinstance(names, str):
1394  names = names.split(" ")
1395  return [Bool(name, ctx) for name in names]
1396 
1397 def BoolVector(prefix, sz, ctx=None):
1398  """Return a list of Boolean constants of size `sz`.
1399 
1400  The constants are named using the given prefix.
1401  If `ctx=None`, then the global context is used.
1402 
1403  >>> P = BoolVector('p', 3)
1404  >>> P
1405  [p__0, p__1, p__2]
1406  >>> And(P)
1407  And(p__0, p__1, p__2)
1408  """
1409  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1410 
1411 def FreshBool(prefix='b', ctx=None):
1412  """Return a fresh Boolean constant in the given context using the given prefix.
1413 
1414  If `ctx=None`, then the global context is used.
1415 
1416  >>> b1 = FreshBool()
1417  >>> b2 = FreshBool()
1418  >>> eq(b1, b2)
1419  False
1420  """
1421  ctx = _get_ctx(ctx)
1422  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1423 
1424 def Implies(a, b, ctx=None):
1425  """Create a Z3 implies expression.
1426 
1427  >>> p, q = Bools('p q')
1428  >>> Implies(p, q)
1429  Implies(p, q)
1430  >>> simplify(Implies(p, q))
1431  Or(Not(p), q)
1432  """
1433  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1434  s = BoolSort(ctx)
1435  a = s.cast(a)
1436  b = s.cast(b)
1437  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1438 
1439 def Xor(a, b, ctx=None):
1440  """Create a Z3 Xor expression.
1441 
1442  >>> p, q = Bools('p q')
1443  >>> Xor(p, q)
1444  Xor(p, q)
1445  >>> simplify(Xor(p, q))
1446  Not(p) == q
1447  """
1448  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1449  s = BoolSort(ctx)
1450  a = s.cast(a)
1451  b = s.cast(b)
1452  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1453 
1454 def Not(a, ctx=None):
1455  """Create a Z3 not expression or probe.
1456 
1457  >>> p = Bool('p')
1458  >>> Not(Not(p))
1459  Not(Not(p))
1460  >>> simplify(Not(Not(p)))
1461  p
1462  """
1463  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1464  if is_probe(a):
1465  # Not is also used to build probes
1466  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1467  else:
1468  s = BoolSort(ctx)
1469  a = s.cast(a)
1470  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1471 
1472 def _has_probe(args):
1473  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1474  for arg in args:
1475  if is_probe(arg):
1476  return True
1477  return False
1478 
1479 def And(*args):
1480  """Create a Z3 and-expression or and-probe.
1481 
1482  >>> p, q, r = Bools('p q r')
1483  >>> And(p, q, r)
1484  And(p, q, r)
1485  >>> P = BoolVector('p', 5)
1486  >>> And(P)
1487  And(p__0, p__1, p__2, p__3, p__4)
1488  """
1489  last_arg = None
1490  if len(args) > 0:
1491  last_arg = args[len(args)-1]
1492  if isinstance(last_arg, Context):
1493  ctx = args[len(args)-1]
1494  args = args[:len(args)-1]
1495  else:
1496  ctx = main_ctx()
1497  args = _get_args(args)
1498  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1499  if __debug__:
1500  _z3_assert(ctx_args == None or ctx_args == ctx, "context mismatch")
1501  _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression or probe")
1502  if _has_probe(args):
1503  return _probe_and(args, ctx)
1504  else:
1505  args = _coerce_expr_list(args, ctx)
1506  _args, sz = _to_ast_array(args)
1507  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1508 
1509 def Or(*args):
1510  """Create a Z3 or-expression or or-probe.
1511 
1512  >>> p, q, r = Bools('p q r')
1513  >>> Or(p, q, r)
1514  Or(p, q, r)
1515  >>> P = BoolVector('p', 5)
1516  >>> Or(P)
1517  Or(p__0, p__1, p__2, p__3, p__4)
1518  """
1519  last_arg = None
1520  if len(args) > 0:
1521  last_arg = args[len(args)-1]
1522  if isinstance(last_arg, Context):
1523  ctx = args[len(args)-1]
1524  args = args[:len(args)-1]
1525  else:
1526  ctx = main_ctx()
1527  args = _get_args(args)
1528  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1529  if __debug__:
1530  _z3_assert(ctx_args == None or ctx_args == ctx, "context mismatch")
1531  _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression or probe")
1532  if _has_probe(args):
1533  return _probe_or(args, ctx)
1534  else:
1535  args = _coerce_expr_list(args, ctx)
1536  _args, sz = _to_ast_array(args)
1537  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1538 
1539 #########################################
1540 #
1541 # Patterns
1542 #
1543 #########################################
1544 
1545 class PatternRef(ExprRef):
1546  """Patterns are hints for quantifier instantiation.
1547 
1548  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1549  """
1550  def as_ast(self):
1551  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1552 
1553  def get_id(self):
1554  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1555 
1556 def is_pattern(a):
1557  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1558 
1559  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1560 
1561  >>> f = Function('f', IntSort(), IntSort())
1562  >>> x = Int('x')
1563  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1564  >>> q
1565  ForAll(x, f(x) == 0)
1566  >>> q.num_patterns()
1567  1
1568  >>> is_pattern(q.pattern(0))
1569  True
1570  >>> q.pattern(0)
1571  f(Var(0))
1572  """
1573  return isinstance(a, PatternRef)
1574 
1575 def MultiPattern(*args):
1576  """Create a Z3 multi-pattern using the given expressions `*args`
1577 
1578  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1579 
1580  >>> f = Function('f', IntSort(), IntSort())
1581  >>> g = Function('g', IntSort(), IntSort())
1582  >>> x = Int('x')
1583  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1584  >>> q
1585  ForAll(x, f(x) != g(x))
1586  >>> q.num_patterns()
1587  1
1588  >>> is_pattern(q.pattern(0))
1589  True
1590  >>> q.pattern(0)
1591  MultiPattern(f(Var(0)), g(Var(0)))
1592  """
1593  if __debug__:
1594  _z3_assert(len(args) > 0, "At least one argument expected")
1595  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1596  ctx = args[0].ctx
1597  args, sz = _to_ast_array(args)
1598  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1599 
1600 def _to_pattern(arg):
1601  if is_pattern(arg):
1602  return arg
1603  else:
1604  return MultiPattern(arg)
1605 
1606 #########################################
1607 #
1608 # Quantifiers
1609 #
1610 #########################################
1611 
1612 class QuantifierRef(BoolRef):
1613  """Universally and Existentially quantified formulas."""
1614 
1615  def as_ast(self):
1616  return self.ast
1617 
1618  def get_id(self):
1619  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1620 
1621  def sort(self):
1622  """Return the Boolean sort."""
1623  return BoolSort(self.ctx)
1624 
1625  def is_forall(self):
1626  """Return `True` if `self` is a universal quantifier.
1627 
1628  >>> f = Function('f', IntSort(), IntSort())
1629  >>> x = Int('x')
1630  >>> q = ForAll(x, f(x) == 0)
1631  >>> q.is_forall()
1632  True
1633  >>> q = Exists(x, f(x) != 0)
1634  >>> q.is_forall()
1635  False
1636  """
1637  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1638 
1639  def weight(self):
1640  """Return the weight annotation of `self`.
1641 
1642  >>> f = Function('f', IntSort(), IntSort())
1643  >>> x = Int('x')
1644  >>> q = ForAll(x, f(x) == 0)
1645  >>> q.weight()
1646  1
1647  >>> q = ForAll(x, f(x) == 0, weight=10)
1648  >>> q.weight()
1649  10
1650  """
1651  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1652 
1653  def num_patterns(self):
1654  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1655 
1656  >>> f = Function('f', IntSort(), IntSort())
1657  >>> g = Function('g', IntSort(), IntSort())
1658  >>> x = Int('x')
1659  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1660  >>> q.num_patterns()
1661  2
1662  """
1663  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1664 
1665  def pattern(self, idx):
1666  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1667 
1668  >>> f = Function('f', IntSort(), IntSort())
1669  >>> g = Function('g', IntSort(), IntSort())
1670  >>> x = Int('x')
1671  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1672  >>> q.num_patterns()
1673  2
1674  >>> q.pattern(0)
1675  f(Var(0))
1676  >>> q.pattern(1)
1677  g(Var(0))
1678  """
1679  if __debug__:
1680  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1681  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1682 
1683  def num_no_patterns(self):
1684  """Return the number of no-patterns."""
1685  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1686 
1687  def no_pattern(self, idx):
1688  """Return a no-pattern."""
1689  if __debug__:
1690  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1691  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1692 
1693  def body(self):
1694  """Return the expression being quantified.
1695 
1696  >>> f = Function('f', IntSort(), IntSort())
1697  >>> x = Int('x')
1698  >>> q = ForAll(x, f(x) == 0)
1699  >>> q.body()
1700  f(Var(0)) == 0
1701  """
1702  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1703 
1704  def num_vars(self):
1705  """Return the number of variables bounded by this quantifier.
1706 
1707  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1708  >>> x = Int('x')
1709  >>> y = Int('y')
1710  >>> q = ForAll([x, y], f(x, y) >= x)
1711  >>> q.num_vars()
1712  2
1713  """
1714  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1715 
1716  def var_name(self, idx):
1717  """Return a string representing a name used when displaying the quantifier.
1718 
1719  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1720  >>> x = Int('x')
1721  >>> y = Int('y')
1722  >>> q = ForAll([x, y], f(x, y) >= x)
1723  >>> q.var_name(0)
1724  'x'
1725  >>> q.var_name(1)
1726  'y'
1727  """
1728  if __debug__:
1729  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1730  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1731 
1732  def var_sort(self, idx):
1733  """Return the sort of a bound variable.
1734 
1735  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1736  >>> x = Int('x')
1737  >>> y = Real('y')
1738  >>> q = ForAll([x, y], f(x, y) >= x)
1739  >>> q.var_sort(0)
1740  Int
1741  >>> q.var_sort(1)
1742  Real
1743  """
1744  if __debug__:
1745  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1746  return SortRef(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1747 
1748  def children(self):
1749  """Return a list containing a single element self.body()
1750 
1751  >>> f = Function('f', IntSort(), IntSort())
1752  >>> x = Int('x')
1753  >>> q = ForAll(x, f(x) == 0)
1754  >>> q.children()
1755  [f(Var(0)) == 0]
1756  """
1757  return [ self.body() ]
1758 
1759 def is_quantifier(a):
1760  """Return `True` if `a` is a Z3 quantifier.
1761 
1762  >>> f = Function('f', IntSort(), IntSort())
1763  >>> x = Int('x')
1764  >>> q = ForAll(x, f(x) == 0)
1765  >>> is_quantifier(q)
1766  True
1767  >>> is_quantifier(f(x))
1768  False
1769  """
1770  return isinstance(a, QuantifierRef)
1771 
1772 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1773  if __debug__:
1774  _z3_assert(is_bool(body), "Z3 expression expected")
1775  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1776  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1777  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1778  ctx = body.ctx
1779  if is_app(vs):
1780  vs = [vs]
1781  num_vars = len(vs)
1782  _vs = (Ast * num_vars)()
1783  for i in range(num_vars):
1784  ## TODO: Check if is constant
1785  _vs[i] = vs[i].as_ast()
1786  patterns = [ _to_pattern(p) for p in patterns ]
1787  num_pats = len(patterns)
1788  _pats = (Pattern * num_pats)()
1789  for i in range(num_pats):
1790  _pats[i] = patterns[i].ast
1791  _no_pats, num_no_pats = _to_ast_array(no_patterns)
1792  qid = to_symbol(qid, ctx)
1793  skid = to_symbol(skid, ctx)
1794  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
1795  num_vars, _vs,
1796  num_pats, _pats,
1797  num_no_pats, _no_pats,
1798  body.as_ast()), ctx)
1799 
1800 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1801  """Create a Z3 forall formula.
1802 
1803  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1804 
1805  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1806 
1807  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1808  >>> x = Int('x')
1809  >>> y = Int('y')
1810  >>> ForAll([x, y], f(x, y) >= x)
1811  ForAll([x, y], f(x, y) >= x)
1812  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
1813  ForAll([x, y], f(x, y) >= x)
1814  >>> ForAll([x, y], f(x, y) >= x, weight=10)
1815  ForAll([x, y], f(x, y) >= x)
1816  """
1817  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
1818 
1819 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1820  """Create a Z3 exists formula.
1821 
1822  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1823 
1824  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1825 
1826  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1827  >>> x = Int('x')
1828  >>> y = Int('y')
1829  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
1830  >>> q
1831  Exists([x, y], f(x, y) >= x)
1832  >>> is_quantifier(q)
1833  True
1834  >>> r = Tactic('nnf')(q).as_expr()
1835  >>> is_quantifier(r)
1836  False
1837  """
1838  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
1839 
1840 #########################################
1841 #
1842 # Arithmetic
1843 #
1844 #########################################
1845 
1846 class ArithSortRef(SortRef):
1847  """Real and Integer sorts."""
1848 
1849  def is_real(self):
1850  """Return `True` if `self` is of the sort Real.
1851 
1852  >>> x = Real('x')
1853  >>> x.is_real()
1854  True
1855  >>> (x + 1).is_real()
1856  True
1857  >>> x = Int('x')
1858  >>> x.is_real()
1859  False
1860  """
1861  return self.kind() == Z3_REAL_SORT
1862 
1863  def is_int(self):
1864  """Return `True` if `self` is of the sort Integer.
1865 
1866  >>> x = Int('x')
1867  >>> x.is_int()
1868  True
1869  >>> (x + 1).is_int()
1870  True
1871  >>> x = Real('x')
1872  >>> x.is_int()
1873  False
1874  """
1875  return self.kind() == Z3_INT_SORT
1876 
1877  def subsort(self, other):
1878  """Return `True` if `self` is a subsort of `other`."""
1879  return self.is_int() and is_arith_sort(other) and other.is_real()
1880 
1881  def cast(self, val):
1882  """Try to cast `val` as an Integer or Real.
1883 
1884  >>> IntSort().cast(10)
1885  10
1886  >>> is_int(IntSort().cast(10))
1887  True
1888  >>> is_int(10)
1889  False
1890  >>> RealSort().cast(10)
1891  10
1892  >>> is_real(RealSort().cast(10))
1893  True
1894  """
1895  if is_expr(val):
1896  if __debug__:
1897  _z3_assert(self.ctx == val.ctx, "Context mismatch")
1898  val_s = val.sort()
1899  if self.eq(val_s):
1900  return val
1901  if val_s.is_int() and self.is_real():
1902  return ToReal(val)
1903  if __debug__:
1904  _z3_assert(False, "Z3 Integer/Real expression expected" )
1905  else:
1906  if self.is_int():
1907  return IntVal(val, self.ctx)
1908  if self.is_real():
1909  return RealVal(val, self.ctx)
1910  if __debug__:
1911  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected")
1912 
1913 def is_arith_sort(s):
1914  """Return `True` if s is an arithmetical sort (type).
1915 
1916  >>> is_arith_sort(IntSort())
1917  True
1918  >>> is_arith_sort(RealSort())
1919  True
1920  >>> is_arith_sort(BoolSort())
1921  False
1922  >>> n = Int('x') + 1
1923  >>> is_arith_sort(n.sort())
1924  True
1925  """
1926  return isinstance(s, ArithSortRef)
1927 
1928 class ArithRef(ExprRef):
1929  """Integer and Real expressions."""
1930 
1931  def sort(self):
1932  """Return the sort (type) of the arithmetical expression `self`.
1933 
1934  >>> Int('x').sort()
1935  Int
1936  >>> (Real('x') + 1).sort()
1937  Real
1938  """
1939  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1940 
1941  def is_int(self):
1942  """Return `True` if `self` is an integer expression.
1943 
1944  >>> x = Int('x')
1945  >>> x.is_int()
1946  True
1947  >>> (x + 1).is_int()
1948  True
1949  >>> y = Real('y')
1950  >>> (x + y).is_int()
1951  False
1952  """
1953  return self.sort().is_int()
1954 
1955  def is_real(self):
1956  """Return `True` if `self` is an real expression.
1957 
1958  >>> x = Real('x')
1959  >>> x.is_real()
1960  True
1961  >>> (x + 1).is_real()
1962  True
1963  """
1964  return self.sort().is_real()
1965 
1966  def __add__(self, other):
1967  """Create the Z3 expression `self + other`.
1968 
1969  >>> x = Int('x')
1970  >>> y = Int('y')
1971  >>> x + y
1972  x + y
1973  >>> (x + y).sort()
1974  Int
1975  """
1976  a, b = _coerce_exprs(self, other)
1977  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
1978 
1979  def __radd__(self, other):
1980  """Create the Z3 expression `other + self`.
1981 
1982  >>> x = Int('x')
1983  >>> 10 + x
1984  10 + x
1985  """
1986  a, b = _coerce_exprs(self, other)
1987  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
1988 
1989  def __mul__(self, other):
1990  """Create the Z3 expression `self * other`.
1991 
1992  >>> x = Real('x')
1993  >>> y = Real('y')
1994  >>> x * y
1995  x*y
1996  >>> (x * y).sort()
1997  Real
1998  """
1999  a, b = _coerce_exprs(self, other)
2000  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2001 
2002  def __rmul__(self, other):
2003  """Create the Z3 expression `other * self`.
2004 
2005  >>> x = Real('x')
2006  >>> 10 * x
2007  10*x
2008  """
2009  a, b = _coerce_exprs(self, other)
2010  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2011 
2012  def __sub__(self, other):
2013  """Create the Z3 expression `self - other`.
2014 
2015  >>> x = Int('x')
2016  >>> y = Int('y')
2017  >>> x - y
2018  x - y
2019  >>> (x - y).sort()
2020  Int
2021  """
2022  a, b = _coerce_exprs(self, other)
2023  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2024 
2025  def __rsub__(self, other):
2026  """Create the Z3 expression `other - self`.
2027 
2028  >>> x = Int('x')
2029  >>> 10 - x
2030  10 - x
2031  """
2032  a, b = _coerce_exprs(self, other)
2033  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2034 
2035  def __pow__(self, other):
2036  """Create the Z3 expression `self**other` (** is the power operator).
2037 
2038  >>> x = Real('x')
2039  >>> x**3
2040  x**3
2041  >>> (x**3).sort()
2042  Real
2043  >>> simplify(IntVal(2)**8)
2044  256
2045  """
2046  a, b = _coerce_exprs(self, other)
2047  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2048 
2049  def __rpow__(self, other):
2050  """Create the Z3 expression `other**self` (** is the power operator).
2051 
2052  >>> x = Real('x')
2053  >>> 2**x
2054  2**x
2055  >>> (2**x).sort()
2056  Real
2057  >>> simplify(2**IntVal(8))
2058  256
2059  """
2060  a, b = _coerce_exprs(self, other)
2061  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2062 
2063  def __div__(self, other):
2064  """Create the Z3 expression `other/self`.
2065 
2066  >>> x = Int('x')
2067  >>> y = Int('y')
2068  >>> x/y
2069  x/y
2070  >>> (x/y).sort()
2071  Int
2072  >>> (x/y).sexpr()
2073  '(div x y)'
2074  >>> x = Real('x')
2075  >>> y = Real('y')
2076  >>> x/y
2077  x/y
2078  >>> (x/y).sort()
2079  Real
2080  >>> (x/y).sexpr()
2081  '(/ x y)'
2082  """
2083  a, b = _coerce_exprs(self, other)
2084  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2085 
2086  def __truediv__(self, other):
2087  """Create the Z3 expression `other/self`."""
2088  return self.__div__(other)
2089 
2090  def __rdiv__(self, other):
2091  """Create the Z3 expression `other/self`.
2092 
2093  >>> x = Int('x')
2094  >>> 10/x
2095  10/x
2096  >>> (10/x).sexpr()
2097  '(div 10 x)'
2098  >>> x = Real('x')
2099  >>> 10/x
2100  10/x
2101  >>> (10/x).sexpr()
2102  '(/ 10.0 x)'
2103  """
2104  a, b = _coerce_exprs(self, other)
2105  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2106 
2107  def __rtruediv__(self, other):
2108  """Create the Z3 expression `other/self`."""
2109  return self.__rdiv__(other)
2110 
2111  def __mod__(self, other):
2112  """Create the Z3 expression `other%self`.
2113 
2114  >>> x = Int('x')
2115  >>> y = Int('y')
2116  >>> x % y
2117  x%y
2118  >>> simplify(IntVal(10) % IntVal(3))
2119  1
2120  """
2121  a, b = _coerce_exprs(self, other)
2122  if __debug__:
2123  _z3_assert(a.is_int(), "Z3 integer expression expected")
2124  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2125 
2126  def __rmod__(self, other):
2127  """Create the Z3 expression `other%self`.
2128 
2129  >>> x = Int('x')
2130  >>> 10 % x
2131  10%x
2132  """
2133  a, b = _coerce_exprs(self, other)
2134  if __debug__:
2135  _z3_assert(a.is_int(), "Z3 integer expression expected")
2136  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2137 
2138  def __neg__(self):
2139  """Return an expression representing `-self`.
2140 
2141  >>> x = Int('x')
2142  >>> -x
2143  -x
2144  >>> simplify(-(-x))
2145  x
2146  """
2147  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2148 
2149  def __pos__(self):
2150  """Return `self`.
2151 
2152  >>> x = Int('x')
2153  >>> +x
2154  x
2155  """
2156  return self
2157 
2158  def __le__(self, other):
2159  """Create the Z3 expression `other <= self`.
2160 
2161  >>> x, y = Ints('x y')
2162  >>> x <= y
2163  x <= y
2164  >>> y = Real('y')
2165  >>> x <= y
2166  ToReal(x) <= y
2167  """
2168  a, b = _coerce_exprs(self, other)
2169  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2170 
2171  def __lt__(self, other):
2172  """Create the Z3 expression `other < self`.
2173 
2174  >>> x, y = Ints('x y')
2175  >>> x < y
2176  x < y
2177  >>> y = Real('y')
2178  >>> x < y
2179  ToReal(x) < y
2180  """
2181  a, b = _coerce_exprs(self, other)
2182  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2183 
2184  def __gt__(self, other):
2185  """Create the Z3 expression `other > self`.
2186 
2187  >>> x, y = Ints('x y')
2188  >>> x > y
2189  x > y
2190  >>> y = Real('y')
2191  >>> x > y
2192  ToReal(x) > y
2193  """
2194  a, b = _coerce_exprs(self, other)
2195  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2196 
2197  def __ge__(self, other):
2198  """Create the Z3 expression `other >= self`.
2199 
2200  >>> x, y = Ints('x y')
2201  >>> x >= y
2202  x >= y
2203  >>> y = Real('y')
2204  >>> x >= y
2205  ToReal(x) >= y
2206  """
2207  a, b = _coerce_exprs(self, other)
2208  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2209 
2210 def is_arith(a):
2211  """Return `True` if `a` is an arithmetical expression.
2212 
2213  >>> x = Int('x')
2214  >>> is_arith(x)
2215  True
2216  >>> is_arith(x + 1)
2217  True
2218  >>> is_arith(1)
2219  False
2220  >>> is_arith(IntVal(1))
2221  True
2222  >>> y = Real('y')
2223  >>> is_arith(y)
2224  True
2225  >>> is_arith(y + 1)
2226  True
2227  """
2228  return isinstance(a, ArithRef)
2229 
2230 def is_int(a):
2231  """Return `True` if `a` is an integer expression.
2232 
2233  >>> x = Int('x')
2234  >>> is_int(x + 1)
2235  True
2236  >>> is_int(1)
2237  False
2238  >>> is_int(IntVal(1))
2239  True
2240  >>> y = Real('y')
2241  >>> is_int(y)
2242  False
2243  >>> is_int(y + 1)
2244  False
2245  """
2246  return is_arith(a) and a.is_int()
2247 
2248 def is_real(a):
2249  """Return `True` if `a` is a real expression.
2250 
2251  >>> x = Int('x')
2252  >>> is_real(x + 1)
2253  False
2254  >>> y = Real('y')
2255  >>> is_real(y)
2256  True
2257  >>> is_real(y + 1)
2258  True
2259  >>> is_real(1)
2260  False
2261  >>> is_real(RealVal(1))
2262  True
2263  """
2264  return is_arith(a) and a.is_real()
2265 
2266 def _is_numeral(ctx, a):
2267  return Z3_is_numeral_ast(ctx.ref(), a)
2268 
2269 def _is_algebraic(ctx, a):
2270  return Z3_is_algebraic_number(ctx.ref(), a)
2271 
2272 def is_int_value(a):
2273  """Return `True` if `a` is an integer value of sort Int.
2274 
2275  >>> is_int_value(IntVal(1))
2276  True
2277  >>> is_int_value(1)
2278  False
2279  >>> is_int_value(Int('x'))
2280  False
2281  >>> n = Int('x') + 1
2282  >>> n
2283  x + 1
2284  >>> n.arg(1)
2285  1
2286  >>> is_int_value(n.arg(1))
2287  True
2288  >>> is_int_value(RealVal("1/3"))
2289  False
2290  >>> is_int_value(RealVal(1))
2291  False
2292  """
2293  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2294 
2295 def is_rational_value(a):
2296  """Return `True` if `a` is rational value of sort Real.
2297 
2298  >>> is_rational_value(RealVal(1))
2299  True
2300  >>> is_rational_value(RealVal("3/5"))
2301  True
2302  >>> is_rational_value(IntVal(1))
2303  False
2304  >>> is_rational_value(1)
2305  False
2306  >>> n = Real('x') + 1
2307  >>> n.arg(1)
2308  1
2309  >>> is_rational_value(n.arg(1))
2310  True
2311  >>> is_rational_value(Real('x'))
2312  False
2313  """
2314  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2315 
2316 def is_algebraic_value(a):
2317  """Return `True` if `a` is an algerbraic value of sort Real.
2318 
2319  >>> is_algebraic_value(RealVal("3/5"))
2320  False
2321  >>> n = simplify(Sqrt(2))
2322  >>> n
2323  1.4142135623?
2324  >>> is_algebraic_value(n)
2325  True
2326  """
2327  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2328 
2329 def is_add(a):
2330  """Return `True` if `a` is an expression of the form b + c.
2331 
2332  >>> x, y = Ints('x y')
2333  >>> is_add(x + y)
2334  True
2335  >>> is_add(x - y)
2336  False
2337  """
2338  return is_app_of(a, Z3_OP_ADD)
2339 
2340 def is_mul(a):
2341  """Return `True` if `a` is an expression of the form b * c.
2342 
2343  >>> x, y = Ints('x y')
2344  >>> is_mul(x * y)
2345  True
2346  >>> is_mul(x - y)
2347  False
2348  """
2349  return is_app_of(a, Z3_OP_MUL)
2350 
2351 def is_sub(a):
2352  """Return `True` if `a` is an expression of the form b - c.
2353 
2354  >>> x, y = Ints('x y')
2355  >>> is_sub(x - y)
2356  True
2357  >>> is_sub(x + y)
2358  False
2359  """
2360  return is_app_of(a, Z3_OP_SUB)
2361 
2362 def is_div(a):
2363  """Return `True` if `a` is an expression of the form b / c.
2364 
2365  >>> x, y = Reals('x y')
2366  >>> is_div(x / y)
2367  True
2368  >>> is_div(x + y)
2369  False
2370  >>> x, y = Ints('x y')
2371  >>> is_div(x / y)
2372  False
2373  >>> is_idiv(x / y)
2374  True
2375  """
2376  return is_app_of(a, Z3_OP_DIV)
2377 
2378 def is_idiv(a):
2379  """Return `True` if `a` is an expression of the form b div c.
2380 
2381  >>> x, y = Ints('x y')
2382  >>> is_idiv(x / y)
2383  True
2384  >>> is_idiv(x + y)
2385  False
2386  """
2387  return is_app_of(a, Z3_OP_IDIV)
2388 
2389 def is_mod(a):
2390  """Return `True` if `a` is an expression of the form b % c.
2391 
2392  >>> x, y = Ints('x y')
2393  >>> is_mod(x % y)
2394  True
2395  >>> is_mod(x + y)
2396  False
2397  """
2398  return is_app_of(a, Z3_OP_MOD)
2399 
2400 def is_le(a):
2401  """Return `True` if `a` is an expression of the form b <= c.
2402 
2403  >>> x, y = Ints('x y')
2404  >>> is_le(x <= y)
2405  True
2406  >>> is_le(x < y)
2407  False
2408  """
2409  return is_app_of(a, Z3_OP_LE)
2410 
2411 def is_lt(a):
2412  """Return `True` if `a` is an expression of the form b < c.
2413 
2414  >>> x, y = Ints('x y')
2415  >>> is_lt(x < y)
2416  True
2417  >>> is_lt(x == y)
2418  False
2419  """
2420  return is_app_of(a, Z3_OP_LT)
2421 
2422 def is_ge(a):
2423  """Return `True` if `a` is an expression of the form b >= c.
2424 
2425  >>> x, y = Ints('x y')
2426  >>> is_ge(x >= y)
2427  True
2428  >>> is_ge(x == y)
2429  False
2430  """
2431  return is_app_of(a, Z3_OP_GE)
2432 
2433 def is_gt(a):
2434  """Return `True` if `a` is an expression of the form b > c.
2435 
2436  >>> x, y = Ints('x y')
2437  >>> is_gt(x > y)
2438  True
2439  >>> is_gt(x == y)
2440  False
2441  """
2442  return is_app_of(a, Z3_OP_GT)
2443 
2444 def is_is_int(a):
2445  """Return `True` if `a` is an expression of the form IsInt(b).
2446 
2447  >>> x = Real('x')
2448  >>> is_is_int(IsInt(x))
2449  True
2450  >>> is_is_int(x)
2451  False
2452  """
2453  return is_app_of(a, Z3_OP_IS_INT)
2454 
2455 def is_to_real(a):
2456  """Return `True` if `a` is an expression of the form ToReal(b).
2457 
2458  >>> x = Int('x')
2459  >>> n = ToReal(x)
2460  >>> n
2461  ToReal(x)
2462  >>> is_to_real(n)
2463  True
2464  >>> is_to_real(x)
2465  False
2466  """
2467  return is_app_of(a, Z3_OP_TO_REAL)
2468 
2469 def is_to_int(a):
2470  """Return `True` if `a` is an expression of the form ToInt(b).
2471 
2472  >>> x = Real('x')
2473  >>> n = ToInt(x)
2474  >>> n
2475  ToInt(x)
2476  >>> is_to_int(n)
2477  True
2478  >>> is_to_int(x)
2479  False
2480  """
2481  return is_app_of(a, Z3_OP_TO_INT)
2482 
2483 class IntNumRef(ArithRef):
2484  """Integer values."""
2485 
2486  def as_long(self):
2487  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2488 
2489  >>> v = IntVal(1)
2490  >>> v + 1
2491  1 + 1
2492  >>> v.as_long() + 1
2493  2
2494  """
2495  if __debug__:
2496  _z3_assert(self.is_int(), "Integer value expected")
2497  return int(self.as_string())
2498 
2499  def as_string(self):
2500  """Return a Z3 integer numeral as a Python string.
2501  >>> v = IntVal(100)
2502  >>> v.as_string()
2503  '100'
2504  """
2505  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2506 
2507 class RatNumRef(ArithRef):
2508  """Rational values."""
2509 
2510  def numerator(self):
2511  """ Return the numerator of a Z3 rational numeral.
2512 
2513  >>> is_rational_value(RealVal("3/5"))
2514  True
2515  >>> n = RealVal("3/5")
2516  >>> n.numerator()
2517  3
2518  >>> is_rational_value(Q(3,5))
2519  True
2520  >>> Q(3,5).numerator()
2521  3
2522  """
2523  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2524 
2525  def denominator(self):
2526  """ Return the denominator of a Z3 rational numeral.
2527 
2528  >>> is_rational_value(Q(3,5))
2529  True
2530  >>> n = Q(3,5)
2531  >>> n.denominator()
2532  5
2533  """
2534  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2535 
2536  def numerator_as_long(self):
2537  """ Return the numerator as a Python long.
2538 
2539  >>> v = RealVal(10000000000)
2540  >>> v
2541  10000000000
2542  >>> v + 1
2543  10000000000 + 1
2544  >>> v.numerator_as_long() + 1 == 10000000001
2545  True
2546  """
2547  return self.numerator().as_long()
2548 
2549  def denominator_as_long(self):
2550  """ Return the denominator as a Python long.
2551 
2552  >>> v = RealVal("1/3")
2553  >>> v
2554  1/3
2555  >>> v.denominator_as_long()
2556  3
2557  """
2558  return self.denominator().as_long()
2559 
2560  def as_decimal(self, prec):
2561  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2562 
2563  >>> v = RealVal("1/5")
2564  >>> v.as_decimal(3)
2565  '0.2'
2566  >>> v = RealVal("1/3")
2567  >>> v.as_decimal(3)
2568  '0.333?'
2569  """
2570  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2571 
2572  def as_string(self):
2573  """Return a Z3 rational numeral as a Python string.
2574 
2575  >>> v = Q(3,6)
2576  >>> v.as_string()
2577  '1/2'
2578  """
2579  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2580 
2581  def as_fraction(self):
2582  """Return a Z3 rational as a Python Fraction object.
2583 
2584  >>> v = RealVal("1/5")
2585  >>> v.as_fraction()
2586  Fraction(1, 5)
2587  """
2588  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2589 
2590 class AlgebraicNumRef(ArithRef):
2591  """Algebraic irrational values."""
2592 
2593  def approx(self, precision=10):
2594  """Return a Z3 rational number that approximates the algebraic number `self`.
2595  The result `r` is such that |r - self| <= 1/10^precision
2596 
2597  >>> x = simplify(Sqrt(2))
2598  >>> x.approx(20)
2599  6838717160008073720548335/4835703278458516698824704
2600  >>> x.approx(5)
2601  2965821/2097152
2602  """
2603  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2604  def as_decimal(self, prec):
2605  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2606 
2607  >>> x = simplify(Sqrt(2))
2608  >>> x.as_decimal(10)
2609  '1.4142135623?'
2610  >>> x.as_decimal(20)
2611  '1.41421356237309504880?'
2612  """
2613  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2614 
2615 def _py2expr(a, ctx=None):
2616  if isinstance(a, bool):
2617  return BoolVal(a, ctx)
2618  if _is_int(a):
2619  return IntVal(a, ctx)
2620  if isinstance(a, float):
2621  return RealVal(a, ctx)
2622  if __debug__:
2623  _z3_assert(False, "Python bool, int, long or float expected")
2624 
2625 def IntSort(ctx=None):
2626  """Return the interger sort in the given context. If `ctx=None`, then the global context is used.
2627 
2628  >>> IntSort()
2629  Int
2630  >>> x = Const('x', IntSort())
2631  >>> is_int(x)
2632  True
2633  >>> x.sort() == IntSort()
2634  True
2635  >>> x.sort() == BoolSort()
2636  False
2637  """
2638  ctx = _get_ctx(ctx)
2639  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2640 
2641 def RealSort(ctx=None):
2642  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2643 
2644  >>> RealSort()
2645  Real
2646  >>> x = Const('x', RealSort())
2647  >>> is_real(x)
2648  True
2649  >>> is_int(x)
2650  False
2651  >>> x.sort() == RealSort()
2652  True
2653  """
2654  ctx = _get_ctx(ctx)
2655  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2656 
2657 def _to_int_str(val):
2658  if isinstance(val, float):
2659  return str(int(val))
2660  elif isinstance(val, bool):
2661  if val:
2662  return "1"
2663  else:
2664  return "0"
2665  elif _is_int(val):
2666  return str(val)
2667  elif isinstance(val, str):
2668  return val
2669  if __debug__:
2670  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2671 
2672 def IntVal(val, ctx=None):
2673  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2674 
2675  >>> IntVal(1)
2676  1
2677  >>> IntVal("100")
2678  100
2679  """
2680  ctx = _get_ctx(ctx)
2681  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2682 
2683 def RealVal(val, ctx=None):
2684  """Return a Z3 real value.
2685 
2686  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2687  If `ctx=None`, then the global context is used.
2688 
2689  >>> RealVal(1)
2690  1
2691  >>> RealVal(1).sort()
2692  Real
2693  >>> RealVal("3/5")
2694  3/5
2695  >>> RealVal("1.5")
2696  3/2
2697  """
2698  ctx = _get_ctx(ctx)
2699  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2700 
2701 def RatVal(a, b, ctx=None):
2702  """Return a Z3 rational a/b.
2703 
2704  If `ctx=None`, then the global context is used.
2705 
2706  >>> RatVal(3,5)
2707  3/5
2708  >>> RatVal(3,5).sort()
2709  Real
2710  """
2711  if __debug__:
2712  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2713  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2714  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2715 
2716 def Q(a, b, ctx=None):
2717  """Return a Z3 rational a/b.
2718 
2719  If `ctx=None`, then the global context is used.
2720 
2721  >>> Q(3,5)
2722  3/5
2723  >>> Q(3,5).sort()
2724  Real
2725  """
2726  return simplify(RatVal(a, b))
2727 
2728 def Int(name, ctx=None):
2729  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2730 
2731  >>> x = Int('x')
2732  >>> is_int(x)
2733  True
2734  >>> is_int(x + 1)
2735  True
2736  """
2737  ctx = _get_ctx(ctx)
2738  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2739 
2740 def Ints(names, ctx=None):
2741  """Return a tuple of Integer constants.
2742 
2743  >>> x, y, z = Ints('x y z')
2744  >>> Sum(x, y, z)
2745  x + y + z
2746  """
2747  ctx = _get_ctx(ctx)
2748  if isinstance(names, str):
2749  names = names.split(" ")
2750  return [Int(name, ctx) for name in names]
2751 
2752 def IntVector(prefix, sz, ctx=None):
2753  """Return a list of integer constants of size `sz`.
2754 
2755  >>> X = IntVector('x', 3)
2756  >>> X
2757  [x__0, x__1, x__2]
2758  >>> Sum(X)
2759  x__0 + x__1 + x__2
2760  """
2761  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
2762 
2763 def FreshInt(prefix='x', ctx=None):
2764  """Return a fresh integer constant in the given context using the given prefix.
2765 
2766  >>> x = FreshInt()
2767  >>> y = FreshInt()
2768  >>> eq(x, y)
2769  False
2770  >>> x.sort()
2771  Int
2772  """
2773  ctx = _get_ctx(ctx)
2774  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
2775 
2776 def Real(name, ctx=None):
2777  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
2778 
2779  >>> x = Real('x')
2780  >>> is_real(x)
2781  True
2782  >>> is_real(x + 1)
2783  True
2784  """
2785  ctx = _get_ctx(ctx)
2786  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
2787 
2788 def Reals(names, ctx=None):
2789  """Return a tuple of real constants.
2790 
2791  >>> x, y, z = Reals('x y z')
2792  >>> Sum(x, y, z)
2793  x + y + z
2794  >>> Sum(x, y, z).sort()
2795  Real
2796  """
2797  ctx = _get_ctx(ctx)
2798  if isinstance(names, str):
2799  names = names.split(" ")
2800  return [Real(name, ctx) for name in names]
2801 
2802 def RealVector(prefix, sz, ctx=None):
2803  """Return a list of real constants of size `sz`.
2804 
2805  >>> X = RealVector('x', 3)
2806  >>> X
2807  [x__0, x__1, x__2]
2808  >>> Sum(X)
2809  x__0 + x__1 + x__2
2810  >>> Sum(X).sort()
2811  Real
2812  """
2813  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
2814 
2815 def FreshReal(prefix='b', ctx=None):
2816  """Return a fresh real constant in the given context using the given prefix.
2817 
2818  >>> x = FreshReal()
2819  >>> y = FreshReal()
2820  >>> eq(x, y)
2821  False
2822  >>> x.sort()
2823  Real
2824  """
2825  ctx = _get_ctx(ctx)
2826  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
2827 
2828 def ToReal(a):
2829  """ Return the Z3 expression ToReal(a).
2830 
2831  >>> x = Int('x')
2832  >>> x.sort()
2833  Int
2834  >>> n = ToReal(x)
2835  >>> n
2836  ToReal(x)
2837  >>> n.sort()
2838  Real
2839  """
2840  if __debug__:
2841  _z3_assert(a.is_int(), "Z3 integer expression expected.")
2842  ctx = a.ctx
2843  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
2844 
2845 def ToInt(a):
2846  """ Return the Z3 expression ToInt(a).
2847 
2848  >>> x = Real('x')
2849  >>> x.sort()
2850  Real
2851  >>> n = ToInt(x)
2852  >>> n
2853  ToInt(x)
2854  >>> n.sort()
2855  Int
2856  """
2857  if __debug__:
2858  _z3_assert(a.is_real(), "Z3 real expression expected.")
2859  ctx = a.ctx
2860  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
2861 
2862 def IsInt(a):
2863  """ Return the Z3 predicate IsInt(a).
2864 
2865  >>> x = Real('x')
2866  >>> IsInt(x + "1/2")
2867  IsInt(x + 1/2)
2868  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
2869  [x = 1/2]
2870  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
2871  no solution
2872  """
2873  if __debug__:
2874  _z3_assert(a.is_real(), "Z3 real expression expected.")
2875  ctx = a.ctx
2876  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
2877 
2878 def Sqrt(a, ctx=None):
2879  """ Return a Z3 expression which represents the square root of a.
2880 
2881  >>> x = Real('x')
2882  >>> Sqrt(x)
2883  x**(1/2)
2884  """
2885  if not is_expr(a):
2886  ctx = _get_ctx(ctx)
2887  a = RealVal(a, ctx)
2888  return a ** "1/2"
2889 
2890 def Cbrt(a, ctx=None):
2891  """ Return a Z3 expression which represents the cubic root of a.
2892 
2893  >>> x = Real('x')
2894  >>> Cbrt(x)
2895  x**(1/3)
2896  """
2897  if not is_expr(a):
2898  ctx = _get_ctx(ctx)
2899  a = RealVal(a, ctx)
2900  return a ** "1/3"
2901 
2902 #########################################
2903 #
2904 # Bit-Vectors
2905 #
2906 #########################################
2907 
2908 class BitVecSortRef(SortRef):
2909  """Bit-vector sort."""
2910 
2911  def size(self):
2912  """Return the size (number of bits) of the bit-vector sort `self`.
2913 
2914  >>> b = BitVecSort(32)
2915  >>> b.size()
2916  32
2917  """
2918  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
2919 
2920  def subsort(self, other):
2921  return is_bv_sort(other) and self.size() < other.size()
2922 
2923  def cast(self, val):
2924  """Try to cast `val` as a Bit-Vector.
2925 
2926  >>> b = BitVecSort(32)
2927  >>> b.cast(10)
2928  10
2929  >>> b.cast(10).sexpr()
2930  '#x0000000a'
2931  """
2932  if is_expr(val):
2933  if __debug__:
2934  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2935  # Idea: use sign_extend if sort of val is a bitvector of smaller size
2936  return val
2937  else:
2938  return BitVecVal(val, self)
2939 
2940 def is_bv_sort(s):
2941  """Return True if `s` is a Z3 bit-vector sort.
2942 
2943  >>> is_bv_sort(BitVecSort(32))
2944  True
2945  >>> is_bv_sort(IntSort())
2946  False
2947  """
2948  return isinstance(s, BitVecSortRef)
2949 
2950 class BitVecRef(ExprRef):
2951  """Bit-vector expressions."""
2952 
2953  def sort(self):
2954  """Return the sort of the bit-vector expression `self`.
2955 
2956  >>> x = BitVec('x', 32)
2957  >>> x.sort()
2958  BitVec(32)
2959  >>> x.sort() == BitVecSort(32)
2960  True
2961  """
2962  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2963 
2964  def size(self):
2965  """Return the number of bits of the bit-vector expression `self`.
2966 
2967  >>> x = BitVec('x', 32)
2968  >>> (x + 1).size()
2969  32
2970  >>> Concat(x, x).size()
2971  64
2972  """
2973  return self.sort().size()
2974 
2975  def __add__(self, other):
2976  """Create the Z3 expression `self + other`.
2977 
2978  >>> x = BitVec('x', 32)
2979  >>> y = BitVec('y', 32)
2980  >>> x + y
2981  x + y
2982  >>> (x + y).sort()
2983  BitVec(32)
2984  """
2985  a, b = _coerce_exprs(self, other)
2986  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2987 
2988  def __radd__(self, other):
2989  """Create the Z3 expression `other + self`.
2990 
2991  >>> x = BitVec('x', 32)
2992  >>> 10 + x
2993  10 + x
2994  """
2995  a, b = _coerce_exprs(self, other)
2996  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2997 
2998  def __mul__(self, other):
2999  """Create the Z3 expression `self * other`.
3000 
3001  >>> x = BitVec('x', 32)
3002  >>> y = BitVec('y', 32)
3003  >>> x * y
3004  x*y
3005  >>> (x * y).sort()
3006  BitVec(32)
3007  """
3008  a, b = _coerce_exprs(self, other)
3009  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3010 
3011  def __rmul__(self, other):
3012  """Create the Z3 expression `other * self`.
3013 
3014  >>> x = BitVec('x', 32)
3015  >>> 10 * x
3016  10*x
3017  """
3018  a, b = _coerce_exprs(self, other)
3019  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3020 
3021  def __sub__(self, other):
3022  """Create the Z3 expression `self - other`.
3023 
3024  >>> x = BitVec('x', 32)
3025  >>> y = BitVec('y', 32)
3026  >>> x - y
3027  x - y
3028  >>> (x - y).sort()
3029  BitVec(32)
3030  """
3031  a, b = _coerce_exprs(self, other)
3032  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3033 
3034  def __rsub__(self, other):
3035  """Create the Z3 expression `other - self`.
3036 
3037  >>> x = BitVec('x', 32)
3038  >>> 10 - x
3039  10 - x
3040  """
3041  a, b = _coerce_exprs(self, other)
3042  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3043 
3044  def __or__(self, other):
3045  """Create the Z3 expression bitwise-or `self | other`.
3046 
3047  >>> x = BitVec('x', 32)
3048  >>> y = BitVec('y', 32)
3049  >>> x | y
3050  x | y
3051  >>> (x | y).sort()
3052  BitVec(32)
3053  """
3054  a, b = _coerce_exprs(self, other)
3055  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3056 
3057  def __ror__(self, other):
3058  """Create the Z3 expression bitwise-or `other | self`.
3059 
3060  >>> x = BitVec('x', 32)
3061  >>> 10 | x
3062  10 | x
3063  """
3064  a, b = _coerce_exprs(self, other)
3065  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3066 
3067  def __and__(self, other):
3068  """Create the Z3 expression bitwise-and `self & other`.
3069 
3070  >>> x = BitVec('x', 32)
3071  >>> y = BitVec('y', 32)
3072  >>> x & y
3073  x & y
3074  >>> (x & y).sort()
3075  BitVec(32)
3076  """
3077  a, b = _coerce_exprs(self, other)
3078  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3079 
3080  def __rand__(self, other):
3081  """Create the Z3 expression bitwise-or `other & self`.
3082 
3083  >>> x = BitVec('x', 32)
3084  >>> 10 & x
3085  10 & x
3086  """
3087  a, b = _coerce_exprs(self, other)
3088  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3089 
3090  def __xor__(self, other):
3091  """Create the Z3 expression bitwise-xor `self ^ other`.
3092 
3093  >>> x = BitVec('x', 32)
3094  >>> y = BitVec('y', 32)
3095  >>> x ^ y
3096  x ^ y
3097  >>> (x ^ y).sort()
3098  BitVec(32)
3099  """
3100  a, b = _coerce_exprs(self, other)
3101  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3102 
3103  def __rxor__(self, other):
3104  """Create the Z3 expression bitwise-xor `other ^ self`.
3105 
3106  >>> x = BitVec('x', 32)
3107  >>> 10 ^ x
3108  10 ^ x
3109  """
3110  a, b = _coerce_exprs(self, other)
3111  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3112 
3113  def __pos__(self):
3114  """Return `self`.
3115 
3116  >>> x = BitVec('x', 32)
3117  >>> +x
3118  x
3119  """
3120  return self
3121 
3122  def __neg__(self):
3123  """Return an expression representing `-self`.
3124 
3125  >>> x = BitVec('x', 32)
3126  >>> -x
3127  -x
3128  >>> simplify(-(-x))
3129  x
3130  """
3131  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3132 
3133  def __invert__(self):
3134  """Create the Z3 expression bitwise-not `~self`.
3135 
3136  >>> x = BitVec('x', 32)
3137  >>> ~x
3138  ~x
3139  >>> simplify(~(~x))
3140  x
3141  """
3142  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3143 
3144  def __div__(self, other):
3145  """Create the Z3 expression (signed) division `self / other`.
3146 
3147  Use the function UDiv() for unsigned division.
3148 
3149  >>> x = BitVec('x', 32)
3150  >>> y = BitVec('y', 32)
3151  >>> x / y
3152  x/y
3153  >>> (x / y).sort()
3154  BitVec(32)
3155  >>> (x / y).sexpr()
3156  '(bvsdiv x y)'
3157  >>> UDiv(x, y).sexpr()
3158  '(bvudiv x y)'
3159  """
3160  a, b = _coerce_exprs(self, other)
3161  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3162 
3163  def __truediv__(self, other):
3164  """Create the Z3 expression (signed) division `self / other`."""
3165  return self.__div__(other)
3166 
3167  def __rdiv__(self, other):
3168  """Create the Z3 expression (signed) division `other / self`.
3169 
3170  Use the function UDiv() for unsigned division.
3171 
3172  >>> x = BitVec('x', 32)
3173  >>> 10 / x
3174  10/x
3175  >>> (10 / x).sexpr()
3176  '(bvsdiv #x0000000a x)'
3177  >>> UDiv(10, x).sexpr()
3178  '(bvudiv #x0000000a x)'
3179  """
3180  a, b = _coerce_exprs(self, other)
3181  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3182 
3183  def __rtruediv__(self, other):
3184  """Create the Z3 expression (signed) division `other / self`."""
3185  return self.__rdiv__(other)
3186 
3187  def __mod__(self, other):
3188  """Create the Z3 expression (signed) mod `self % other`.
3189 
3190  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3191 
3192  >>> x = BitVec('x', 32)
3193  >>> y = BitVec('y', 32)
3194  >>> x % y
3195  x%y
3196  >>> (x % y).sort()
3197  BitVec(32)
3198  >>> (x % y).sexpr()
3199  '(bvsmod x y)'
3200  >>> URem(x, y).sexpr()
3201  '(bvurem x y)'
3202  >>> SRem(x, y).sexpr()
3203  '(bvsrem x y)'
3204  """
3205  a, b = _coerce_exprs(self, other)
3206  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3207 
3208  def __rmod__(self, other):
3209  """Create the Z3 expression (signed) mod `other % self`.
3210 
3211  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3212 
3213  >>> x = BitVec('x', 32)
3214  >>> 10 % x
3215  10%x
3216  >>> (10 % x).sexpr()
3217  '(bvsmod #x0000000a x)'
3218  >>> URem(10, x).sexpr()
3219  '(bvurem #x0000000a x)'
3220  >>> SRem(10, x).sexpr()
3221  '(bvsrem #x0000000a x)'
3222  """
3223  a, b = _coerce_exprs(self, other)
3224  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3225 
3226  def __le__(self, other):
3227  """Create the Z3 expression (signed) `other <= self`.
3228 
3229  Use the function ULE() for unsigned less than or equal to.
3230 
3231  >>> x, y = BitVecs('x y', 32)
3232  >>> x <= y
3233  x <= y
3234  >>> (x <= y).sexpr()
3235  '(bvsle x y)'
3236  >>> ULE(x, y).sexpr()
3237  '(bvule x y)'
3238  """
3239  a, b = _coerce_exprs(self, other)
3240  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3241 
3242  def __lt__(self, other):
3243  """Create the Z3 expression (signed) `other < self`.
3244 
3245  Use the function ULT() for unsigned less than.
3246 
3247  >>> x, y = BitVecs('x y', 32)
3248  >>> x < y
3249  x < y
3250  >>> (x < y).sexpr()
3251  '(bvslt x y)'
3252  >>> ULT(x, y).sexpr()
3253  '(bvult x y)'
3254  """
3255  a, b = _coerce_exprs(self, other)
3256  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3257 
3258  def __gt__(self, other):
3259  """Create the Z3 expression (signed) `other > self`.
3260 
3261  Use the function UGT() for unsigned greater than.
3262 
3263  >>> x, y = BitVecs('x y', 32)
3264  >>> x > y
3265  x > y
3266  >>> (x > y).sexpr()
3267  '(bvsgt x y)'
3268  >>> UGT(x, y).sexpr()
3269  '(bvugt x y)'
3270  """
3271  a, b = _coerce_exprs(self, other)
3272  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3273 
3274  def __ge__(self, other):
3275  """Create the Z3 expression (signed) `other >= self`.
3276 
3277  Use the function UGE() for unsigned greater than or equal to.
3278 
3279  >>> x, y = BitVecs('x y', 32)
3280  >>> x >= y
3281  x >= y
3282  >>> (x >= y).sexpr()
3283  '(bvsge x y)'
3284  >>> UGE(x, y).sexpr()
3285  '(bvuge x y)'
3286  """
3287  a, b = _coerce_exprs(self, other)
3288  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3289 
3290  def __rshift__(self, other):
3291  """Create the Z3 expression (arithmetical) right shift `self >> other`
3292 
3293  Use the function LShR() for the right logical shift
3294 
3295  >>> x, y = BitVecs('x y', 32)
3296  >>> x >> y
3297  x >> y
3298  >>> (x >> y).sexpr()
3299  '(bvashr x y)'
3300  >>> LShR(x, y).sexpr()
3301  '(bvlshr x y)'
3302  >>> BitVecVal(4, 3)
3303  4
3304  >>> BitVecVal(4, 3).as_signed_long()
3305  -4
3306  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3307  -2
3308  >>> simplify(BitVecVal(4, 3) >> 1)
3309  6
3310  >>> simplify(LShR(BitVecVal(4, 3), 1))
3311  2
3312  >>> simplify(BitVecVal(2, 3) >> 1)
3313  1
3314  >>> simplify(LShR(BitVecVal(2, 3), 1))
3315  1
3316  """
3317  a, b = _coerce_exprs(self, other)
3318  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3319 
3320  def __lshift__(self, other):
3321  """Create the Z3 expression left shift `self << other`
3322 
3323  >>> x, y = BitVecs('x y', 32)
3324  >>> x << y
3325  x << y
3326  >>> (x << y).sexpr()
3327  '(bvshl x y)'
3328  >>> simplify(BitVecVal(2, 3) << 1)
3329  4
3330  """
3331  a, b = _coerce_exprs(self, other)
3332  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3333 
3334  def __rrshift__(self, other):
3335  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3336 
3337  Use the function LShR() for the right logical shift
3338 
3339  >>> x = BitVec('x', 32)
3340  >>> 10 >> x
3341  10 >> x
3342  >>> (10 >> x).sexpr()
3343  '(bvashr #x0000000a x)'
3344  """
3345  a, b = _coerce_exprs(self, other)
3346  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3347 
3348  def __rlshift__(self, other):
3349  """Create the Z3 expression left shift `other << self`.
3350 
3351  Use the function LShR() for the right logical shift
3352 
3353  >>> x = BitVec('x', 32)
3354  >>> 10 << x
3355  10 << x
3356  >>> (10 << x).sexpr()
3357  '(bvshl #x0000000a x)'
3358  """
3359  a, b = _coerce_exprs(self, other)
3360  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3361 
3362 class BitVecNumRef(BitVecRef):
3363  """Bit-vector values."""
3364 
3365  def as_long(self):
3366  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3367 
3368  >>> v = BitVecVal(0xbadc0de, 32)
3369  >>> v
3370  195936478
3371  >>> print("0x%.8x" % v.as_long())
3372  0x0badc0de
3373  """
3374  return int(self.as_string())
3375 
3376  def as_signed_long(self):
3377  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3378 
3379  >>> BitVecVal(4, 3).as_signed_long()
3380  -4
3381  >>> BitVecVal(7, 3).as_signed_long()
3382  -1
3383  >>> BitVecVal(3, 3).as_signed_long()
3384  3
3385  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3386  -1
3387  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3388  -1
3389  """
3390  sz = self.size()
3391  val = self.as_long()
3392  if val >= 2**(sz - 1):
3393  val = val - 2**sz
3394  if val < -2**(sz - 1):
3395  val = val + 2**sz
3396  return int(val)
3397 
3398  def as_string(self):
3399  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3400 
3401 def is_bv(a):
3402  """Return `True` if `a` is a Z3 bit-vector expression.
3403 
3404  >>> b = BitVec('b', 32)
3405  >>> is_bv(b)
3406  True
3407  >>> is_bv(b + 10)
3408  True
3409  >>> is_bv(Int('x'))
3410  False
3411  """
3412  return isinstance(a, BitVecRef)
3413 
3414 def is_bv_value(a):
3415  """Return `True` if `a` is a Z3 bit-vector numeral value.
3416 
3417  >>> b = BitVec('b', 32)
3418  >>> is_bv_value(b)
3419  False
3420  >>> b = BitVecVal(10, 32)
3421  >>> b
3422  10
3423  >>> is_bv_value(b)
3424  True
3425  """
3426  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3427 
3428 def BV2Int(a):
3429  """Return the Z3 expression BV2Int(a).
3430 
3431  >>> b = BitVec('b', 3)
3432  >>> BV2Int(b).sort()
3433  Int
3434  >>> x = Int('x')
3435  >>> x > BV2Int(b)
3436  x > BV2Int(b)
3437  >>> solve(x > BV2Int(b), b == 1, x < 3)
3438  [b = 1, x = 2]
3439  """
3440  if __debug__:
3441  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3442  ctx = a.ctx
3443  ## investigate problem with bv2int
3444  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), 0), ctx)
3445 
3446 def BitVecSort(sz, ctx=None):
3447  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3448 
3449  >>> Byte = BitVecSort(8)
3450  >>> Word = BitVecSort(16)
3451  >>> Byte
3452  BitVec(8)
3453  >>> x = Const('x', Byte)
3454  >>> eq(x, BitVec('x', 8))
3455  True
3456  """
3457  ctx = _get_ctx(ctx)
3458  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3459 
3460 def BitVecVal(val, bv, ctx=None):
3461  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3462 
3463  >>> v = BitVecVal(10, 32)
3464  >>> v
3465  10
3466  >>> print("0x%.8x" % v.as_long())
3467  0x0000000a
3468  """
3469  if is_bv_sort(bv):
3470  ctx = bv.ctx
3471  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3472  else:
3473  ctx = _get_ctx(ctx)
3474  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3475 
3476 def BitVec(name, bv, ctx=None):
3477  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3478  If `ctx=None`, then the global context is used.
3479 
3480  >>> x = BitVec('x', 16)
3481  >>> is_bv(x)
3482  True
3483  >>> x.size()
3484  16
3485  >>> x.sort()
3486  BitVec(16)
3487  >>> word = BitVecSort(16)
3488  >>> x2 = BitVec('x', word)
3489  >>> eq(x, x2)
3490  True
3491  """
3492  if isinstance(bv, BitVecSortRef):
3493  ctx = bv.ctx
3494  else:
3495  ctx = _get_ctx(ctx)
3496  bv = BitVecSort(bv, ctx)
3497  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3498 
3499 def BitVecs(names, bv, ctx=None):
3500  """Return a tuple of bit-vector constants of size bv.
3501 
3502  >>> x, y, z = BitVecs('x y z', 16)
3503  >>> x.size()
3504  16
3505  >>> x.sort()
3506  BitVec(16)
3507  >>> Sum(x, y, z)
3508  0 + x + y + z
3509  >>> Product(x, y, z)
3510  1*x*y*z
3511  >>> simplify(Product(x, y, z))
3512  x*y*z
3513  """
3514  ctx = _get_ctx(ctx)
3515  if isinstance(names, str):
3516  names = names.split(" ")
3517  return [BitVec(name, bv, ctx) for name in names]
3518 
3519 def Concat(*args):
3520  """Create a Z3 bit-vector concatenation expression.
3521 
3522  >>> v = BitVecVal(1, 4)
3523  >>> Concat(v, v+1, v)
3524  Concat(Concat(1, 1 + 1), 1)
3525  >>> simplify(Concat(v, v+1, v))
3526  289
3527  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3528  121
3529  """
3530  args = _get_args(args)
3531  if __debug__:
3532  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3533  _z3_assert(len(args) >= 2, "At least two arguments expected.")
3534  ctx = args[0].ctx
3535  r = args[0]
3536  for i in range(len(args) - 1):
3537  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3538  return r
3539 
3540 def Extract(high, low, a):
3541  """Create a Z3 bit-vector extraction expression.
3542 
3543  >>> x = BitVec('x', 8)
3544  >>> Extract(6, 2, x)
3545  Extract(6, 2, x)
3546  >>> Extract(6, 2, x).sort()
3547  BitVec(5)
3548  """
3549  if __debug__:
3550  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3551  _z3_assert(isinstance(high, int) and high >= 0 and isinstance(low, int) and low >= 0, "First and second arguments must be non negative integers")
3552  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3553  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3554 
3555 def _check_bv_args(a, b):
3556  if __debug__:
3557  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3558 
3559 def ULE(a, b):
3560  """Create the Z3 expression (unsigned) `other <= self`.
3561 
3562  Use the operator <= for signed less than or equal to.
3563 
3564  >>> x, y = BitVecs('x y', 32)
3565  >>> ULE(x, y)
3566  ULE(x, y)
3567  >>> (x <= y).sexpr()
3568  '(bvsle x y)'
3569  >>> ULE(x, y).sexpr()
3570  '(bvule x y)'
3571  """
3572  _check_bv_args(a, b)
3573  a, b = _coerce_exprs(a, b)
3574  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3575 
3576 def ULT(a, b):
3577  """Create the Z3 expression (unsigned) `other < self`.
3578 
3579  Use the operator < for signed less than.
3580 
3581  >>> x, y = BitVecs('x y', 32)
3582  >>> ULT(x, y)
3583  ULT(x, y)
3584  >>> (x < y).sexpr()
3585  '(bvslt x y)'
3586  >>> ULT(x, y).sexpr()
3587  '(bvult x y)'
3588  """
3589  _check_bv_args(a, b)
3590  a, b = _coerce_exprs(a, b)
3591  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3592 
3593 def UGE(a, b):
3594  """Create the Z3 expression (unsigned) `other >= self`.
3595 
3596  Use the operator >= for signed greater than or equal to.
3597 
3598  >>> x, y = BitVecs('x y', 32)
3599  >>> UGE(x, y)
3600  UGE(x, y)
3601  >>> (x >= y).sexpr()
3602  '(bvsge x y)'
3603  >>> UGE(x, y).sexpr()
3604  '(bvuge x y)'
3605  """
3606  _check_bv_args(a, b)
3607  a, b = _coerce_exprs(a, b)
3608  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3609 
3610 def UGT(a, b):
3611  """Create the Z3 expression (unsigned) `other > self`.
3612 
3613  Use the operator > for signed greater than.
3614 
3615  >>> x, y = BitVecs('x y', 32)
3616  >>> UGT(x, y)
3617  UGT(x, y)
3618  >>> (x > y).sexpr()
3619  '(bvsgt x y)'
3620  >>> UGT(x, y).sexpr()
3621  '(bvugt x y)'
3622  """
3623  _check_bv_args(a, b)
3624  a, b = _coerce_exprs(a, b)
3625  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3626 
3627 def UDiv(a, b):
3628  """Create the Z3 expression (unsigned) division `self / other`.
3629 
3630  Use the operator / for signed division.
3631 
3632  >>> x = BitVec('x', 32)
3633  >>> y = BitVec('y', 32)
3634  >>> UDiv(x, y)
3635  UDiv(x, y)
3636  >>> UDiv(x, y).sort()
3637  BitVec(32)
3638  >>> (x / y).sexpr()
3639  '(bvsdiv x y)'
3640  >>> UDiv(x, y).sexpr()
3641  '(bvudiv x y)'
3642  """
3643  _check_bv_args(a, b)
3644  a, b = _coerce_exprs(a, b)
3645  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3646 
3647 def URem(a, b):
3648  """Create the Z3 expression (unsigned) remainder `self % other`.
3649 
3650  Use the operator % for signed modulus, and SRem() for signed remainder.
3651 
3652  >>> x = BitVec('x', 32)
3653  >>> y = BitVec('y', 32)
3654  >>> URem(x, y)
3655  URem(x, y)
3656  >>> URem(x, y).sort()
3657  BitVec(32)
3658  >>> (x % y).sexpr()
3659  '(bvsmod x y)'
3660  >>> URem(x, y).sexpr()
3661  '(bvurem x y)'
3662  """
3663  _check_bv_args(a, b)
3664  a, b = _coerce_exprs(a, b)
3665  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3666 
3667 def SRem(a, b):
3668  """Create the Z3 expression signed remainder.
3669 
3670  Use the operator % for signed modulus, and URem() for unsigned remainder.
3671 
3672  >>> x = BitVec('x', 32)
3673  >>> y = BitVec('y', 32)
3674  >>> SRem(x, y)
3675  SRem(x, y)
3676  >>> SRem(x, y).sort()
3677  BitVec(32)
3678  >>> (x % y).sexpr()
3679  '(bvsmod x y)'
3680  >>> SRem(x, y).sexpr()
3681  '(bvsrem x y)'
3682  """
3683  _check_bv_args(a, b)
3684  a, b = _coerce_exprs(a, b)
3685  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3686 
3687 def LShR(a, b):
3688  """Create the Z3 expression logical right shift.
3689 
3690  Use the operator >> for the arithmetical right shift.
3691 
3692  >>> x, y = BitVecs('x y', 32)
3693  >>> LShR(x, y)
3694  LShR(x, y)
3695  >>> (x >> y).sexpr()
3696  '(bvashr x y)'
3697  >>> LShR(x, y).sexpr()
3698  '(bvlshr x y)'
3699  >>> BitVecVal(4, 3)
3700  4
3701  >>> BitVecVal(4, 3).as_signed_long()
3702  -4
3703  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3704  -2
3705  >>> simplify(BitVecVal(4, 3) >> 1)
3706  6
3707  >>> simplify(LShR(BitVecVal(4, 3), 1))
3708  2
3709  >>> simplify(BitVecVal(2, 3) >> 1)
3710  1
3711  >>> simplify(LShR(BitVecVal(2, 3), 1))
3712  1
3713  """
3714  _check_bv_args(a, b)
3715  a, b = _coerce_exprs(a, b)
3716  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3717 
3718 def RotateLeft(a, b):
3719  """Return an expression representing `a` rotated to the left `b` times.
3720 
3721  >>> a, b = BitVecs('a b', 16)
3722  >>> RotateLeft(a, b)
3723  RotateLeft(a, b)
3724  >>> simplify(RotateLeft(a, 0))
3725  a
3726  >>> simplify(RotateLeft(a, 16))
3727  a
3728  """
3729  _check_bv_args(a, b)
3730  a, b = _coerce_exprs(a, b)
3731  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3732 
3733 def RotateRight(a, b):
3734  """Return an expression representing `a` rotated to the right `b` times.
3735 
3736  >>> a, b = BitVecs('a b', 16)
3737  >>> RotateRight(a, b)
3738  RotateRight(a, b)
3739  >>> simplify(RotateRight(a, 0))
3740  a
3741  >>> simplify(RotateRight(a, 16))
3742  a
3743  """
3744  _check_bv_args(a, b)
3745  a, b = _coerce_exprs(a, b)
3746  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3747 
3748 def SignExt(n, a):
3749  """Return a bit-vector expression with `n` extra sign-bits.
3750 
3751  >>> x = BitVec('x', 16)
3752  >>> n = SignExt(8, x)
3753  >>> n.size()
3754  24
3755  >>> n
3756  SignExt(8, x)
3757  >>> n.sort()
3758  BitVec(24)
3759  >>> v0 = BitVecVal(2, 2)
3760  >>> v0
3761  2
3762  >>> v0.size()
3763  2
3764  >>> v = simplify(SignExt(6, v0))
3765  >>> v
3766  254
3767  >>> v.size()
3768  8
3769  >>> print("%.x" % v.as_long())
3770  fe
3771  """
3772  if __debug__:
3773  _z3_assert(isinstance(n, int), "First argument must be an integer")
3774  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3775  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3776 
3777 def ZeroExt(n, a):
3778  """Return a bit-vector expression with `n` extra zero-bits.
3779 
3780  >>> x = BitVec('x', 16)
3781  >>> n = ZeroExt(8, x)
3782  >>> n.size()
3783  24
3784  >>> n
3785  ZeroExt(8, x)
3786  >>> n.sort()
3787  BitVec(24)
3788  >>> v0 = BitVecVal(2, 2)
3789  >>> v0
3790  2
3791  >>> v0.size()
3792  2
3793  >>> v = simplify(ZeroExt(6, v0))
3794  >>> v
3795  2
3796  >>> v.size()
3797  8
3798  """
3799  if __debug__:
3800  _z3_assert(isinstance(n, int), "First argument must be an integer")
3801  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3802  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3803 
3804 def RepeatBitVec(n, a):
3805  """Return an expression representing `n` copies of `a`.
3806 
3807  >>> x = BitVec('x', 8)
3808  >>> n = RepeatBitVec(4, x)
3809  >>> n
3810  RepeatBitVec(4, x)
3811  >>> n.size()
3812  32
3813  >>> v0 = BitVecVal(10, 4)
3814  >>> print("%.x" % v0.as_long())
3815  a
3816  >>> v = simplify(RepeatBitVec(4, v0))
3817  >>> v.size()
3818  16
3819  >>> print("%.x" % v.as_long())
3820  aaaa
3821  """
3822  if __debug__:
3823  _z3_assert(isinstance(n, int), "First argument must be an integer")
3824  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3825  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
3826 
3827 def BVRedAnd(a):
3828  """Return the reduction-and expression of `a`."""
3829  if __debug__:
3830  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3831  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
3832 
3833 def BVRedOr(a):
3834  """Return the reduction-or expression of `a`."""
3835  if __debug__:
3836  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3837  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
3838 
3839 #########################################
3840 #
3841 # Arrays
3842 #
3843 #########################################
3844 
3845 class ArraySortRef(SortRef):
3846  """Array sorts."""
3847 
3848  def domain(self):
3849  """Return the domain of the array sort `self`.
3850 
3851  >>> A = ArraySort(IntSort(), BoolSort())
3852  >>> A.domain()
3853  Int
3854  """
3855  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
3856 
3857  def range(self):
3858  """Return the range of the array sort `self`.
3859 
3860  >>> A = ArraySort(IntSort(), BoolSort())
3861  >>> A.range()
3862  Bool
3863  """
3864  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
3865 
3866 class ArrayRef(ExprRef):
3867  """Array expressions. """
3868 
3869  def sort(self):
3870  """Return the array sort of the array expression `self`.
3871 
3872  >>> a = Array('a', IntSort(), BoolSort())
3873  >>> a.sort()
3874  Array(Int, Bool)
3875  """
3876  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3877 
3878  def domain(self):
3879  """Shorthand for `self.sort().domain()`.
3880 
3881  >>> a = Array('a', IntSort(), BoolSort())
3882  >>> a.domain()
3883  Int
3884  """
3885  return self.sort().domain()
3886 
3887  def range(self):
3888  """Shorthand for `self.sort().range()`.
3889 
3890  >>> a = Array('a', IntSort(), BoolSort())
3891  >>> a.range()
3892  Bool
3893  """
3894  return self.sort().range()
3895 
3896  def __getitem__(self, arg):
3897  """Return the Z3 expression `self[arg]`.
3898 
3899  >>> a = Array('a', IntSort(), BoolSort())
3900  >>> i = Int('i')
3901  >>> a[i]
3902  a[i]
3903  >>> a[i].sexpr()
3904  '(select a i)'
3905  """
3906  arg = self.domain().cast(arg)
3907  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
3908 
3909 def is_array(a):
3910  """Return `True` if `a` is a Z3 array expression.
3911 
3912  >>> a = Array('a', IntSort(), IntSort())
3913  >>> is_array(a)
3914  True
3915  >>> is_array(Store(a, 0, 1))
3916  True
3917  >>> is_array(a[0])
3918  False
3919  """
3920  return isinstance(a, ArrayRef)
3921 
3922 def is_const_array(a):
3923  """Return `True` if `a` is a Z3 constant array.
3924 
3925  >>> a = K(IntSort(), 10)
3926  >>> is_const_array(a)
3927  True
3928  >>> a = Array('a', IntSort(), IntSort())
3929  >>> is_const_array(a)
3930  False
3931  """
3932  return is_app_of(a, Z3_OP_CONST_ARRAY)
3933 
3934 def is_K(a):
3935  """Return `True` if `a` is a Z3 constant array.
3936 
3937  >>> a = K(IntSort(), 10)
3938  >>> is_K(a)
3939  True
3940  >>> a = Array('a', IntSort(), IntSort())
3941  >>> is_K(a)
3942  False
3943  """
3944  return is_app_of(a, Z3_OP_CONST_ARRAY)
3945 
3946 def is_map(a):
3947  """Return `True` if `a` is a Z3 map array expression.
3948 
3949  >>> f = Function('f', IntSort(), IntSort())
3950  >>> b = Array('b', IntSort(), IntSort())
3951  >>> a = Map(f, b)
3952  >>> a
3953  Map(f, b)
3954  >>> is_map(a)
3955  True
3956  >>> is_map(b)
3957  False
3958  """
3959  return is_app_of(a, Z3_OP_ARRAY_MAP)
3960 
3961 def get_map_func(a):
3962  """Return the function declaration associated with a Z3 map array expression.
3963 
3964  >>> f = Function('f', IntSort(), IntSort())
3965  >>> b = Array('b', IntSort(), IntSort())
3966  >>> a = Map(f, b)
3967  >>> eq(f, get_map_func(a))
3968  True
3969  >>> get_map_func(a)
3970  f
3971  >>> get_map_func(a)(0)
3972  f(0)
3973  """
3974  if __debug__:
3975  _z3_assert(is_map(a), "Z3 array map expression expected.")
3976  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
3977 
3978 def ArraySort(d, r):
3979  """Return the Z3 array sort with the given domain and range sorts.
3980 
3981  >>> A = ArraySort(IntSort(), BoolSort())
3982  >>> A
3983  Array(Int, Bool)
3984  >>> A.domain()
3985  Int
3986  >>> A.range()
3987  Bool
3988  >>> AA = ArraySort(IntSort(), A)
3989  >>> AA
3990  Array(Int, Array(Int, Bool))
3991  """
3992  if __debug__:
3993  _z3_assert(is_sort(d), "Z3 sort expected")
3994  _z3_assert(is_sort(r), "Z3 sort expected")
3995  _z3_assert(d.ctx == r.ctx, "Context mismatch")
3996  ctx = d.ctx
3997  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
3998 
3999 def Array(name, dom, rng):
4000  """Return an array constant named `name` with the given domain and range sorts.
4001 
4002  >>> a = Array('a', IntSort(), IntSort())
4003  >>> a.sort()
4004  Array(Int, Int)
4005  >>> a[0]
4006  a[0]
4007  """
4008  s = ArraySort(dom, rng)
4009  ctx = s.ctx
4010  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4011 
4012 def Update(a, i, v):
4013  """Return a Z3 store array expression.
4014 
4015  >>> a = Array('a', IntSort(), IntSort())
4016  >>> i, v = Ints('i v')
4017  >>> s = Update(a, i, v)
4018  >>> s.sort()
4019  Array(Int, Int)
4020  >>> prove(s[i] == v)
4021  proved
4022  >>> j = Int('j')
4023  >>> prove(Implies(i != j, s[j] == a[j]))
4024  proved
4025  """
4026  if __debug__:
4027  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4028  i = a.domain().cast(i)
4029  v = a.range().cast(v)
4030  ctx = a.ctx
4031  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4032 
4033 def Store(a, i, v):
4034  """Return a Z3 store array expression.
4035 
4036  >>> a = Array('a', IntSort(), IntSort())
4037  >>> i, v = Ints('i v')
4038  >>> s = Store(a, i, v)
4039  >>> s.sort()
4040  Array(Int, Int)
4041  >>> prove(s[i] == v)
4042  proved
4043  >>> j = Int('j')
4044  >>> prove(Implies(i != j, s[j] == a[j]))
4045  proved
4046  """
4047  return Update(a, i, v)
4048 
4049 def Select(a, i):
4050  """Return a Z3 select array expression.
4051 
4052  >>> a = Array('a', IntSort(), IntSort())
4053  >>> i = Int('i')
4054  >>> Select(a, i)
4055  a[i]
4056  >>> eq(Select(a, i), a[i])
4057  True
4058  """
4059  if __debug__:
4060  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4061  return a[i]
4062 
4063 def Map(f, *args):
4064  """Return a Z3 map array expression.
4065 
4066  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4067  >>> a1 = Array('a1', IntSort(), IntSort())
4068  >>> a2 = Array('a2', IntSort(), IntSort())
4069  >>> b = Map(f, a1, a2)
4070  >>> b
4071  Map(f, a1, a2)
4072  >>> prove(b[0] == f(a1[0], a2[0]))
4073  proved
4074  """
4075  args = _get_args(args)
4076  if __debug__:
4077  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4078  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4079  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4080  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4081  _args, sz = _to_ast_array(args)
4082  ctx = f.ctx
4083  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4084 
4085 def K(dom, v):
4086  """Return a Z3 constant array expression.
4087 
4088  >>> a = K(IntSort(), 10)
4089  >>> a
4090  K(Int, 10)
4091  >>> a.sort()
4092  Array(Int, Int)
4093  >>> i = Int('i')
4094  >>> a[i]
4095  K(Int, 10)[i]
4096  >>> simplify(a[i])
4097  10
4098  """
4099  if __debug__:
4100  _z3_assert(is_sort(dom), "Z3 sort expected")
4101  ctx = dom.ctx
4102  if not is_expr(v):
4103  v = _py2expr(v, ctx)
4104  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4105 
4106 def is_select(a):
4107  """Return `True` if `a` is a Z3 array select application.
4108 
4109  >>> a = Array('a', IntSort(), IntSort())
4110  >>> is_select(a)
4111  False
4112  >>> i = Int('i')
4113  >>> is_select(a[i])
4114  True
4115  """
4116  return is_app_of(a, Z3_OP_SELECT)
4117 
4118 def is_store(a):
4119  """Return `True` if `a` is a Z3 array store application.
4120 
4121  >>> a = Array('a', IntSort(), IntSort())
4122  >>> is_store(a)
4123  False
4124  >>> is_store(Store(a, 0, 1))
4125  True
4126  """
4127  return is_app_of(a, Z3_OP_STORE)
4128 
4129 #########################################
4130 #
4131 # Datatypes
4132 #
4133 #########################################
4134 
4135 def _valid_accessor(acc):
4136  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4137  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4138 
4139 class Datatype:
4140  """Helper class for declaring Z3 datatypes.
4141 
4142  >>> List = Datatype('List')
4143  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4144  >>> List.declare('nil')
4145  >>> List = List.create()
4146  >>> # List is now a Z3 declaration
4147  >>> List.nil
4148  nil
4149  >>> List.cons(10, List.nil)
4150  cons(10, nil)
4151  >>> List.cons(10, List.nil).sort()
4152  List
4153  >>> cons = List.cons
4154  >>> nil = List.nil
4155  >>> car = List.car
4156  >>> cdr = List.cdr
4157  >>> n = cons(1, cons(0, nil))
4158  >>> n
4159  cons(1, cons(0, nil))
4160  >>> simplify(cdr(n))
4161  cons(0, nil)
4162  >>> simplify(car(n))
4163  1
4164  """
4165  def __init__(self, name, ctx=None):
4166  self.ctx = _get_ctx(ctx)
4167  self.name = name
4168  self.constructors = []
4169 
4170  def declare_core(self, name, rec_name, *args):
4171  if __debug__:
4172  _z3_assert(isinstance(name, str), "String expected")
4173  _z3_assert(isinstance(rec_name, str), "String expected")
4174  _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)")
4175  self.constructors.append((name, rec_name, args))
4176 
4177  def declare(self, name, *args):
4178  """Declare constructor named `name` with the given accessors `args`.
4179  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.
4180 
4181  In the followin example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4182  declares the constructor named `cons` that builds a new List using an integer and a List.
4183  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4184  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4185  the actual datatype in Z3.
4186 
4187  >>> List = Datatype('List')
4188  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4189  >>> List.declare('nil')
4190  >>> List = List.create()
4191  """
4192  if __debug__:
4193  _z3_assert(isinstance(name, str), "String expected")
4194  _z3_assert(name != "", "Constructor name cannot be empty")
4195  return self.declare_core(name, "is_" + name, *args)
4196 
4197  def __repr__(self):
4198  return "Datatype(%s, %s)" % (self.name, self.constructors)
4199 
4200  def create(self):
4201  """Create a Z3 datatype based on the constructors declared using the mehtod `declare()`.
4202 
4203  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4204 
4205  >>> List = Datatype('List')
4206  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4207  >>> List.declare('nil')
4208  >>> List = List.create()
4209  >>> List.nil
4210  nil
4211  >>> List.cons(10, List.nil)
4212  cons(10, nil)
4213  """
4214  return CreateDatatypes([self])[0]
4215 
4216 class ScopedConstructor:
4217  """Auxiliary object used to create Z3 datatypes."""
4218  def __init__(self, c, ctx):
4219  self.c = c
4220  self.ctx = ctx
4221  def __del__(self):
4222  Z3_del_constructor(self.ctx.ref(), self.c)
4223 
4224 class ScopedConstructorList:
4225  """Auxiliary object used to create Z3 datatypes."""
4226  def __init__(self, c, ctx):
4227  self.c = c
4228  self.ctx = ctx
4229  def __del__(self):
4230  Z3_del_constructor_list(self.ctx.ref(), self.c)
4231 
4232 def CreateDatatypes(*ds):
4233  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4234 
4235  In the following example we define a Tree-List using two mutually recursive datatypes.
4236 
4237  >>> TreeList = Datatype('TreeList')
4238  >>> Tree = Datatype('Tree')
4239  >>> # Tree has two constructors: leaf and node
4240  >>> Tree.declare('leaf', ('val', IntSort()))
4241  >>> # a node contains a list of trees
4242  >>> Tree.declare('node', ('children', TreeList))
4243  >>> TreeList.declare('nil')
4244  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4245  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4246  >>> Tree.val(Tree.leaf(10))
4247  val(leaf(10))
4248  >>> simplify(Tree.val(Tree.leaf(10)))
4249  10
4250  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4251  >>> n1
4252  node(cons(leaf(10), cons(leaf(20), nil)))
4253  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4254  >>> simplify(n2 == n1)
4255  False
4256  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4257  True
4258  """
4259  ds = _get_args(ds)
4260  if __debug__:
4261  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4262  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4263  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4264  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4265  ctx = ds[0].ctx
4266  num = len(ds)
4267  names = (Symbol * num)()
4268  out = (Sort * num)()
4269  clists = (ConstructorList * num)()
4270  to_delete = []
4271  for i in range(num):
4272  d = ds[i]
4273  names[i] = to_symbol(d.name, ctx)
4274  num_cs = len(d.constructors)
4275  cs = (Constructor * num_cs)()
4276  for j in range(num_cs):
4277  c = d.constructors[j]
4278  cname = to_symbol(c[0], ctx)
4279  rname = to_symbol(c[1], ctx)
4280  fs = c[2]
4281  num_fs = len(fs)
4282  fnames = (Symbol * num_fs)()
4283  sorts = (Sort * num_fs)()
4284  refs = (ctypes.c_uint * num_fs)()
4285  for k in range(num_fs):
4286  fname = fs[k][0]
4287  ftype = fs[k][1]
4288  fnames[k] = to_symbol(fname, ctx)
4289  if isinstance(ftype, Datatype):
4290  if __debug__:
4291  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4292  sorts[k] = None
4293  refs[k] = ds.index(ftype)
4294  else:
4295  if __debug__:
4296  _z3_assert(is_sort(ftype), "Z3 sort expected")
4297  sorts[k] = ftype.ast
4298  refs[k] = 0
4299  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4300  to_delete.append(ScopedConstructor(cs[j], ctx))
4301  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4302  to_delete.append(ScopedConstructorList(clists[i], ctx))
4303  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4304  result = []
4305  ## Create a field for every constructor, recognizer and accessor
4306  for i in range(num):
4307  dref = DatatypeSortRef(out[i], ctx)
4308  num_cs = dref.num_constructors()
4309  for j in range(num_cs):
4310  cref = dref.constructor(j)
4311  cref_name = cref.name()
4312  cref_arity = cref.arity()
4313  if cref.arity() == 0:
4314  cref = cref()
4315  setattr(dref, cref_name, cref)
4316  rref = dref.recognizer(j)
4317  setattr(dref, rref.name(), rref)
4318  for k in range(cref_arity):
4319  aref = dref.accessor(j, k)
4320  setattr(dref, aref.name(), aref)
4321  result.append(dref)
4322  return tuple(result)
4323 
4324 class DatatypeSortRef(SortRef):
4325  """Datatype sorts."""
4326  def num_constructors(self):
4327  """Return the number of constructors in the given Z3 datatype.
4328 
4329  >>> List = Datatype('List')
4330  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4331  >>> List.declare('nil')
4332  >>> List = List.create()
4333  >>> # List is now a Z3 declaration
4334  >>> List.num_constructors()
4335  2
4336  """
4337  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4338 
4339  def constructor(self, idx):
4340  """Return a constructor of the datatype `self`.
4341 
4342  >>> List = Datatype('List')
4343  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4344  >>> List.declare('nil')
4345  >>> List = List.create()
4346  >>> # List is now a Z3 declaration
4347  >>> List.num_constructors()
4348  2
4349  >>> List.constructor(0)
4350  cons
4351  >>> List.constructor(1)
4352  nil
4353  """
4354  if __debug__:
4355  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4356  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4357 
4358  def recognizer(self, idx):
4359  """In Z3, each constructor has an associated recognizer predicate.
4360 
4361  If the constructor is named `name`, then the recognizer `is_name`.
4362 
4363  >>> List = Datatype('List')
4364  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4365  >>> List.declare('nil')
4366  >>> List = List.create()
4367  >>> # List is now a Z3 declaration
4368  >>> List.num_constructors()
4369  2
4370  >>> List.recognizer(0)
4371  is_cons
4372  >>> List.recognizer(1)
4373  is_nil
4374  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4375  False
4376  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4377  True
4378  >>> l = Const('l', List)
4379  >>> simplify(List.is_cons(l))
4380  is_cons(l)
4381  """
4382  if __debug__:
4383  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4384  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4385 
4386  def accessor(self, i, j):
4387  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4388 
4389  >>> List = Datatype('List')
4390  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4391  >>> List.declare('nil')
4392  >>> List = List.create()
4393  >>> List.num_constructors()
4394  2
4395  >>> List.constructor(0)
4396  cons
4397  >>> num_accs = List.constructor(0).arity()
4398  >>> num_accs
4399  2
4400  >>> List.accessor(0, 0)
4401  car
4402  >>> List.accessor(0, 1)
4403  cdr
4404  >>> List.constructor(1)
4405  nil
4406  >>> num_accs = List.constructor(1).arity()
4407  >>> num_accs
4408  0
4409  """
4410  if __debug__:
4411  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4412  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4413  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4414 
4415 class DatatypeRef(ExprRef):
4416  """Datatype expressions."""
4417  def sort(self):
4418  """Return the datatype sort of the datatype expression `self`."""
4419  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4420 
4421 def EnumSort(name, values, ctx=None):
4422  """Return a new enumeration sort named `name` containing the given values.
4423 
4424  The result is a pair (sort, list of constants).
4425  Example:
4426  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4427  """
4428  if __debug__:
4429  _z3_assert(isinstance(name, str), "Name must be a string")
4430  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4431  _z3_assert(len(values) > 0, "At least one value expected")
4432  ctx = _get_ctx(ctx)
4433  num = len(values)
4434  _val_names = (Symbol * num)()
4435  for i in range(num):
4436  _val_names[i] = to_symbol(values[i])
4437  _values = (FuncDecl * num)()
4438  _testers = (FuncDecl * num)()
4439  name = to_symbol(name)
4440  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4441  V = []
4442  for i in range(num):
4443  V.append(FuncDeclRef(_values[i], ctx))
4444  V = [a() for a in V]
4445  return S, V
4446 
4447 #########################################
4448 #
4449 # Parameter Sets
4450 #
4451 #########################################
4452 
4453 class ParamsRef:
4454  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4455 
4456  Consider using the function `args2params` to create instances of this object.
4457  """
4458  def __init__(self, ctx=None):
4459  self.ctx = _get_ctx(ctx)
4460  self.params = Z3_mk_params(self.ctx.ref())
4461  Z3_params_inc_ref(self.ctx.ref(), self.params)
4462 
4463  def __del__(self):
4464  Z3_params_dec_ref(self.ctx.ref(), self.params)
4465 
4466  def set(self, name, val):
4467  """Set parameter name with value val."""
4468  if __debug__:
4469  _z3_assert(isinstance(name, str), "parameter name must be a string")
4470  name_sym = to_symbol(name, self.ctx)
4471  if isinstance(val, bool):
4472  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4473  elif isinstance(val, int):
4474  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4475  elif isinstance(val, float):
4476  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4477  elif isinstance(val, str):
4478  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4479  else:
4480  if __debug__:
4481  _z3_assert(False, "invalid parameter value")
4482 
4483  def __repr__(self):
4484  return Z3_params_to_string(self.ctx.ref(), self.params)
4485 
4486  def validate(self, ds):
4487  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
4488  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
4489 
4490 def args2params(arguments, keywords, ctx=None):
4491  """Convert python arguments into a Z3_params object.
4492  A ':' is added to the keywords, and '_' is replaced with '-'
4493 
4494  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
4495  (params model true relevancy 2 elim_and true)
4496  """
4497  if __debug__:
4498  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
4499  prev = None
4500  r = ParamsRef(ctx)
4501  for a in arguments:
4502  if prev == None:
4503  prev = a
4504  else:
4505  r.set(prev, a)
4506  prev = None
4507  for k in keywords:
4508  v = keywords[k]
4509  r.set(k, v)
4510  return r
4511 
4512 class ParamDescrsRef:
4513  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
4514  """
4515  def __init__(self, descr, ctx=None):
4516  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
4517  self.ctx = _get_ctx(ctx)
4518  self.descr = descr
4519  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
4520 
4521  def __del__(self):
4522  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
4523 
4524  def size(self):
4525  """Return the size of in the parameter description `self`.
4526  """
4527  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
4528 
4529  def __len__(self):
4530  """Return the size of in the parameter description `self`.
4531  """
4532  return self.size()
4533 
4534  def get_name(self, i):
4535  """Return the i-th parameter name in the parameter description `self`.
4536  """
4537  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
4538 
4539  def get_kind(self, n):
4540  """Return the kind of the parameter named `n`.
4541  """
4542  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4543 
4544  def __getitem__(self, arg):
4545  if _is_int(arg):
4546  return self.get_name(arg)
4547  else:
4548  return self.get_kind(arg)
4549 
4550  def __repr__(self):
4551  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
4552 
4553 #########################################
4554 #
4555 # Goals
4556 #
4557 #########################################
4558 
4559 class Goal(Z3PPObject):
4560  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
4561 
4562  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
4563  A goal has a solution if one of its subgoals has a solution.
4564  A goal is unsatisfiable if all subgoals are unsatisfiable.
4565  """
4566 
4567  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
4568  if __debug__:
4569  _z3_assert(goal == None or ctx != None, "If goal is different from None, then ctx must be also different from None")
4570  self.ctx = _get_ctx(ctx)
4571  self.goal = goal
4572  if self.goal == None:
4573  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
4574  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
4575 
4576  def __del__(self):
4577  if self.goal != None:
4578  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
4579 
4580  def depth(self):
4581  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
4582 
4583  >>> x, y = Ints('x y')
4584  >>> g = Goal()
4585  >>> g.add(x == 0, y >= x + 1)
4586  >>> g.depth()
4587  0
4588  >>> r = Then('simplify', 'solve-eqs')(g)
4589  >>> # r has 1 subgoal
4590  >>> len(r)
4591  1
4592  >>> r[0].depth()
4593  2
4594  """
4595  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
4596 
4597  def inconsistent(self):
4598  """Return `True` if `self` contains the `False` constraints.
4599 
4600  >>> x, y = Ints('x y')
4601  >>> g = Goal()
4602  >>> g.inconsistent()
4603  False
4604  >>> g.add(x == 0, x == 1)
4605  >>> g
4606  [x == 0, x == 1]
4607  >>> g.inconsistent()
4608  False
4609  >>> g2 = Tactic('propagate-values')(g)[0]
4610  >>> g2.inconsistent()
4611  True
4612  """
4613  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
4614 
4615  def prec(self):
4616  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
4617 
4618  >>> g = Goal()
4619  >>> g.prec() == Z3_GOAL_PRECISE
4620  True
4621  >>> x, y = Ints('x y')
4622  >>> g.add(x == y + 1)
4623  >>> g.prec() == Z3_GOAL_PRECISE
4624  True
4625  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
4626  >>> g2 = t(g)[0]
4627  >>> g2
4628  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
4629  >>> g2.prec() == Z3_GOAL_PRECISE
4630  False
4631  >>> g2.prec() == Z3_GOAL_UNDER
4632  True
4633  """
4634  return Z3_goal_precision(self.ctx.ref(), self.goal)
4635 
4636  def precision(self):
4637  """Alias for `prec()`.
4638 
4639  >>> g = Goal()
4640  >>> g.precision() == Z3_GOAL_PRECISE
4641  True
4642  """
4643  return self.prec()
4644 
4645  def size(self):
4646  """Return the number of constraints in the goal `self`.
4647 
4648  >>> g = Goal()
4649  >>> g.size()
4650  0
4651  >>> x, y = Ints('x y')
4652  >>> g.add(x == 0, y > x)
4653  >>> g.size()
4654  2
4655  """
4656  return int(Z3_goal_size(self.ctx.ref(), self.goal))
4657 
4658  def __len__(self):
4659  """Return the number of constraints in the goal `self`.
4660 
4661  >>> g = Goal()
4662  >>> len(g)
4663  0
4664  >>> x, y = Ints('x y')
4665  >>> g.add(x == 0, y > x)
4666  >>> len(g)
4667  2
4668  """
4669  return self.size()
4670 
4671  def get(self, i):
4672  """Return a constraint in the goal `self`.
4673 
4674  >>> g = Goal()
4675  >>> x, y = Ints('x y')
4676  >>> g.add(x == 0, y > x)
4677  >>> g.get(0)
4678  x == 0
4679  >>> g.get(1)
4680  y > x
4681  """
4682  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
4683 
4684  def __getitem__(self, arg):
4685  """Return a constraint in the goal `self`.
4686 
4687  >>> g = Goal()
4688  >>> x, y = Ints('x y')
4689  >>> g.add(x == 0, y > x)
4690  >>> g[0]
4691  x == 0
4692  >>> g[1]
4693  y > x
4694  """
4695  if arg >= len(self):
4696  raise IndexError
4697  return self.get(arg)
4698 
4699  def assert_exprs(self, *args):
4700  """Assert constraints into the goal.
4701 
4702  >>> x = Int('x')
4703  >>> g = Goal()
4704  >>> g.assert_exprs(x > 0, x < 2)
4705  >>> g
4706  [x > 0, x < 2]
4707  """
4708  args = _get_args(args)
4709  s = BoolSort(self.ctx)
4710  for arg in args:
4711  arg = s.cast(arg)
4712  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
4713 
4714  def append(self, *args):
4715  """Add constraints.
4716 
4717  >>> x = Int('x')
4718  >>> g = Goal()
4719  >>> g.append(x > 0, x < 2)
4720  >>> g
4721  [x > 0, x < 2]
4722  """
4723  self.assert_exprs(*args)
4724 
4725  def insert(self, *args):
4726  """Add constraints.
4727 
4728  >>> x = Int('x')
4729  >>> g = Goal()
4730  >>> g.insert(x > 0, x < 2)
4731  >>> g
4732  [x > 0, x < 2]
4733  """
4734  self.assert_exprs(*args)
4735 
4736  def add(self, *args):
4737  """Add constraints.
4738 
4739  >>> x = Int('x')
4740  >>> g = Goal()
4741  >>> g.add(x > 0, x < 2)
4742  >>> g
4743  [x > 0, x < 2]
4744  """
4745  self.assert_exprs(*args)
4746 
4747  def __repr__(self):
4748  return obj_to_string(self)
4749 
4750  def sexpr(self):
4751  """Return a textual representation of the s-expression representing the goal."""
4752  return Z3_goal_to_string(self.ctx.ref(), self.goal)
4753 
4754  def translate(self, target):
4755  """Copy goal `self` to context `target`.
4756 
4757  >>> x = Int('x')
4758  >>> g = Goal()
4759  >>> g.add(x > 10)
4760  >>> g
4761  [x > 10]
4762  >>> c2 = Context()
4763  >>> g2 = g.translate(c2)
4764  >>> g2
4765  [x > 10]
4766  >>> g.ctx == main_ctx()
4767  True
4768  >>> g2.ctx == c2
4769  True
4770  >>> g2.ctx == main_ctx()
4771  False
4772  """
4773  if __debug__:
4774  _z3_assert(isinstance(target, Context), "target must be a context")
4775  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
4776 
4777  def simplify(self, *arguments, **keywords):
4778  """Return a new simplified goal.
4779 
4780  This method is essentially invoking the simplify tactic.
4781 
4782  >>> g = Goal()
4783  >>> x = Int('x')
4784  >>> g.add(x + 1 >= 2)
4785  >>> g
4786  [x + 1 >= 2]
4787  >>> g2 = g.simplify()
4788  >>> g2
4789  [x >= 1]
4790  >>> # g was not modified
4791  >>> g
4792  [x + 1 >= 2]
4793  """
4794  t = Tactic('simplify')
4795  return t.apply(self, *arguments, **keywords)[0]
4796 
4797  def as_expr(self):
4798  """Return goal `self` as a single Z3 expression.
4799 
4800  >>> x = Int('x')
4801  >>> g = Goal()
4802  >>> g.as_expr()
4803  True
4804  >>> g.add(x > 1)
4805  >>> g.as_expr()
4806  x > 1
4807  >>> g.add(x < 10)
4808  >>> g.as_expr()
4809  And(x > 1, x < 10)
4810  """
4811  sz = len(self)
4812  if sz == 0:
4813  return BoolVal(True, self.ctx)
4814  elif sz == 1:
4815  return self.get(0)
4816  else:
4817  return And([ self.get(i) for i in range(len(self)) ])
4818 
4819 #########################################
4820 #
4821 # AST Vector
4822 #
4823 #########################################
4824 class AstVector(Z3PPObject):
4825  """A collection (vector) of ASTs."""
4826 
4827  def __init__(self, v=None, ctx=None):
4828  self.vector = None
4829  if v == None:
4830  self.ctx = _get_ctx(ctx)
4831  self.vector = Z3_mk_ast_vector(self.ctx.ref())
4832  else:
4833  self.vector = v
4834  assert ctx != None
4835  self.ctx = ctx
4836  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
4837 
4838  def __del__(self):
4839  if self.vector != None:
4840  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
4841 
4842  def __len__(self):
4843  """Return the size of the vector `self`.
4844 
4845  >>> A = AstVector()
4846  >>> len(A)
4847  0
4848  >>> A.push(Int('x'))
4849  >>> A.push(Int('x'))
4850  >>> len(A)
4851  2
4852  """
4853  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
4854 
4855  def __getitem__(self, i):
4856  """Return the AST at position `i`.
4857 
4858  >>> A = AstVector()
4859  >>> A.push(Int('x') + 1)
4860  >>> A.push(Int('y'))
4861  >>> A[0]
4862  x + 1
4863  >>> A[1]
4864  y
4865  """
4866  if i >= self.__len__():
4867  raise IndexError
4868  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
4869 
4870  def __setitem__(self, i, v):
4871  """Update AST at position `i`.
4872 
4873  >>> A = AstVector()
4874  >>> A.push(Int('x') + 1)
4875  >>> A.push(Int('y'))
4876  >>> A[0]
4877  x + 1
4878  >>> A[0] = Int('x')
4879  >>> A[0]
4880  x
4881  """
4882  if i >= self.__len__():
4883  raise IndexError
4884  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
4885 
4886  def push(self, v):
4887  """Add `v` in the end of the vector.
4888 
4889  >>> A = AstVector()
4890  >>> len(A)
4891  0
4892  >>> A.push(Int('x'))
4893  >>> len(A)
4894  1
4895  """
4896  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
4897 
4898  def resize(self, sz):
4899  """Resize the vector to `sz` elements.
4900 
4901  >>> A = AstVector()
4902  >>> A.resize(10)
4903  >>> len(A)
4904  10
4905  >>> for i in range(10): A[i] = Int('x')
4906  >>> A[5]
4907  x
4908  """
4909  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
4910 
4911  def __contains__(self, item):
4912  """Return `True` if the vector contains `item`.
4913 
4914  >>> x = Int('x')
4915  >>> A = AstVector()
4916  >>> x in A
4917  False
4918  >>> A.push(x)
4919  >>> x in A
4920  True
4921  >>> (x+1) in A
4922  False
4923  >>> A.push(x+1)
4924  >>> (x+1) in A
4925  True
4926  >>> A
4927  [x, x + 1]
4928  """
4929  for elem in self:
4930  if elem.eq(item):
4931  return True
4932  return False
4933 
4934  def translate(self, other_ctx):
4935  """Copy vector `self` to context `other_ctx`.
4936 
4937  >>> x = Int('x')
4938  >>> A = AstVector()
4939  >>> A.push(x)
4940  >>> c2 = Context()
4941  >>> B = A.translate(c2)
4942  >>> B
4943  [x]
4944  """
4945  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
4946 
4947  def __repr__(self):
4948  return obj_to_string(self)
4949 
4950  def sexpr(self):
4951  """Return a textual representation of the s-expression representing the vector."""
4952  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
4953 
4954 #########################################
4955 #
4956 # AST Map
4957 #
4958 #########################################
4959 class AstMap:
4960  """A mapping from ASTs to ASTs."""
4961 
4962  def __init__(self, m=None, ctx=None):
4963  self.map = None
4964  if m == None:
4965  self.ctx = _get_ctx(ctx)
4966  self.map = Z3_mk_ast_map(self.ctx.ref())
4967  else:
4968  self.map = m
4969  assert ctx != None
4970  self.ctx = ctx
4971  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
4972 
4973  def __del__(self):
4974  if self.map != None:
4975  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
4976 
4977  def __len__(self):
4978  """Return the size of the map.
4979 
4980  >>> M = AstMap()
4981  >>> len(M)
4982  0
4983  >>> x = Int('x')
4984  >>> M[x] = IntVal(1)
4985  >>> len(M)
4986  1
4987  """
4988  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
4989 
4990  def __contains__(self, key):
4991  """Return `True` if the map contains key `key`.
4992 
4993  >>> M = AstMap()
4994  >>> x = Int('x')
4995  >>> M[x] = x + 1
4996  >>> x in M
4997  True
4998  >>> x+1 in M
4999  False
5000  """
5001  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5002 
5003  def __getitem__(self, key):
5004  """Retrieve the value associated with key `key`.
5005 
5006  >>> M = AstMap()
5007  >>> x = Int('x')
5008  >>> M[x] = x + 1
5009  >>> M[x]
5010  x + 1
5011  """
5012  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5013 
5014  def __setitem__(self, k, v):
5015  """Add/Update key `k` with value `v`.
5016 
5017  >>> M = AstMap()
5018  >>> x = Int('x')
5019  >>> M[x] = x + 1
5020  >>> len(M)
5021  1
5022  >>> M[x]
5023  x + 1
5024  >>> M[x] = IntVal(1)
5025  >>> M[x]
5026  1
5027  """
5028  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5029 
5030  def __repr__(self):
5031  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5032 
5033  def erase(self, k):
5034  """Remove the entry associated with key `k`.
5035 
5036  >>> M = AstMap()
5037  >>> x = Int('x')
5038  >>> M[x] = x + 1
5039  >>> len(M)
5040  1
5041  >>> M.erase(x)
5042  >>> len(M)
5043  0
5044  """
5045  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5046 
5047  def reset(self):
5048  """Remove all entries from the map.
5049 
5050  >>> M = AstMap()
5051  >>> x = Int('x')
5052  >>> M[x] = x + 1
5053  >>> M[x+x] = IntVal(1)
5054  >>> len(M)
5055  2
5056  >>> M.reset()
5057  >>> len(M)
5058  0
5059  """
5060  Z3_ast_map_reset(self.ctx.ref(), self.map)
5061 
5062  def keys(self):
5063  """Return an AstVector containing all keys in the map.
5064 
5065  >>> M = AstMap()
5066  >>> x = Int('x')
5067  >>> M[x] = x + 1
5068  >>> M[x+x] = IntVal(1)
5069  >>> M.keys()
5070  [x, x + x]
5071  """
5072  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5073 
5074 #########################################
5075 #
5076 # Model
5077 #
5078 #########################################
5079 
5080 class FuncEntry:
5081  """Store the value of the interpretation of a function in a particular point."""
5082 
5083  def __init__(self, entry, ctx):
5084  self.entry = entry
5085  self.ctx = ctx
5086  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5087 
5088  def __del__(self):
5089  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5090 
5091  def num_args(self):
5092  """Return the number of arguments in the given entry.
5093 
5094  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5095  >>> s = Solver()
5096  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5097  >>> s.check()
5098  sat
5099  >>> m = s.model()
5100  >>> f_i = m[f]
5101  >>> f_i.num_entries()
5102  3
5103  >>> e = f_i.entry(0)
5104  >>> e.num_args()
5105  2
5106  """
5107  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5108 
5109  def arg_value(self, idx):
5110  """Return the value of argument `idx`.
5111 
5112  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5113  >>> s = Solver()
5114  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5115  >>> s.check()
5116  sat
5117  >>> m = s.model()
5118  >>> f_i = m[f]
5119  >>> f_i.num_entries()
5120  3
5121  >>> e = f_i.entry(0)
5122  >>> e
5123  [0, 1, 10]
5124  >>> e.num_args()
5125  2
5126  >>> e.arg_value(0)
5127  0
5128  >>> e.arg_value(1)
5129  1
5130  >>> try:
5131  ... e.arg_value(2)
5132  ... except IndexError:
5133  ... print("index error")
5134  index error
5135  """
5136  if idx >= self.num_args():
5137  raise IndexError
5138  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5139 
5140  def value(self):
5141  """Return the value of the function at point `self`.
5142 
5143  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5144  >>> s = Solver()
5145  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5146  >>> s.check()
5147  sat
5148  >>> m = s.model()
5149  >>> f_i = m[f]
5150  >>> f_i.num_entries()
5151  3
5152  >>> e = f_i.entry(0)
5153  >>> e
5154  [0, 1, 10]
5155  >>> e.num_args()
5156  2
5157  >>> e.value()
5158  10
5159  """
5160  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5161 
5162  def as_list(self):
5163  """Return entry `self` as a Python list.
5164  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5165  >>> s = Solver()
5166  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5167  >>> s.check()
5168  sat
5169  >>> m = s.model()
5170  >>> f_i = m[f]
5171  >>> f_i.num_entries()
5172  3
5173  >>> e = f_i.entry(0)
5174  >>> e.as_list()
5175  [0, 1, 10]
5176  """
5177  args = [ self.arg_value(i) for i in range(self.num_args())]
5178  args.append(self.value())
5179  return args
5180 
5181  def __repr__(self):
5182  return repr(self.as_list())
5183 
5184 class FuncInterp(Z3PPObject):
5185  """Stores the interpretation of a function in a Z3 model."""
5186 
5187  def __init__(self, f, ctx):
5188  self.f = f
5189  self.ctx = ctx
5190  if self.f != None:
5191  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5192 
5193  def __del__(self):
5194  if self.f != None:
5195  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5196 
5197  def else_value(self):
5198  """
5199  Return the `else` value for a function interpretation.
5200  Return None if Z3 did not specify the `else` value for
5201  this object.
5202 
5203  >>> f = Function('f', IntSort(), IntSort())
5204  >>> s = Solver()
5205  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5206  >>> s.check()
5207  sat
5208  >>> m = s.model()
5209  >>> m[f]
5210  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5211  >>> m[f].else_value()
5212  1
5213  """
5214  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5215  if r:
5216  return _to_expr_ref(r, self.ctx)
5217  else:
5218  return None
5219 
5220  def num_entries(self):
5221  """Return the number of entries/points in the function interpretation `self`.
5222 
5223  >>> f = Function('f', IntSort(), IntSort())
5224  >>> s = Solver()
5225  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5226  >>> s.check()
5227  sat
5228  >>> m = s.model()
5229  >>> m[f]
5230  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5231  >>> m[f].num_entries()
5232  3
5233  """
5234  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5235 
5236  def arity(self):
5237  """Return the number of arguments for each entry in the function interpretation `self`.
5238 
5239  >>> f = Function('f', IntSort(), IntSort())
5240  >>> s = Solver()
5241  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5242  >>> s.check()
5243  sat
5244  >>> m = s.model()
5245  >>> m[f].arity()
5246  1
5247  """
5248  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5249 
5250  def entry(self, idx):
5251  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5252 
5253  >>> f = Function('f', IntSort(), IntSort())
5254  >>> s = Solver()
5255  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5256  >>> s.check()
5257  sat
5258  >>> m = s.model()
5259  >>> m[f]
5260  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5261  >>> m[f].num_entries()
5262  3
5263  >>> m[f].entry(0)
5264  [0, 1]
5265  >>> m[f].entry(1)
5266  [1, 1]
5267  >>> m[f].entry(2)
5268  [2, 0]
5269  """
5270  if idx >= self.num_entries():
5271  raise IndexError
5272  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5273 
5274  def as_list(self):
5275  """Return the function interpretation as a Python list.
5276  >>> f = Function('f', IntSort(), IntSort())
5277  >>> s = Solver()
5278  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5279  >>> s.check()
5280  sat
5281  >>> m = s.model()
5282  >>> m[f]
5283  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5284  >>> m[f].as_list()
5285  [[0, 1], [1, 1], [2, 0], 1]
5286  """
5287  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5288  r.append(self.else_value())
5289  return r
5290 
5291  def __repr__(self):
5292  return obj_to_string(self)
5293 
5294 class ModelRef(Z3PPObject):
5295  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5296 
5297  def __init__(self, m, ctx):
5298  assert ctx != None
5299  self.model = m
5300  self.ctx = ctx
5301  Z3_model_inc_ref(self.ctx.ref(), self.model)
5302 
5303  def __del__(self):
5304  Z3_model_dec_ref(self.ctx.ref(), self.model)
5305 
5306  def __repr__(self):
5307  return obj_to_string(self)
5308 
5309  def sexpr(self):
5310  """Return a textual representation of the s-expression representing the model."""
5311  return Z3_model_to_string(self.ctx.ref(), self.model)
5312 
5313  def eval(self, t, model_completion=False):
5314  """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`.
5315 
5316  >>> x = Int('x')
5317  >>> s = Solver()
5318  >>> s.add(x > 0, x < 2)
5319  >>> s.check()
5320  sat
5321  >>> m = s.model()
5322  >>> m.eval(x + 1)
5323  2
5324  >>> m.eval(x == 1)
5325  True
5326  >>> y = Int('y')
5327  >>> m.eval(y + x)
5328  1 + y
5329  >>> m.eval(y)
5330  y
5331  >>> m.eval(y, model_completion=True)
5332  0
5333  >>> # Now, m contains an interpretation for y
5334  >>> m.eval(y + x)
5335  1
5336  """
5337  r = (Ast * 1)()
5338  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5339  return _to_expr_ref(r[0], self.ctx)
5340  raise Z3Exception("failed to evaluate expression in the model")
5341 
5342  def evaluate(self, t, model_completion=False):
5343  """Alias for `eval`.
5344 
5345  >>> x = Int('x')
5346  >>> s = Solver()
5347  >>> s.add(x > 0, x < 2)
5348  >>> s.check()
5349  sat
5350  >>> m = s.model()
5351  >>> m.evaluate(x + 1)
5352  2
5353  >>> m.evaluate(x == 1)
5354  True
5355  >>> y = Int('y')
5356  >>> m.evaluate(y + x)
5357  1 + y
5358  >>> m.evaluate(y)
5359  y
5360  >>> m.evaluate(y, model_completion=True)
5361  0
5362  >>> # Now, m contains an interpretation for y
5363  >>> m.evaluate(y + x)
5364  1
5365  """
5366  return self.eval(t, model_completion)
5367 
5368  def __len__(self):
5369  """Return the number of constant and function declarations in the model `self`.
5370 
5371  >>> f = Function('f', IntSort(), IntSort())
5372  >>> x = Int('x')
5373  >>> s = Solver()
5374  >>> s.add(x > 0, f(x) != x)
5375  >>> s.check()
5376  sat
5377  >>> m = s.model()
5378  >>> len(m)
5379  2
5380  """
5381  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5382 
5383  def get_interp(self, decl):
5384  """Return the interpretation for a given declaration or constant.
5385 
5386  >>> f = Function('f', IntSort(), IntSort())
5387  >>> x = Int('x')
5388  >>> s = Solver()
5389  >>> s.add(x > 0, x < 2, f(x) == 0)
5390  >>> s.check()
5391  sat
5392  >>> m = s.model()
5393  >>> m[x]
5394  1
5395  >>> m[f]
5396  [1 -> 0, else -> 0]
5397  """
5398  if __debug__:
5399  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
5400  if is_const(decl):
5401  decl = decl.decl()
5402  try:
5403  if decl.arity() == 0:
5404  r = _to_expr_ref(Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
5405  if is_as_array(r):
5406  return self.get_interp(get_as_array_func(r))
5407  else:
5408  return r
5409  else:
5410  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
5411  except Z3Exception:
5412  return None
5413 
5414  def num_sorts(self):
5415  """Return the number of unintepreted sorts that contain an interpretation in the model `self`.
5416 
5417  >>> A = DeclareSort('A')
5418  >>> a, b = Consts('a b', A)
5419  >>> s = Solver()
5420  >>> s.add(a != b)
5421  >>> s.check()
5422  sat
5423  >>> m = s.model()
5424  >>> m.num_sorts()
5425  1
5426  """
5427  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
5428 
5429  def get_sort(self, idx):
5430  """Return the unintepreted sort at position `idx` < self.num_sorts().
5431 
5432  >>> A = DeclareSort('A')
5433  >>> B = DeclareSort('B')
5434  >>> a1, a2 = Consts('a1 a2', A)
5435  >>> b1, b2 = Consts('b1 b2', B)
5436  >>> s = Solver()
5437  >>> s.add(a1 != a2, b1 != b2)
5438  >>> s.check()
5439  sat
5440  >>> m = s.model()
5441  >>> m.num_sorts()
5442  2
5443  >>> m.get_sort(0)
5444  A
5445  >>> m.get_sort(1)
5446  B
5447  """
5448  if idx >= self.num_sorts():
5449  raise IndexError
5450  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
5451 
5452  def sorts(self):
5453  """Return all uninterpreted sorts that have an interpretation in the model `self`.
5454 
5455  >>> A = DeclareSort('A')
5456  >>> B = DeclareSort('B')
5457  >>> a1, a2 = Consts('a1 a2', A)
5458  >>> b1, b2 = Consts('b1 b2', B)
5459  >>> s = Solver()
5460  >>> s.add(a1 != a2, b1 != b2)
5461  >>> s.check()
5462  sat
5463  >>> m = s.model()
5464  >>> m.sorts()
5465  [A, B]
5466  """
5467  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
5468 
5469  def get_universe(self, s):
5470  """Return the intepretation for the uninterpreted sort `s` in the model `self`.
5471 
5472  >>> A = DeclareSort('A')
5473  >>> a, b = Consts('a b', A)
5474  >>> s = Solver()
5475  >>> s.add(a != b)
5476  >>> s.check()
5477  sat
5478  >>> m = s.model()
5479  >>> m.get_universe(A)
5480  [A!val!0, A!val!1]
5481  """
5482  if __debug__:
5483  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
5484  try:
5485  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
5486  except Z3Exception:
5487  return None
5488 
5489  def __getitem__(self, idx):
5490  """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 interpreation is returned.
5491 
5492  The elements can be retrieved using position or the actual declaration.
5493 
5494  >>> f = Function('f', IntSort(), IntSort())
5495  >>> x = Int('x')
5496  >>> s = Solver()
5497  >>> s.add(x > 0, x < 2, f(x) == 0)
5498  >>> s.check()
5499  sat
5500  >>> m = s.model()
5501  >>> len(m)
5502  2
5503  >>> m[0]
5504  x
5505  >>> m[1]
5506  f
5507  >>> m[x]
5508  1
5509  >>> m[f]
5510  [1 -> 0, else -> 0]
5511  >>> for d in m: print("%s -> %s" % (d, m[d]))
5512  x -> 1
5513  f -> [1 -> 0, else -> 0]
5514  """
5515  if isinstance(idx, int):
5516  if idx >= len(self):
5517  raise IndexError
5518  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
5519  if (idx < num_consts):
5520  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
5521  else:
5522  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
5523  if isinstance(idx, FuncDeclRef):
5524  return self.get_interp(idx)
5525  if is_const(idx):
5526  return self.get_interp(idx.decl())
5527  if isinstance(idx, SortRef):
5528  return self.get_universe(idx)
5529  if __debug__:
5530  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
5531  return None
5532 
5533  def decls(self):
5534  """Return a list with all symbols that have an interpreation in the model `self`.
5535  >>> f = Function('f', IntSort(), IntSort())
5536  >>> x = Int('x')
5537  >>> s = Solver()
5538  >>> s.add(x > 0, x < 2, f(x) == 0)
5539  >>> s.check()
5540  sat
5541  >>> m = s.model()
5542  >>> m.decls()
5543  [x, f]
5544  """
5545  r = []
5546  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
5547  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
5548  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
5549  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
5550  return r
5551 
5552 def is_as_array(n):
5553  """Return true if n is a Z3 expression of the form (_ as-array f)."""
5554  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
5555 
5556 def get_as_array_func(n):
5557  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
5558  if __debug__:
5559  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
5560  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
5561 
5562 #########################################
5563 #
5564 # Statistics
5565 #
5566 #########################################
5567 class Statistics:
5568  """Statistics for `Solver.check()`."""
5569 
5570  def __init__(self, stats, ctx):
5571  self.stats = stats
5572  self.ctx = ctx
5573  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
5574 
5575  def __del__(self):
5576  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
5577 
5578  def __repr__(self):
5579  if in_html_mode():
5580  out = io.StringIO()
5581  even = True
5582  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
5583  for k, v in self:
5584  if even:
5585  out.write(u('<tr style="background-color:#CFCFCF">'))
5586  even = False
5587  else:
5588  out.write(u('<tr>'))
5589  even = True
5590  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
5591  out.write(u('</table>'))
5592  return out.getvalue()
5593  else:
5594  return Z3_stats_to_string(self.ctx.ref(), self.stats)
5595 
5596  def __len__(self):
5597  """Return the number of statistical counters.
5598 
5599  >>> x = Int('x')
5600  >>> s = Then('simplify', 'nlsat').solver()
5601  >>> s.add(x > 0)
5602  >>> s.check()
5603  sat
5604  >>> st = s.statistics()
5605  >>> len(st)
5606  2
5607  """
5608  return int(Z3_stats_size(self.ctx.ref(), self.stats))
5609 
5610  def __getitem__(self, idx):
5611  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
5612 
5613  >>> x = Int('x')
5614  >>> s = Then('simplify', 'nlsat').solver()
5615  >>> s.add(x > 0)
5616  >>> s.check()
5617  sat
5618  >>> st = s.statistics()
5619  >>> len(st)
5620  2
5621  >>> st[0]
5622  ('nlsat propagations', 2)
5623  >>> st[1]
5624  ('nlsat stages', 2)
5625  """
5626  if idx >= len(self):
5627  raise IndexError
5628  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5629  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5630  else:
5631  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5632  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
5633 
5634  def keys(self):
5635  """Return the list of statistical counters.
5636 
5637  >>> x = Int('x')
5638  >>> s = Then('simplify', 'nlsat').solver()
5639  >>> s.add(x > 0)
5640  >>> s.check()
5641  sat
5642  >>> st = s.statistics()
5643  >>> st.keys()
5644  ['nlsat propagations', 'nlsat stages']
5645  """
5646  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
5647 
5648  def get_key_value(self, key):
5649  """Return the value of a particular statistical counter.
5650 
5651  >>> x = Int('x')
5652  >>> s = Then('simplify', 'nlsat').solver()
5653  >>> s.add(x > 0)
5654  >>> s.check()
5655  sat
5656  >>> st = s.statistics()
5657  >>> st.get_key_value('nlsat propagations')
5658  2
5659  """
5660  for idx in range(len(self)):
5661  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
5662  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5663  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5664  else:
5665  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5666  raise Z3Exception("unknown key")
5667 
5668  def __getattr__(self, name):
5669  """Access the value of statistical using attributes.
5670 
5671  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
5672  we should use '_' (e.g., 'nlsat_propagations').
5673 
5674  >>> x = Int('x')
5675  >>> s = Then('simplify', 'nlsat').solver()
5676  >>> s.add(x > 0)
5677  >>> s.check()
5678  sat
5679  >>> st = s.statistics()
5680  >>> st.keys()
5681  ['nlsat propagations', 'nlsat stages']
5682  >>> st.nlsat_propagations
5683  2
5684  >>> st.nlsat_stages
5685  2
5686  """
5687  key = name.replace('_', ' ')
5688  try:
5689  return self.get_key_value(key)
5690  except Z3Exception:
5691  raise AttributeError
5692 
5693 #########################################
5694 #
5695 # Solver
5696 #
5697 #########################################
5698 class CheckSatResult:
5699  """Represents the result of a satisfiability check: sat, unsat, unknown.
5700 
5701  >>> s = Solver()
5702  >>> s.check()
5703  sat
5704  >>> r = s.check()
5705  >>> isinstance(r, CheckSatResult)
5706  True
5707  """
5708 
5709  def __init__(self, r):
5710  self.r = r
5711 
5712  def __eq__(self, other):
5713  return isinstance(other, CheckSatResult) and self.r == other.r
5714 
5715  def __ne__(self, other):
5716  return not self.__eq__(other)
5717 
5718  def __repr__(self):
5719  if in_html_mode():
5720  if self.r == Z3_L_TRUE:
5721  return "<b>sat</b>"
5722  elif self.r == Z3_L_FALSE:
5723  return "<b>unsat</b>"
5724  else:
5725  return "<b>unknown</b>"
5726  else:
5727  if self.r == Z3_L_TRUE:
5728  return "sat"
5729  elif self.r == Z3_L_FALSE:
5730  return "unsat"
5731  else:
5732  return "unknown"
5733 
5734 sat = CheckSatResult(Z3_L_TRUE)
5735 unsat = CheckSatResult(Z3_L_FALSE)
5736 unknown = CheckSatResult(Z3_L_UNDEF)
5737 
5738 class Solver(Z3PPObject):
5739  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
5740 
5741  def __init__(self, solver=None, ctx=None):
5742  assert solver == None or ctx != None
5743  self.ctx = _get_ctx(ctx)
5744  self.solver = None
5745  if solver == None:
5746  self.solver = Z3_mk_solver(self.ctx.ref())
5747  else:
5748  self.solver = solver
5749  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
5750 
5751  def __del__(self):
5752  if self.solver != None:
5753  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
5754 
5755  def set(self, *args, **keys):
5756  """Set a configuration option. The method `help()` return a string containing all available options.
5757 
5758  >>> s = Solver()
5759  >>> # The option MBQI can be set using three different approaches.
5760  >>> s.set(mbqi=True)
5761  >>> s.set('MBQI', True)
5762  >>> s.set(':mbqi', True)
5763  """
5764  p = args2params(args, keys, self.ctx)
5765  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
5766 
5767  def push(self):
5768  """Create a backtracking point.
5769 
5770  >>> x = Int('x')
5771  >>> s = Solver()
5772  >>> s.add(x > 0)
5773  >>> s
5774  [x > 0]
5775  >>> s.push()
5776  >>> s.add(x < 1)
5777  >>> s
5778  [x > 0, x < 1]
5779  >>> s.check()
5780  unsat
5781  >>> s.pop()
5782  >>> s.check()
5783  sat
5784  >>> s
5785  [x > 0]
5786  """
5787  Z3_solver_push(self.ctx.ref(), self.solver)
5788 
5789  def pop(self, num=1):
5790  """Backtrack \c num backtracking points.
5791 
5792  >>> x = Int('x')
5793  >>> s = Solver()
5794  >>> s.add(x > 0)
5795  >>> s
5796  [x > 0]
5797  >>> s.push()
5798  >>> s.add(x < 1)
5799  >>> s
5800  [x > 0, x < 1]
5801  >>> s.check()
5802  unsat
5803  >>> s.pop()
5804  >>> s.check()
5805  sat
5806  >>> s
5807  [x > 0]
5808  """
5809  Z3_solver_pop(self.ctx.ref(), self.solver, num)
5810 
5811  def reset(self):
5812  """Remove all asserted constraints and backtracking points created using `push()`.
5813 
5814  >>> x = Int('x')
5815  >>> s = Solver()
5816  >>> s.add(x > 0)
5817  >>> s
5818  [x > 0]
5819  >>> s.reset()
5820  >>> s
5821  []
5822  """
5823  Z3_solver_reset(self.ctx.ref(), self.solver)
5824 
5825  def assert_exprs(self, *args):
5826  """Assert constraints into the solver.
5827 
5828  >>> x = Int('x')
5829  >>> s = Solver()
5830  >>> s.assert_exprs(x > 0, x < 2)
5831  >>> s
5832  [x > 0, x < 2]
5833  """
5834  args = _get_args(args)
5835  s = BoolSort(self.ctx)
5836  for arg in args:
5837  if isinstance(arg, Goal) or isinstance(arg, AstVector):
5838  for f in arg:
5839  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
5840  else:
5841  arg = s.cast(arg)
5842  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
5843 
5844  def add(self, *args):
5845  """Assert constraints into the solver.
5846 
5847  >>> x = Int('x')
5848  >>> s = Solver()
5849  >>> s.add(x > 0, x < 2)
5850  >>> s
5851  [x > 0, x < 2]
5852  """
5853  self.assert_exprs(*args)
5854 
5855  def append(self, *args):
5856  """Assert constraints into the solver.
5857 
5858  >>> x = Int('x')
5859  >>> s = Solver()
5860  >>> s.append(x > 0, x < 2)
5861  >>> s
5862  [x > 0, x < 2]
5863  """
5864  self.assert_exprs(*args)
5865 
5866  def insert(self, *args):
5867  """Assert constraints into the solver.
5868 
5869  >>> x = Int('x')
5870  >>> s = Solver()
5871  >>> s.insert(x > 0, x < 2)
5872  >>> s
5873  [x > 0, x < 2]
5874  """
5875  self.assert_exprs(*args)
5876 
5877  def assert_and_track(self, a, p):
5878  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
5879 
5880  If `p` is a string, it will be automatically converted into a Boolean constant.
5881 
5882  >>> x = Int('x')
5883  >>> p3 = Bool('p3')
5884  >>> s = Solver()
5885  >>> s.set(unsat_core=True)
5886  >>> s.assert_and_track(x > 0, 'p1')
5887  >>> s.assert_and_track(x != 1, 'p2')
5888  >>> s.assert_and_track(x < 0, p3)
5889  >>> print(s.check())
5890  unsat
5891  >>> c = s.unsat_core()
5892  >>> len(c)
5893  2
5894  >>> Bool('p1') in c
5895  True
5896  >>> Bool('p2') in c
5897  False
5898  >>> p3 in c
5899  True
5900  """
5901  if isinstance(p, str):
5902  p = Bool(p, self.ctx)
5903  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
5904  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
5905  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
5906 
5907  def check(self, *assumptions):
5908  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
5909 
5910  >>> x = Int('x')
5911  >>> s = Solver()
5912  >>> s.check()
5913  sat
5914  >>> s.add(x > 0, x < 2)
5915  >>> s.check()
5916  sat
5917  >>> s.model()
5918  [x = 1]
5919  >>> s.add(x < 1)
5920  >>> s.check()
5921  unsat
5922  >>> s.reset()
5923  >>> s.add(2**x == 4)
5924  >>> s.check()
5925  unknown
5926  """
5927  assumptions = _get_args(assumptions)
5928  num = len(assumptions)
5929  _assumptions = (Ast * num)()
5930  for i in range(num):
5931  _assumptions[i] = assumptions[i].as_ast()
5932  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
5933  return CheckSatResult(r)
5934 
5935  def model(self):
5936  """Return a model for the last `check()`.
5937 
5938  This function raises an exception if
5939  a model is not available (e.g., last `check()` returned unsat).
5940 
5941  >>> s = Solver()
5942  >>> a = Int('a')
5943  >>> s.add(a + 2 == 0)
5944  >>> s.check()
5945  sat
5946  >>> s.model()
5947  [a = -2]
5948  """
5949  try:
5950  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
5951  except Z3Exception:
5952  raise Z3Exception("model is not available")
5953 
5954  def unsat_core(self):
5955  """Return a subset (as an AST vector) of the assumptions provided to the last check().
5956 
5957  These are the assumptions Z3 used in the unsatisfiability proof.
5958  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
5959  They may be also used to "retract" assumptions. Note that, assumptions are not really
5960  "soft constraints", but they can be used to implement them.
5961 
5962  >>> p1, p2, p3 = Bools('p1 p2 p3')
5963  >>> x, y = Ints('x y')
5964  >>> s = Solver()
5965  >>> s.add(Implies(p1, x > 0))
5966  >>> s.add(Implies(p2, y > x))
5967  >>> s.add(Implies(p2, y < 1))
5968  >>> s.add(Implies(p3, y > -3))
5969  >>> s.check(p1, p2, p3)
5970  unsat
5971  >>> core = s.unsat_core()
5972  >>> len(core)
5973  2
5974  >>> p1 in core
5975  True
5976  >>> p2 in core
5977  True
5978  >>> p3 in core
5979  False
5980  >>> # "Retracting" p2
5981  >>> s.check(p1, p3)
5982  sat
5983  """
5984  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
5985 
5986  def proof(self):
5987  """Return a proof for the last `check()`. Proof construction must be enabled."""
5988  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
5989 
5990  def assertions(self):
5991  """Return an AST vector containing all added constraints.
5992 
5993  >>> s = Solver()
5994  >>> s.assertions()
5995  []
5996  >>> a = Int('a')
5997  >>> s.add(a > 0)
5998  >>> s.add(a < 10)
5999  >>> s.assertions()
6000  [a > 0, a < 10]
6001  """
6002  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6003 
6004  def statistics(self):
6005  """Return statistics for the last `check()`.
6006 
6007  >>> s = SimpleSolver()
6008  >>> x = Int('x')
6009  >>> s.add(x > 0)
6010  >>> s.check()
6011  sat
6012  >>> st = s.statistics()
6013  >>> st.get_key_value('final checks')
6014  1
6015  >>> len(st) > 0
6016  True
6017  >>> st[0] != 0
6018  True
6019  """
6020  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6021 
6022  def reason_unknown(self):
6023  """Return a string describing why the last `check()` returned `unknown`.
6024 
6025  >>> x = Int('x')
6026  >>> s = SimpleSolver()
6027  >>> s.add(2**x == 4)
6028  >>> s.check()
6029  unknown
6030  >>> s.reason_unknown()
6031  '(incomplete (theory arithmetic))'
6032  """
6033  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6034 
6035  def help(self):
6036  """Display a string describing all available options."""
6037  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6038 
6039  def param_descrs(self):
6040  """Return the parameter description set."""
6041  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6042 
6043  def __repr__(self):
6044  """Return a formatted string with all added constraints."""
6045  return obj_to_string(self)
6046 
6047  def sexpr(self):
6048  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6049 
6050  >>> x = Int('x')
6051  >>> s = Solver()
6052  >>> s.add(x > 0)
6053  >>> s.add(x < 2)
6054  >>> r = s.sexpr()
6055  """
6056  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6057 
6058  def to_smt2(self):
6059  """return SMTLIB2 formatted benchmark for solver's assertions"""
6060  es = self.assertions()
6061  sz = len(es)
6062  sz1 = sz
6063  if sz1 > 0:
6064  sz1 -= 1
6065  v = (Ast * sz1)()
6066  for i in range(sz1):
6067  v[i] = es[i].as_ast()
6068  if sz > 0:
6069  e = es[sz1].as_ast()
6070  else:
6071  e = BoolVal(True, self.ctx).as_ast()
6072  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6073 
6074 
6075 
6076 def SolverFor(logic, ctx=None):
6077  """Create a solver customized for the given logic.
6078 
6079  The parameter `logic` is a string. It should be contains
6080  the name of a SMT-LIB logic.
6081  See http://www.smtlib.org/ for the name of all available logics.
6082 
6083  >>> s = SolverFor("QF_LIA")
6084  >>> x = Int('x')
6085  >>> s.add(x > 0)
6086  >>> s.add(x < 2)
6087  >>> s.check()
6088  sat
6089  >>> s.model()
6090  [x = 1]
6091  """
6092  ctx = _get_ctx(ctx)
6093  logic = to_symbol(logic)
6094  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6095 
6096 def SimpleSolver(ctx=None):
6097  """Return a simple general purpose solver with limited amount of preprocessing.
6098 
6099  >>> s = SimpleSolver()
6100  >>> x = Int('x')
6101  >>> s.add(x > 0)
6102  >>> s.check()
6103  sat
6104  """
6105  ctx = _get_ctx(ctx)
6106  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6107 
6108 #########################################
6109 #
6110 # Fixedpoint
6111 #
6112 #########################################
6113 
6115  """Fixedpoint API provides methods for solving with recursive predicates"""
6116 
6117  def __init__(self, fixedpoint=None, ctx=None):
6118  assert fixedpoint == None or ctx != None
6119  self.ctx = _get_ctx(ctx)
6120  self.fixedpoint = None
6121  if fixedpoint == None:
6122  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6123  else:
6124  self.fixedpoint = fixedpoint
6125  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6126  self.vars = []
6127 
6128  def __del__(self):
6129  if self.fixedpoint != None:
6130  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6131 
6132  def set(self, *args, **keys):
6133  """Set a configuration option. The method `help()` return a string containing all available options.
6134  """
6135  p = args2params(args, keys, self.ctx)
6136  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6137 
6138  def help(self):
6139  """Display a string describing all available options."""
6140  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6141 
6142  def param_descrs(self):
6143  """Return the parameter description set."""
6144  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6145 
6146  def assert_exprs(self, *args):
6147  """Assert constraints as background axioms for the fixedpoint solver."""
6148  args = _get_args(args)
6149  s = BoolSort(self.ctx)
6150  for arg in args:
6151  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6152  for f in arg:
6153  f = self.abstract(f)
6154  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6155  else:
6156  arg = s.cast(arg)
6157  arg = self.abstract(arg)
6158  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6159 
6160  def add(self, *args):
6161  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6162  self.assert_exprs(*args)
6163 
6164  def append(self, *args):
6165  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6166  self.assert_exprs(*args)
6167 
6168  def insert(self, *args):
6169  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6170  self.assert_exprs(*args)
6171 
6172  def add_rule(self, head, body = None, name = None):
6173  """Assert rules defining recursive predicates to the fixedpoint solver.
6174  >>> a = Bool('a')
6175  >>> b = Bool('b')
6176  >>> s = Fixedpoint()
6177  >>> s.register_relation(a.decl())
6178  >>> s.register_relation(b.decl())
6179  >>> s.fact(a)
6180  >>> s.rule(b, a)
6181  >>> s.query(b)
6182  sat
6183  """
6184  if name == None:
6185  name = ""
6186  name = to_symbol(name, self.ctx)
6187  if body == None:
6188  head = self.abstract(head)
6189  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6190  else:
6191  body = _get_args(body)
6192  f = self.abstract(Implies(And(body, self.ctx),head))
6193  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6194 
6195  def rule(self, head, body = None, name = None):
6196  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6197  self.add_rule(head, body, name)
6198 
6199  def fact(self, head, name = None):
6200  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6201  self.add_rule(head, None, name)
6202 
6203  def query(self, *query):
6204  """Query the fixedpoint engine whether formula is derivable.
6205  You can also pass an tuple or list of recursive predicates.
6206  """
6207  query = _get_args(query)
6208  sz = len(query)
6209  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6210  _decls = (FuncDecl * sz)()
6211  i = 0
6212  for q in query:
6213  _decls[i] = q.ast
6214  i = i + 1
6215  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6216  else:
6217  if sz == 1:
6218  query = query[0]
6219  else:
6220  query = And(query, self.ctx)
6221  query = self.abstract(query, False)
6222  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6223  return CheckSatResult(r)
6224 
6225  def push(self):
6226  """create a backtracking point for added rules, facts and assertions"""
6227  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6228 
6229  def pop(self):
6230  """restore to previously created backtracking point"""
6231  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
6232 
6233  def update_rule(self, head, body, name):
6234  """update rule"""
6235  if name == None:
6236  name = ""
6237  name = to_symbol(name, self.ctx)
6238  body = _get_args(body)
6239  f = self.abstract(Implies(And(body, self.ctx),head))
6240  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6241 
6242  def get_answer(self):
6243  """Retrieve answer from last query call."""
6244  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
6245  return _to_expr_ref(r, self.ctx)
6246 
6247  def get_num_levels(self, predicate):
6248  """Retrieve number of levels used for predicate in PDR engine"""
6249  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
6250 
6251  def get_cover_delta(self, level, predicate):
6252  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
6253  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
6254  return _to_expr_ref(r, self.ctx)
6255 
6256  def add_cover(self, level, predicate, property):
6257  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
6258  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
6259 
6260  def register_relation(self, *relations):
6261  """Register relation as recursive"""
6262  relations = _get_args(relations)
6263  for f in relations:
6264  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
6265 
6266  def set_predicate_representation(self, f, *representations):
6267  """Control how relation is represented"""
6268  representations = _get_args(representations)
6269  representations = [to_symbol(s) for s in representations]
6270  sz = len(representations)
6271  args = (Symbol * sz)()
6272  for i in range(sz):
6273  args[i] = representations[i]
6274  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
6275 
6276  def parse_string(self, s):
6277  """Parse rules and queries from a string"""
6278  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
6279 
6280  def parse_file(self, f):
6281  """Parse rules and queries from a file"""
6282  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
6283 
6284  def get_rules(self):
6285  """retrieve rules that have been added to fixedpoint context"""
6286  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
6287 
6288  def get_assertions(self):
6289  """retrieve assertions that have been added to fixedpoint context"""
6290  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
6291 
6292  def __repr__(self):
6293  """Return a formatted string with all added rules and constraints."""
6294  return self.sexpr()
6295 
6296  def sexpr(self):
6297  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6298  """
6299  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
6300 
6301  def to_string(self, queries):
6302  """Return a formatted string (in Lisp-like format) with all added constraints.
6303  We say the string is in s-expression format.
6304  Include also queries.
6305  """
6306  args, len = _to_ast_array(queries)
6307  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
6308 
6309  def statistics(self):
6310  """Return statistics for the last `query()`.
6311  """
6312  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
6313 
6314  def reason_unknown(self):
6315  """Return a string describing why the last `query()` returned `unknown`.
6316  """
6317  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
6318 
6319  def declare_var(self, *vars):
6320  """Add variable or several variables.
6321  The added variable or variables will be bound in the rules
6322  and queries
6323  """
6324  vars = _get_args(vars)
6325  for v in vars:
6326  self.vars += [v]
6327 
6328  def abstract(self, fml, is_forall=True):
6329  if self.vars == []:
6330  return fml
6331  if is_forall:
6332  return ForAll(self.vars, fml)
6333  else:
6334  return Exists(self.vars, fml)
6335 
6336 #########################################
6337 #
6338 # ApplyResult
6339 #
6340 #########################################
6342  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
6343 
6344  def __init__(self, result, ctx):
6345  self.result = result
6346  self.ctx = ctx
6347  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
6348 
6349  def __del__(self):
6350  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
6351 
6352  def __len__(self):
6353  """Return the number of subgoals in `self`.
6354 
6355  >>> a, b = Ints('a b')
6356  >>> g = Goal()
6357  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6358  >>> t = Tactic('split-clause')
6359  >>> r = t(g)
6360  >>> len(r)
6361  2
6362  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
6363  >>> len(t(g))
6364  4
6365  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
6366  >>> len(t(g))
6367  1
6368  """
6369  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
6370 
6371  def __getitem__(self, idx):
6372  """Return one of the subgoals stored in ApplyResult object `self`.
6373 
6374  >>> a, b = Ints('a b')
6375  >>> g = Goal()
6376  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6377  >>> t = Tactic('split-clause')
6378  >>> r = t(g)
6379  >>> r[0]
6380  [a == 0, Or(b == 0, b == 1), a > b]
6381  >>> r[1]
6382  [a == 1, Or(b == 0, b == 1), a > b]
6383  """
6384  if idx >= len(self):
6385  raise IndexError
6386  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
6387 
6388  def __repr__(self):
6389  return obj_to_string(self)
6390 
6391  def sexpr(self):
6392  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
6393  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
6394 
6395  def convert_model(self, model, idx=0):
6396  """Convert a model for a subgoal into a model for the original goal.
6397 
6398  >>> a, b = Ints('a b')
6399  >>> g = Goal()
6400  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6401  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6402  >>> r = t(g)
6403  >>> r[0]
6404  [Or(b == 0, b == 1), Not(0 <= b)]
6405  >>> r[1]
6406  [Or(b == 0, b == 1), Not(1 <= b)]
6407  >>> # Remark: the subgoal r[0] is unsatisfiable
6408  >>> # Creating a solver for solving the second subgoal
6409  >>> s = Solver()
6410  >>> s.add(r[1])
6411  >>> s.check()
6412  sat
6413  >>> s.model()
6414  [b = 0]
6415  >>> # Model s.model() does not assign a value to `a`
6416  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6417  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6418  >>> r.convert_model(s.model(), 1)
6419  [b = 0, a = 1]
6420  """
6421  if __debug__:
6422  _z3_assert(idx < len(self), "index out of bounds")
6423  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
6424  return ModelRef(Z3_apply_result_convert_model(self.ctx.ref(), self.result, idx, model.model), self.ctx)
6425 
6426  def as_expr(self):
6427  """Return a Z3 expression consisting of all subgoals.
6428 
6429  >>> x = Int('x')
6430  >>> g = Goal()
6431  >>> g.add(x > 1)
6432  >>> g.add(Or(x == 2, x == 3))
6433  >>> r = Tactic('simplify')(g)
6434  >>> r
6435  [[Not(x <= 1), Or(x == 2, x == 3)]]
6436  >>> r.as_expr()
6437  And(Not(x <= 1), Or(x == 2, x == 3))
6438  >>> r = Tactic('split-clause')(g)
6439  >>> r
6440  [[x > 1, x == 2], [x > 1, x == 3]]
6441  >>> r.as_expr()
6442  Or(And(x > 1, x == 2), And(x > 1, x == 3))
6443  """
6444  sz = len(self)
6445  if sz == 0:
6446  return BoolVal(False, self.ctx)
6447  elif sz == 1:
6448  return self[0].as_expr()
6449  else:
6450  return Or([ self[i].as_expr() for i in range(len(self)) ])
6451 
6452 #########################################
6453 #
6454 # Tactics
6455 #
6456 #########################################
6457 class Tactic:
6458  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
6459 
6460  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
6461  """
6462  def __init__(self, tactic, ctx=None):
6463  self.ctx = _get_ctx(ctx)
6464  self.tactic = None
6465  if isinstance(tactic, TacticObj):
6466  self.tactic = tactic
6467  else:
6468  if __debug__:
6469  _z3_assert(isinstance(tactic, str), "tactic name expected")
6470  try:
6471  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
6472  except Z3Exception:
6473  raise Z3Exception("unknown tactic '%s'" % tactic)
6474  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
6475 
6476  def __del__(self):
6477  if self.tactic != None:
6478  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
6479 
6480  def solver(self):
6481  """Create a solver using the tactic `self`.
6482 
6483  The solver supports the methods `push()` and `pop()`, but it
6484  will always solve each `check()` from scratch.
6485 
6486  >>> t = Then('simplify', 'nlsat')
6487  >>> s = t.solver()
6488  >>> x = Real('x')
6489  >>> s.add(x**2 == 2, x > 0)
6490  >>> s.check()
6491  sat
6492  >>> s.model()
6493  [x = 1.4142135623?]
6494  """
6495  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
6496 
6497  def apply(self, goal, *arguments, **keywords):
6498  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
6499 
6500  >>> x, y = Ints('x y')
6501  >>> t = Tactic('solve-eqs')
6502  >>> t.apply(And(x == 0, y >= x + 1))
6503  [[y >= 1]]
6504  """
6505  if __debug__:
6506  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
6507  goal = _to_goal(goal)
6508  if len(arguments) > 0 or len(keywords) > 0:
6509  p = args2params(arguments, keywords, self.ctx)
6510  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
6511  else:
6512  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
6513 
6514  def __call__(self, goal, *arguments, **keywords):
6515  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
6516 
6517  >>> x, y = Ints('x y')
6518  >>> t = Tactic('solve-eqs')
6519  >>> t(And(x == 0, y >= x + 1))
6520  [[y >= 1]]
6521  """
6522  return self.apply(goal, *arguments, **keywords)
6523 
6524  def help(self):
6525  """Display a string containing a description of the available options for the `self` tactic."""
6526  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
6527 
6528  def param_descrs(self):
6529  """Return the parameter description set."""
6530  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
6531 
6532 def _to_goal(a):
6533  if isinstance(a, BoolRef):
6534  goal = Goal(ctx = a.ctx)
6535  goal.add(a)
6536  return goal
6537  else:
6538  return a
6539 
6540 def _to_tactic(t, ctx=None):
6541  if isinstance(t, Tactic):
6542  return t
6543  else:
6544  return Tactic(t, ctx)
6545 
6546 def _and_then(t1, t2, ctx=None):
6547  t1 = _to_tactic(t1, ctx)
6548  t2 = _to_tactic(t2, ctx)
6549  if __debug__:
6550  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
6551  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
6552 
6553 def _or_else(t1, t2, ctx=None):
6554  t1 = _to_tactic(t1, ctx)
6555  t2 = _to_tactic(t2, ctx)
6556  if __debug__:
6557  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
6558  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
6559 
6560 def AndThen(*ts, **ks):
6561  """Return a tactic that applies the tactics in `*ts` in sequence.
6562 
6563  >>> x, y = Ints('x y')
6564  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
6565  >>> t(And(x == 0, y > x + 1))
6566  [[Not(y <= 1)]]
6567  >>> t(And(x == 0, y > x + 1)).as_expr()
6568  Not(y <= 1)
6569  """
6570  if __debug__:
6571  _z3_assert(len(ts) >= 2, "At least two arguments expected")
6572  ctx = ks.get('ctx', None)
6573  num = len(ts)
6574  r = ts[0]
6575  for i in range(num - 1):
6576  r = _and_then(r, ts[i+1], ctx)
6577  return r
6578 
6579 def Then(*ts, **ks):
6580  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
6581 
6582  >>> x, y = Ints('x y')
6583  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
6584  >>> t(And(x == 0, y > x + 1))
6585  [[Not(y <= 1)]]
6586  >>> t(And(x == 0, y > x + 1)).as_expr()
6587  Not(y <= 1)
6588  """
6589  return AndThen(*ts, **ks)
6590 
6591 def OrElse(*ts, **ks):
6592  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
6593 
6594  >>> x = Int('x')
6595  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
6596  >>> # Tactic split-clause fails if there is no clause in the given goal.
6597  >>> t(x == 0)
6598  [[x == 0]]
6599  >>> t(Or(x == 0, x == 1))
6600  [[x == 0], [x == 1]]
6601  """
6602  if __debug__:
6603  _z3_assert(len(ts) >= 2, "At least two arguments expected")
6604  ctx = ks.get('ctx', None)
6605  num = len(ts)
6606  r = ts[0]
6607  for i in range(num - 1):
6608  r = _or_else(r, ts[i+1], ctx)
6609  return r
6610 
6611 def ParOr(*ts, **ks):
6612  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
6613 
6614  >>> x = Int('x')
6615  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
6616  >>> t(x + 1 == 2)
6617  [[x == 1]]
6618  """
6619  if __debug__:
6620  _z3_assert(len(ts) >= 2, "At least two arguments expected")
6621  ctx = _get_ctx(ks.get('ctx', None))
6622  ts = [ _to_tactic(t, ctx) for t in ts ]
6623  sz = len(ts)
6624  _args = (TacticObj * sz)()
6625  for i in range(sz):
6626  _args[i] = ts[i].tactic
6627  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
6628 
6629 def ParThen(t1, t2, ctx=None):
6630  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
6631 
6632  >>> x, y = Ints('x y')
6633  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
6634  >>> t(And(Or(x == 1, x == 2), y == x + 1))
6635  [[x == 1, y == 2], [x == 2, y == 3]]
6636  """
6637  t1 = _to_tactic(t1, ctx)
6638  t2 = _to_tactic(t2, ctx)
6639  if __debug__:
6640  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
6641  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
6642 
6643 def ParAndThen(t1, t2, ctx=None):
6644  """Alias for ParThen(t1, t2, ctx)."""
6645  return ParThen(t1, t2, ctx)
6646 
6647 def With(t, *args, **keys):
6648  """Return a tactic that applies tactic `t` using the given configuration options.
6649 
6650  >>> x, y = Ints('x y')
6651  >>> t = With(Tactic('simplify'), som=True)
6652  >>> t((x + 1)*(y + 2) == 0)
6653  [[2*x + y + x*y == -2]]
6654  """
6655  ctx = keys.get('ctx', None)
6656  t = _to_tactic(t, ctx)
6657  p = args2params(args, keys, t.ctx)
6658  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
6659 
6660 def Repeat(t, max=4294967295, ctx=None):
6661  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
6662 
6663  >>> x, y = Ints('x y')
6664  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
6665  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
6666  >>> r = t(c)
6667  >>> for subgoal in r: print(subgoal)
6668  [x == 0, y == 0, x > y]
6669  [x == 0, y == 1, x > y]
6670  [x == 1, y == 0, x > y]
6671  [x == 1, y == 1, x > y]
6672  >>> t = Then(t, Tactic('propagate-values'))
6673  >>> t(c)
6674  [[x == 1, y == 0]]
6675  """
6676  t = _to_tactic(t, ctx)
6677  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
6678 
6679 def TryFor(t, ms, ctx=None):
6680  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
6681 
6682  If `t` does not terminate in `ms` milliseconds, then it fails.
6683  """
6684  t = _to_tactic(t, ctx)
6685  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
6686 
6687 def tactics(ctx=None):
6688  """Return a list of all available tactics in Z3.
6689 
6690  >>> l = tactics()
6691  >>> l.count('simplify') == 1
6692  True
6693  """
6694  ctx = _get_ctx(ctx)
6695  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
6696 
6697 def tactic_description(name, ctx=None):
6698  """Return a short description for the tactic named `name`.
6699 
6700  >>> d = tactic_description('simplify')
6701  """
6702  ctx = _get_ctx(ctx)
6703  return Z3_tactic_get_descr(ctx.ref(), name)
6704 
6706  """Display a (tabular) description of all available tactics in Z3."""
6707  if in_html_mode():
6708  even = True
6709  print('<table border="1" cellpadding="2" cellspacing="0">')
6710  for t in tactics():
6711  if even:
6712  print('<tr style="background-color:#CFCFCF">')
6713  even = False
6714  else:
6715  print('<tr>')
6716  even = True
6717  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
6718  print('</table>')
6719  else:
6720  for t in tactics():
6721  print('%s : %s' % (t, tactic_description(t)))
6722 
6723 class Probe:
6724  """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."""
6725  def __init__(self, probe, ctx=None):
6726  self.ctx = _get_ctx(ctx)
6727  self.probe = None
6728  if isinstance(probe, ProbeObj):
6729  self.probe = probe
6730  elif isinstance(probe, float):
6731  self.probe = Z3_probe_const(self.ctx.ref(), probe)
6732  elif _is_int(probe):
6733  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
6734  elif isinstance(probe, bool):
6735  if probe:
6736  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
6737  else:
6738  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
6739  else:
6740  if __debug__:
6741  _z3_assert(isinstance(probe, str), "probe name expected")
6742  try:
6743  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
6744  except Z3Exception:
6745  raise Z3Exception("unknown probe '%s'" % probe)
6746  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
6747 
6748  def __del__(self):
6749  if self.probe != None:
6750  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
6751 
6752  def __lt__(self, other):
6753  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
6754 
6755  >>> p = Probe('size') < 10
6756  >>> x = Int('x')
6757  >>> g = Goal()
6758  >>> g.add(x > 0)
6759  >>> g.add(x < 10)
6760  >>> p(g)
6761  1.0
6762  """
6763  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
6764 
6765  def __gt__(self, other):
6766  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
6767 
6768  >>> p = Probe('size') > 10
6769  >>> x = Int('x')
6770  >>> g = Goal()
6771  >>> g.add(x > 0)
6772  >>> g.add(x < 10)
6773  >>> p(g)
6774  0.0
6775  """
6776  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
6777 
6778  def __le__(self, other):
6779  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
6780 
6781  >>> p = Probe('size') <= 2
6782  >>> x = Int('x')
6783  >>> g = Goal()
6784  >>> g.add(x > 0)
6785  >>> g.add(x < 10)
6786  >>> p(g)
6787  1.0
6788  """
6789  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
6790 
6791  def __ge__(self, other):
6792  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
6793 
6794  >>> p = Probe('size') >= 2
6795  >>> x = Int('x')
6796  >>> g = Goal()
6797  >>> g.add(x > 0)
6798  >>> g.add(x < 10)
6799  >>> p(g)
6800  1.0
6801  """
6802  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
6803 
6804  def __eq__(self, other):
6805  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
6806 
6807  >>> p = Probe('size') == 2
6808  >>> x = Int('x')
6809  >>> g = Goal()
6810  >>> g.add(x > 0)
6811  >>> g.add(x < 10)
6812  >>> p(g)
6813  1.0
6814  """
6815  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
6816 
6817  def __ne__(self, other):
6818  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
6819 
6820  >>> p = Probe('size') != 2
6821  >>> x = Int('x')
6822  >>> g = Goal()
6823  >>> g.add(x > 0)
6824  >>> g.add(x < 10)
6825  >>> p(g)
6826  0.0
6827  """
6828  p = self.__eq__(other)
6829  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
6830 
6831  def __call__(self, goal):
6832  """Evaluate the probe `self` in the given goal.
6833 
6834  >>> p = Probe('size')
6835  >>> x = Int('x')
6836  >>> g = Goal()
6837  >>> g.add(x > 0)
6838  >>> g.add(x < 10)
6839  >>> p(g)
6840  2.0
6841  >>> g.add(x < 20)
6842  >>> p(g)
6843  3.0
6844  >>> p = Probe('num-consts')
6845  >>> p(g)
6846  1.0
6847  >>> p = Probe('is-propositional')
6848  >>> p(g)
6849  0.0
6850  >>> p = Probe('is-qflia')
6851  >>> p(g)
6852  1.0
6853  """
6854  if __debug__:
6855  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
6856  goal = _to_goal(goal)
6857  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
6858 
6859 def is_probe(p):
6860  """Return `True` if `p` is a Z3 probe.
6861 
6862  >>> is_probe(Int('x'))
6863  False
6864  >>> is_probe(Probe('memory'))
6865  True
6866  """
6867  return isinstance(p, Probe)
6868 
6869 def _to_probe(p, ctx=None):
6870  if is_probe(p):
6871  return p
6872  else:
6873  return Probe(p, ctx)
6874 
6875 def probes(ctx=None):
6876  """Return a list of all available probes in Z3.
6877 
6878  >>> l = probes()
6879  >>> l.count('memory') == 1
6880  True
6881  """
6882  ctx = _get_ctx(ctx)
6883  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
6884 
6885 def probe_description(name, ctx=None):
6886  """Return a short description for the probe named `name`.
6887 
6888  >>> d = probe_description('memory')
6889  """
6890  ctx = _get_ctx(ctx)
6891  return Z3_probe_get_descr(ctx.ref(), name)
6892 
6894  """Display a (tabular) description of all available probes in Z3."""
6895  if in_html_mode():
6896  even = True
6897  print('<table border="1" cellpadding="2" cellspacing="0">')
6898  for p in probes():
6899  if even:
6900  print('<tr style="background-color:#CFCFCF">')
6901  even = False
6902  else:
6903  print('<tr>')
6904  even = True
6905  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
6906  print('</table>')
6907  else:
6908  for p in probes():
6909  print('%s : %s' % (p, probe_description(p)))
6910 
6911 def _probe_nary(f, args, ctx):
6912  if __debug__:
6913  _z3_assert(len(args) > 0, "At least one argument expected")
6914  num = len(args)
6915  r = _to_probe(args[0], ctx)
6916  for i in range(num - 1):
6917  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
6918  return r
6919 
6920 def _probe_and(args, ctx):
6921  return _probe_nary(Z3_probe_and, args, ctx)
6922 
6923 def _probe_or(args, ctx):
6924  return _probe_nary(Z3_probe_or, args, ctx)
6925 
6926 def FailIf(p, ctx=None):
6927  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
6928 
6929  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
6930 
6931  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
6932  >>> x, y = Ints('x y')
6933  >>> g = Goal()
6934  >>> g.add(x > 0)
6935  >>> g.add(y > 0)
6936  >>> t(g)
6937  [[x > 0, y > 0]]
6938  >>> g.add(x == y + 1)
6939  >>> t(g)
6940  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
6941  """
6942  p = _to_probe(p, ctx)
6943  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
6944 
6945 def When(p, t, ctx=None):
6946  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
6947 
6948  >>> t = When(Probe('size') > 2, Tactic('simplify'))
6949  >>> x, y = Ints('x y')
6950  >>> g = Goal()
6951  >>> g.add(x > 0)
6952  >>> g.add(y > 0)
6953  >>> t(g)
6954  [[x > 0, y > 0]]
6955  >>> g.add(x == y + 1)
6956  >>> t(g)
6957  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
6958  """
6959  p = _to_probe(p, ctx)
6960  t = _to_tactic(t, ctx)
6961  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
6962 
6963 def Cond(p, t1, t2, ctx=None):
6964  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
6965 
6966  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
6967  """
6968  p = _to_probe(p, ctx)
6969  t1 = _to_tactic(t1, ctx)
6970  t2 = _to_tactic(t2, ctx)
6971  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
6972 
6973 #########################################
6974 #
6975 # Utils
6976 #
6977 #########################################
6978 
6979 def simplify(a, *arguments, **keywords):
6980  """Simplify the expression `a` using the given options.
6981 
6982  This function has many options. Use `help_simplify` to obtain the complete list.
6983 
6984  >>> x = Int('x')
6985  >>> y = Int('y')
6986  >>> simplify(x + 1 + y + x + 1)
6987  2 + 2*x + y
6988  >>> simplify((x + 1)*(y + 1), som=True)
6989  1 + x + y + x*y
6990  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
6991  And(Not(x == y), Not(x == 1), Not(y == 1))
6992  >>> simplify(And(x == 0, y == 1), elim_and=True)
6993  Not(Or(Not(x == 0), Not(y == 1)))
6994  """
6995  if __debug__:
6996  _z3_assert(is_expr(a), "Z3 expression expected")
6997  if len(arguments) > 0 or len(keywords) > 0:
6998  p = args2params(arguments, keywords, a.ctx)
6999  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
7000  else:
7001  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
7002 
7004  """Return a string describing all options available for Z3 `simplify` procedure."""
7005  print(Z3_simplify_get_help(main_ctx().ref()))
7006 
7008  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
7010 
7011 def substitute(t, *m):
7012  """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.
7013 
7014  >>> x = Int('x')
7015  >>> y = Int('y')
7016  >>> substitute(x + 1, (x, y + 1))
7017  y + 1 + 1
7018  >>> f = Function('f', IntSort(), IntSort())
7019  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
7020  1 + 1
7021  """
7022  if isinstance(m, tuple):
7023  m1 = _get_args(m)
7024  if isinstance(m1, list):
7025  m = m1
7026  if __debug__:
7027  _z3_assert(is_expr(t), "Z3 expression expected")
7028  _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.")
7029  num = len(m)
7030  _from = (Ast * num)()
7031  _to = (Ast * num)()
7032  for i in range(num):
7033  _from[i] = m[i][0].as_ast()
7034  _to[i] = m[i][1].as_ast()
7035  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
7036 
7037 def substitute_vars(t, *m):
7038  """Substitute the free variables in t with the expression in m.
7039 
7040  >>> v0 = Var(0, IntSort())
7041  >>> v1 = Var(1, IntSort())
7042  >>> x = Int('x')
7043  >>> f = Function('f', IntSort(), IntSort(), IntSort())
7044  >>> # replace v0 with x+1 and v1 with x
7045  >>> substitute_vars(f(v0, v1), x + 1, x)
7046  f(x + 1, x)
7047  """
7048  if __debug__:
7049  _z3_assert(is_expr(t), "Z3 expression expected")
7050  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
7051  num = len(m)
7052  _to = (Ast * num)()
7053  for i in range(num):
7054  _to[i] = m[i].as_ast()
7055  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
7056 
7057 def Sum(*args):
7058  """Create the sum of the Z3 expressions.
7059 
7060  >>> a, b, c = Ints('a b c')
7061  >>> Sum(a, b, c)
7062  a + b + c
7063  >>> Sum([a, b, c])
7064  a + b + c
7065  >>> A = IntVector('a', 5)
7066  >>> Sum(A)
7067  a__0 + a__1 + a__2 + a__3 + a__4
7068  """
7069  args = _get_args(args)
7070  if __debug__:
7071  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7072  ctx = _ctx_from_ast_arg_list(args)
7073  if __debug__:
7074  _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression")
7075  args = _coerce_expr_list(args, ctx)
7076  if is_bv(args[0]):
7077  return _reduce(lambda a, b: a + b, args, 0)
7078  else:
7079  _args, sz = _to_ast_array(args)
7080  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
7081 
7082 def Product(*args):
7083  """Create the product of the Z3 expressions.
7084 
7085  >>> a, b, c = Ints('a b c')
7086  >>> Product(a, b, c)
7087  a*b*c
7088  >>> Product([a, b, c])
7089  a*b*c
7090  >>> A = IntVector('a', 5)
7091  >>> Product(A)
7092  a__0*a__1*a__2*a__3*a__4
7093  """
7094  args = _get_args(args)
7095  if __debug__:
7096  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7097  ctx = _ctx_from_ast_arg_list(args)
7098  if __debug__:
7099  _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression")
7100  args = _coerce_expr_list(args, ctx)
7101  if is_bv(args[0]):
7102  return _reduce(lambda a, b: a * b, args, 1)
7103  else:
7104  _args, sz = _to_ast_array(args)
7105  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
7106 
7107 def solve(*args, **keywords):
7108  """Solve the constraints `*args`.
7109 
7110  This is a simple function for creating demonstrations. It creates a solver,
7111  configure it using the options in `keywords`, adds the constraints
7112  in `args`, and invokes check.
7113 
7114  >>> a = Int('a')
7115  >>> solve(a > 0, a < 2)
7116  [a = 1]
7117  """
7118  s = Solver()
7119  s.set(**keywords)
7120  s.add(*args)
7121  if keywords.get('show', False):
7122  print(s)
7123  r = s.check()
7124  if r == unsat:
7125  print("no solution")
7126  elif r == unknown:
7127  print("failed to solve")
7128  try:
7129  print(s.model())
7130  except Z3Exception:
7131  return
7132  else:
7133  print(s.model())
7134 
7135 def solve_using(s, *args, **keywords):
7136  """Solve the constraints `*args` using solver `s`.
7137 
7138  This is a simple function for creating demonstrations. It is similar to `solve`,
7139  but it uses the given solver `s`.
7140  It configures solver `s` using the options in `keywords`, adds the constraints
7141  in `args`, and invokes check.
7142  """
7143  if __debug__:
7144  _z3_assert(isinstance(s, Solver), "Solver object expected")
7145  s.set(**keywords)
7146  s.add(*args)
7147  if keywords.get('show', False):
7148  print("Problem:")
7149  print(s)
7150  r = s.check()
7151  if r == unsat:
7152  print("no solution")
7153  elif r == unknown:
7154  print("failed to solve")
7155  try:
7156  print(s.model())
7157  except Z3Exception:
7158  return
7159  else:
7160  if keywords.get('show', False):
7161  print("Solution:")
7162  print(s.model())
7163 
7164 def prove(claim, **keywords):
7165  """Try to prove the given claim.
7166 
7167  This is a simple function for creating demonstrations. It tries to prove
7168  `claim` by showing the negation is unsatisfiable.
7169 
7170  >>> p, q = Bools('p q')
7171  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
7172  proved
7173  """
7174  if __debug__:
7175  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
7176  s = Solver()
7177  s.set(**keywords)
7178  s.add(Not(claim))
7179  if keywords.get('show', False):
7180  print(s)
7181  r = s.check()
7182  if r == unsat:
7183  print("proved")
7184  elif r == unknown:
7185  print("failed to prove")
7186  print(s.model())
7187  else:
7188  print("counterexample")
7189  print(s.model())
7190 
7191 def _solve_html(*args, **keywords):
7192  """Version of funcion `solve` used in RiSE4Fun."""
7193  s = Solver()
7194  s.set(**keywords)
7195  s.add(*args)
7196  if keywords.get('show', False):
7197  print("<b>Problem:</b>")
7198  print(s)
7199  r = s.check()
7200  if r == unsat:
7201  print("<b>no solution</b>")
7202  elif r == unknown:
7203  print("<b>failed to solve</b>")
7204  try:
7205  print(s.model())
7206  except Z3Exception:
7207  return
7208  else:
7209  if keywords.get('show', False):
7210  print("<b>Solution:</b>")
7211  print(s.model())
7212 
7213 def _solve_using_html(s, *args, **keywords):
7214  """Version of funcion `solve_using` used in RiSE4Fun."""
7215  if __debug__:
7216  _z3_assert(isinstance(s, Solver), "Solver object expected")
7217  s.set(**keywords)
7218  s.add(*args)
7219  if keywords.get('show', False):
7220  print("<b>Problem:</b>")
7221  print(s)
7222  r = s.check()
7223  if r == unsat:
7224  print("<b>no solution</b>")
7225  elif r == unknown:
7226  print("<b>failed to solve</b>")
7227  try:
7228  print(s.model())
7229  except Z3Exception:
7230  return
7231  else:
7232  if keywords.get('show', False):
7233  print("<b>Solution:</b>")
7234  print(s.model())
7235 
7236 def _prove_html(claim, **keywords):
7237  """Version of funcion `prove` used in RiSE4Fun."""
7238  if __debug__:
7239  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
7240  s = Solver()
7241  s.set(**keywords)
7242  s.add(Not(claim))
7243  if keywords.get('show', False):
7244  print(s)
7245  r = s.check()
7246  if r == unsat:
7247  print("<b>proved</b>")
7248  elif r == unknown:
7249  print("<b>failed to prove</b>")
7250  print(s.model())
7251  else:
7252  print("<b>counterexample</b>")
7253  print(s.model())
7254 
7255 def _dict2sarray(sorts, ctx):
7256  sz = len(sorts)
7257  _names = (Symbol * sz)()
7258  _sorts = (Sort * sz) ()
7259  i = 0
7260  for k in sorts:
7261  v = sorts[k]
7262  if __debug__:
7263  _z3_assert(isinstance(k, str), "String expected")
7264  _z3_assert(is_sort(v), "Z3 sort expected")
7265  _names[i] = to_symbol(k, ctx)
7266  _sorts[i] = v.ast
7267  i = i + 1
7268  return sz, _names, _sorts
7269 
7270 def _dict2darray(decls, ctx):
7271  sz = len(decls)
7272  _names = (Symbol * sz)()
7273  _decls = (FuncDecl * sz) ()
7274  i = 0
7275  for k in decls:
7276  v = decls[k]
7277  if __debug__:
7278  _z3_assert(isinstance(k, str), "String expected")
7279  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
7280  _names[i] = to_symbol(k, ctx)
7281  if is_const(v):
7282  _decls[i] = v.decl().ast
7283  else:
7284  _decls[i] = v.ast
7285  i = i + 1
7286  return sz, _names, _decls
7287 
7288 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
7289  """Parse a string in SMT 2.0 format using the given sorts and decls.
7290 
7291  The arguments sorts and decls are Python dictionaries used to initialize
7292  the symbol table used for the SMT 2.0 parser.
7293 
7294  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
7295  And(x > 0, x < 10)
7296  >>> x, y = Ints('x y')
7297  >>> f = Function('f', IntSort(), IntSort())
7298  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
7299  x + f(y) > 0
7300  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
7301  a > 0
7302  """
7303  ctx = _get_ctx(ctx)
7304  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
7305  dsz, dnames, ddecls = _dict2darray(decls, ctx)
7306  return _to_expr_ref(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
7307 
7308 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
7309  """Parse a file in SMT 2.0 format using the given sorts and decls.
7310 
7311  This function is similar to parse_smt2_string().
7312  """
7313  ctx = _get_ctx(ctx)
7314  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
7315  dsz, dnames, ddecls = _dict2darray(decls, ctx)
7316  return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
7317 
7318 def Interpolant(a,ctx=None):
7319  """Create an interpolation operator.
7320 
7321  The argument is an interpolation pattern (see tree_interpolant).
7322 
7323  >>> x = Int('x')
7324  >>> print Interpolant(x>0)
7325  interp(x > 0)
7326  """
7327  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
7328  s = BoolSort(ctx)
7329  a = s.cast(a)
7330  return BoolRef(Z3_mk_interpolant(ctx.ref(), a.as_ast()), ctx)
7331 
7332 def tree_interpolant(pat,p=None,ctx=None):
7333  """Compute interpolant for a tree of formulas.
7334 
7335  The input is an interpolation pattern over a set of formulas C.
7336  The pattern pat is a formula combining the formulas in C using
7337  logical conjunction and the "interp" operator (see Interp). This
7338  interp operator is logically the identity operator. It marks the
7339  sub-formulas of the pattern for which interpolants should be
7340  computed. The interpolant is a map sigma from marked subformulas
7341  to formulas, such that, for each marked subformula phi of pat
7342  (where phi sigma is phi with sigma(psi) substituted for each
7343  subformula psi of phi such that psi in dom(sigma)):
7344 
7345  1) phi sigma implies sigma(phi), and
7346 
7347  2) sigma(phi) is in the common uninterpreted vocabulary between
7348  the formulas of C occurring in phi and those not occurring in
7349  phi
7350 
7351  and moreover pat sigma implies false. In the simplest case
7352  an interpolant for the pattern "(and (interp A) B)" maps A
7353  to an interpolant for A /\ B.
7354 
7355  The return value is a vector of formulas representing sigma. This
7356  vector contains sigma(phi) for each marked subformula of pat, in
7357  pre-order traversal. This means that subformulas of phi occur before phi
7358  in the vector. Also, subformulas that occur multiply in pat will
7359  occur multiply in the result vector.
7360 
7361  If pat is satisfiable, raises an object of class ModelRef
7362  that represents a model of pat.
7363 
7364  If parameters p are supplied, these are used in creating the
7365  solver that determines satisfiability.
7366 
7367  >>> x = Int('x')
7368  >>> y = Int('y')
7369  >>> print tree_interpolant(And(Interpolant(x < 0), Interpolant(y > 2), x == y))
7370  [Not(x >= 0), Not(y <= 2)]
7371 
7372  >>> g = And(Interpolant(x<0),x<2)
7373  >>> try:
7374  ... print tree_interpolant(g).sexpr()
7375  ... except ModelRef as m:
7376  ... print m.sexpr()
7377  (define-fun x () Int
7378  (- 1))
7379  """
7380  f = pat
7381  ctx = _get_ctx(_ctx_from_ast_arg_list([f], ctx))
7382  ptr = (AstVectorObj * 1)()
7383  mptr = (Model * 1)()
7384  if p == None:
7385  p = ParamsRef(ctx)
7386  res = Z3_compute_interpolant(ctx.ref(),f.as_ast(),p.params,ptr,mptr)
7387  if res == Z3_L_FALSE:
7388  return AstVector(ptr[0],ctx)
7389  raise ModelRef(mptr[0], ctx)
7390 
7391 def binary_interpolant(a,b,p=None,ctx=None):
7392  """Compute an interpolant for a binary conjunction.
7393 
7394  If a & b is unsatisfiable, returns an interpolant for a & b.
7395  This is a formula phi such that
7396 
7397  1) a implies phi
7398  2) b implies not phi
7399  3) All the uninterpreted symbols of phi occur in both a and b.
7400 
7401  If a & b is satisfiable, raises an object of class ModelRef
7402  that represents a model of a &b.
7403 
7404  If parameters p are supplied, these are used in creating the
7405  solver that determines satisfiability.
7406 
7407  x = Int('x')
7408  print binary_interpolant(x<0,x>2)
7409  Not(x >= 0)
7410  """
7411  f = And(Interpolant(a),b)
7412  return tree_interpolant(f,p,ctx)[0]
7413 
7414 def sequence_interpolant(v,p=None,ctx=None):
7415  """Compute interpolant for a sequence of formulas.
7416 
7417  If len(v) == N, and if the conjunction of the formulas in v is
7418  unsatisfiable, the interpolant is a sequence of formulas w
7419  such that len(w) = N-1 and v[0] implies w[0] and for i in 0..N-1:
7420 
7421  1) w[i] & v[i+1] implies w[i+1] (or false if i+1 = N)
7422  2) All uninterpreted symbols in w[i] occur in both v[0]..v[i]
7423  and v[i+1]..v[n]
7424 
7425  Requires len(v) >= 1.
7426 
7427  If a & b is satisfiable, raises an object of class ModelRef
7428  that represents a model of a & b.
7429 
7430  If parameters p are supplied, these are used in creating the
7431  solver that determines satisfiability.
7432 
7433  >>> x = Int('x')
7434  >>> y = Int('y')
7435  >>> print sequence_interpolant([x < 0, y == x , y > 2])
7436  [Not(x >= 0), Not(y >= 0)]
7437  """
7438  f = v[0]
7439  for i in range(1,len(v)):
7440  f = And(Interpolant(f),v[i])
7441  return tree_interpolant(f,p,ctx)
7442 
7443 #########################################
7444 #
7445 # Floating-Point Arithmetic
7446 #
7447 #########################################
7448 
7449 
7450 # Global default rounding mode
7451 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
7452 _dflt_fpsort_ebits = 11
7453 _dflt_fpsort_sbits = 53
7454 
7455 def get_default_rounding_mode(ctx=None):
7456  """Retrieves the global default rounding mode."""
7457  global _dflt_rounding_mode
7458  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
7459  return RTZ(ctx)
7460  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
7461  return RTN(ctx)
7462  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
7463  return RTP(ctx)
7464  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
7465  return RNE(ctx)
7466  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
7467  return RNA(ctx)
7468 
7469 def set_default_rounding_mode(rm, ctx=None):
7470  global _dflt_rounding_mode
7471  if is_fprm_value(rm):
7472  _dflt_rounding_mode = rm.decl().kind()
7473  else:
7474  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
7475  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
7476  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
7477  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
7478  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
7479  "illegal rounding mode")
7480  _dflt_rounding_mode = rm
7481 
7482 def get_default_fp_sort(ctx=None):
7483  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
7484 
7485 def set_default_fp_sort(ebits, sbits, ctx=None):
7486  global _dflt_fpsort_ebits
7487  global _dflt_fpsort_sbits
7488  _dflt_fpsort_ebits = ebits
7489  _dflt_fpsort_sbits = sbits
7490 
7491 def _dflt_rm(ctx=None):
7492  return get_default_rounding_mode(ctx)
7493 
7494 def _dflt_fps(ctx=None):
7495  return get_default_fp_sort(ctx)
7496 
7497 ### FP Sorts
7498 
7499 class FPSortRef(SortRef):
7500  """Floating-point sort."""
7501 
7502  def ebits(self):
7503  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
7504  >>> b = FPSort(8, 24)
7505  >>> b.ebits()
7506  8
7507  """
7508  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
7509 
7510  def sbits(self):
7511  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
7512  >>> b = FPSort(8, 24)
7513  >>> b.sbits()
7514  24
7515  """
7516  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
7517 
7518  def cast(self, val):
7519  """Try to cast `val` as a Floating-point expression
7520 
7521  >>> b = FPSort(8, 24)
7522  >>> b.cast(1.0)
7523  1
7524  >>> b.cast(1.0).sexpr()
7525  '(fp #b0 #x7f #b00000000000000000000000)'
7526  """
7527  if is_expr(val):
7528  if __debug__:
7529  _z3_assert(self.ctx == val.ctx, "Context mismatch")
7530  return val
7531  else:
7532  return FPVal(val, None, self, self.ctx)
7533 
7534 
7535 def Float16(ctx=None):
7536  """Floating-point 16-bit (half) sort."""
7537  ctx = _get_ctx(ctx)
7538  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
7539 
7540 def FloatHalf(ctx=None):
7541  """Floating-point 16-bit (half) sort."""
7542  ctx = _get_ctx(ctx)
7543  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
7544 
7545 def Float32(ctx=None):
7546  """Floating-point 32-bit (single) sort."""
7547  ctx = _get_ctx(ctx)
7548  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
7549 
7550 def FloatSingle(ctx=None):
7551  """Floating-point 32-bit (single) sort."""
7552  ctx = _get_ctx(ctx)
7553  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
7554 
7555 def Float64(ctx=None):
7556  """Floating-point 64-bit (double) sort."""
7557  ctx = _get_ctx(ctx)
7558  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
7559 
7560 def FloatSingle(ctx=None):
7561  """Floating-point 64-bit (double) sort."""
7562  ctx = _get_ctx(ctx)
7563  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
7564 
7565 def Float128(ctx=None):
7566  """Floating-point 128-bit (quadruple) sort."""
7567  ctx = _get_ctx(ctx)
7568  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
7569 
7570 def FloatSingle(ctx=None):
7571  """Floating-point 128-bit (quadruple) sort."""
7572  ctx = _get_ctx(ctx)
7573  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
7574 
7575 class FPRMSortRef(SortRef):
7576  """"Floating-point rounding mode sort."""
7577 
7578 
7579 def is_fp_sort(s):
7580  """Return True if `s` is a Z3 floating-point sort.
7581 
7582  >>> is_fp_sort(FPSort(8, 24))
7583  True
7584  >>> is_fp_sort(IntSort())
7585  False
7586  """
7587  return isinstance(s, FPSortRef)
7588 
7589 def is_fprm_sort(s):
7590  """Return True if `s` is a Z3 floating-point rounding mode sort.
7591 
7592  >>> is_fprm_sort(FPSort(8, 24))
7593  False
7594  >>> is_fprm_sort(RNE().sort())
7595  True
7596  """
7597  return isinstance(s, FPRMSortRef)
7598 
7599 ### FP Expressions
7600 
7601 class FPRef(ExprRef):
7602  """Floating-point expressions."""
7603 
7604  def sort(self):
7605  """Return the sort of the floating-point expression `self`.
7606 
7607  >>> x = FP('1.0', FPSort(8, 24))
7608  >>> x.sort()
7609  FPSort(8, 24)
7610  >>> x.sort() == FPSort(8, 24)
7611  True
7612  """
7613  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
7614 
7615  def ebits(self):
7616  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
7617  >>> b = FPSort(8, 24)
7618  >>> b.ebits()
7619  8
7620  """
7621  return self.sort().ebits();
7622 
7623  def sbits(self):
7624  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
7625  >>> b = FPSort(8, 24)
7626  >>> b.sbits()
7627  24
7628  """
7629  return self.sort().sbits();
7630 
7631  def as_string(self):
7632  """Return a Z3 floating point expression as a Python string."""
7633  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7634 
7635  def __le__(self, other):
7636  return fpLEQ(self, other)
7637 
7638  def __lt__(self, other):
7639  return fpLEQ(self, other)
7640 
7641  def __ge__(self, other):
7642  return fpGEQ(self, other)
7643 
7644  def __gt__(self, other):
7645  return fpGT(self, other)
7646 
7647  def __ne__(self, other):
7648  return fpNEQ(self, other)
7649 
7650 
7651  def __add__(self, other):
7652  """Create the Z3 expression `self + other`.
7653 
7654  >>> x = FP('x', FPSort(8, 24))
7655  >>> y = FP('y', FPSort(8, 24))
7656  >>> x + y
7657  x + y
7658  >>> (x + y).sort()
7659  FPSort(8, 24)
7660  """
7661  a, b = z3._coerce_exprs(self, other)
7662  return fpAdd(_dflt_rm(), self, other)
7663 
7664  def __radd__(self, other):
7665  """Create the Z3 expression `other + self`.
7666 
7667  >>> x = FP('x', FPSort(8, 24))
7668  >>> 10 + x
7669  1.25*(2**3) + x
7670  """
7671  a, b = _coerce_exprs(self, other)
7672  return fpAdd(_dflt_rm(), other, self)
7673 
7674  def __sub__(self, other):
7675  """Create the Z3 expression `self - other`.
7676 
7677  >>> x = FP('x', FPSort(8, 24))
7678  >>> y = FP('y', FPSort(8, 24))
7679  >>> x - y
7680  x - y
7681  >>> (x - y).sort()
7682  FPSort(8, 24)
7683  """
7684  a, b = z3._coerce_exprs(self, other)
7685  return fpSub(_dflt_rm(), self, other)
7686 
7687  def __rsub__(self, other):
7688  """Create the Z3 expression `other - self`.
7689 
7690  >>> x = FP('x', FPSort(8, 24))
7691  >>> 10 - x
7692  1.25*(2**3) - x
7693  """
7694  a, b = _coerce_exprs(self, other)
7695  return fpSub(_dflt_rm(), other, self)
7696 
7697  def __mul__(self, other):
7698  """Create the Z3 expression `self * other`.
7699 
7700  >>> x = FP('x', FPSort(8, 24))
7701  >>> y = FP('y', FPSort(8, 24))
7702  >>> x * y
7703  x * y
7704  >>> (x * y).sort()
7705  FPSort(8, 24)
7706  >>> 10 * y
7707  1.25*(2**3) * y
7708  """
7709  a, b = z3._coerce_exprs(self, other)
7710  return fpMul(_dflt_rm(), self, other)
7711 
7712  def __rmul__(self, other):
7713  """Create the Z3 expression `other * self`.
7714 
7715  >>> x = FP('x', FPSort(8, 24))
7716  >>> y = FP('y', FPSort(8, 24))
7717  >>> x * y
7718  x * y
7719  >>> x * 10
7720  x * 1.25*(2**3)
7721  """
7722  a, b = _coerce_exprs(self, other)
7723  return fpMul(_dflt_rm(), other, self)
7724 
7725  def __pos__(self):
7726  """Create the Z3 expression `+self`."""
7727  return self
7728 
7729  def __neg__(self):
7730  """Create the Z3 expression `-self`."""
7731  return FPRef(fpNeg(self))
7732 
7733  def __truediv__(self, other):
7734  """Create the Z3 expression division `self / other`."""
7735  return self.__div__(other)
7736 
7737  def __rtruediv__(self, other):
7738  """Create the Z3 expression division `other / self`."""
7739  return self.__rdiv__(other)
7740 
7741  def __mod__(self, other):
7742  """Create the Z3 expression mod `self % other`."""
7743  return fpRem(self, other)
7744 
7745  def __rmod__(self, other):
7746  """Create the Z3 expression mod `other % self`."""
7747  return fpRem(other, self)
7748 
7749 class FPRMRef(ExprRef):
7750  """Floating-point rounding mode expressions"""
7751 
7752  def as_string(self):
7753  """Return a Z3 floating point expression as a Python string."""
7754  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
7755 
7756 
7757 def RoundNearestTiesToEven(ctx=None):
7758  ctx = _get_ctx(ctx)
7759  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
7760 
7761 def RNE (ctx=None):
7762  ctx = _get_ctx(ctx)
7763  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
7764 
7765 def RoundNearestTiesToAway(ctx=None):
7766  ctx = _get_ctx(ctx)
7767  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
7768 
7769 def RNA (ctx=None):
7770  ctx = _get_ctx(ctx)
7771  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
7772 
7773 def RoundTowardPositive(ctx=None):
7774  ctx = _get_ctx(ctx)
7775  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
7776 
7777 def RTP(ctx=None):
7778  ctx = _get_ctx(ctx)
7779  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
7780 
7781 def RoundTowardNegative(ctx=None):
7782  ctx = _get_ctx(ctx)
7783  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
7784 
7785 def RTN(ctx=None):
7786  ctx = _get_ctx(ctx)
7787  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
7788 
7789 def RoundTowardZero(ctx=None):
7790  ctx = _get_ctx(ctx)
7791  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
7792 
7793 def RTZ(ctx=None):
7794  ctx = _get_ctx(ctx)
7795  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
7796 
7797 def is_fprm(a):
7798  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
7799 
7800  >>> rm = RNE()
7801  >>> is_fprm(rm)
7802  True
7803  >>> rm = 1.0
7804  >>> is_fprm(rm)
7805  False
7806  """
7807  return isinstance(a, FPRMRef)
7808 
7809 def is_fprm_value(a):
7810  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
7811  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
7812 
7813 ### FP Numerals
7814 
7815 class FPNumRef(FPRef):
7816  def isNaN(self):
7817  return self.decl().kind() == Z3_OP_FPA_NAN
7818 
7819  def isInf(self):
7820  return self.decl().kind() == Z3_OP_FPA_PLUS_INF or self.decl().kind() == Z3_OP_FPA_MINUS_INF
7821 
7822  def isZero(self):
7823  return self.decl().kind() == Z3_OP_FPA_PLUS_ZERO or self.decl().kind() == Z3_OP_FPA_MINUS_ZERO
7824 
7825  def isNegative(self):
7826  k = self.decl().kind()
7827  return (self.num_args() == 0 and (k == Z3_OP_FPA_MINUS_INF or k == Z3_OP_FPA_MINUS_ZERO)) or (self.sign() == True)
7828 
7829  """
7830  The sign of the numeral
7831 
7832  >>> x = FPNumRef(+1.0, FPSort(8, 24))
7833  >>> x.sign()
7834  False
7835  >>> x = FPNumRef(-1.0, FPSort(8, 24))
7836  >>> x.sign()
7837  True
7838  """
7839  def sign(self):
7840  l = (ctypes.c_int)()
7841  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
7842  raise Z3Exception("error retrieving the sign of a numeral.")
7843  return l.value != 0
7844 
7845  """
7846  The significand of the numeral
7847 
7848  >>> x = FPNumRef(2.5, FPSort(8, 24))
7849  1.25
7850  """
7851  def significand(self):
7852  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
7853 
7854  """
7855  The exponent of the numeral
7856 
7857  >>> x = FPNumRef(2.5, FPSort(8, 24))
7858  >>>
7859  1
7860  """
7861  def exponent(self):
7862  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast())
7863 
7864  """
7865  The exponent of the numeral as a long
7866 
7867  >>> x = FPNumRef(2.5, FPSort(8, 24))
7868  1
7869  """
7870  def exponent_as_long(self):
7871  ptr = (ctypes.c_longlong * 1)()
7872  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr):
7873  raise Z3Exception("error retrieving the exponent of a numeral.")
7874  return ptr[0]
7875 
7876  """
7877  The string representation of the numeral
7878 
7879  >>> x = FPNumRef(20, FPSort(8, 24))
7880  1.25*(2**4)
7881  """
7882  def as_string(self):
7883  s = Z3_fpa_get_numeral_string(self.ctx.ref(), self.as_ast())
7884  return ("FPVal(%s, %s)" % (s, FPSortRef(self.sort()).as_string()))
7885 
7886 
7887 def _to_fpnum(num, ctx=None):
7888  if isinstance(num, FPNum):
7889  return num
7890  else:
7891  return FPNum(num, ctx)
7892 
7893 def is_fp(a):
7894  """Return `True` if `a` is a Z3 floating-point expression.
7895 
7896  >>> b = FP('b', FPSort(8, 24))
7897  >>> is_fp(b)
7898  True
7899  >>> is_fp(b + 1.0)
7900  True
7901  >>> is_fp(Int('x'))
7902  False
7903  """
7904  return isinstance(a, FPRef)
7905 
7906 def is_fp_value(a):
7907  """Return `True` if `a` is a Z3 floating-point numeral value.
7908 
7909  >>> b = FP('b', FPSort(8, 24))
7910  >>> is_fp_value(b)
7911  False
7912  >>> b = FPVal(1.0, FPSort(8, 24))
7913  >>> b
7914  1
7915  >>> is_fp_value(b)
7916  True
7917  """
7918  return is_fp(a) and _is_numeral(a.ctx, a.ast)
7919 
7920 def FPSort(ebits, sbits, ctx=None):
7921  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
7922 
7923  >>> Single = FPSort(8, 24)
7924  >>> Double = FPSort(11, 53)
7925  >>> Single
7926  FPSort(8, 24)
7927  >>> x = Const('x', Single)
7928  >>> eq(x, FP('x', FPSort(8, 24)))
7929  True
7930  """
7931  ctx = z3._get_ctx(ctx)
7932  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
7933 
7934 def _to_float_str(val):
7935  if isinstance(val, float):
7936  return str(val)
7937  elif isinstance(val, bool):
7938  if val:
7939  return "1.0"
7940  else:
7941  return "0.0"
7942  elif _is_int(val):
7943  return str(val)
7944  elif isinstance(val, str):
7945  return val
7946  if __debug__:
7947  _z3_assert(False, "Python value cannot be used as a double")
7948 
7949 def fpNaN(s):
7950  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7951  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
7952 
7953 def fpPlusInfinity(s):
7954  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7955  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
7956 
7957 def fpMinusInfinity(s):
7958  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7959  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
7960 
7961 def fpInfinity(s, negative):
7962  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7963  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
7964  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
7965 
7966 def fpPlusZero(s):
7967  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7968  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
7969 
7970 def fpMinusZero(s):
7971  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7972  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
7973 
7974 def fpZero(s, negative):
7975  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
7976  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
7977  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
7978 
7979 def FPVal(sig, exp=None, fps=None, ctx=None):
7980  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
7981 
7982  >>> v = FPVal(20.0, FPSort(8, 24))
7983  >>> v
7984  1.25*(2**4)
7985  >>> print("0x%.8x" % v.exponent_as_long())
7986  0x00000004
7987  >>> v = FPVal(2.25, FPSort(8, 24))
7988  >>> v
7989  1.125*(2**1)
7990  >>> v = FPVal(-2.25, FPSort(8, 24))
7991  >>> v
7992  -1.125*(2**1)
7993  """
7994  ctx = _get_ctx(ctx)
7995  if is_fp_sort(exp):
7996  fps = exp
7997  exp = None
7998  elif fps == None:
7999  fps = _dflt_fps(ctx)
8000  _z3_assert(is_fp_sort(fps), "sort mismatch")
8001  if exp == None:
8002  exp = 0
8003  val = _to_float_str(sig)
8004  val = val + 'p'
8005  val = val + _to_int_str(exp)
8006  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
8007 
8008 def FP(name, fpsort, ctx=None):
8009  """Return a floating-point constant named `name`.
8010  `fpsort` is the floating-point sort.
8011  If `ctx=None`, then the global context is used.
8012 
8013  >>> x = FP('x', FPSort(8, 24))
8014  >>> is_fp(x)
8015  True
8016  >>> x.ebits()
8017  8
8018  >>> x.sort()
8019  FPSort(8, 24)
8020  >>> word = FPSort(8, 24)
8021  >>> x2 = FP('x', word)
8022  >>> eq(x, x2)
8023  True
8024  """
8025  ctx = fpsort.ctx
8026  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
8027 
8028 def FPs(names, fpsort, ctx=None):
8029  """Return an array of floating-point constants.
8030 
8031  >>> x, y, z = BitVecs('x y z', 16)
8032  >>> x.size()
8033  16
8034  >>> x.sort()
8035  BitVec(16)
8036  >>> Sum(x, y, z)
8037  0 + x + y + z
8038  >>> Product(x, y, z)
8039  1*x*y*z
8040  >>> simplify(Product(x, y, z))
8041  x*y*z
8042  """
8043  ctx = z3._get_ctx(ctx)
8044  if isinstance(names, str):
8045  names = names.split(" ")
8046  return [FP(name, fpsort, ctx) for name in names]
8047 
8048 def fpAbs(a):
8049  """Create a Z3 floating-point absolute value expression.
8050 
8051  >>> s = FPSort(8, 24)
8052  >>> rm = RNE()
8053  >>> x = FPVal(1.0, s)
8054  >>> fpAbs(x)
8055  fpAbs(1)
8056  >>> y = FPVal(-20.0, s)
8057  >>> y
8058  -1.25*(2**4)
8059  >>> fpAbs(y)
8060  fpAbs(-1.25*(2**4))
8061  >>> fpAbs(-1.25*(2**4))
8062  fpAbs(-1.25*(2**4))
8063  >>> fpAbs(x).sort()
8064  FPSort(8, 24)
8065  """
8066  ctx = None
8067  if not is_expr(a):
8068  ctx =_get_ctx(ctx)
8069  s = get_default_fp_sort(ctx)
8070  a = FPVal(a, s)
8071  else:
8072  ctx = a.ctx
8073  if __debug__:
8074  _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression")
8075  return FPRef(Z3_mk_fpa_abs(a.ctx_ref(), a.as_ast()), a.ctx)
8076 
8077 def fpNeg(a):
8078  """Create a Z3 floating-point addition expression.
8079 
8080  >>> s = FPSort(8, 24)
8081  >>> rm = RNE()
8082  >>> x = FP('x', s)
8083  >>> fpNeg(x)
8084  -x
8085  >>> fpNeg(x).sort()
8086  FPSort(8, 24)
8087  """
8088  ctx = None
8089  if not is_expr(a):
8090  ctx =_get_ctx(ctx)
8091  s = get_default_fp_sort(ctx)
8092  a = FPVal(a, s)
8093  else:
8094  ctx = a.ctx
8095  if __debug__:
8096  _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression")
8097  return FPRef(Z3_mk_fpa_neg(a.ctx_ref(), a.as_ast()), a.ctx)
8098 
8099 def fpAdd(rm, a, b):
8100  """Create a Z3 floating-point addition expression.
8101 
8102  >>> s = FPSort(8, 24)
8103  >>> rm = RNE()
8104  >>> x = FP('x', s)
8105  >>> y = FP('y', s)
8106  >>> fpAdd(rm, x, y)
8107  fpAdd(RNE(), x, y)
8108  >>> fpAdd(rm, x, y).sort()
8109  FPSort(8, 24)
8110  """
8111  if __debug__:
8112  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8113  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8114  a, b = _coerce_exprs(a, b)
8115  return FPRef(Z3_mk_fpa_add(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
8116 
8117 def fpSub(rm, a, b):
8118  """Create a Z3 floating-point subtraction expression.
8119 
8120  >>> s = FPSort(8, 24)
8121  >>> rm = RNE()
8122  >>> x = FP('x', s)
8123  >>> y = FP('y', s)
8124  >>> fpSub(rm, x, y)
8125  fpSub(RNE(), x, y)
8126  >>> fpSub(rm, x, y).sort()
8127  FPSort(8, 24)
8128  """
8129  if __debug__:
8130  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8131  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8132  a, b = _coerce_exprs(a, b)
8133  return FPRef(Z3_mk_fpa_sub(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
8134 
8135 def fpMul(rm, a, b):
8136  """Create a Z3 floating-point multiplication expression.
8137 
8138  >>> s = FPSort(8, 24)
8139  >>> rm = RNE()
8140  >>> x = FP('x', s)
8141  >>> y = FP('y', s)
8142  >>> fpMul(rm, x, y)
8143  fpMul(RNE(), x, y)
8144  >>> fpMul(rm, x, y).sort()
8145  FPSort(8, 24)
8146  """
8147  if __debug__:
8148  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8149  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8150  a, b = _coerce_exprs(a, b)
8151  return FPRef(Z3_mk_fpa_mul(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
8152 
8153 def fpDiv(rm, a, b):
8154  """Create a Z3 floating-point divison expression.
8155 
8156  >>> s = FPSort(8, 24)
8157  >>> rm = RNE()
8158  >>> x = FP('x', s)
8159  >>> y = FP('y', s)
8160  >>> fpDiv(rm, x, y)
8161  fpDiv(RNE(), x, y)
8162  >>> fpDiv(rm, x, y).sort()
8163  FPSort(8, 24)
8164  """
8165  if __debug__:
8166  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8167  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8168  a, b = _coerce_exprs(a, b)
8169  return FPRef(Z3_mk_fpa_div(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
8170 
8171 def fpRem(a, b):
8172  """Create a Z3 floating-point remainder expression.
8173 
8174  >>> s = FPSort(8, 24)
8175  >>> x = FP('x', s)
8176  >>> y = FP('y', s)
8177  >>> fpRem(x, y)
8178  fpRem(x, y)
8179  >>> fpRem(x, y).sort()
8180  FPSort(8, 24)
8181  """
8182  if __debug__:
8183  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8184  a, b = _coerce_exprs(a, b)
8185  return FPRef(Z3_mk_fpa_rem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8186 
8187 def fpMin(a, b):
8188  """Create a Z3 floating-point minimium expression.
8189 
8190  >>> s = FPSort(8, 24)
8191  >>> rm = RNE()
8192  >>> x = FP('x', s)
8193  >>> y = FP('y', s)
8194  >>> fpMin(x, y)
8195  fpMin(x, y)
8196  >>> fpMin(x, y).sort()
8197  FPSort(8, 24)
8198  """
8199  if __debug__:
8200  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8201  a, b = _coerce_exprs(a, b)
8202  return FPRef(Z3_mk_fpa_min(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8203 
8204 def fpMax(a, b):
8205  """Create a Z3 floating-point maximum expression.
8206 
8207  >>> s = FPSort(8, 24)
8208  >>> rm = RNE()
8209  >>> x = FP('x', s)
8210  >>> y = FP('y', s)
8211  >>> fpMax(x, y)
8212  fpMax(x, y)
8213  >>> fpMax(x, y).sort()
8214  FPSort(8, 24)
8215  """
8216  if __debug__:
8217  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
8218  a, b = _coerce_exprs(a, b)
8219  return FPRef(Z3_mk_fpa_max(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8220 
8221 def fpFMA(rm, a, b, c):
8222  """Create a Z3 floating-point fused multiply-add expression.
8223  """
8224  if __debug__:
8225  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8226  _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "Second, third, or fourth argument must be a Z3 floating-point expression")
8227  a, b, c = _coerce_expr_list([a, b, c])
8228  return FPRef(Z3_mk_fpa_fma(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), rm.ctx)
8229 
8230 def fpSqrt(rm, a):
8231  """Create a Z3 floating-point square root expression.
8232  """
8233  ctx = None
8234  if not is_expr(a):
8235  ctx =_get_ctx(ctx)
8236  s = get_default_fp_sort(ctx)
8237  a = FPVal(a, s)
8238  else:
8239  ctx = a.ctx
8240  if __debug__:
8241  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8242  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions")
8243  return FPRef(Z3_mk_fpa_sqrt(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx)
8244 
8245 def fpRoundToIntegral(rm, a):
8246  """Create a Z3 floating-point roundToIntegral expression.
8247  """
8248  ctx = None
8249  if not is_expr(a):
8250  ctx =_get_ctx(ctx)
8251  s = get_default_fp_sort(ctx)
8252  a = FPVal(a, s)
8253  else:
8254  ctx = a.ctx
8255  if __debug__:
8256  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8257  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions")
8258  return FPRef(Z3_mk_fpa_round_to_integral(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx)
8259 
8260 def fpIsNaN(a):
8261  """Create a Z3 floating-point isNaN expression.
8262  """
8263  if __debug__:
8264  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8265  return FPRef(Z3_mk_fpa_is_nan(a.ctx_ref(), a.as_ast()), a.ctx)
8266 
8267 def fpIsInfinite(a):
8268  """Create a Z3 floating-point isNaN expression.
8269  """
8270  if __debug__:
8271  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8272  return FPRef(Z3_mk_fpa_is_infinite(a.ctx_ref(), a.as_ast()), a.ctx)
8273 
8274 def fpIsZero(a):
8275  """Create a Z3 floating-point isNaN expression.
8276  """
8277  if __debug__:
8278  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8279  return FPRef(Z3_mk_fpa_is_zero(a.ctx_ref(), a.as_ast()), a.ctx)
8280 
8281 def fpIsNormal(a):
8282  """Create a Z3 floating-point isNaN expression.
8283  """
8284  if __debug__:
8285  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8286  return FPRef(Z3_mk_fpa_is_normal(a.ctx_ref(), a.as_ast()), a.ctx)
8287 
8288 def fpIsSubnormal(a):
8289  """Create a Z3 floating-point isNaN expression.
8290  """
8291  if __debug__:
8292  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8293  return FPRef(Z3_mk_fpa_is_subnormal(a.ctx_ref(), a.as_ast()), a.ctx)
8294 
8295 def fpIsNegative(a):
8296  """Create a Z3 floating-point isNaN expression.
8297  """
8298  if __debug__:
8299  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8300  return FPRef(Z3_mk_fpa_is_negative(a.ctx_ref(), a.as_ast()), a.ctx)
8301 
8302 def fpIsPositive(a):
8303  """Create a Z3 floating-point isNaN expression.
8304  """
8305  if __debug__:
8306  _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
8307  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
8308 
8309 def _check_fp_args(a, b):
8310  if __debug__:
8311  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
8312 
8313 def fpLT(a, b):
8314  """Create the Z3 floating-point expression `other <= self`.
8315 
8316  >>> x, y = FPs('x y', FPSort(8, 24))
8317  >>> fpLT(x, y)
8318  x < y
8319  >>> (x <= y).sexpr()
8320  '(fp.leq x y)'
8321  """
8322  _check_fp_args(a, b)
8323  a, b = _coerce_exprs(a, b)
8324  return BoolRef(Z3_mk_fpa_lt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8325 
8326 def fpLEQ(a, b):
8327  """Create the Z3 floating-point expression `other <= self`.
8328 
8329  >>> x, y = FPs('x y', FPSort(8, 24))
8330  >>> fpLEQ(x, y)
8331  x <= y
8332  >>> (x <= y).sexpr()
8333  '(fp.leq x y)'
8334  """
8335  _check_fp_args(a, b)
8336  a, b = _coerce_exprs(a, b)
8337  return BoolRef(Z3_mk_fpa_leq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8338 
8339 def fpGT(a, b):
8340  """Create the Z3 floating-point expression `other <= self`.
8341 
8342  >>> x, y = FPs('x y', FPSort(8, 24))
8343  >>> fpGT(x, y)
8344  x > y
8345  >>> (x > y).sexpr()
8346  '(fp.gt x y)'
8347  """
8348  _check_fp_args(a, b)
8349  a, b = _coerce_exprs(a, b)
8350  return BoolRef(Z3_mk_fpa_gt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8351 
8352 
8353 def fpGEQ(a, b):
8354  """Create the Z3 floating-point expression `other <= self`.
8355 
8356  >>> x, y = FPs('x y', FPSort(8, 24))
8357  >>> x + y
8358  x + y
8359  >>> fpGEQ(x, y)
8360  x >= y
8361  >>> (x >= y).sexpr()
8362  '(fp.geq x y)'
8363  """
8364  _check_fp_args(a, b)
8365  a, b = _coerce_exprs(a, b)
8366  return BoolRef(Z3_mk_fpa_geq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8367 
8368 def fpEQ(a, b):
8369  """Create the Z3 floating-point expression `other <= self`.
8370 
8371  >>> x, y = FPs('x y', FPSort(8, 24))
8372  >>> fpEQ(x, y)
8373  fpEQ(x, y)
8374  >>> fpEQ(x, y).sexpr()
8375  '(fp.eq x y)'
8376  """
8377  _check_fp_args(a, b)
8378  a, b = _coerce_exprs(a, b)
8379  return BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
8380 
8381 def fpNEQ(a, b):
8382  """Create the Z3 floating-point expression `other <= self`.
8383 
8384  >>> x, y = FPs('x y', FPSort(8, 24))
8385  >>> fpNEQ(x, y)
8386  Not(fpEQ(x, y))
8387  >>> (x != y).sexpr()
8388  '(not (fp.eq x y))'
8389  """
8390  _check_fp_args(a, b)
8391  a, b = _coerce_exprs(a, b)
8392  return Not(BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx), a.ctx)
8393 
8394 
8395 
8396 def fpFP(sgn, exp, sig):
8397  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectorssgn, sig, and exp."""
8398  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
8399  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
8400  return FPRef(Z3_mk_fpa_fp(sgn.ctx_ref(), sgn.ast, exp.ast, sig.ast), sgn.ctx)
8401 
8402 
8403 def fpToFP(a1, a2=None, a3=None):
8404  """Create a Z3 floating-point conversion expression from other terms."""
8405  if is_bv(a1) and is_fp_sort(a2):
8406  return FPRef(Z3_mk_fpa_to_fp_bv(a1.ctx_ref(), a1.ast, a2.ast), a1.ctx)
8407  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
8408  return FPRef(Z3_mk_fpa_to_fp_float(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
8409  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
8410  return FPRef(Z3_mk_fpa_to_fp_real(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
8411  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
8412  return FPRef(Z3_mk_fpa_to_fp_signed(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
8413  else:
8414  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
8415 
8416 def fpToFPUnsigned(rm, x, s):
8417  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
8418  if __debug__:
8419  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8420  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
8421  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
8422  return FPRef(Z3_mk_fpa_to_fp_unsigned(rm.ctx_ref(), rm.ast, x.ast, s.ast), rm.ctx)
8423 
8424 def fpToSBV(rm, x, s):
8425  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
8426 
8427  >>> x = FP('x', FPSort(8, 24))
8428  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
8429  >>> print is_fp(x)
8430  True
8431  >>> print is_bv(y)
8432  True
8433  >>> print is_fp(y)
8434  False
8435  >>> print is_bv(x)
8436  False
8437  """
8438  if __debug__:
8439  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8440  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
8441  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
8442  return BitVecRef(Z3_mk_fpa_to_sbv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx)
8443 
8444 def fpToUBV(rm, x, s):
8445  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
8446 
8447  >>> x = FP('x', FPSort(8, 24))
8448  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
8449  >>> print is_fp(x)
8450  True
8451  >>> print is_bv(y)
8452  True
8453  >>> print is_fp(y)
8454  False
8455  >>> print is_bv(x)
8456  False
8457  """
8458  if __debug__:
8459  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
8460  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
8461  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
8462  return BitVecRef(Z3_mk_fpa_to_ubv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx)
8463 
8464 def fpToReal(x):
8465  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
8466 
8467  >>> x = FP('x', FPSort(8, 24))
8468  >>> y = fpToReal(x)
8469  >>> print is_fp(x)
8470  True
8471  >>> print is_real(y)
8472  True
8473  >>> print is_fp(y)
8474  False
8475  >>> print is_real(x)
8476  False
8477  """
8478  if __debug__:
8479  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
8480  return ArithRef(Z3_mk_fpa_to_real(x.ctx_ref(), x.ast), x.ctx)
8481 
8482 def fpToIEEEBV(x):
8483  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
8484 
8485  The size of the resulting bit-vector is automatically determined.
8486 
8487  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
8488  knows only one NaN and it will always produce the same bit-vector represenatation of
8489  that NaN.
8490 
8491  >>> x = FP('x', FPSort(8, 24))
8492  >>> y = fpToIEEEBV(x)
8493  >>> print is_fp(x)
8494  True
8495  >>> print is_bv(y)
8496  True
8497  >>> print is_fp(y)
8498  False
8499  >>> print is_bv(x)
8500  False
8501  """
8502  if __debug__:
8503  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
8504  return BitVecRef(Z3_mk_fpa_to_ieee_bv(x.ctx_ref(), x.ast), x.ctx)
def Not
Definition: z3py.py:1454
def name(self)
Definition: z3py.py:607
Z3_ast Z3_API Z3_mk_const(__in Z3_context c, __in Z3_symbol s, __in Z3_sort ty)
Declare and create a constant.
def is_lt(a)
Definition: z3py.py:2411
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:6979
def __ge__(self, other)
Definition: z3py.py:6791
def RealSort
Definition: z3py.py:2641
Z3_tactic Z3_API Z3_tactic_par_and_then(__in Z3_context c, __in Z3_tactic t1, __in Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
def is_distinct(a)
Definition: z3py.py:1325
void Z3_API Z3_fixedpoint_assert(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def __gt__(self, other)
Definition: z3py.py:6765
def Then(ts, ks)
Definition: z3py.py:6579
Z3_context Z3_API Z3_mk_context_rc(__in 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_ast Z3_API Z3_translate(__in Z3_context source, __in Z3_ast a, __in Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
Z3_ast Z3_API Z3_mk_mul(__in Z3_context c, __in unsigned num_args, __in_ecount(num_args) Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].The array args must have num_args el...
Z3_string Z3_API Z3_fixedpoint_get_help(__in Z3_context c, __in Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
def SignExt(n, a)
Definition: z3py.py:3748
def update_rule(self, head, body, name)
Definition: z3py.py:6233
Fixedpoint.
Definition: z3py.py:6114
void Z3_API Z3_inc_ref(__in Z3_context c, __in Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
def OrElse(ts, ks)
Definition: z3py.py:6591
def is_fprm_sort(s)
Definition: z3py.py:7589
def get_version_string()
Definition: z3py.py:64
Quantifiers.
Definition: z3py.py:1612
def fpToUBV(rm, x, s)
Definition: z3py.py:8444
def entry(self, idx)
Definition: z3py.py:5250
def get_cover_delta(self, level, predicate)
Definition: z3py.py:6251
void Z3_API Z3_apply_result_inc_ref(__in Z3_context c, __in Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
def __getitem__(self, idx)
Definition: z3py.py:6371
def BoolVal
Definition: z3py.py:1353
Function Declarations.
Definition: z3py.py:591
def FP
Definition: z3py.py:8008
Z3_tactic Z3_API Z3_mk_tactic(__in Z3_context c, __in Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Booleans.
Definition: z3py.py:1209
Z3_string Z3_API Z3_tactic_get_help(__in Z3_context c, __in Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def IntSort
Definition: z3py.py:2625
def Product(args)
Definition: z3py.py:7082
def prec(self)
Definition: z3py.py:4615
def IsInt(a)
Definition: z3py.py:2862
def BoolSort
Definition: z3py.py:1336
Z3_string Z3_API Z3_get_tactic_name(__in Z3_context c, unsigned i)
Return the name of the idx tactic.
def Sum(args)
Definition: z3py.py:7057
def __repr__(self)
Definition: z3py.py:284
def fpLT(a, b)
Definition: z3py.py:8313
def is_arith_sort(s)
Definition: z3py.py:1913
Z3_ast Z3_API Z3_mk_bound(__in Z3_context c, __in unsigned index, __in Z3_sort ty)
Create a bound variable.
def push(self)
Definition: z3py.py:6225
def Function(name, sig)
Definition: z3py.py:705
Z3_symbol Z3_API Z3_get_decl_name(__in Z3_context c, __in Z3_func_decl d)
Return the constant declaration name as a symbol.
def as_ast(self)
Definition: z3py.py:746
Z3_probe Z3_API Z3_probe_eq(__in Z3_context x, __in Z3_probe p1, __in Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def get_rules(self)
Definition: z3py.py:6284
void Z3_API Z3_fixedpoint_update_rule(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_ast a, __in Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
def Real
Definition: z3py.py:2776
Z3_ast Z3_API Z3_substitute_vars(__in Z3_context c, __in Z3_ast a, __in unsigned num_exprs, __in_ecount(num_exprs) Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs...
Z3_tactic Z3_API Z3_tactic_fail_if(__in Z3_context c, __in Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
def AndThen(ts, ks)
Definition: z3py.py:6560
def ZeroExt(n, a)
Definition: z3py.py:3777
unsigned Z3_API Z3_get_app_num_args(__in Z3_context c, __in Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
def SolverFor
Definition: z3py.py:6076
def substitute_vars(t, m)
Definition: z3py.py:7037
def BitVecSort
Definition: z3py.py:3446
def is_int(self)
Definition: z3py.py:1863
def Var(idx, s)
Definition: z3py.py:1170
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(__in Z3_context c, __in Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def __del__(self)
Definition: z3py.py:6748
def fpLEQ(a, b)
Definition: z3py.py:8326
Z3_bool Z3_API Z3_global_param_get(__in Z3_string param_id, __out Z3_string_ptr param_value)
Get a global (or module) parameter.
def help(self)
Definition: z3py.py:6035
def RealVarVector
Definition: z3py.py:1192
def reset_params()
Definition: z3py.py:237
def declare(self, name, args)
Definition: z3py.py:4177
void Z3_API Z3_enable_trace(__in Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def as_ast(self)
Definition: z3py.py:296
def LShR(a, b)
Definition: z3py.py:3687
def set_option(args, kws)
Definition: z3py.py:242
Bit-Vectors.
Definition: z3py.py:2908
Z3_apply_result Z3_API Z3_tactic_apply(__in Z3_context c, __in Z3_tactic t, __in Z3_goal g)
Apply tactic t to the goal g.
def Consts(names, sort)
Definition: z3py.py:1156
def use_pp(self)
Definition: z3py.py:268
Z3_model Z3_API Z3_apply_result_convert_model(__in Z3_context c, __in Z3_apply_result r, __in unsigned i, __in Z3_model m)
Convert a model for the subgoal Z3_apply_result_get_subgoal(c, r, i) into a model for the original go...
def Implies
Definition: z3py.py:1424
Z3_bool Z3_API Z3_open_log(__in Z3_string filename)
Log interaction to a file.
def is_and(a)
Definition: z3py.py:1283
def ref(self)
Definition: z3py.py:173
def push(self)
Definition: z3py.py:5767
def fpAdd(rm, a, b)
Definition: z3py.py:8099
def Cbrt
Definition: z3py.py:2890
def sort(self)
Definition: z3py.py:1233
Z3_symbol Z3_API Z3_mk_string_symbol(__in Z3_context c, __in Z3_string s)
Create a Z3 symbol using a C string.
def ULT(a, b)
Definition: z3py.py:3576
def When
Definition: z3py.py:6945
unsigned Z3_API Z3_get_num_tactics(__in Z3_context c)
Return the number of builtin tactics available in Z3.
def BitVecVal
Definition: z3py.py:3460
Arithmetic.
Definition: z3py.py:1846
FP Expressions.
Definition: z3py.py:7601
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(__in Z3_context c, __in Z3_fixedpoint f, __in Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
Z3_sort Z3_API Z3_get_range(__in Z3_context c, __in Z3_func_decl d)
Return the range of the given declaration.
def sort(self)
Definition: z3py.py:1931
def is_to_real(a)
Definition: z3py.py:2455
def as_ast(self)
Definition: z3py.py:452
def assert_exprs(self, args)
Definition: z3py.py:6146
def param_descrs(self)
Definition: z3py.py:6142
def is_select(a)
Definition: z3py.py:4106
def is_real(self)
Definition: z3py.py:1955
def RNE
Definition: z3py.py:7761
Z3_probe Z3_API Z3_probe_gt(__in Z3_context x, __in Z3_probe p1, __in Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def is_int(self)
Definition: z3py.py:1941
ASTs base class.
Definition: z3py.py:266
def __ne__(self, other)
Definition: z3py.py:792
def is_gt(a)
Definition: z3py.py:2433
def sexpr(self)
Definition: z3py.py:6391
def set_param(args, kws)
Definition: z3py.py:214
Z3_ast Z3_API Z3_substitute(__in Z3_context c, __in Z3_ast a, __in unsigned num_exprs, __in_ecount(num_exprs) Z3_ast const from[], __in_ecount(num_exprs) 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].
def __eq__(self, other)
Definition: z3py.py:775
def domain(self, i)
Definition: z3py.py:627
def If
Definition: z3py.py:1092
Z3_bool Z3_API Z3_is_eq_ast(__in Z3_context c, __in Z3_ast t1, Z3_ast t2)
compare terms.
def fpSub(rm, a, b)
Definition: z3py.py:8117
def RealVector
Definition: z3py.py:2802
def register_relation(self, relations)
Definition: z3py.py:6260
def __init__
Definition: z3py.py:6725
def is_app(a)
Definition: z3py.py:981
void Z3_API Z3_global_param_set(__in Z3_string param_id, __in Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def args2params
Definition: z3py.py:4490
def __len__(self)
Definition: z3py.py:6352
void Z3_API Z3_set_ast_print_mode(__in Z3_context c, __in Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
def fpAbs(a)
Definition: z3py.py:8048
Z3_string Z3_API Z3_apply_result_to_string(__in Z3_context c, __in Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
def And(args)
Definition: z3py.py:1479
def open_log(fname)
Definition: z3py.py:86
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(__in Z3_context c, __in Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
void Z3_API Z3_apply_result_dec_ref(__in Z3_context c, __in Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
Z3_sort Z3_API Z3_mk_uninterpreted_sort(__in Z3_context c, __in Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
def solver(self)
Definition: z3py.py:6480
Z3_tactic Z3_API Z3_tactic_repeat(__in Z3_context c, __in 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 fpRem(a, b)
Definition: z3py.py:8171
def range(self)
Definition: z3py.py:3887
Z3_ast_kind Z3_API Z3_get_ast_kind(__in Z3_context c, __in Z3_ast a)
Return the kind of the given AST.
def __repr__(self)
Definition: z3py.py:6388
def FPVal
Definition: z3py.py:7979
def disable_trace(msg)
Definition: z3py.py:61
def RotateRight(a, b)
Definition: z3py.py:3733
def sort(self)
Definition: z3py.py:2953
def is_ge(a)
Definition: z3py.py:2422
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
def is_K(a)
Definition: z3py.py:3934
def __init__
Definition: z3py.py:6117
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(__in Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:764
def is_const(a)
Definition: z3py.py:1006
void Z3_API Z3_get_version(__out unsigned *major, __out unsigned *minor, __out unsigned *build_number, __out unsigned *revision_number)
Return Z3 version number information.
Z3_goal Z3_API Z3_apply_result_get_subgoal(__in Z3_context c, __in Z3_apply_result r, __in unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def FreshBool
Definition: z3py.py:1411
def Ints
Definition: z3py.py:2740
def fpMin(a, b)
Definition: z3py.py:8187
Z3_decl_kind Z3_API Z3_get_decl_kind(__in Z3_context c, __in Z3_func_decl d)
Return declaration kind corresponding to declaration.
def fpFP(sgn, exp, sig)
Definition: z3py.py:8396
def RotateLeft(a, b)
Definition: z3py.py:3718
def Const(name, sort)
Definition: z3py.py:1145
Z3_tactic Z3_API Z3_tactic_try_for(__in Z3_context c, __in Z3_tactic t, __in unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
def substitute(t, m)
Definition: z3py.py:7011
def Exists
Definition: z3py.py:1819
def Array(name, dom, rng)
Definition: z3py.py:3999
def main_ctx()
Definition: z3py.py:188
Z3_tactic Z3_API Z3_tactic_using_params(__in Z3_context c, __in Z3_tactic t, __in Z3_params p)
Return a tactic that applies t using the given set of parameters.
def ForAll
Definition: z3py.py:1800
def Int
Definition: z3py.py:2728
def get_id(self)
Definition: z3py.py:601
void Z3_API Z3_dec_ref(__in Z3_context c, __in Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def is_array(a)
Definition: z3py.py:3909
def sequence_interpolant
Definition: z3py.py:7414
def is_pattern(a)
Definition: z3py.py:1556
Statistics.
Definition: z3py.py:5567
def __init__
Definition: z3py.py:6462
def is_fp_value(a)
Definition: z3py.py:7906
Z3_tactic Z3_API Z3_tactic_and_then(__in Z3_context c, __in Z3_tactic t1, __in Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
def help_simplify()
Definition: z3py.py:7003
Z3_ast Z3_API Z3_simplify(__in Z3_context c, __in Z3_ast a)
Interface to simplifier.
def DeclareSort
Definition: z3py.py:567
def __repr__(self)
Definition: z3py.py:6292
Arrays.
Definition: z3py.py:3845
def simplify_param_descrs()
Definition: z3py.py:7007
def is_map(a)
Definition: z3py.py:3946
def is_or(a)
Definition: z3py.py:1294
Patterns.
Definition: z3py.py:1545
def is_int_value(a)
Definition: z3py.py:2272
Z3_solver Z3_API Z3_mk_solver_for_logic(__in Z3_context c, __in Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
void Z3_API Z3_probe_inc_ref(__in Z3_context c, __in Z3_probe p)
Increment the reference counter of the given probe.
def Interpolant
Definition: z3py.py:7318
Z3_string Z3_API Z3_fixedpoint_to_string(__in Z3_context c, __in Z3_fixedpoint f, __in unsigned num_queries, __in_ecount(num_queries) Z3_ast queries[])
Print the current rules and background axioms as a string.
def fpNEQ(a, b)
Definition: z3py.py:8381
Z3_probe Z3_API Z3_probe_not(__in Z3_context x, __in Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def RealVar
Definition: z3py.py:1182
Z3_symbol_kind Z3_API Z3_get_symbol_kind(__in Z3_context c, __in Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
def Repeat
Definition: z3py.py:6660
def fpEQ(a, b)
Definition: z3py.py:8368
def CreateDatatypes(ds)
Definition: z3py.py:4232
Z3_lbool Z3_API Z3_fixedpoint_query(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_ast query)
Pose a query against the asserted rules.
def URem(a, b)
Definition: z3py.py:3647
def Q
Definition: z3py.py:2716
def Xor
Definition: z3py.py:1439
Z3_lbool Z3_API Z3_fixedpoint_query_relations(__in Z3_context c, __in Z3_fixedpoint d, __in unsigned num_relations, __in_ecount(num_relations) Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def abstract
Definition: z3py.py:6328
def is_mod(a)
Definition: z3py.py:2389
def ParThen
Definition: z3py.py:6629
def UGE(a, b)
Definition: z3py.py:3593
def __init__(self, args, kws)
Definition: z3py.py:148
def cast(self, val)
Definition: z3py.py:483
Z3_ast Z3_API Z3_mk_ite(__in Z3_context c, __in Z3_ast t1, __in Z3_ast t2, __in Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
def decl(self)
Definition: z3py.py:810
def is_eq(a)
Definition: z3py.py:1316
def __del__(self)
Definition: z3py.py:170
def depth(self)
Definition: z3py.py:4580
Z3_tactic Z3_API Z3_tactic_cond(__in Z3_context c, __in Z3_probe p, __in Z3_tactic t1, __in 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...
Z3_string Z3_API Z3_probe_get_descr(__in Z3_context c, __in Z3_string name)
Return a string containing a description of the probe with the given name.
def sort(self)
Definition: z3py.py:752
def is_real(a)
Definition: z3py.py:2248
def get_id(self)
Definition: z3py.py:749
def Extract(high, low, a)
Definition: z3py.py:3540
void Z3_API Z3_fixedpoint_inc_ref(__in Z3_context c, __in Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
def solve_using(s, args, keywords)
Definition: z3py.py:7135
def set_predicate_representation(self, f, representations)
Definition: z3py.py:6266
void Z3_API Z3_fixedpoint_add_rule(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_ast rule, __in Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def eq(a, b)
Definition: z3py.py:372
def help(self)
Definition: z3py.py:6524
unsigned Z3_API Z3_get_arity(__in Z3_context c, __in Z3_func_decl d)
Alias for Z3_get_domain_size.
int Z3_API Z3_get_symbol_int(__in Z3_context c, __in Z3_symbol s)
Return the symbol int value.
def is_le(a)
Definition: z3py.py:2400
def fpToSBV(rm, x, s)
Definition: z3py.py:8424
unsigned Z3_API Z3_get_ast_id(__in 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 is_not(a)
Definition: z3py.py:1305
def get_map_func(a)
Definition: z3py.py:3961
def __init__
Definition: z3py.py:273
unsigned Z3_API Z3_get_ast_hash(__in Z3_context c, __in 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 probe_description
Definition: z3py.py:6885
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(__in Z3_context c, __in Z3_fixedpoint f, __in Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def apply(self, goal, arguments, keywords)
Definition: z3py.py:6497
def solve(args, keywords)
Definition: z3py.py:7107
def is_arith(a)
Definition: z3py.py:2210
def __del__(self)
Definition: z3py.py:6476
def is_sort(s)
Definition: z3py.py:532
def IntVector
Definition: z3py.py:2752
def Or(args)
Definition: z3py.py:1509
def num_sorts(self)
Definition: z3py.py:5414
def add_rule
Definition: z3py.py:6172
def add(self, args)
Definition: z3py.py:6160
def hash(self)
Definition: z3py.py:342
def tree_interpolant
Definition: z3py.py:7332
def is_int(a)
Definition: z3py.py:2230
def check(self, assumptions)
Definition: z3py.py:5907
def FreshReal
Definition: z3py.py:2815
def insert(self, args)
Definition: z3py.py:6168
Z3_string Z3_API Z3_ast_to_string(__in Z3_context c, __in Z3_ast a)
Convert the given AST node into a string.
def is_quantifier(a)
Definition: z3py.py:1759
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:6514
def fpMax(a, b)
Definition: z3py.py:8204
def FPs
Definition: z3py.py:8028
Z3_solver Z3_API Z3_mk_simple_solver(__in Z3_context c)
Create a new (incremental) solver.
Z3_probe Z3_API Z3_probe_const(__in Z3_context x, __in double val)
Return a probe that always evaluates to val.
def num_args(self)
Definition: z3py.py:825
def __del__(self)
Definition: z3py.py:6349
def prove(claim, keywords)
Definition: z3py.py:7164
Z3_string Z3_API Z3_tactic_get_descr(__in Z3_context c, __in Z3_string name)
Return a string containing a description of the tactic with the given name.
def parse_file(self, f)
Definition: z3py.py:6280
def binary_interpolant
Definition: z3py.py:7391
void Z3_API Z3_set_error_handler(__in Z3_context c, __in Z3_error_handler h)
Register a Z3 error handler.
def pop(self)
Definition: z3py.py:6229
def is_true(a)
Definition: z3py.py:1253
Z3_stats Z3_API Z3_fixedpoint_get_statistics(__in Z3_context c, __in Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_string Z3_API Z3_simplify_get_help(__in Z3_context c)
Return a string describing all available parameters.
def fpGEQ(a, b)
Definition: z3py.py:8353
def is_real(self)
Definition: z3py.py:1849
def fpMul(rm, a, b)
Definition: z3py.py:8135
Z3_string Z3_API Z3_get_probe_name(__in Z3_context c, unsigned i)
Return the name of the i probe.
void Z3_API Z3_disable_trace(__in Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def param_descrs(self)
Definition: z3py.py:6528
Z3_string Z3_API Z3_benchmark_to_smtlib_string(__in Z3_context c, __in Z3_string name, __in Z3_string logic, __in Z3_string status, __in Z3_string attributes, __in unsigned num_assumptions, __in_ecount(num_assumptions) Z3_ast const assumptions[], __in Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
Z3_probe Z3_API Z3_probe_ge(__in Z3_context x, __in Z3_probe p1, __in Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
def is_store(a)
Definition: z3py.py:4118
def get_version()
Definition: z3py.py:72
void Z3_API Z3_del_config(__in Z3_config c)
Delete the given configuration object.
def SRem(a, b)
Definition: z3py.py:3667
void Z3_API Z3_fixedpoint_dec_ref(__in Z3_context c, __in Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
Z3_ast Z3_API Z3_sort_to_ast(__in Z3_context c, __in Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def EnumSort
Definition: z3py.py:4421
Z3_sort Z3_API Z3_get_sort(__in Z3_context c, __in Z3_ast a)
Return the sort of an AST node.
def Cond
Definition: z3py.py:6963
def eq(self, other)
Definition: z3py.py:309
def get_id(self)
Definition: z3py.py:455
def ToReal(a)
Definition: z3py.py:2828
def is_bv_value(a)
Definition: z3py.py:3414
def range(self)
Definition: z3py.py:640
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(__in Z3_context c, __in Z3_tactic t)
Return the parameter description set for the given tactic object.
def Reals
Definition: z3py.py:2788
def is_idiv(a)
Definition: z3py.py:2378
def translate(self, target)
Definition: z3py.py:326
def probes
Definition: z3py.py:6875
Z3_func_decl Z3_API Z3_get_app_decl(__in Z3_context c, __in Z3_app a)
Return the declaration of a constant or function application.
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. ...
def __ne__(self, other)
Definition: z3py.py:521
def FailIf
Definition: z3py.py:6926
def __le__(self, other)
Definition: z3py.py:6778
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...
def cast(self, val)
Definition: z3py.py:1211
def Bools
Definition: z3py.py:1382
unsigned Z3_API Z3_get_num_probes(__in Z3_context c)
Return the number of builtin probes available in Z3.
def as_func_decl(self)
Definition: z3py.py:604
def size(self)
Definition: z3py.py:2964
Z3_sort Z3_API Z3_get_domain(__in Z3_context c, __in Z3_func_decl d, __in unsigned i)
Return the sort of the i-th parameter of the given function declaration.
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_tactic_dec_ref(__in Z3_context c, __in Z3_tactic g)
Decrement the reference counter of the given tactic.
def to_string(self, queries)
Definition: z3py.py:6301
def assertions(self)
Definition: z3py.py:5990
Z3_ast Z3_API Z3_mk_distinct(__in Z3_context c, __in unsigned num_args, __in_ecount(num_args) Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).The distinct construct is us...
def get_id(self)
Definition: z3py.py:300
def __lt__(self, other)
Definition: z3py.py:6752
def ArraySort(d, r)
Definition: z3py.py:3978
def create(self)
Definition: z3py.py:4200
def is_const_array(a)
Definition: z3py.py:3922
void Z3_API Z3_interrupt(__in Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def cast(self, val)
Definition: z3py.py:1881
def sexpr(self)
Definition: z3py.py:287
Z3_symbol Z3_API Z3_get_sort_name(__in Z3_context c, __in Z3_sort d)
Return the sort name as a symbol.
def fpGT(a, b)
Definition: z3py.py:8339
def Bool
Definition: z3py.py:1371
def kind(self)
Definition: z3py.py:459
def parse_string(self, s)
Definition: z3py.py:6276
def is_rational_value(a)
Definition: z3py.py:2295
Z3_tactic Z3_API Z3_tactic_when(__in Z3_context c, __in Z3_probe p, __in Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
def sexpr(self)
Definition: z3py.py:6296
def __ne__(self, other)
Definition: z3py.py:6817
Z3_probe Z3_API Z3_probe_le(__in Z3_context x, __in Z3_probe p1, __in 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 declare_var(self, vars)
Definition: z3py.py:6319
def arg(self, idx)
Definition: z3py.py:841
def sort(self)
Definition: z3py.py:7604
unsigned Z3_API Z3_get_index_value(__in Z3_context c, __in Z3_ast a)
Return index of de-Brujin bound variable.
Z3_solver Z3_API Z3_mk_solver_from_tactic(__in Z3_context c, __in Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
def Select(a, i)
Definition: z3py.py:4049
def query(self, query)
Definition: z3py.py:6203
def get_var_index(a)
Definition: z3py.py:1048
def MultiPattern(args)
Definition: z3py.py:1575
def is_div(a)
Definition: z3py.py:2362
FP Numerals.
Definition: z3py.py:7815
void Z3_API Z3_fixedpoint_register_relation(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
FP Sorts.
Definition: z3py.py:7499
def ctx_ref(self)
Definition: z3py.py:305
def help(self)
Definition: z3py.py:6138
Z3_ast Z3_API Z3_func_decl_to_ast(__in Z3_context c, __in Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def RTZ
Definition: z3py.py:7793
def is_fp_sort(s)
Definition: z3py.py:7579
Z3_probe Z3_API Z3_probe_lt(__in Z3_context x, __in Z3_probe p1, __in Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Expressions.
Definition: z3py.py:736
def is_app_of(a, k)
Definition: z3py.py:1080
def is_probe(p)
Definition: z3py.py:6859
def is_mul(a)
Definition: z3py.py:2340
def subsort(self, other)
Definition: z3py.py:475
def kind(self)
Definition: z3py.py:649
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(__in Z3_context c)
Create a new fixedpoint context.
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:2940
def Update(a, i, v)
Definition: z3py.py:4012
def With(t, args, keys)
Definition: z3py.py:6647
def append_log(s)
Definition: z3py.py:90
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(__in Z3_context c, __in Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
def statistics(self)
Definition: z3py.py:6309
def RealVal
Definition: z3py.py:2683
Z3_string Z3_API Z3_get_symbol_string(__in Z3_context c, __in Z3_symbol s)
Return the symbol name.
def is_add(a)
Definition: z3py.py:2329
void Z3_API Z3_probe_dec_ref(__in Z3_context c, __in Z3_probe p)
Decrement the reference counter of the given probe.
Z3_ast Z3_API Z3_mk_eq(__in Z3_context c, __in Z3_ast l, __in Z3_ast r)
Create an AST node representing l = r.
def parse_smt2_string
Definition: z3py.py:7288
def ParOr(ts, ks)
Definition: z3py.py:6611
def K(dom, v)
Definition: z3py.py:4085
def BitVec
Definition: z3py.py:3476
Z3_tactic Z3_API Z3_tactic_par_or(__in Z3_context c, __in unsigned num, __in_ecount(num) Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
def fpToReal(x)
Definition: z3py.py:8464
def ParAndThen
Definition: z3py.py:6643
def get_assertions(self)
Definition: z3py.py:6288
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
def get_num_levels(self, predicate)
Definition: z3py.py:6247
def UGT(a, b)
Definition: z3py.py:3610
void Z3_API Z3_fixedpoint_set_predicate_representation(__in Z3_context c, __in Z3_fixedpoint d, __in Z3_func_decl f, __in unsigned num_relations, __in_ecount(num_relations) Z3_symbol const relation_kinds[])
Configure the predicate representation.
def fpDiv(rm, a, b)
Definition: z3py.py:8153
Z3_sort_kind Z3_API Z3_get_sort_kind(__in Z3_context c, __in Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def get_answer(self)
Definition: z3py.py:6242
def children(self)
Definition: z3py.py:862
def arity(self)
Definition: z3py.py:5236
def Store(a, i, v)
Definition: z3py.py:4033
Z3_ast Z3_API Z3_mk_app(__in Z3_context c, __in Z3_func_decl d, __in unsigned num_args, __in_ecount(num_args) Z3_ast const args[])
Create a constant or function application.
def numerator(self)
Definition: z3py.py:2510
Z3_func_decl Z3_API Z3_mk_func_decl(__in Z3_context c, __in Z3_symbol s, __in unsigned domain_size, __in_ecount(domain_size) Z3_sort const domain[], __in Z3_sort range)
Declare a constant or function.
def __str__(self)
Definition: z3py.py:281
def fpNeg(a)
Definition: z3py.py:8077
def is_ast(a)
Definition: z3py.py:352
def domain(self)
Definition: z3py.py:3878
def UDiv(a, b)
Definition: z3py.py:3627
def BV2Int(a)
Definition: z3py.py:3428
def is_expr(a)
Definition: z3py.py:961
def FreshInt
Definition: z3py.py:2763
def __init__(self, result, ctx)
Definition: z3py.py:6344
def set(self, args, keys)
Definition: z3py.py:6132
def Map(f, args)
Definition: z3py.py:4063
def __call__(self, args)
Definition: z3py.py:661
def else_value(self)
Definition: z3py.py:5197
def describe_probes()
Definition: z3py.py:6893
def add_cover(self, level, predicate, property)
Definition: z3py.py:6256
def TryFor
Definition: z3py.py:6679
def describe_tactics()
Definition: z3py.py:6705
def is_bool(a)
Definition: z3py.py:1236
def Distinct(args)
Definition: z3py.py:1114
def to_symbol
Definition: z3py.py:94
def __call__(self, goal)
Definition: z3py.py:6831
def fpToIEEEBV(x)
Definition: z3py.py:8482
def body(self)
Definition: z3py.py:1693
def as_list(self)
Definition: z3py.py:5274
def SimpleSolver
Definition: z3py.py:6096
Z3_tactic Z3_API Z3_tactic_or_else(__in Z3_context c, __in Z3_tactic t1, __in 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 arity(self)
Definition: z3py.py:618
def is_bv(a)
Definition: z3py.py:3401
def is_var(a)
Definition: z3py.py:1024
def as_expr(self)
Definition: z3py.py:6426
void Z3_API Z3_fixedpoint_set_params(__in Z3_context c, __in Z3_fixedpoint f, __in Z3_params p)
Set parameters on fixedpoint context.
def tactic_description
Definition: z3py.py:6697
tuple _error_handler_fptr
Definition: z3py.py:108
Z3_symbol Z3_API Z3_mk_int_symbol(__in Z3_context c, __in int i)
Create a Z3 symbol using an integer.
def convert_model
Definition: z3py.py:6395
def RepeatBitVec(n, a)
Definition: z3py.py:3804
Z3_ast Z3_API Z3_mk_add(__in Z3_context c, __in unsigned num_args, __in_ecount(num_args) Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].The array args must have num_args el...
Z3_ast Z3_API Z3_get_app_arg(__in Z3_context c, __in Z3_app a, __in unsigned i)
Return the i-th argument of the given application.
void Z3_API Z3_set_param_value(__in Z3_config c, __in Z3_string param_id, __in Z3_string param_value)
Set a configuration parameter.
Z3_probe Z3_API Z3_mk_probe(__in Z3_context c, __in Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
def FPSort
Definition: z3py.py:7920
def as_ast(self)
Definition: z3py.py:598
def is_false(a)
Definition: z3py.py:1270
def ULE(a, b)
Definition: z3py.py:3559
def is_is_int(a)
Definition: z3py.py:2444
def BitVecs
Definition: z3py.py:3499
void Z3_API Z3_tactic_inc_ref(__in Z3_context c, __in Z3_tactic t)
Increment the reference counter of the given tactic.
def enable_trace(msg)
Definition: z3py.py:58
def Sqrt
Definition: z3py.py:2878
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(__in Z3_context c, __in Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def name(self)
Definition: z3py.py:498
def is_fprm(a)
Definition: z3py.py:7797
double Z3_API Z3_probe_apply(__in Z3_context c, __in Z3_probe p, __in Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0...
def tactics
Definition: z3py.py:6687
def as_signed_long(self)
Definition: z3py.py:3376
def RatVal
Definition: z3py.py:2701
Z3_ast Z3_API Z3_simplify_ex(__in Z3_context c, __in Z3_ast a, __in Z3_params p)
Interface to simplifier.
def __del__(self)
Definition: z3py.py:6128
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(__in Z3_context c)
Return the parameter description set for the simplify procedure.
def is_func_decl(a)
Definition: z3py.py:693
def interrupt(self)
Definition: z3py.py:177
def is_sub(a)
Definition: z3py.py:2351
def BoolVector
Definition: z3py.py:1397
def Concat(args)
Definition: z3py.py:3519
unsigned Z3_API Z3_apply_result_get_num_subgoals(__in Z3_context c, __in Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def IntVal
Definition: z3py.py:2672
def append(self, args)
Definition: z3py.py:6164
def is_algebraic_value(a)
Definition: z3py.py:2316
def get_param(name)
Definition: z3py.py:247
def is_to_int(a)
Definition: z3py.py:2469
def __eq__(self, other)
Definition: z3py.py:6804
def reason_unknown(self)
Definition: z3py.py:6314
Z3_bool Z3_API Z3_is_eq_sort(__in Z3_context c, __in Z3_sort s1, __in Z3_sort s2)
compare sorts.
Z3_ast Z3_API Z3_fixedpoint_get_answer(__in Z3_context c, __in Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
def ToInt(a)
Definition: z3py.py:2845
def num_entries(self)
Definition: z3py.py:5220
def __del__(self)
Definition: z3py.py:278
def is_fp(a)
Definition: z3py.py:7893
def __eq__(self, other)
Definition: z3py.py:508