Z3
z3py.py
Go to the documentation of this file.
1 
2 
9 
10 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
11 
12 Several online tutorials for Z3Py are available at:
13 http://rise4fun.com/Z3Py/tutorial/guide
14 
15 Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
16 
17 Small example:
18 
19 >>> x = Int('x')
20 >>> y = Int('y')
21 >>> s = Solver()
22 >>> s.add(x > 0)
23 >>> s.add(x < 2)
24 >>> s.add(y == x + 1)
25 >>> s.check()
26 sat
27 >>> m = s.model()
28 >>> m[x]
29 1
30 >>> m[y]
31 2
32 
33 Z3 exceptions:
34 
35 >>> try:
36 ... x = BitVec('x', 32)
37 ... y = Bool('y')
38 ... # the expression x + y is type incorrect
39 ... n = x + y
40 ... except Z3Exception as ex:
41 ... print("failed: %s" % ex)
42 failed: sort mismatch
43 """
44 from . import z3core
45 from .z3core import *
46 from .z3types import *
47 from .z3consts import *
48 from .z3printer import *
49 from fractions import Fraction
50 import sys
51 import io
52 import math
53 import copy
54 
55 if sys.version < '3':
56  def _is_int(v):
57  return isinstance(v, (int, long))
58 else:
59  def _is_int(v):
60  return isinstance(v, int)
61 
62 def enable_trace(msg):
63  Z3_enable_trace(msg)
64 
65 def disable_trace(msg):
66  Z3_disable_trace(msg)
67 
69  major = ctypes.c_uint(0)
70  minor = ctypes.c_uint(0)
71  build = ctypes.c_uint(0)
72  rev = ctypes.c_uint(0)
73  Z3_get_version(major, minor, build, rev)
74  return "%s.%s.%s" % (major.value, minor.value, build.value)
75 
77  major = ctypes.c_uint(0)
78  minor = ctypes.c_uint(0)
79  build = ctypes.c_uint(0)
80  rev = ctypes.c_uint(0)
81  Z3_get_version(major, minor, build, rev)
82  return (major.value, minor.value, build.value, rev.value)
83 
85  return Z3_get_full_version()
86 
87 # We use _z3_assert instead of the assert command because we want to
88 # produce nice error messages in Z3Py at rise4fun.com
89 def _z3_assert(cond, msg):
90  if not cond:
91  raise Z3Exception(msg)
92 
93 def open_log(fname):
94  """Log interaction to a file. This function must be invoked immediately after init(). """
95  Z3_open_log(fname)
96 
97 def append_log(s):
98  """Append user-defined string to interaction log. """
99  Z3_append_log(s)
100 
101 def to_symbol(s, ctx=None):
102  """Convert an integer or string into a Z3 symbol."""
103  if _is_int(s):
104  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
105  else:
106  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
107 
108 def _symbol2py(ctx, s):
109  """Convert a Z3 symbol back into a Python object. """
110  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
111  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
112  else:
113  return Z3_get_symbol_string(ctx.ref(), s)
114 
115 # Hack for having nary functions that can receive one argument that is the
116 # list of arguments.
117 def _get_args(args):
118  try:
119  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
120  return args[0]
121  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
122  return [arg for arg in args[0]]
123  else:
124  return args
125  except: # len is not necessarily defined when args is not a sequence (use reflection?)
126  return args
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 
138  # Do nothing error handler, just avoid exit(0)
139  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
140  return
141 
142 class Context:
143  """A Context manages all other Z3 objects, global configuration options, etc.
144 
145  Z3Py uses a default global context. For most applications this is sufficient.
146  An application may use multiple Z3 contexts. Objects created in one context
147  cannot be used in another one. However, several objects may be "translated" from
148  one context to another. It is not safe to access Z3 objects from multiple threads.
149  The only exception is the method `interrupt()` that can be used to interrupt() a long
150  computation.
151  The initialization method receives global configuration options for the new context.
152  """
153  def __init__(self, *args, **kws):
154  if __debug__:
155  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
156  conf = Z3_mk_config()
157  for key in kws:
158  value = kws[key]
159  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
160  prev = None
161  for a in args:
162  if prev is None:
163  prev = a
164  else:
165  Z3_set_param_value(conf, str(prev), _to_param_value(a))
166  prev = None
167  self.ctx = Z3_mk_context_rc(conf)
168  self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
169  Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
170  Z3_del_config(conf)
171 
172  def __del__(self):
173  Z3_del_context(self.ctx)
174  self.ctx = None
175  self.eh = None
176 
177  def ref(self):
178  """Return a reference to the actual C pointer to the Z3 context."""
179  return self.ctx
180 
181  def interrupt(self):
182  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
183 
184  This method can be invoked from a thread different from the one executing the
185  interruptable procedure.
186  """
187  Z3_interrupt(self.ref())
188 
189 
190 # Global Z3 context
191 _main_ctx = None
192 def main_ctx():
193  """Return a reference to the global Z3 context.
194 
195  >>> x = Real('x')
196  >>> x.ctx == main_ctx()
197  True
198  >>> c = Context()
199  >>> c == main_ctx()
200  False
201  >>> x2 = Real('x', c)
202  >>> x2.ctx == c
203  True
204  >>> eq(x, x2)
205  False
206  """
207  global _main_ctx
208  if _main_ctx is None:
209  _main_ctx = Context()
210  return _main_ctx
211 
212 def _get_ctx(ctx):
213  if ctx is None:
214  return main_ctx()
215  else:
216  return ctx
217 
218 def set_param(*args, **kws):
219  """Set Z3 global (or module) parameters.
220 
221  >>> set_param(precision=10)
222  """
223  if __debug__:
224  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
225  new_kws = {}
226  for k in kws:
227  v = kws[k]
228  if not set_pp_option(k, v):
229  new_kws[k] = v
230  for key in new_kws:
231  value = new_kws[key]
232  Z3_global_param_set(str(key).upper(), _to_param_value(value))
233  prev = None
234  for a in args:
235  if prev is None:
236  prev = a
237  else:
238  Z3_global_param_set(str(prev), _to_param_value(a))
239  prev = None
240 
242  """Reset all global (or module) parameters.
243  """
245 
246 def set_option(*args, **kws):
247  """Alias for 'set_param' for backward compatibility.
248  """
249  return set_param(*args, **kws)
250 
251 def get_param(name):
252  """Return the value of a Z3 global (or module) parameter
253 
254  >>> get_param('nlsat.reorder')
255  'true'
256  """
257  ptr = (ctypes.c_char_p * 1)()
258  if Z3_global_param_get(str(name), ptr):
259  r = z3core._to_pystr(ptr[0])
260  return r
261  raise Z3Exception("failed to retrieve value for '%s'" % name)
262 
263 
268 
269 # Mark objects that use pretty printer
271  """Superclass for all Z3 objects that have support for pretty printing."""
272  def use_pp(self):
273  return True
274 
276  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
277  def __init__(self, ast, ctx=None):
278  self.ast = ast
279  self.ctx = _get_ctx(ctx)
280  Z3_inc_ref(self.ctx.ref(), self.as_ast())
281 
282  def __del__(self):
283  if self.ctx.ref() is not None:
284  Z3_dec_ref(self.ctx.ref(), self.as_ast())
285 
286  def __deepcopy__(self, memo={}):
287  return _to_ast_ref(self.ast, self.ctx)
288 
289  def __str__(self):
290  return obj_to_string(self)
291 
292  def __repr__(self):
293  return obj_to_string(self)
294 
295  def __eq__(self, other):
296  return self.eq(other)
297 
298  def __hash__(self):
299  return self.hash()
300 
301  def __nonzero__(self):
302  return self.__bool__()
303 
304  def __bool__(self):
305  if is_true(self):
306  return True
307  elif is_false(self):
308  return False
309  elif is_eq(self) and self.num_args() == 2:
310  return self.arg(0).eq(self.arg(1))
311  else:
312  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
313 
314  def sexpr(self):
315  """Return a string representing the AST node in s-expression notation.
316 
317  >>> x = Int('x')
318  >>> ((x + 1)*x).sexpr()
319  '(* (+ x 1) x)'
320  """
321  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
322 
323  def as_ast(self):
324  """Return a pointer to the corresponding C Z3_ast object."""
325  return self.ast
326 
327  def get_id(self):
328  """Return unique identifier for object. It can be used for hash-tables and maps."""
329  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
330 
331  def ctx_ref(self):
332  """Return a reference to the C context where this AST node is stored."""
333  return self.ctx.ref()
334 
335  def eq(self, other):
336  """Return `True` if `self` and `other` are structurally identical.
337 
338  >>> x = Int('x')
339  >>> n1 = x + 1
340  >>> n2 = 1 + x
341  >>> n1.eq(n2)
342  False
343  >>> n1 = simplify(n1)
344  >>> n2 = simplify(n2)
345  >>> n1.eq(n2)
346  True
347  """
348  if __debug__:
349  _z3_assert(is_ast(other), "Z3 AST expected")
350  return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
351 
352  def translate(self, target):
353  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
354 
355  >>> c1 = Context()
356  >>> c2 = Context()
357  >>> x = Int('x', c1)
358  >>> y = Int('y', c2)
359  >>> # Nodes in different contexts can't be mixed.
360  >>> # However, we can translate nodes from one context to another.
361  >>> x.translate(c2) + y
362  x + y
363  """
364  if __debug__:
365  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
366  return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
367 
368  def hash(self):
369  """Return a hashcode for the `self`.
370 
371  >>> n1 = simplify(Int('x') + 1)
372  >>> n2 = simplify(2 + Int('x') - 1)
373  >>> n1.hash() == n2.hash()
374  True
375  """
376  return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
377 
378 def is_ast(a):
379  """Return `True` if `a` is an AST node.
380 
381  >>> is_ast(10)
382  False
383  >>> is_ast(IntVal(10))
384  True
385  >>> is_ast(Int('x'))
386  True
387  >>> is_ast(BoolSort())
388  True
389  >>> is_ast(Function('f', IntSort(), IntSort()))
390  True
391  >>> is_ast("x")
392  False
393  >>> is_ast(Solver())
394  False
395  """
396  return isinstance(a, AstRef)
397 
398 def eq(a, b):
399  """Return `True` if `a` and `b` are structurally identical AST nodes.
400 
401  >>> x = Int('x')
402  >>> y = Int('y')
403  >>> eq(x, y)
404  False
405  >>> eq(x + 1, x + 1)
406  True
407  >>> eq(x + 1, 1 + x)
408  False
409  >>> eq(simplify(x + 1), simplify(1 + x))
410  True
411  """
412  if __debug__:
413  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
414  return a.eq(b)
415 
416 def _ast_kind(ctx, a):
417  if is_ast(a):
418  a = a.as_ast()
419  return Z3_get_ast_kind(ctx.ref(), a)
420 
421 def _ctx_from_ast_arg_list(args, default_ctx=None):
422  ctx = None
423  for a in args:
424  if is_ast(a) or is_probe(a):
425  if ctx is None:
426  ctx = a.ctx
427  else:
428  if __debug__:
429  _z3_assert(ctx == a.ctx, "Context mismatch")
430  if ctx is None:
431  ctx = default_ctx
432  return ctx
433 
434 def _ctx_from_ast_args(*args):
435  return _ctx_from_ast_arg_list(args)
436 
437 def _to_func_decl_array(args):
438  sz = len(args)
439  _args = (FuncDecl * sz)()
440  for i in range(sz):
441  _args[i] = args[i].as_func_decl()
442  return _args, sz
443 
444 def _to_ast_array(args):
445  sz = len(args)
446  _args = (Ast * sz)()
447  for i in range(sz):
448  _args[i] = args[i].as_ast()
449  return _args, sz
450 
451 def _to_ref_array(ref, args):
452  sz = len(args)
453  _args = (ref * sz)()
454  for i in range(sz):
455  _args[i] = args[i].as_ast()
456  return _args, sz
457 
458 def _to_ast_ref(a, ctx):
459  k = _ast_kind(ctx, a)
460  if k == Z3_SORT_AST:
461  return _to_sort_ref(a, ctx)
462  elif k == Z3_FUNC_DECL_AST:
463  return _to_func_decl_ref(a, ctx)
464  else:
465  return _to_expr_ref(a, ctx)
466 
467 
472 
473 def _sort_kind(ctx, s):
474  return Z3_get_sort_kind(ctx.ref(), s)
475 
477  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
478  def as_ast(self):
479  return Z3_sort_to_ast(self.ctx_ref(), self.ast)
480 
481  def get_id(self):
482  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
483 
484  def kind(self):
485  """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
486 
487  >>> b = BoolSort()
488  >>> b.kind() == Z3_BOOL_SORT
489  True
490  >>> b.kind() == Z3_INT_SORT
491  False
492  >>> A = ArraySort(IntSort(), IntSort())
493  >>> A.kind() == Z3_ARRAY_SORT
494  True
495  >>> A.kind() == Z3_INT_SORT
496  False
497  """
498  return _sort_kind(self.ctx, self.ast)
499 
500  def subsort(self, other):
501  """Return `True` if `self` is a subsort of `other`.
502 
503  >>> IntSort().subsort(RealSort())
504  True
505  """
506  return False
507 
508  def cast(self, val):
509  """Try to cast `val` as an element of sort `self`.
510 
511  This method is used in Z3Py to convert Python objects such as integers,
512  floats, longs and strings into Z3 expressions.
513 
514  >>> x = Int('x')
515  >>> RealSort().cast(x)
516  ToReal(x)
517  """
518  if __debug__:
519  _z3_assert(is_expr(val), "Z3 expression expected")
520  _z3_assert(self.eq(val.sort()), "Sort mismatch")
521  return val
522 
523  def name(self):
524  """Return the name (string) of sort `self`.
525 
526  >>> BoolSort().name()
527  'Bool'
528  >>> ArraySort(IntSort(), IntSort()).name()
529  'Array'
530  """
531  return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
532 
533  def __eq__(self, other):
534  """Return `True` if `self` and `other` are the same Z3 sort.
535 
536  >>> p = Bool('p')
537  >>> p.sort() == BoolSort()
538  True
539  >>> p.sort() == IntSort()
540  False
541  """
542  if other is None:
543  return False
544  return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
545 
546  def __ne__(self, other):
547  """Return `True` if `self` and `other` are not the same Z3 sort.
548 
549  >>> p = Bool('p')
550  >>> p.sort() != BoolSort()
551  False
552  >>> p.sort() != IntSort()
553  True
554  """
555  return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
556 
557  def __hash__(self):
558  """ Hash code. """
559  return AstRef.__hash__(self)
560 
561 def is_sort(s):
562  """Return `True` if `s` is a Z3 sort.
563 
564  >>> is_sort(IntSort())
565  True
566  >>> is_sort(Int('x'))
567  False
568  >>> is_expr(Int('x'))
569  True
570  """
571  return isinstance(s, SortRef)
572 
573 def _to_sort_ref(s, ctx):
574  if __debug__:
575  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
576  k = _sort_kind(ctx, s)
577  if k == Z3_BOOL_SORT:
578  return BoolSortRef(s, ctx)
579  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
580  return ArithSortRef(s, ctx)
581  elif k == Z3_BV_SORT:
582  return BitVecSortRef(s, ctx)
583  elif k == Z3_ARRAY_SORT:
584  return ArraySortRef(s, ctx)
585  elif k == Z3_DATATYPE_SORT:
586  return DatatypeSortRef(s, ctx)
587  elif k == Z3_FINITE_DOMAIN_SORT:
588  return FiniteDomainSortRef(s, ctx)
589  elif k == Z3_FLOATING_POINT_SORT:
590  return FPSortRef(s, ctx)
591  elif k == Z3_ROUNDING_MODE_SORT:
592  return FPRMSortRef(s, ctx)
593  return SortRef(s, ctx)
594 
595 def _sort(ctx, a):
596  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
597 
598 def DeclareSort(name, ctx=None):
599  """Create a new uninterpred sort named `name`.
600 
601  If `ctx=None`, then the new sort is declared in the global Z3Py context.
602 
603  >>> A = DeclareSort('A')
604  >>> a = Const('a', A)
605  >>> b = Const('b', A)
606  >>> a.sort() == A
607  True
608  >>> b.sort() == A
609  True
610  >>> a == b
611  a == b
612  """
613  ctx = _get_ctx(ctx)
614  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
615 
616 
621 
623  """Function declaration. Every constant and function have an associated declaration.
624 
625  The declaration assigns a name, a sort (i.e., type), and for function
626  the sort (i.e., type) of each of its arguments. Note that, in Z3,
627  a constant is a function with 0 arguments.
628  """
629  def as_ast(self):
630  return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
631 
632  def get_id(self):
633  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
634 
635  def as_func_decl(self):
636  return self.ast
637 
638  def name(self):
639  """Return the name of the function declaration `self`.
640 
641  >>> f = Function('f', IntSort(), IntSort())
642  >>> f.name()
643  'f'
644  >>> isinstance(f.name(), str)
645  True
646  """
647  return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
648 
649  def arity(self):
650  """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
651 
652  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
653  >>> f.arity()
654  2
655  """
656  return int(Z3_get_arity(self.ctx_ref(), self.ast))
657 
658  def domain(self, i):
659  """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
660 
661  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
662  >>> f.domain(0)
663  Int
664  >>> f.domain(1)
665  Real
666  """
667  if __debug__:
668  _z3_assert(i < self.arity(), "Index out of bounds")
669  return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
670 
671  def range(self):
672  """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
673 
674  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
675  >>> f.range()
676  Bool
677  """
678  return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
679 
680  def kind(self):
681  """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
682 
683  >>> x = Int('x')
684  >>> d = (x + 1).decl()
685  >>> d.kind() == Z3_OP_ADD
686  True
687  >>> d.kind() == Z3_OP_MUL
688  False
689  """
690  return Z3_get_decl_kind(self.ctx_ref(), self.ast)
691 
692  def params(self):
693  ctx = self.ctx
694  n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
695  result = [ None for i in range(n) ]
696  for i in range(n):
697  k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
698  if k == Z3_PARAMETER_INT:
699  result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
700  elif k == Z3_PARAMETER_DOUBLE:
701  result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
702  elif k == Z3_PARAMETER_RATIONAL:
703  result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
704  elif k == Z3_PARAMETER_SYMBOL:
705  result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
706  elif k == Z3_PARAMETER_SORT:
707  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
708  elif k == Z3_PARAMETER_AST:
709  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
710  elif k == Z3_PARAMETER_FUNC_DECL:
711  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
712  else:
713  assert(False)
714  return result
715 
716  def __call__(self, *args):
717  """Create a Z3 application expression using the function `self`, and the given arguments.
718 
719  The arguments must be Z3 expressions. This method assumes that
720  the sorts of the elements in `args` match the sorts of the
721  domain. Limited coersion is supported. For example, if
722  args[0] is a Python integer, and the function expects a Z3
723  integer, then the argument is automatically converted into a
724  Z3 integer.
725 
726  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
727  >>> x = Int('x')
728  >>> y = Real('y')
729  >>> f(x, y)
730  f(x, y)
731  >>> f(x, x)
732  f(x, ToReal(x))
733  """
734  args = _get_args(args)
735  num = len(args)
736  if __debug__:
737  _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
738  _args = (Ast * num)()
739  saved = []
740  for i in range(num):
741  # self.domain(i).cast(args[i]) may create a new Z3 expression,
742  # then we must save in 'saved' to prevent it from being garbage collected.
743  tmp = self.domain(i).cast(args[i])
744  saved.append(tmp)
745  _args[i] = tmp.as_ast()
746  return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
747 
749  """Return `True` if `a` is a Z3 function declaration.
750 
751  >>> f = Function('f', IntSort(), IntSort())
752  >>> is_func_decl(f)
753  True
754  >>> x = Real('x')
755  >>> is_func_decl(x)
756  False
757  """
758  return isinstance(a, FuncDeclRef)
759 
760 def Function(name, *sig):
761  """Create a new Z3 uninterpreted function with the given sorts.
762 
763  >>> f = Function('f', IntSort(), IntSort())
764  >>> f(f(0))
765  f(f(0))
766  """
767  sig = _get_args(sig)
768  if __debug__:
769  _z3_assert(len(sig) > 0, "At least two arguments expected")
770  arity = len(sig) - 1
771  rng = sig[arity]
772  if __debug__:
773  _z3_assert(is_sort(rng), "Z3 sort expected")
774  dom = (Sort * arity)()
775  for i in range(arity):
776  if __debug__:
777  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
778  dom[i] = sig[i].ast
779  ctx = rng.ctx
780  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
781 
782 def _to_func_decl_ref(a, ctx):
783  return FuncDeclRef(a, ctx)
784 
785 
790 
792  """Constraints, formulas and terms are expressions in Z3.
793 
794  Expressions are ASTs. Every expression has a sort.
795  There are three main kinds of expressions:
796  function applications, quantifiers and bounded variables.
797  A constant is a function application with 0 arguments.
798  For quantifier free problems, all expressions are
799  function applications.
800  """
801  def as_ast(self):
802  return self.ast
803 
804  def get_id(self):
805  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
806 
807  def sort(self):
808  """Return the sort of expression `self`.
809 
810  >>> x = Int('x')
811  >>> (x + 1).sort()
812  Int
813  >>> y = Real('y')
814  >>> (x + y).sort()
815  Real
816  """
817  return _sort(self.ctx, self.as_ast())
818 
819  def sort_kind(self):
820  """Shorthand for `self.sort().kind()`.
821 
822  >>> a = Array('a', IntSort(), IntSort())
823  >>> a.sort_kind() == Z3_ARRAY_SORT
824  True
825  >>> a.sort_kind() == Z3_INT_SORT
826  False
827  """
828  return self.sort().kind()
829 
830  def __eq__(self, other):
831  """Return a Z3 expression that represents the constraint `self == other`.
832 
833  If `other` is `None`, then this method simply returns `False`.
834 
835  >>> a = Int('a')
836  >>> b = Int('b')
837  >>> a == b
838  a == b
839  >>> a is None
840  False
841  """
842  if other is None:
843  return False
844  a, b = _coerce_exprs(self, other)
845  return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
846 
847  def __hash__(self):
848  """ Hash code. """
849  return AstRef.__hash__(self)
850 
851  def __ne__(self, other):
852  """Return a Z3 expression that represents the constraint `self != other`.
853 
854  If `other` is `None`, then this method simply returns `True`.
855 
856  >>> a = Int('a')
857  >>> b = Int('b')
858  >>> a != b
859  a != b
860  >>> a is not None
861  True
862  """
863  if other is None:
864  return True
865  a, b = _coerce_exprs(self, other)
866  _args, sz = _to_ast_array((a, b))
867  return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
868 
869  def params(self):
870  return self.decl().params()
871 
872  def decl(self):
873  """Return the Z3 function declaration associated with a Z3 application.
874 
875  >>> f = Function('f', IntSort(), IntSort())
876  >>> a = Int('a')
877  >>> t = f(a)
878  >>> eq(t.decl(), f)
879  True
880  >>> (a + 1).decl()
881  +
882  """
883  if __debug__:
884  _z3_assert(is_app(self), "Z3 application expected")
885  return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
886 
887  def num_args(self):
888  """Return the number of arguments of a Z3 application.
889 
890  >>> a = Int('a')
891  >>> b = Int('b')
892  >>> (a + b).num_args()
893  2
894  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
895  >>> t = f(a, b, 0)
896  >>> t.num_args()
897  3
898  """
899  if __debug__:
900  _z3_assert(is_app(self), "Z3 application expected")
901  return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
902 
903  def arg(self, idx):
904  """Return argument `idx` of the application `self`.
905 
906  This method assumes that `self` is a function application with at least `idx+1` arguments.
907 
908  >>> a = Int('a')
909  >>> b = Int('b')
910  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
911  >>> t = f(a, b, 0)
912  >>> t.arg(0)
913  a
914  >>> t.arg(1)
915  b
916  >>> t.arg(2)
917  0
918  """
919  if __debug__:
920  _z3_assert(is_app(self), "Z3 application expected")
921  _z3_assert(idx < self.num_args(), "Invalid argument index")
922  return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
923 
924  def children(self):
925  """Return a list containing the children of the given expression
926 
927  >>> a = Int('a')
928  >>> b = Int('b')
929  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
930  >>> t = f(a, b, 0)
931  >>> t.children()
932  [a, b, 0]
933  """
934  if is_app(self):
935  return [self.arg(i) for i in range(self.num_args())]
936  else:
937  return []
938 
939 def _to_expr_ref(a, ctx):
940  if isinstance(a, Pattern):
941  return PatternRef(a, ctx)
942  ctx_ref = ctx.ref()
943  k = Z3_get_ast_kind(ctx_ref, a)
944  if k == Z3_QUANTIFIER_AST:
945  return QuantifierRef(a, ctx)
946  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
947  if sk == Z3_BOOL_SORT:
948  return BoolRef(a, ctx)
949  if sk == Z3_INT_SORT:
950  if k == Z3_NUMERAL_AST:
951  return IntNumRef(a, ctx)
952  return ArithRef(a, ctx)
953  if sk == Z3_REAL_SORT:
954  if k == Z3_NUMERAL_AST:
955  return RatNumRef(a, ctx)
956  if _is_algebraic(ctx, a):
957  return AlgebraicNumRef(a, ctx)
958  return ArithRef(a, ctx)
959  if sk == Z3_BV_SORT:
960  if k == Z3_NUMERAL_AST:
961  return BitVecNumRef(a, ctx)
962  else:
963  return BitVecRef(a, ctx)
964  if sk == Z3_ARRAY_SORT:
965  return ArrayRef(a, ctx)
966  if sk == Z3_DATATYPE_SORT:
967  return DatatypeRef(a, ctx)
968  if sk == Z3_FLOATING_POINT_SORT:
969  if k == Z3_APP_AST and _is_numeral(ctx, a):
970  return FPNumRef(a, ctx)
971  else:
972  return FPRef(a, ctx)
973  if sk == Z3_FINITE_DOMAIN_SORT:
974  if k == Z3_NUMERAL_AST:
975  return FiniteDomainNumRef(a, ctx)
976  else:
977  return FiniteDomainRef(a, ctx)
978  if sk == Z3_ROUNDING_MODE_SORT:
979  return FPRMRef(a, ctx)
980  if sk == Z3_SEQ_SORT:
981  return SeqRef(a, ctx)
982  if sk == Z3_RE_SORT:
983  return ReRef(a, ctx)
984  return ExprRef(a, ctx)
985 
986 def _coerce_expr_merge(s, a):
987  if is_expr(a):
988  s1 = a.sort()
989  if s is None:
990  return s1
991  if s1.eq(s):
992  return s
993  elif s.subsort(s1):
994  return s1
995  elif s1.subsort(s):
996  return s
997  else:
998  if __debug__:
999  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1000  _z3_assert(False, "sort mismatch")
1001  else:
1002  return s
1003 
1004 def _coerce_exprs(a, b, ctx=None):
1005  if not is_expr(a) and not is_expr(b):
1006  a = _py2expr(a, ctx)
1007  b = _py2expr(b, ctx)
1008  s = None
1009  s = _coerce_expr_merge(s, a)
1010  s = _coerce_expr_merge(s, b)
1011  a = s.cast(a)
1012  b = s.cast(b)
1013  return (a, b)
1014 
1015 
1016 def _reduce(f, l, a):
1017  r = a
1018  for e in l:
1019  r = f(r, e)
1020  return r
1021 
1022 def _coerce_expr_list(alist, ctx=None):
1023  has_expr = False
1024  for a in alist:
1025  if is_expr(a):
1026  has_expr = True
1027  break
1028  if not has_expr:
1029  alist = [ _py2expr(a, ctx) for a in alist ]
1030  s = _reduce(_coerce_expr_merge, alist, None)
1031  return [ s.cast(a) for a in alist ]
1032 
1033 def is_expr(a):
1034  """Return `True` if `a` is a Z3 expression.
1035 
1036  >>> a = Int('a')
1037  >>> is_expr(a)
1038  True
1039  >>> is_expr(a + 1)
1040  True
1041  >>> is_expr(IntSort())
1042  False
1043  >>> is_expr(1)
1044  False
1045  >>> is_expr(IntVal(1))
1046  True
1047  >>> x = Int('x')
1048  >>> is_expr(ForAll(x, x >= 0))
1049  True
1050  >>> is_expr(FPVal(1.0))
1051  True
1052  """
1053  return isinstance(a, ExprRef)
1054 
1055 def is_app(a):
1056  """Return `True` if `a` is a Z3 function application.
1057 
1058  Note that, constants are function applications with 0 arguments.
1059 
1060  >>> a = Int('a')
1061  >>> is_app(a)
1062  True
1063  >>> is_app(a + 1)
1064  True
1065  >>> is_app(IntSort())
1066  False
1067  >>> is_app(1)
1068  False
1069  >>> is_app(IntVal(1))
1070  True
1071  >>> x = Int('x')
1072  >>> is_app(ForAll(x, x >= 0))
1073  False
1074  """
1075  if not isinstance(a, ExprRef):
1076  return False
1077  k = _ast_kind(a.ctx, a)
1078  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1079 
1080 def is_const(a):
1081  """Return `True` if `a` is Z3 constant/variable expression.
1082 
1083  >>> a = Int('a')
1084  >>> is_const(a)
1085  True
1086  >>> is_const(a + 1)
1087  False
1088  >>> is_const(1)
1089  False
1090  >>> is_const(IntVal(1))
1091  True
1092  >>> x = Int('x')
1093  >>> is_const(ForAll(x, x >= 0))
1094  False
1095  """
1096  return is_app(a) and a.num_args() == 0
1097 
1098 def is_var(a):
1099  """Return `True` if `a` is variable.
1100 
1101  Z3 uses de-Bruijn indices for representing bound variables in
1102  quantifiers.
1103 
1104  >>> x = Int('x')
1105  >>> is_var(x)
1106  False
1107  >>> is_const(x)
1108  True
1109  >>> f = Function('f', IntSort(), IntSort())
1110  >>> # Z3 replaces x with bound variables when ForAll is executed.
1111  >>> q = ForAll(x, f(x) == x)
1112  >>> b = q.body()
1113  >>> b
1114  f(Var(0)) == Var(0)
1115  >>> b.arg(1)
1116  Var(0)
1117  >>> is_var(b.arg(1))
1118  True
1119  """
1120  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1121 
1123  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1124 
1125  >>> x = Int('x')
1126  >>> y = Int('y')
1127  >>> is_var(x)
1128  False
1129  >>> is_const(x)
1130  True
1131  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1132  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1133  >>> q = ForAll([x, y], f(x, y) == x + y)
1134  >>> q.body()
1135  f(Var(1), Var(0)) == Var(1) + Var(0)
1136  >>> b = q.body()
1137  >>> b.arg(0)
1138  f(Var(1), Var(0))
1139  >>> v1 = b.arg(0).arg(0)
1140  >>> v2 = b.arg(0).arg(1)
1141  >>> v1
1142  Var(1)
1143  >>> v2
1144  Var(0)
1145  >>> get_var_index(v1)
1146  1
1147  >>> get_var_index(v2)
1148  0
1149  """
1150  if __debug__:
1151  _z3_assert(is_var(a), "Z3 bound variable expected")
1152  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1153 
1154 def is_app_of(a, k):
1155  """Return `True` if `a` is an application of the given kind `k`.
1156 
1157  >>> x = Int('x')
1158  >>> n = x + 1
1159  >>> is_app_of(n, Z3_OP_ADD)
1160  True
1161  >>> is_app_of(n, Z3_OP_MUL)
1162  False
1163  """
1164  return is_app(a) and a.decl().kind() == k
1165 
1166 def If(a, b, c, ctx=None):
1167  """Create a Z3 if-then-else expression.
1168 
1169  >>> x = Int('x')
1170  >>> y = Int('y')
1171  >>> max = If(x > y, x, y)
1172  >>> max
1173  If(x > y, x, y)
1174  >>> simplify(max)
1175  If(x <= y, y, x)
1176  """
1177  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1178  return Cond(a, b, c, ctx)
1179  else:
1180  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1181  s = BoolSort(ctx)
1182  a = s.cast(a)
1183  b, c = _coerce_exprs(b, c, ctx)
1184  if __debug__:
1185  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1186  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1187 
1188 def Distinct(*args):
1189  """Create a Z3 distinct expression.
1190 
1191  >>> x = Int('x')
1192  >>> y = Int('y')
1193  >>> Distinct(x, y)
1194  x != y
1195  >>> z = Int('z')
1196  >>> Distinct(x, y, z)
1197  Distinct(x, y, z)
1198  >>> simplify(Distinct(x, y, z))
1199  Distinct(x, y, z)
1200  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1201  And(Not(x == y), Not(x == z), Not(y == z))
1202  """
1203  args = _get_args(args)
1204  ctx = _ctx_from_ast_arg_list(args)
1205  if __debug__:
1206  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1207  args = _coerce_expr_list(args, ctx)
1208  _args, sz = _to_ast_array(args)
1209  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1210 
1211 def _mk_bin(f, a, b):
1212  args = (Ast * 2)()
1213  if __debug__:
1214  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1215  args[0] = a.as_ast()
1216  args[1] = b.as_ast()
1217  return f(a.ctx.ref(), 2, args)
1218 
1219 def Const(name, sort):
1220  """Create a constant of the given sort.
1221 
1222  >>> Const('x', IntSort())
1223  x
1224  """
1225  if __debug__:
1226  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1227  ctx = sort.ctx
1228  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1229 
1230 def Consts(names, sort):
1231  """Create a several constants of the given sort.
1232 
1233  `names` is a string containing the names of all constants to be created.
1234  Blank spaces separate the names of different constants.
1235 
1236  >>> x, y, z = Consts('x y z', IntSort())
1237  >>> x + y + z
1238  x + y + z
1239  """
1240  if isinstance(names, str):
1241  names = names.split(" ")
1242  return [Const(name, sort) for name in names]
1243 
1244 def Var(idx, s):
1245  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1246 
1247  >>> Var(0, IntSort())
1248  Var(0)
1249  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1250  False
1251  """
1252  if __debug__:
1253  _z3_assert(is_sort(s), "Z3 sort expected")
1254  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1255 
1256 def RealVar(idx, ctx=None):
1257  """
1258  Create a real free variable. Free variables are used to create quantified formulas.
1259  They are also used to create polynomials.
1260 
1261  >>> RealVar(0)
1262  Var(0)
1263  """
1264  return Var(idx, RealSort(ctx))
1265 
1266 def RealVarVector(n, ctx=None):
1267  """
1268  Create a list of Real free variables.
1269  The variables have ids: 0, 1, ..., n-1
1270 
1271  >>> x0, x1, x2, x3 = RealVarVector(4)
1272  >>> x2
1273  Var(2)
1274  """
1275  return [ RealVar(i, ctx) for i in range(n) ]
1276 
1277 
1282 
1284  """Boolean sort."""
1285  def cast(self, val):
1286  """Try to cast `val` as a Boolean.
1287 
1288  >>> x = BoolSort().cast(True)
1289  >>> x
1290  True
1291  >>> is_expr(x)
1292  True
1293  >>> is_expr(True)
1294  False
1295  >>> x.sort()
1296  Bool
1297  """
1298  if isinstance(val, bool):
1299  return BoolVal(val, self.ctx)
1300  if __debug__:
1301  if not is_expr(val):
1302  _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1303  if not self.eq(val.sort()):
1304  _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1305  return val
1306 
1307  def subsort(self, other):
1308  return isinstance(other, ArithSortRef)
1309 
1310  def is_int(self):
1311  return True
1312 
1313  def is_bool(self):
1314  return True
1315 
1316 
1318  """All Boolean expressions are instances of this class."""
1319  def sort(self):
1320  return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1321 
1322  def __rmul__(self, other):
1323  return self * other
1324 
1325  def __mul__(self, other):
1326  """Create the Z3 expression `self * other`.
1327  """
1328  if other == 1:
1329  return self
1330  if other == 0:
1331  return 0
1332  return If(self, other, 0)
1333 
1334 
1335 def is_bool(a):
1336  """Return `True` if `a` is a Z3 Boolean expression.
1337 
1338  >>> p = Bool('p')
1339  >>> is_bool(p)
1340  True
1341  >>> q = Bool('q')
1342  >>> is_bool(And(p, q))
1343  True
1344  >>> x = Real('x')
1345  >>> is_bool(x)
1346  False
1347  >>> is_bool(x == 0)
1348  True
1349  """
1350  return isinstance(a, BoolRef)
1351 
1352 def is_true(a):
1353  """Return `True` if `a` is the Z3 true expression.
1354 
1355  >>> p = Bool('p')
1356  >>> is_true(p)
1357  False
1358  >>> is_true(simplify(p == p))
1359  True
1360  >>> x = Real('x')
1361  >>> is_true(x == 0)
1362  False
1363  >>> # True is a Python Boolean expression
1364  >>> is_true(True)
1365  False
1366  """
1367  return is_app_of(a, Z3_OP_TRUE)
1368 
1369 def is_false(a):
1370  """Return `True` if `a` is the Z3 false expression.
1371 
1372  >>> p = Bool('p')
1373  >>> is_false(p)
1374  False
1375  >>> is_false(False)
1376  False
1377  >>> is_false(BoolVal(False))
1378  True
1379  """
1380  return is_app_of(a, Z3_OP_FALSE)
1381 
1382 def is_and(a):
1383  """Return `True` if `a` is a Z3 and expression.
1384 
1385  >>> p, q = Bools('p q')
1386  >>> is_and(And(p, q))
1387  True
1388  >>> is_and(Or(p, q))
1389  False
1390  """
1391  return is_app_of(a, Z3_OP_AND)
1392 
1393 def is_or(a):
1394  """Return `True` if `a` is a Z3 or expression.
1395 
1396  >>> p, q = Bools('p q')
1397  >>> is_or(Or(p, q))
1398  True
1399  >>> is_or(And(p, q))
1400  False
1401  """
1402  return is_app_of(a, Z3_OP_OR)
1403 
1404 def is_not(a):
1405  """Return `True` if `a` is a Z3 not expression.
1406 
1407  >>> p = Bool('p')
1408  >>> is_not(p)
1409  False
1410  >>> is_not(Not(p))
1411  True
1412  """
1413  return is_app_of(a, Z3_OP_NOT)
1414 
1415 def is_eq(a):
1416  """Return `True` if `a` is a Z3 equality expression.
1417 
1418  >>> x, y = Ints('x y')
1419  >>> is_eq(x == y)
1420  True
1421  """
1422  return is_app_of(a, Z3_OP_EQ)
1423 
1425  """Return `True` if `a` is a Z3 distinct expression.
1426 
1427  >>> x, y, z = Ints('x y z')
1428  >>> is_distinct(x == y)
1429  False
1430  >>> is_distinct(Distinct(x, y, z))
1431  True
1432  """
1433  return is_app_of(a, Z3_OP_DISTINCT)
1434 
1435 def BoolSort(ctx=None):
1436  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1437 
1438  >>> BoolSort()
1439  Bool
1440  >>> p = Const('p', BoolSort())
1441  >>> is_bool(p)
1442  True
1443  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1444  >>> r(0, 1)
1445  r(0, 1)
1446  >>> is_bool(r(0, 1))
1447  True
1448  """
1449  ctx = _get_ctx(ctx)
1450  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1451 
1452 def BoolVal(val, ctx=None):
1453  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1454 
1455  >>> BoolVal(True)
1456  True
1457  >>> is_true(BoolVal(True))
1458  True
1459  >>> is_true(True)
1460  False
1461  >>> is_false(BoolVal(False))
1462  True
1463  """
1464  ctx = _get_ctx(ctx)
1465  if val == False:
1466  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1467  else:
1468  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1469 
1470 def Bool(name, ctx=None):
1471  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1472 
1473  >>> p = Bool('p')
1474  >>> q = Bool('q')
1475  >>> And(p, q)
1476  And(p, q)
1477  """
1478  ctx = _get_ctx(ctx)
1479  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1480 
1481 def Bools(names, ctx=None):
1482  """Return a tuple of Boolean constants.
1483 
1484  `names` is a single string containing all names separated by blank spaces.
1485  If `ctx=None`, then the global context is used.
1486 
1487  >>> p, q, r = Bools('p q r')
1488  >>> And(p, Or(q, r))
1489  And(p, Or(q, r))
1490  """
1491  ctx = _get_ctx(ctx)
1492  if isinstance(names, str):
1493  names = names.split(" ")
1494  return [Bool(name, ctx) for name in names]
1495 
1496 def BoolVector(prefix, sz, ctx=None):
1497  """Return a list of Boolean constants of size `sz`.
1498 
1499  The constants are named using the given prefix.
1500  If `ctx=None`, then the global context is used.
1501 
1502  >>> P = BoolVector('p', 3)
1503  >>> P
1504  [p__0, p__1, p__2]
1505  >>> And(P)
1506  And(p__0, p__1, p__2)
1507  """
1508  return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1509 
1510 def FreshBool(prefix='b', ctx=None):
1511  """Return a fresh Boolean constant in the given context using the given prefix.
1512 
1513  If `ctx=None`, then the global context is used.
1514 
1515  >>> b1 = FreshBool()
1516  >>> b2 = FreshBool()
1517  >>> eq(b1, b2)
1518  False
1519  """
1520  ctx = _get_ctx(ctx)
1521  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1522 
1523 def Implies(a, b, ctx=None):
1524  """Create a Z3 implies expression.
1525 
1526  >>> p, q = Bools('p q')
1527  >>> Implies(p, q)
1528  Implies(p, q)
1529  >>> simplify(Implies(p, q))
1530  Or(Not(p), q)
1531  """
1532  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1533  s = BoolSort(ctx)
1534  a = s.cast(a)
1535  b = s.cast(b)
1536  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1537 
1538 def Xor(a, b, ctx=None):
1539  """Create a Z3 Xor expression.
1540 
1541  >>> p, q = Bools('p q')
1542  >>> Xor(p, q)
1543  Xor(p, q)
1544  >>> simplify(Xor(p, q))
1545  Not(p) == q
1546  """
1547  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1548  s = BoolSort(ctx)
1549  a = s.cast(a)
1550  b = s.cast(b)
1551  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1552 
1553 def Not(a, ctx=None):
1554  """Create a Z3 not expression or probe.
1555 
1556  >>> p = Bool('p')
1557  >>> Not(Not(p))
1558  Not(Not(p))
1559  >>> simplify(Not(Not(p)))
1560  p
1561  """
1562  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1563  if is_probe(a):
1564  # Not is also used to build probes
1565  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1566  else:
1567  s = BoolSort(ctx)
1568  a = s.cast(a)
1569  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1570 
1571 def _has_probe(args):
1572  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1573  for arg in args:
1574  if is_probe(arg):
1575  return True
1576  return False
1577 
1578 def And(*args):
1579  """Create a Z3 and-expression or and-probe.
1580 
1581  >>> p, q, r = Bools('p q r')
1582  >>> And(p, q, r)
1583  And(p, q, r)
1584  >>> P = BoolVector('p', 5)
1585  >>> And(P)
1586  And(p__0, p__1, p__2, p__3, p__4)
1587  """
1588  last_arg = None
1589  if len(args) > 0:
1590  last_arg = args[len(args)-1]
1591  if isinstance(last_arg, Context):
1592  ctx = args[len(args)-1]
1593  args = args[:len(args)-1]
1594  elif len(args) == 1 and isinstance(args[0], AstVector):
1595  ctx = args[0].ctx
1596  args = [a for a in args[0]]
1597  else:
1598  ctx = main_ctx()
1599  args = _get_args(args)
1600  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1601  if __debug__:
1602  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1603  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1604  if _has_probe(args):
1605  return _probe_and(args, ctx)
1606  else:
1607  args = _coerce_expr_list(args, ctx)
1608  _args, sz = _to_ast_array(args)
1609  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1610 
1611 def Or(*args):
1612  """Create a Z3 or-expression or or-probe.
1613 
1614  >>> p, q, r = Bools('p q r')
1615  >>> Or(p, q, r)
1616  Or(p, q, r)
1617  >>> P = BoolVector('p', 5)
1618  >>> Or(P)
1619  Or(p__0, p__1, p__2, p__3, p__4)
1620  """
1621  last_arg = None
1622  if len(args) > 0:
1623  last_arg = args[len(args)-1]
1624  if isinstance(last_arg, Context):
1625  ctx = args[len(args)-1]
1626  args = args[:len(args)-1]
1627  else:
1628  ctx = main_ctx()
1629  args = _get_args(args)
1630  ctx_args = _ctx_from_ast_arg_list(args, ctx)
1631  if __debug__:
1632  _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1633  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1634  if _has_probe(args):
1635  return _probe_or(args, ctx)
1636  else:
1637  args = _coerce_expr_list(args, ctx)
1638  _args, sz = _to_ast_array(args)
1639  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1640 
1641 #########################################
1642 #
1643 # Patterns
1644 #
1645 #########################################
1646 
1647 class PatternRef(ExprRef):
1648  """Patterns are hints for quantifier instantiation.
1649 
1650  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1651  """
1652  def as_ast(self):
1653  return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1654 
1655  def get_id(self):
1656  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1657 
1658 def is_pattern(a):
1659  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1660 
1661  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1662 
1663  >>> f = Function('f', IntSort(), IntSort())
1664  >>> x = Int('x')
1665  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1666  >>> q
1667  ForAll(x, f(x) == 0)
1668  >>> q.num_patterns()
1669  1
1670  >>> is_pattern(q.pattern(0))
1671  True
1672  >>> q.pattern(0)
1673  f(Var(0))
1674  """
1675  return isinstance(a, PatternRef)
1676 
1677 def MultiPattern(*args):
1678  """Create a Z3 multi-pattern using the given expressions `*args`
1679 
1680  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1681 
1682  >>> f = Function('f', IntSort(), IntSort())
1683  >>> g = Function('g', IntSort(), IntSort())
1684  >>> x = Int('x')
1685  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1686  >>> q
1687  ForAll(x, f(x) != g(x))
1688  >>> q.num_patterns()
1689  1
1690  >>> is_pattern(q.pattern(0))
1691  True
1692  >>> q.pattern(0)
1693  MultiPattern(f(Var(0)), g(Var(0)))
1694  """
1695  if __debug__:
1696  _z3_assert(len(args) > 0, "At least one argument expected")
1697  _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1698  ctx = args[0].ctx
1699  args, sz = _to_ast_array(args)
1700  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1701 
1702 def _to_pattern(arg):
1703  if is_pattern(arg):
1704  return arg
1705  else:
1706  return MultiPattern(arg)
1707 
1708 #########################################
1709 #
1710 # Quantifiers
1711 #
1712 #########################################
1713 
1714 class QuantifierRef(BoolRef):
1715  """Universally and Existentially quantified formulas."""
1716 
1717  def as_ast(self):
1718  return self.ast
1719 
1720  def get_id(self):
1721  return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1722 
1723  def sort(self):
1724  """Return the Boolean sort."""
1725  return BoolSort(self.ctx)
1726 
1727  def is_forall(self):
1728  """Return `True` if `self` is a universal quantifier.
1729 
1730  >>> f = Function('f', IntSort(), IntSort())
1731  >>> x = Int('x')
1732  >>> q = ForAll(x, f(x) == 0)
1733  >>> q.is_forall()
1734  True
1735  >>> q = Exists(x, f(x) != 0)
1736  >>> q.is_forall()
1737  False
1738  """
1739  return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1740 
1741  def weight(self):
1742  """Return the weight annotation of `self`.
1743 
1744  >>> f = Function('f', IntSort(), IntSort())
1745  >>> x = Int('x')
1746  >>> q = ForAll(x, f(x) == 0)
1747  >>> q.weight()
1748  1
1749  >>> q = ForAll(x, f(x) == 0, weight=10)
1750  >>> q.weight()
1751  10
1752  """
1753  return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1754 
1755  def num_patterns(self):
1756  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1757 
1758  >>> f = Function('f', IntSort(), IntSort())
1759  >>> g = Function('g', IntSort(), IntSort())
1760  >>> x = Int('x')
1761  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1762  >>> q.num_patterns()
1763  2
1764  """
1765  return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1766 
1767  def pattern(self, idx):
1768  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1769 
1770  >>> f = Function('f', IntSort(), IntSort())
1771  >>> g = Function('g', IntSort(), IntSort())
1772  >>> x = Int('x')
1773  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1774  >>> q.num_patterns()
1775  2
1776  >>> q.pattern(0)
1777  f(Var(0))
1778  >>> q.pattern(1)
1779  g(Var(0))
1780  """
1781  if __debug__:
1782  _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1783  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1784 
1785  def num_no_patterns(self):
1786  """Return the number of no-patterns."""
1787  return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1788 
1789  def no_pattern(self, idx):
1790  """Return a no-pattern."""
1791  if __debug__:
1792  _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1793  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1794 
1795  def body(self):
1796  """Return the expression being quantified.
1797 
1798  >>> f = Function('f', IntSort(), IntSort())
1799  >>> x = Int('x')
1800  >>> q = ForAll(x, f(x) == 0)
1801  >>> q.body()
1802  f(Var(0)) == 0
1803  """
1804  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1805 
1806  def num_vars(self):
1807  """Return the number of variables bounded by this quantifier.
1808 
1809  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1810  >>> x = Int('x')
1811  >>> y = Int('y')
1812  >>> q = ForAll([x, y], f(x, y) >= x)
1813  >>> q.num_vars()
1814  2
1815  """
1816  return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1817 
1818  def var_name(self, idx):
1819  """Return a string representing a name used when displaying the quantifier.
1820 
1821  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1822  >>> x = Int('x')
1823  >>> y = Int('y')
1824  >>> q = ForAll([x, y], f(x, y) >= x)
1825  >>> q.var_name(0)
1826  'x'
1827  >>> q.var_name(1)
1828  'y'
1829  """
1830  if __debug__:
1831  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1832  return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1833 
1834  def var_sort(self, idx):
1835  """Return the sort of a bound variable.
1836 
1837  >>> f = Function('f', IntSort(), RealSort(), IntSort())
1838  >>> x = Int('x')
1839  >>> y = Real('y')
1840  >>> q = ForAll([x, y], f(x, y) >= x)
1841  >>> q.var_sort(0)
1842  Int
1843  >>> q.var_sort(1)
1844  Real
1845  """
1846  if __debug__:
1847  _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1848  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1849 
1850  def children(self):
1851  """Return a list containing a single element self.body()
1852 
1853  >>> f = Function('f', IntSort(), IntSort())
1854  >>> x = Int('x')
1855  >>> q = ForAll(x, f(x) == 0)
1856  >>> q.children()
1857  [f(Var(0)) == 0]
1858  """
1859  return [ self.body() ]
1860 
1861 def is_quantifier(a):
1862  """Return `True` if `a` is a Z3 quantifier.
1863 
1864  >>> f = Function('f', IntSort(), IntSort())
1865  >>> x = Int('x')
1866  >>> q = ForAll(x, f(x) == 0)
1867  >>> is_quantifier(q)
1868  True
1869  >>> is_quantifier(f(x))
1870  False
1871  """
1872  return isinstance(a, QuantifierRef)
1873 
1874 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1875  if __debug__:
1876  _z3_assert(is_bool(body), "Z3 expression expected")
1877  _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
1878  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
1879  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
1880  ctx = body.ctx
1881  if is_app(vs):
1882  vs = [vs]
1883  num_vars = len(vs)
1884  if num_vars == 0:
1885  return body
1886  _vs = (Ast * num_vars)()
1887  for i in range(num_vars):
1888  ## TODO: Check if is constant
1889  _vs[i] = vs[i].as_ast()
1890  patterns = [ _to_pattern(p) for p in patterns ]
1891  num_pats = len(patterns)
1892  _pats = (Pattern * num_pats)()
1893  for i in range(num_pats):
1894  _pats[i] = patterns[i].ast
1895  _no_pats, num_no_pats = _to_ast_array(no_patterns)
1896  qid = to_symbol(qid, ctx)
1897  skid = to_symbol(skid, ctx)
1898  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
1899  num_vars, _vs,
1900  num_pats, _pats,
1901  num_no_pats, _no_pats,
1902  body.as_ast()), ctx)
1903 
1904 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1905  """Create a Z3 forall formula.
1906 
1907  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1908 
1909  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1910 
1911  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1912  >>> x = Int('x')
1913  >>> y = Int('y')
1914  >>> ForAll([x, y], f(x, y) >= x)
1915  ForAll([x, y], f(x, y) >= x)
1916  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
1917  ForAll([x, y], f(x, y) >= x)
1918  >>> ForAll([x, y], f(x, y) >= x, weight=10)
1919  ForAll([x, y], f(x, y) >= x)
1920  """
1921  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
1922 
1923 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
1924  """Create a Z3 exists formula.
1925 
1926  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
1927 
1928  See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
1929 
1930  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1931  >>> x = Int('x')
1932  >>> y = Int('y')
1933  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
1934  >>> q
1935  Exists([x, y], f(x, y) >= x)
1936  >>> is_quantifier(q)
1937  True
1938  >>> r = Tactic('nnf')(q).as_expr()
1939  >>> is_quantifier(r)
1940  False
1941  """
1942  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
1943 
1944 #########################################
1945 #
1946 # Arithmetic
1947 #
1948 #########################################
1949 
1950 class ArithSortRef(SortRef):
1951  """Real and Integer sorts."""
1952 
1953  def is_real(self):
1954  """Return `True` if `self` is of the sort Real.
1955 
1956  >>> x = Real('x')
1957  >>> x.is_real()
1958  True
1959  >>> (x + 1).is_real()
1960  True
1961  >>> x = Int('x')
1962  >>> x.is_real()
1963  False
1964  """
1965  return self.kind() == Z3_REAL_SORT
1966 
1967  def is_int(self):
1968  """Return `True` if `self` is of the sort Integer.
1969 
1970  >>> x = Int('x')
1971  >>> x.is_int()
1972  True
1973  >>> (x + 1).is_int()
1974  True
1975  >>> x = Real('x')
1976  >>> x.is_int()
1977  False
1978  """
1979  return self.kind() == Z3_INT_SORT
1980 
1981  def subsort(self, other):
1982  """Return `True` if `self` is a subsort of `other`."""
1983  return self.is_int() and is_arith_sort(other) and other.is_real()
1984 
1985  def cast(self, val):
1986  """Try to cast `val` as an Integer or Real.
1987 
1988  >>> IntSort().cast(10)
1989  10
1990  >>> is_int(IntSort().cast(10))
1991  True
1992  >>> is_int(10)
1993  False
1994  >>> RealSort().cast(10)
1995  10
1996  >>> is_real(RealSort().cast(10))
1997  True
1998  """
1999  if is_expr(val):
2000  if __debug__:
2001  _z3_assert(self.ctx == val.ctx, "Context mismatch")
2002  val_s = val.sort()
2003  if self.eq(val_s):
2004  return val
2005  if val_s.is_int() and self.is_real():
2006  return ToReal(val)
2007  if val_s.is_bool() and self.is_int():
2008  return If(val, 1, 0)
2009  if val_s.is_bool() and self.is_real():
2010  return ToReal(If(val, 1, 0))
2011  if __debug__:
2012  _z3_assert(False, "Z3 Integer/Real expression expected" )
2013  else:
2014  if self.is_int():
2015  return IntVal(val, self.ctx)
2016  if self.is_real():
2017  return RealVal(val, self.ctx)
2018  if __debug__:
2019  _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2020 
2021 def is_arith_sort(s):
2022  """Return `True` if s is an arithmetical sort (type).
2023 
2024  >>> is_arith_sort(IntSort())
2025  True
2026  >>> is_arith_sort(RealSort())
2027  True
2028  >>> is_arith_sort(BoolSort())
2029  False
2030  >>> n = Int('x') + 1
2031  >>> is_arith_sort(n.sort())
2032  True
2033  """
2034  return isinstance(s, ArithSortRef)
2035 
2036 class ArithRef(ExprRef):
2037  """Integer and Real expressions."""
2038 
2039  def sort(self):
2040  """Return the sort (type) of the arithmetical expression `self`.
2041 
2042  >>> Int('x').sort()
2043  Int
2044  >>> (Real('x') + 1).sort()
2045  Real
2046  """
2047  return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2048 
2049  def is_int(self):
2050  """Return `True` if `self` is an integer expression.
2051 
2052  >>> x = Int('x')
2053  >>> x.is_int()
2054  True
2055  >>> (x + 1).is_int()
2056  True
2057  >>> y = Real('y')
2058  >>> (x + y).is_int()
2059  False
2060  """
2061  return self.sort().is_int()
2062 
2063  def is_real(self):
2064  """Return `True` if `self` is an real expression.
2065 
2066  >>> x = Real('x')
2067  >>> x.is_real()
2068  True
2069  >>> (x + 1).is_real()
2070  True
2071  """
2072  return self.sort().is_real()
2073 
2074  def __add__(self, other):
2075  """Create the Z3 expression `self + other`.
2076 
2077  >>> x = Int('x')
2078  >>> y = Int('y')
2079  >>> x + y
2080  x + y
2081  >>> (x + y).sort()
2082  Int
2083  """
2084  a, b = _coerce_exprs(self, other)
2085  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2086 
2087  def __radd__(self, other):
2088  """Create the Z3 expression `other + self`.
2089 
2090  >>> x = Int('x')
2091  >>> 10 + x
2092  10 + x
2093  """
2094  a, b = _coerce_exprs(self, other)
2095  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2096 
2097  def __mul__(self, other):
2098  """Create the Z3 expression `self * other`.
2099 
2100  >>> x = Real('x')
2101  >>> y = Real('y')
2102  >>> x * y
2103  x*y
2104  >>> (x * y).sort()
2105  Real
2106  """
2107  a, b = _coerce_exprs(self, other)
2108  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2109 
2110  def __rmul__(self, other):
2111  """Create the Z3 expression `other * self`.
2112 
2113  >>> x = Real('x')
2114  >>> 10 * x
2115  10*x
2116  """
2117  a, b = _coerce_exprs(self, other)
2118  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2119 
2120  def __sub__(self, other):
2121  """Create the Z3 expression `self - other`.
2122 
2123  >>> x = Int('x')
2124  >>> y = Int('y')
2125  >>> x - y
2126  x - y
2127  >>> (x - y).sort()
2128  Int
2129  """
2130  a, b = _coerce_exprs(self, other)
2131  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2132 
2133  def __rsub__(self, other):
2134  """Create the Z3 expression `other - self`.
2135 
2136  >>> x = Int('x')
2137  >>> 10 - x
2138  10 - x
2139  """
2140  a, b = _coerce_exprs(self, other)
2141  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2142 
2143  def __pow__(self, other):
2144  """Create the Z3 expression `self**other` (** is the power operator).
2145 
2146  >>> x = Real('x')
2147  >>> x**3
2148  x**3
2149  >>> (x**3).sort()
2150  Real
2151  >>> simplify(IntVal(2)**8)
2152  256
2153  """
2154  a, b = _coerce_exprs(self, other)
2155  return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2156 
2157  def __rpow__(self, other):
2158  """Create the Z3 expression `other**self` (** is the power operator).
2159 
2160  >>> x = Real('x')
2161  >>> 2**x
2162  2**x
2163  >>> (2**x).sort()
2164  Real
2165  >>> simplify(2**IntVal(8))
2166  256
2167  """
2168  a, b = _coerce_exprs(self, other)
2169  return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2170 
2171  def __div__(self, other):
2172  """Create the Z3 expression `other/self`.
2173 
2174  >>> x = Int('x')
2175  >>> y = Int('y')
2176  >>> x/y
2177  x/y
2178  >>> (x/y).sort()
2179  Int
2180  >>> (x/y).sexpr()
2181  '(div x y)'
2182  >>> x = Real('x')
2183  >>> y = Real('y')
2184  >>> x/y
2185  x/y
2186  >>> (x/y).sort()
2187  Real
2188  >>> (x/y).sexpr()
2189  '(/ x y)'
2190  """
2191  a, b = _coerce_exprs(self, other)
2192  return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2193 
2194  def __truediv__(self, other):
2195  """Create the Z3 expression `other/self`."""
2196  return self.__div__(other)
2197 
2198  def __rdiv__(self, other):
2199  """Create the Z3 expression `other/self`.
2200 
2201  >>> x = Int('x')
2202  >>> 10/x
2203  10/x
2204  >>> (10/x).sexpr()
2205  '(div 10 x)'
2206  >>> x = Real('x')
2207  >>> 10/x
2208  10/x
2209  >>> (10/x).sexpr()
2210  '(/ 10.0 x)'
2211  """
2212  a, b = _coerce_exprs(self, other)
2213  return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2214 
2215  def __rtruediv__(self, other):
2216  """Create the Z3 expression `other/self`."""
2217  return self.__rdiv__(other)
2218 
2219  def __mod__(self, other):
2220  """Create the Z3 expression `other%self`.
2221 
2222  >>> x = Int('x')
2223  >>> y = Int('y')
2224  >>> x % y
2225  x%y
2226  >>> simplify(IntVal(10) % IntVal(3))
2227  1
2228  """
2229  a, b = _coerce_exprs(self, other)
2230  if __debug__:
2231  _z3_assert(a.is_int(), "Z3 integer expression expected")
2232  return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2233 
2234  def __rmod__(self, other):
2235  """Create the Z3 expression `other%self`.
2236 
2237  >>> x = Int('x')
2238  >>> 10 % x
2239  10%x
2240  """
2241  a, b = _coerce_exprs(self, other)
2242  if __debug__:
2243  _z3_assert(a.is_int(), "Z3 integer expression expected")
2244  return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2245 
2246  def __neg__(self):
2247  """Return an expression representing `-self`.
2248 
2249  >>> x = Int('x')
2250  >>> -x
2251  -x
2252  >>> simplify(-(-x))
2253  x
2254  """
2255  return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2256 
2257  def __pos__(self):
2258  """Return `self`.
2259 
2260  >>> x = Int('x')
2261  >>> +x
2262  x
2263  """
2264  return self
2265 
2266  def __le__(self, other):
2267  """Create the Z3 expression `other <= self`.
2268 
2269  >>> x, y = Ints('x y')
2270  >>> x <= y
2271  x <= y
2272  >>> y = Real('y')
2273  >>> x <= y
2274  ToReal(x) <= y
2275  """
2276  a, b = _coerce_exprs(self, other)
2277  return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2278 
2279  def __lt__(self, other):
2280  """Create the Z3 expression `other < self`.
2281 
2282  >>> x, y = Ints('x y')
2283  >>> x < y
2284  x < y
2285  >>> y = Real('y')
2286  >>> x < y
2287  ToReal(x) < y
2288  """
2289  a, b = _coerce_exprs(self, other)
2290  return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2291 
2292  def __gt__(self, other):
2293  """Create the Z3 expression `other > self`.
2294 
2295  >>> x, y = Ints('x y')
2296  >>> x > y
2297  x > y
2298  >>> y = Real('y')
2299  >>> x > y
2300  ToReal(x) > y
2301  """
2302  a, b = _coerce_exprs(self, other)
2303  return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2304 
2305  def __ge__(self, other):
2306  """Create the Z3 expression `other >= self`.
2307 
2308  >>> x, y = Ints('x y')
2309  >>> x >= y
2310  x >= y
2311  >>> y = Real('y')
2312  >>> x >= y
2313  ToReal(x) >= y
2314  """
2315  a, b = _coerce_exprs(self, other)
2316  return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2317 
2318 def is_arith(a):
2319  """Return `True` if `a` is an arithmetical expression.
2320 
2321  >>> x = Int('x')
2322  >>> is_arith(x)
2323  True
2324  >>> is_arith(x + 1)
2325  True
2326  >>> is_arith(1)
2327  False
2328  >>> is_arith(IntVal(1))
2329  True
2330  >>> y = Real('y')
2331  >>> is_arith(y)
2332  True
2333  >>> is_arith(y + 1)
2334  True
2335  """
2336  return isinstance(a, ArithRef)
2337 
2338 def is_int(a):
2339  """Return `True` if `a` is an integer expression.
2340 
2341  >>> x = Int('x')
2342  >>> is_int(x + 1)
2343  True
2344  >>> is_int(1)
2345  False
2346  >>> is_int(IntVal(1))
2347  True
2348  >>> y = Real('y')
2349  >>> is_int(y)
2350  False
2351  >>> is_int(y + 1)
2352  False
2353  """
2354  return is_arith(a) and a.is_int()
2355 
2356 def is_real(a):
2357  """Return `True` if `a` is a real expression.
2358 
2359  >>> x = Int('x')
2360  >>> is_real(x + 1)
2361  False
2362  >>> y = Real('y')
2363  >>> is_real(y)
2364  True
2365  >>> is_real(y + 1)
2366  True
2367  >>> is_real(1)
2368  False
2369  >>> is_real(RealVal(1))
2370  True
2371  """
2372  return is_arith(a) and a.is_real()
2373 
2374 def _is_numeral(ctx, a):
2375  return Z3_is_numeral_ast(ctx.ref(), a)
2376 
2377 def _is_algebraic(ctx, a):
2378  return Z3_is_algebraic_number(ctx.ref(), a)
2379 
2380 def is_int_value(a):
2381  """Return `True` if `a` is an integer value of sort Int.
2382 
2383  >>> is_int_value(IntVal(1))
2384  True
2385  >>> is_int_value(1)
2386  False
2387  >>> is_int_value(Int('x'))
2388  False
2389  >>> n = Int('x') + 1
2390  >>> n
2391  x + 1
2392  >>> n.arg(1)
2393  1
2394  >>> is_int_value(n.arg(1))
2395  True
2396  >>> is_int_value(RealVal("1/3"))
2397  False
2398  >>> is_int_value(RealVal(1))
2399  False
2400  """
2401  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2402 
2403 def is_rational_value(a):
2404  """Return `True` if `a` is rational value of sort Real.
2405 
2406  >>> is_rational_value(RealVal(1))
2407  True
2408  >>> is_rational_value(RealVal("3/5"))
2409  True
2410  >>> is_rational_value(IntVal(1))
2411  False
2412  >>> is_rational_value(1)
2413  False
2414  >>> n = Real('x') + 1
2415  >>> n.arg(1)
2416  1
2417  >>> is_rational_value(n.arg(1))
2418  True
2419  >>> is_rational_value(Real('x'))
2420  False
2421  """
2422  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2423 
2424 def is_algebraic_value(a):
2425  """Return `True` if `a` is an algerbraic value of sort Real.
2426 
2427  >>> is_algebraic_value(RealVal("3/5"))
2428  False
2429  >>> n = simplify(Sqrt(2))
2430  >>> n
2431  1.4142135623?
2432  >>> is_algebraic_value(n)
2433  True
2434  """
2435  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2436 
2437 def is_add(a):
2438  """Return `True` if `a` is an expression of the form b + c.
2439 
2440  >>> x, y = Ints('x y')
2441  >>> is_add(x + y)
2442  True
2443  >>> is_add(x - y)
2444  False
2445  """
2446  return is_app_of(a, Z3_OP_ADD)
2447 
2448 def is_mul(a):
2449  """Return `True` if `a` is an expression of the form b * c.
2450 
2451  >>> x, y = Ints('x y')
2452  >>> is_mul(x * y)
2453  True
2454  >>> is_mul(x - y)
2455  False
2456  """
2457  return is_app_of(a, Z3_OP_MUL)
2458 
2459 def is_sub(a):
2460  """Return `True` if `a` is an expression of the form b - c.
2461 
2462  >>> x, y = Ints('x y')
2463  >>> is_sub(x - y)
2464  True
2465  >>> is_sub(x + y)
2466  False
2467  """
2468  return is_app_of(a, Z3_OP_SUB)
2469 
2470 def is_div(a):
2471  """Return `True` if `a` is an expression of the form b / c.
2472 
2473  >>> x, y = Reals('x y')
2474  >>> is_div(x / y)
2475  True
2476  >>> is_div(x + y)
2477  False
2478  >>> x, y = Ints('x y')
2479  >>> is_div(x / y)
2480  False
2481  >>> is_idiv(x / y)
2482  True
2483  """
2484  return is_app_of(a, Z3_OP_DIV)
2485 
2486 def is_idiv(a):
2487  """Return `True` if `a` is an expression of the form b div c.
2488 
2489  >>> x, y = Ints('x y')
2490  >>> is_idiv(x / y)
2491  True
2492  >>> is_idiv(x + y)
2493  False
2494  """
2495  return is_app_of(a, Z3_OP_IDIV)
2496 
2497 def is_mod(a):
2498  """Return `True` if `a` is an expression of the form b % c.
2499 
2500  >>> x, y = Ints('x y')
2501  >>> is_mod(x % y)
2502  True
2503  >>> is_mod(x + y)
2504  False
2505  """
2506  return is_app_of(a, Z3_OP_MOD)
2507 
2508 def is_le(a):
2509  """Return `True` if `a` is an expression of the form b <= c.
2510 
2511  >>> x, y = Ints('x y')
2512  >>> is_le(x <= y)
2513  True
2514  >>> is_le(x < y)
2515  False
2516  """
2517  return is_app_of(a, Z3_OP_LE)
2518 
2519 def is_lt(a):
2520  """Return `True` if `a` is an expression of the form b < c.
2521 
2522  >>> x, y = Ints('x y')
2523  >>> is_lt(x < y)
2524  True
2525  >>> is_lt(x == y)
2526  False
2527  """
2528  return is_app_of(a, Z3_OP_LT)
2529 
2530 def is_ge(a):
2531  """Return `True` if `a` is an expression of the form b >= c.
2532 
2533  >>> x, y = Ints('x y')
2534  >>> is_ge(x >= y)
2535  True
2536  >>> is_ge(x == y)
2537  False
2538  """
2539  return is_app_of(a, Z3_OP_GE)
2540 
2541 def is_gt(a):
2542  """Return `True` if `a` is an expression of the form b > c.
2543 
2544  >>> x, y = Ints('x y')
2545  >>> is_gt(x > y)
2546  True
2547  >>> is_gt(x == y)
2548  False
2549  """
2550  return is_app_of(a, Z3_OP_GT)
2551 
2552 def is_is_int(a):
2553  """Return `True` if `a` is an expression of the form IsInt(b).
2554 
2555  >>> x = Real('x')
2556  >>> is_is_int(IsInt(x))
2557  True
2558  >>> is_is_int(x)
2559  False
2560  """
2561  return is_app_of(a, Z3_OP_IS_INT)
2562 
2563 def is_to_real(a):
2564  """Return `True` if `a` is an expression of the form ToReal(b).
2565 
2566  >>> x = Int('x')
2567  >>> n = ToReal(x)
2568  >>> n
2569  ToReal(x)
2570  >>> is_to_real(n)
2571  True
2572  >>> is_to_real(x)
2573  False
2574  """
2575  return is_app_of(a, Z3_OP_TO_REAL)
2576 
2577 def is_to_int(a):
2578  """Return `True` if `a` is an expression of the form ToInt(b).
2579 
2580  >>> x = Real('x')
2581  >>> n = ToInt(x)
2582  >>> n
2583  ToInt(x)
2584  >>> is_to_int(n)
2585  True
2586  >>> is_to_int(x)
2587  False
2588  """
2589  return is_app_of(a, Z3_OP_TO_INT)
2590 
2591 class IntNumRef(ArithRef):
2592  """Integer values."""
2593 
2594  def as_long(self):
2595  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2596 
2597  >>> v = IntVal(1)
2598  >>> v + 1
2599  1 + 1
2600  >>> v.as_long() + 1
2601  2
2602  """
2603  if __debug__:
2604  _z3_assert(self.is_int(), "Integer value expected")
2605  return int(self.as_string())
2606 
2607  def as_string(self):
2608  """Return a Z3 integer numeral as a Python string.
2609  >>> v = IntVal(100)
2610  >>> v.as_string()
2611  '100'
2612  """
2613  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2614 
2615 class RatNumRef(ArithRef):
2616  """Rational values."""
2617 
2618  def numerator(self):
2619  """ Return the numerator of a Z3 rational numeral.
2620 
2621  >>> is_rational_value(RealVal("3/5"))
2622  True
2623  >>> n = RealVal("3/5")
2624  >>> n.numerator()
2625  3
2626  >>> is_rational_value(Q(3,5))
2627  True
2628  >>> Q(3,5).numerator()
2629  3
2630  """
2631  return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
2632 
2633  def denominator(self):
2634  """ Return the denominator of a Z3 rational numeral.
2635 
2636  >>> is_rational_value(Q(3,5))
2637  True
2638  >>> n = Q(3,5)
2639  >>> n.denominator()
2640  5
2641  """
2642  return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
2643 
2644  def numerator_as_long(self):
2645  """ Return the numerator as a Python long.
2646 
2647  >>> v = RealVal(10000000000)
2648  >>> v
2649  10000000000
2650  >>> v + 1
2651  10000000000 + 1
2652  >>> v.numerator_as_long() + 1 == 10000000001
2653  True
2654  """
2655  return self.numerator().as_long()
2656 
2657  def denominator_as_long(self):
2658  """ Return the denominator as a Python long.
2659 
2660  >>> v = RealVal("1/3")
2661  >>> v
2662  1/3
2663  >>> v.denominator_as_long()
2664  3
2665  """
2666  return self.denominator().as_long()
2667 
2668  def is_int(self):
2669  return False
2670 
2671  def is_real(self):
2672  return True
2673 
2674  def is_int_value(self):
2675  return self.denominator().is_int() and self.denominator_as_long() == 1
2676 
2677  def as_long(self):
2678  _z3_assert(self.is_int(), "Expected integer fraction")
2679  return self.numerator_as_long()
2680 
2681  def as_decimal(self, prec):
2682  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2683 
2684  >>> v = RealVal("1/5")
2685  >>> v.as_decimal(3)
2686  '0.2'
2687  >>> v = RealVal("1/3")
2688  >>> v.as_decimal(3)
2689  '0.333?'
2690  """
2691  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2692 
2693  def as_string(self):
2694  """Return a Z3 rational numeral as a Python string.
2695 
2696  >>> v = Q(3,6)
2697  >>> v.as_string()
2698  '1/2'
2699  """
2700  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
2701 
2702  def as_fraction(self):
2703  """Return a Z3 rational as a Python Fraction object.
2704 
2705  >>> v = RealVal("1/5")
2706  >>> v.as_fraction()
2707  Fraction(1, 5)
2708  """
2709  return Fraction(self.numerator_as_long(), self.denominator_as_long())
2710 
2711 class AlgebraicNumRef(ArithRef):
2712  """Algebraic irrational values."""
2713 
2714  def approx(self, precision=10):
2715  """Return a Z3 rational number that approximates the algebraic number `self`.
2716  The result `r` is such that |r - self| <= 1/10^precision
2717 
2718  >>> x = simplify(Sqrt(2))
2719  >>> x.approx(20)
2720  6838717160008073720548335/4835703278458516698824704
2721  >>> x.approx(5)
2722  2965821/2097152
2723  """
2724  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
2725  def as_decimal(self, prec):
2726  """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2727 
2728  >>> x = simplify(Sqrt(2))
2729  >>> x.as_decimal(10)
2730  '1.4142135623?'
2731  >>> x.as_decimal(20)
2732  '1.41421356237309504880?'
2733  """
2734  return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
2735 
2736 def _py2expr(a, ctx=None):
2737  if isinstance(a, bool):
2738  return BoolVal(a, ctx)
2739  if _is_int(a):
2740  return IntVal(a, ctx)
2741  if isinstance(a, float):
2742  return RealVal(a, ctx)
2743  if __debug__:
2744  _z3_assert(False, "Python bool, int, long or float expected")
2745 
2746 def IntSort(ctx=None):
2747  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2748 
2749  >>> IntSort()
2750  Int
2751  >>> x = Const('x', IntSort())
2752  >>> is_int(x)
2753  True
2754  >>> x.sort() == IntSort()
2755  True
2756  >>> x.sort() == BoolSort()
2757  False
2758  """
2759  ctx = _get_ctx(ctx)
2760  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2761 
2762 def RealSort(ctx=None):
2763  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2764 
2765  >>> RealSort()
2766  Real
2767  >>> x = Const('x', RealSort())
2768  >>> is_real(x)
2769  True
2770  >>> is_int(x)
2771  False
2772  >>> x.sort() == RealSort()
2773  True
2774  """
2775  ctx = _get_ctx(ctx)
2776  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2777 
2778 def _to_int_str(val):
2779  if isinstance(val, float):
2780  return str(int(val))
2781  elif isinstance(val, bool):
2782  if val:
2783  return "1"
2784  else:
2785  return "0"
2786  elif _is_int(val):
2787  return str(val)
2788  elif isinstance(val, str):
2789  return val
2790  if __debug__:
2791  _z3_assert(False, "Python value cannot be used as a Z3 integer")
2792 
2793 def IntVal(val, ctx=None):
2794  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2795 
2796  >>> IntVal(1)
2797  1
2798  >>> IntVal("100")
2799  100
2800  """
2801  ctx = _get_ctx(ctx)
2802  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2803 
2804 def RealVal(val, ctx=None):
2805  """Return a Z3 real value.
2806 
2807  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2808  If `ctx=None`, then the global context is used.
2809 
2810  >>> RealVal(1)
2811  1
2812  >>> RealVal(1).sort()
2813  Real
2814  >>> RealVal("3/5")
2815  3/5
2816  >>> RealVal("1.5")
2817  3/2
2818  """
2819  ctx = _get_ctx(ctx)
2820  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2821 
2822 def RatVal(a, b, ctx=None):
2823  """Return a Z3 rational a/b.
2824 
2825  If `ctx=None`, then the global context is used.
2826 
2827  >>> RatVal(3,5)
2828  3/5
2829  >>> RatVal(3,5).sort()
2830  Real
2831  """
2832  if __debug__:
2833  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2834  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2835  return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2836 
2837 def Q(a, b, ctx=None):
2838  """Return a Z3 rational a/b.
2839 
2840  If `ctx=None`, then the global context is used.
2841 
2842  >>> Q(3,5)
2843  3/5
2844  >>> Q(3,5).sort()
2845  Real
2846  """
2847  return simplify(RatVal(a, b))
2848 
2849 def Int(name, ctx=None):
2850  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
2851 
2852  >>> x = Int('x')
2853  >>> is_int(x)
2854  True
2855  >>> is_int(x + 1)
2856  True
2857  """
2858  ctx = _get_ctx(ctx)
2859  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2860 
2861 def Ints(names, ctx=None):
2862  """Return a tuple of Integer constants.
2863 
2864  >>> x, y, z = Ints('x y z')
2865  >>> Sum(x, y, z)
2866  x + y + z
2867  """
2868  ctx = _get_ctx(ctx)
2869  if isinstance(names, str):
2870  names = names.split(" ")
2871  return [Int(name, ctx) for name in names]
2872 
2873 def IntVector(prefix, sz, ctx=None):
2874  """Return a list of integer constants of size `sz`.
2875 
2876  >>> X = IntVector('x', 3)
2877  >>> X
2878  [x__0, x__1, x__2]
2879  >>> Sum(X)
2880  x__0 + x__1 + x__2
2881  """
2882  return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
2883 
2884 def FreshInt(prefix='x', ctx=None):
2885  """Return a fresh integer constant in the given context using the given prefix.
2886 
2887  >>> x = FreshInt()
2888  >>> y = FreshInt()
2889  >>> eq(x, y)
2890  False
2891  >>> x.sort()
2892  Int
2893  """
2894  ctx = _get_ctx(ctx)
2895  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
2896 
2897 def Real(name, ctx=None):
2898  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
2899 
2900  >>> x = Real('x')
2901  >>> is_real(x)
2902  True
2903  >>> is_real(x + 1)
2904  True
2905  """
2906  ctx = _get_ctx(ctx)
2907  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
2908 
2909 def Reals(names, ctx=None):
2910  """Return a tuple of real constants.
2911 
2912  >>> x, y, z = Reals('x y z')
2913  >>> Sum(x, y, z)
2914  x + y + z
2915  >>> Sum(x, y, z).sort()
2916  Real
2917  """
2918  ctx = _get_ctx(ctx)
2919  if isinstance(names, str):
2920  names = names.split(" ")
2921  return [Real(name, ctx) for name in names]
2922 
2923 def RealVector(prefix, sz, ctx=None):
2924  """Return a list of real constants of size `sz`.
2925 
2926  >>> X = RealVector('x', 3)
2927  >>> X
2928  [x__0, x__1, x__2]
2929  >>> Sum(X)
2930  x__0 + x__1 + x__2
2931  >>> Sum(X).sort()
2932  Real
2933  """
2934  return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
2935 
2936 def FreshReal(prefix='b', ctx=None):
2937  """Return a fresh real constant in the given context using the given prefix.
2938 
2939  >>> x = FreshReal()
2940  >>> y = FreshReal()
2941  >>> eq(x, y)
2942  False
2943  >>> x.sort()
2944  Real
2945  """
2946  ctx = _get_ctx(ctx)
2947  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
2948 
2949 def ToReal(a):
2950  """ Return the Z3 expression ToReal(a).
2951 
2952  >>> x = Int('x')
2953  >>> x.sort()
2954  Int
2955  >>> n = ToReal(x)
2956  >>> n
2957  ToReal(x)
2958  >>> n.sort()
2959  Real
2960  """
2961  if __debug__:
2962  _z3_assert(a.is_int(), "Z3 integer expression expected.")
2963  ctx = a.ctx
2964  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
2965 
2966 def ToInt(a):
2967  """ Return the Z3 expression ToInt(a).
2968 
2969  >>> x = Real('x')
2970  >>> x.sort()
2971  Real
2972  >>> n = ToInt(x)
2973  >>> n
2974  ToInt(x)
2975  >>> n.sort()
2976  Int
2977  """
2978  if __debug__:
2979  _z3_assert(a.is_real(), "Z3 real expression expected.")
2980  ctx = a.ctx
2981  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
2982 
2983 def IsInt(a):
2984  """ Return the Z3 predicate IsInt(a).
2985 
2986  >>> x = Real('x')
2987  >>> IsInt(x + "1/2")
2988  IsInt(x + 1/2)
2989  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
2990  [x = 1/2]
2991  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
2992  no solution
2993  """
2994  if __debug__:
2995  _z3_assert(a.is_real(), "Z3 real expression expected.")
2996  ctx = a.ctx
2997  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
2998 
2999 def Sqrt(a, ctx=None):
3000  """ Return a Z3 expression which represents the square root of a.
3001 
3002  >>> x = Real('x')
3003  >>> Sqrt(x)
3004  x**(1/2)
3005  """
3006  if not is_expr(a):
3007  ctx = _get_ctx(ctx)
3008  a = RealVal(a, ctx)
3009  return a ** "1/2"
3010 
3011 def Cbrt(a, ctx=None):
3012  """ Return a Z3 expression which represents the cubic root of a.
3013 
3014  >>> x = Real('x')
3015  >>> Cbrt(x)
3016  x**(1/3)
3017  """
3018  if not is_expr(a):
3019  ctx = _get_ctx(ctx)
3020  a = RealVal(a, ctx)
3021  return a ** "1/3"
3022 
3023 #########################################
3024 #
3025 # Bit-Vectors
3026 #
3027 #########################################
3028 
3029 class BitVecSortRef(SortRef):
3030  """Bit-vector sort."""
3031 
3032  def size(self):
3033  """Return the size (number of bits) of the bit-vector sort `self`.
3034 
3035  >>> b = BitVecSort(32)
3036  >>> b.size()
3037  32
3038  """
3039  return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3040 
3041  def subsort(self, other):
3042  return is_bv_sort(other) and self.size() < other.size()
3043 
3044  def cast(self, val):
3045  """Try to cast `val` as a Bit-Vector.
3046 
3047  >>> b = BitVecSort(32)
3048  >>> b.cast(10)
3049  10
3050  >>> b.cast(10).sexpr()
3051  '#x0000000a'
3052  """
3053  if is_expr(val):
3054  if __debug__:
3055  _z3_assert(self.ctx == val.ctx, "Context mismatch")
3056  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3057  return val
3058  else:
3059  return BitVecVal(val, self)
3060 
3061 def is_bv_sort(s):
3062  """Return True if `s` is a Z3 bit-vector sort.
3063 
3064  >>> is_bv_sort(BitVecSort(32))
3065  True
3066  >>> is_bv_sort(IntSort())
3067  False
3068  """
3069  return isinstance(s, BitVecSortRef)
3070 
3071 class BitVecRef(ExprRef):
3072  """Bit-vector expressions."""
3073 
3074  def sort(self):
3075  """Return the sort of the bit-vector expression `self`.
3076 
3077  >>> x = BitVec('x', 32)
3078  >>> x.sort()
3079  BitVec(32)
3080  >>> x.sort() == BitVecSort(32)
3081  True
3082  """
3083  return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3084 
3085  def size(self):
3086  """Return the number of bits of the bit-vector expression `self`.
3087 
3088  >>> x = BitVec('x', 32)
3089  >>> (x + 1).size()
3090  32
3091  >>> Concat(x, x).size()
3092  64
3093  """
3094  return self.sort().size()
3095 
3096  def __add__(self, other):
3097  """Create the Z3 expression `self + other`.
3098 
3099  >>> x = BitVec('x', 32)
3100  >>> y = BitVec('y', 32)
3101  >>> x + y
3102  x + y
3103  >>> (x + y).sort()
3104  BitVec(32)
3105  """
3106  a, b = _coerce_exprs(self, other)
3107  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3108 
3109  def __radd__(self, other):
3110  """Create the Z3 expression `other + self`.
3111 
3112  >>> x = BitVec('x', 32)
3113  >>> 10 + x
3114  10 + x
3115  """
3116  a, b = _coerce_exprs(self, other)
3117  return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3118 
3119  def __mul__(self, other):
3120  """Create the Z3 expression `self * other`.
3121 
3122  >>> x = BitVec('x', 32)
3123  >>> y = BitVec('y', 32)
3124  >>> x * y
3125  x*y
3126  >>> (x * y).sort()
3127  BitVec(32)
3128  """
3129  a, b = _coerce_exprs(self, other)
3130  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3131 
3132  def __rmul__(self, other):
3133  """Create the Z3 expression `other * self`.
3134 
3135  >>> x = BitVec('x', 32)
3136  >>> 10 * x
3137  10*x
3138  """
3139  a, b = _coerce_exprs(self, other)
3140  return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3141 
3142  def __sub__(self, other):
3143  """Create the Z3 expression `self - other`.
3144 
3145  >>> x = BitVec('x', 32)
3146  >>> y = BitVec('y', 32)
3147  >>> x - y
3148  x - y
3149  >>> (x - y).sort()
3150  BitVec(32)
3151  """
3152  a, b = _coerce_exprs(self, other)
3153  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3154 
3155  def __rsub__(self, other):
3156  """Create the Z3 expression `other - self`.
3157 
3158  >>> x = BitVec('x', 32)
3159  >>> 10 - x
3160  10 - x
3161  """
3162  a, b = _coerce_exprs(self, other)
3163  return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3164 
3165  def __or__(self, other):
3166  """Create the Z3 expression bitwise-or `self | other`.
3167 
3168  >>> x = BitVec('x', 32)
3169  >>> y = BitVec('y', 32)
3170  >>> x | y
3171  x | y
3172  >>> (x | y).sort()
3173  BitVec(32)
3174  """
3175  a, b = _coerce_exprs(self, other)
3176  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3177 
3178  def __ror__(self, other):
3179  """Create the Z3 expression bitwise-or `other | self`.
3180 
3181  >>> x = BitVec('x', 32)
3182  >>> 10 | x
3183  10 | x
3184  """
3185  a, b = _coerce_exprs(self, other)
3186  return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3187 
3188  def __and__(self, other):
3189  """Create the Z3 expression bitwise-and `self & other`.
3190 
3191  >>> x = BitVec('x', 32)
3192  >>> y = BitVec('y', 32)
3193  >>> x & y
3194  x & y
3195  >>> (x & y).sort()
3196  BitVec(32)
3197  """
3198  a, b = _coerce_exprs(self, other)
3199  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3200 
3201  def __rand__(self, other):
3202  """Create the Z3 expression bitwise-or `other & self`.
3203 
3204  >>> x = BitVec('x', 32)
3205  >>> 10 & x
3206  10 & x
3207  """
3208  a, b = _coerce_exprs(self, other)
3209  return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3210 
3211  def __xor__(self, other):
3212  """Create the Z3 expression bitwise-xor `self ^ other`.
3213 
3214  >>> x = BitVec('x', 32)
3215  >>> y = BitVec('y', 32)
3216  >>> x ^ y
3217  x ^ y
3218  >>> (x ^ y).sort()
3219  BitVec(32)
3220  """
3221  a, b = _coerce_exprs(self, other)
3222  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3223 
3224  def __rxor__(self, other):
3225  """Create the Z3 expression bitwise-xor `other ^ self`.
3226 
3227  >>> x = BitVec('x', 32)
3228  >>> 10 ^ x
3229  10 ^ x
3230  """
3231  a, b = _coerce_exprs(self, other)
3232  return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3233 
3234  def __pos__(self):
3235  """Return `self`.
3236 
3237  >>> x = BitVec('x', 32)
3238  >>> +x
3239  x
3240  """
3241  return self
3242 
3243  def __neg__(self):
3244  """Return an expression representing `-self`.
3245 
3246  >>> x = BitVec('x', 32)
3247  >>> -x
3248  -x
3249  >>> simplify(-(-x))
3250  x
3251  """
3252  return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3253 
3254  def __invert__(self):
3255  """Create the Z3 expression bitwise-not `~self`.
3256 
3257  >>> x = BitVec('x', 32)
3258  >>> ~x
3259  ~x
3260  >>> simplify(~(~x))
3261  x
3262  """
3263  return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3264 
3265  def __div__(self, other):
3266  """Create the Z3 expression (signed) division `self / other`.
3267 
3268  Use the function UDiv() for unsigned division.
3269 
3270  >>> x = BitVec('x', 32)
3271  >>> y = BitVec('y', 32)
3272  >>> x / y
3273  x/y
3274  >>> (x / y).sort()
3275  BitVec(32)
3276  >>> (x / y).sexpr()
3277  '(bvsdiv x y)'
3278  >>> UDiv(x, y).sexpr()
3279  '(bvudiv x y)'
3280  """
3281  a, b = _coerce_exprs(self, other)
3282  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3283 
3284  def __truediv__(self, other):
3285  """Create the Z3 expression (signed) division `self / other`."""
3286  return self.__div__(other)
3287 
3288  def __rdiv__(self, other):
3289  """Create the Z3 expression (signed) division `other / self`.
3290 
3291  Use the function UDiv() for unsigned division.
3292 
3293  >>> x = BitVec('x', 32)
3294  >>> 10 / x
3295  10/x
3296  >>> (10 / x).sexpr()
3297  '(bvsdiv #x0000000a x)'
3298  >>> UDiv(10, x).sexpr()
3299  '(bvudiv #x0000000a x)'
3300  """
3301  a, b = _coerce_exprs(self, other)
3302  return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3303 
3304  def __rtruediv__(self, other):
3305  """Create the Z3 expression (signed) division `other / self`."""
3306  return self.__rdiv__(other)
3307 
3308  def __mod__(self, other):
3309  """Create the Z3 expression (signed) mod `self % other`.
3310 
3311  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3312 
3313  >>> x = BitVec('x', 32)
3314  >>> y = BitVec('y', 32)
3315  >>> x % y
3316  x%y
3317  >>> (x % y).sort()
3318  BitVec(32)
3319  >>> (x % y).sexpr()
3320  '(bvsmod x y)'
3321  >>> URem(x, y).sexpr()
3322  '(bvurem x y)'
3323  >>> SRem(x, y).sexpr()
3324  '(bvsrem x y)'
3325  """
3326  a, b = _coerce_exprs(self, other)
3327  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3328 
3329  def __rmod__(self, other):
3330  """Create the Z3 expression (signed) mod `other % self`.
3331 
3332  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3333 
3334  >>> x = BitVec('x', 32)
3335  >>> 10 % x
3336  10%x
3337  >>> (10 % x).sexpr()
3338  '(bvsmod #x0000000a x)'
3339  >>> URem(10, x).sexpr()
3340  '(bvurem #x0000000a x)'
3341  >>> SRem(10, x).sexpr()
3342  '(bvsrem #x0000000a x)'
3343  """
3344  a, b = _coerce_exprs(self, other)
3345  return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3346 
3347  def __le__(self, other):
3348  """Create the Z3 expression (signed) `other <= self`.
3349 
3350  Use the function ULE() for unsigned less than or equal to.
3351 
3352  >>> x, y = BitVecs('x y', 32)
3353  >>> x <= y
3354  x <= y
3355  >>> (x <= y).sexpr()
3356  '(bvsle x y)'
3357  >>> ULE(x, y).sexpr()
3358  '(bvule x y)'
3359  """
3360  a, b = _coerce_exprs(self, other)
3361  return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3362 
3363  def __lt__(self, other):
3364  """Create the Z3 expression (signed) `other < self`.
3365 
3366  Use the function ULT() for unsigned less than.
3367 
3368  >>> x, y = BitVecs('x y', 32)
3369  >>> x < y
3370  x < y
3371  >>> (x < y).sexpr()
3372  '(bvslt x y)'
3373  >>> ULT(x, y).sexpr()
3374  '(bvult x y)'
3375  """
3376  a, b = _coerce_exprs(self, other)
3377  return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3378 
3379  def __gt__(self, other):
3380  """Create the Z3 expression (signed) `other > self`.
3381 
3382  Use the function UGT() for unsigned greater than.
3383 
3384  >>> x, y = BitVecs('x y', 32)
3385  >>> x > y
3386  x > y
3387  >>> (x > y).sexpr()
3388  '(bvsgt x y)'
3389  >>> UGT(x, y).sexpr()
3390  '(bvugt x y)'
3391  """
3392  a, b = _coerce_exprs(self, other)
3393  return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3394 
3395  def __ge__(self, other):
3396  """Create the Z3 expression (signed) `other >= self`.
3397 
3398  Use the function UGE() for unsigned greater than or equal to.
3399 
3400  >>> x, y = BitVecs('x y', 32)
3401  >>> x >= y
3402  x >= y
3403  >>> (x >= y).sexpr()
3404  '(bvsge x y)'
3405  >>> UGE(x, y).sexpr()
3406  '(bvuge x y)'
3407  """
3408  a, b = _coerce_exprs(self, other)
3409  return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3410 
3411  def __rshift__(self, other):
3412  """Create the Z3 expression (arithmetical) right shift `self >> other`
3413 
3414  Use the function LShR() for the right logical shift
3415 
3416  >>> x, y = BitVecs('x y', 32)
3417  >>> x >> y
3418  x >> y
3419  >>> (x >> y).sexpr()
3420  '(bvashr x y)'
3421  >>> LShR(x, y).sexpr()
3422  '(bvlshr x y)'
3423  >>> BitVecVal(4, 3)
3424  4
3425  >>> BitVecVal(4, 3).as_signed_long()
3426  -4
3427  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3428  -2
3429  >>> simplify(BitVecVal(4, 3) >> 1)
3430  6
3431  >>> simplify(LShR(BitVecVal(4, 3), 1))
3432  2
3433  >>> simplify(BitVecVal(2, 3) >> 1)
3434  1
3435  >>> simplify(LShR(BitVecVal(2, 3), 1))
3436  1
3437  """
3438  a, b = _coerce_exprs(self, other)
3439  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3440 
3441  def __lshift__(self, other):
3442  """Create the Z3 expression left shift `self << other`
3443 
3444  >>> x, y = BitVecs('x y', 32)
3445  >>> x << y
3446  x << y
3447  >>> (x << y).sexpr()
3448  '(bvshl x y)'
3449  >>> simplify(BitVecVal(2, 3) << 1)
3450  4
3451  """
3452  a, b = _coerce_exprs(self, other)
3453  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3454 
3455  def __rrshift__(self, other):
3456  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3457 
3458  Use the function LShR() for the right logical shift
3459 
3460  >>> x = BitVec('x', 32)
3461  >>> 10 >> x
3462  10 >> x
3463  >>> (10 >> x).sexpr()
3464  '(bvashr #x0000000a x)'
3465  """
3466  a, b = _coerce_exprs(self, other)
3467  return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3468 
3469  def __rlshift__(self, other):
3470  """Create the Z3 expression left shift `other << self`.
3471 
3472  Use the function LShR() for the right logical shift
3473 
3474  >>> x = BitVec('x', 32)
3475  >>> 10 << x
3476  10 << x
3477  >>> (10 << x).sexpr()
3478  '(bvshl #x0000000a x)'
3479  """
3480  a, b = _coerce_exprs(self, other)
3481  return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3482 
3483 class BitVecNumRef(BitVecRef):
3484  """Bit-vector values."""
3485 
3486  def as_long(self):
3487  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3488 
3489  >>> v = BitVecVal(0xbadc0de, 32)
3490  >>> v
3491  195936478
3492  >>> print("0x%.8x" % v.as_long())
3493  0x0badc0de
3494  """
3495  return int(self.as_string())
3496 
3497  def as_signed_long(self):
3498  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3499 
3500  >>> BitVecVal(4, 3).as_signed_long()
3501  -4
3502  >>> BitVecVal(7, 3).as_signed_long()
3503  -1
3504  >>> BitVecVal(3, 3).as_signed_long()
3505  3
3506  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3507  -1
3508  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3509  -1
3510  """
3511  sz = self.size()
3512  val = self.as_long()
3513  if val >= 2**(sz - 1):
3514  val = val - 2**sz
3515  if val < -2**(sz - 1):
3516  val = val + 2**sz
3517  return int(val)
3518 
3519  def as_string(self):
3520  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3521 
3522 def is_bv(a):
3523  """Return `True` if `a` is a Z3 bit-vector expression.
3524 
3525  >>> b = BitVec('b', 32)
3526  >>> is_bv(b)
3527  True
3528  >>> is_bv(b + 10)
3529  True
3530  >>> is_bv(Int('x'))
3531  False
3532  """
3533  return isinstance(a, BitVecRef)
3534 
3535 def is_bv_value(a):
3536  """Return `True` if `a` is a Z3 bit-vector numeral value.
3537 
3538  >>> b = BitVec('b', 32)
3539  >>> is_bv_value(b)
3540  False
3541  >>> b = BitVecVal(10, 32)
3542  >>> b
3543  10
3544  >>> is_bv_value(b)
3545  True
3546  """
3547  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3548 
3549 def BV2Int(a, is_signed=False):
3550  """Return the Z3 expression BV2Int(a).
3551 
3552  >>> b = BitVec('b', 3)
3553  >>> BV2Int(b).sort()
3554  Int
3555  >>> x = Int('x')
3556  >>> x > BV2Int(b)
3557  x > BV2Int(b)
3558  >>> x > BV2Int(b, is_signed=False)
3559  x > BV2Int(b)
3560  >>> x > BV2Int(b, is_signed=True)
3561  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3562  >>> solve(x > BV2Int(b), b == 1, x < 3)
3563  [b = 1, x = 2]
3564  """
3565  if __debug__:
3566  _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3567  ctx = a.ctx
3568  ## investigate problem with bv2int
3569  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3570 
3571 def BitVecSort(sz, ctx=None):
3572  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3573 
3574  >>> Byte = BitVecSort(8)
3575  >>> Word = BitVecSort(16)
3576  >>> Byte
3577  BitVec(8)
3578  >>> x = Const('x', Byte)
3579  >>> eq(x, BitVec('x', 8))
3580  True
3581  """
3582  ctx = _get_ctx(ctx)
3583  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3584 
3585 def BitVecVal(val, bv, ctx=None):
3586  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3587 
3588  >>> v = BitVecVal(10, 32)
3589  >>> v
3590  10
3591  >>> print("0x%.8x" % v.as_long())
3592  0x0000000a
3593  """
3594  if is_bv_sort(bv):
3595  ctx = bv.ctx
3596  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3597  else:
3598  ctx = _get_ctx(ctx)
3599  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3600 
3601 def BitVec(name, bv, ctx=None):
3602  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3603  If `ctx=None`, then the global context is used.
3604 
3605  >>> x = BitVec('x', 16)
3606  >>> is_bv(x)
3607  True
3608  >>> x.size()
3609  16
3610  >>> x.sort()
3611  BitVec(16)
3612  >>> word = BitVecSort(16)
3613  >>> x2 = BitVec('x', word)
3614  >>> eq(x, x2)
3615  True
3616  """
3617  if isinstance(bv, BitVecSortRef):
3618  ctx = bv.ctx
3619  else:
3620  ctx = _get_ctx(ctx)
3621  bv = BitVecSort(bv, ctx)
3622  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3623 
3624 def BitVecs(names, bv, ctx=None):
3625  """Return a tuple of bit-vector constants of size bv.
3626 
3627  >>> x, y, z = BitVecs('x y z', 16)
3628  >>> x.size()
3629  16
3630  >>> x.sort()
3631  BitVec(16)
3632  >>> Sum(x, y, z)
3633  0 + x + y + z
3634  >>> Product(x, y, z)
3635  1*x*y*z
3636  >>> simplify(Product(x, y, z))
3637  x*y*z
3638  """
3639  ctx = _get_ctx(ctx)
3640  if isinstance(names, str):
3641  names = names.split(" ")
3642  return [BitVec(name, bv, ctx) for name in names]
3643 
3644 def Concat(*args):
3645  """Create a Z3 bit-vector concatenation expression.
3646 
3647  >>> v = BitVecVal(1, 4)
3648  >>> Concat(v, v+1, v)
3649  Concat(Concat(1, 1 + 1), 1)
3650  >>> simplify(Concat(v, v+1, v))
3651  289
3652  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3653  121
3654  """
3655  args = _get_args(args)
3656  sz = len(args)
3657  if __debug__:
3658  _z3_assert(sz >= 2, "At least two arguments expected.")
3659 
3660  ctx = None
3661  for a in args:
3662  if is_expr(a):
3663  ctx = a.ctx
3664  break
3665  if is_seq(args[0]) or isinstance(args[0], str):
3666  args = [_coerce_seq(s, ctx) for s in args]
3667  if __debug__:
3668  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3669  v = (Ast * sz)()
3670  for i in range(sz):
3671  v[i] = args[i].as_ast()
3672  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3673 
3674  if is_re(args[0]):
3675  if __debug__:
3676  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3677  v = (Ast * sz)()
3678  for i in range(sz):
3679  v[i] = args[i].as_ast()
3680  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3681 
3682  if __debug__:
3683  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3684  r = args[0]
3685  for i in range(sz - 1):
3686  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3687  return r
3688 
3689 def Extract(high, low, a):
3690  """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3691 
3692  >>> x = BitVec('x', 8)
3693  >>> Extract(6, 2, x)
3694  Extract(6, 2, x)
3695  >>> Extract(6, 2, x).sort()
3696  BitVec(5)
3697  >>> simplify(Extract(StringVal("abcd"),2,1))
3698  "c"
3699  """
3700  if isinstance(high, str):
3701  high = StringVal(high)
3702  if is_seq(high):
3703  s = high
3704  offset, length = _coerce_exprs(low, a, s.ctx)
3705  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3706  if __debug__:
3707  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3708  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3709  _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3710  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3711 
3712 def _check_bv_args(a, b):
3713  if __debug__:
3714  _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3715 
3716 def ULE(a, b):
3717  """Create the Z3 expression (unsigned) `other <= self`.
3718 
3719  Use the operator <= for signed less than or equal to.
3720 
3721  >>> x, y = BitVecs('x y', 32)
3722  >>> ULE(x, y)
3723  ULE(x, y)
3724  >>> (x <= y).sexpr()
3725  '(bvsle x y)'
3726  >>> ULE(x, y).sexpr()
3727  '(bvule x y)'
3728  """
3729  _check_bv_args(a, b)
3730  a, b = _coerce_exprs(a, b)
3731  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3732 
3733 def ULT(a, b):
3734  """Create the Z3 expression (unsigned) `other < self`.
3735 
3736  Use the operator < for signed less than.
3737 
3738  >>> x, y = BitVecs('x y', 32)
3739  >>> ULT(x, y)
3740  ULT(x, y)
3741  >>> (x < y).sexpr()
3742  '(bvslt x y)'
3743  >>> ULT(x, y).sexpr()
3744  '(bvult x y)'
3745  """
3746  _check_bv_args(a, b)
3747  a, b = _coerce_exprs(a, b)
3748  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3749 
3750 def UGE(a, b):
3751  """Create the Z3 expression (unsigned) `other >= self`.
3752 
3753  Use the operator >= for signed greater than or equal to.
3754 
3755  >>> x, y = BitVecs('x y', 32)
3756  >>> UGE(x, y)
3757  UGE(x, y)
3758  >>> (x >= y).sexpr()
3759  '(bvsge x y)'
3760  >>> UGE(x, y).sexpr()
3761  '(bvuge x y)'
3762  """
3763  _check_bv_args(a, b)
3764  a, b = _coerce_exprs(a, b)
3765  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3766 
3767 def UGT(a, b):
3768  """Create the Z3 expression (unsigned) `other > self`.
3769 
3770  Use the operator > for signed greater than.
3771 
3772  >>> x, y = BitVecs('x y', 32)
3773  >>> UGT(x, y)
3774  UGT(x, y)
3775  >>> (x > y).sexpr()
3776  '(bvsgt x y)'
3777  >>> UGT(x, y).sexpr()
3778  '(bvugt x y)'
3779  """
3780  _check_bv_args(a, b)
3781  a, b = _coerce_exprs(a, b)
3782  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3783 
3784 def UDiv(a, b):
3785  """Create the Z3 expression (unsigned) division `self / other`.
3786 
3787  Use the operator / for signed division.
3788 
3789  >>> x = BitVec('x', 32)
3790  >>> y = BitVec('y', 32)
3791  >>> UDiv(x, y)
3792  UDiv(x, y)
3793  >>> UDiv(x, y).sort()
3794  BitVec(32)
3795  >>> (x / y).sexpr()
3796  '(bvsdiv x y)'
3797  >>> UDiv(x, y).sexpr()
3798  '(bvudiv x y)'
3799  """
3800  _check_bv_args(a, b)
3801  a, b = _coerce_exprs(a, b)
3802  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3803 
3804 def URem(a, b):
3805  """Create the Z3 expression (unsigned) remainder `self % other`.
3806 
3807  Use the operator % for signed modulus, and SRem() for signed remainder.
3808 
3809  >>> x = BitVec('x', 32)
3810  >>> y = BitVec('y', 32)
3811  >>> URem(x, y)
3812  URem(x, y)
3813  >>> URem(x, y).sort()
3814  BitVec(32)
3815  >>> (x % y).sexpr()
3816  '(bvsmod x y)'
3817  >>> URem(x, y).sexpr()
3818  '(bvurem x y)'
3819  """
3820  _check_bv_args(a, b)
3821  a, b = _coerce_exprs(a, b)
3822  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3823 
3824 def SRem(a, b):
3825  """Create the Z3 expression signed remainder.
3826 
3827  Use the operator % for signed modulus, and URem() for unsigned remainder.
3828 
3829  >>> x = BitVec('x', 32)
3830  >>> y = BitVec('y', 32)
3831  >>> SRem(x, y)
3832  SRem(x, y)
3833  >>> SRem(x, y).sort()
3834  BitVec(32)
3835  >>> (x % y).sexpr()
3836  '(bvsmod x y)'
3837  >>> SRem(x, y).sexpr()
3838  '(bvsrem x y)'
3839  """
3840  _check_bv_args(a, b)
3841  a, b = _coerce_exprs(a, b)
3842  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3843 
3844 def LShR(a, b):
3845  """Create the Z3 expression logical right shift.
3846 
3847  Use the operator >> for the arithmetical right shift.
3848 
3849  >>> x, y = BitVecs('x y', 32)
3850  >>> LShR(x, y)
3851  LShR(x, y)
3852  >>> (x >> y).sexpr()
3853  '(bvashr x y)'
3854  >>> LShR(x, y).sexpr()
3855  '(bvlshr x y)'
3856  >>> BitVecVal(4, 3)
3857  4
3858  >>> BitVecVal(4, 3).as_signed_long()
3859  -4
3860  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3861  -2
3862  >>> simplify(BitVecVal(4, 3) >> 1)
3863  6
3864  >>> simplify(LShR(BitVecVal(4, 3), 1))
3865  2
3866  >>> simplify(BitVecVal(2, 3) >> 1)
3867  1
3868  >>> simplify(LShR(BitVecVal(2, 3), 1))
3869  1
3870  """
3871  _check_bv_args(a, b)
3872  a, b = _coerce_exprs(a, b)
3873  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3874 
3875 def RotateLeft(a, b):
3876  """Return an expression representing `a` rotated to the left `b` times.
3877 
3878  >>> a, b = BitVecs('a b', 16)
3879  >>> RotateLeft(a, b)
3880  RotateLeft(a, b)
3881  >>> simplify(RotateLeft(a, 0))
3882  a
3883  >>> simplify(RotateLeft(a, 16))
3884  a
3885  """
3886  _check_bv_args(a, b)
3887  a, b = _coerce_exprs(a, b)
3888  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3889 
3890 def RotateRight(a, b):
3891  """Return an expression representing `a` rotated to the right `b` times.
3892 
3893  >>> a, b = BitVecs('a b', 16)
3894  >>> RotateRight(a, b)
3895  RotateRight(a, b)
3896  >>> simplify(RotateRight(a, 0))
3897  a
3898  >>> simplify(RotateRight(a, 16))
3899  a
3900  """
3901  _check_bv_args(a, b)
3902  a, b = _coerce_exprs(a, b)
3903  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3904 
3905 def SignExt(n, a):
3906  """Return a bit-vector expression with `n` extra sign-bits.
3907 
3908  >>> x = BitVec('x', 16)
3909  >>> n = SignExt(8, x)
3910  >>> n.size()
3911  24
3912  >>> n
3913  SignExt(8, x)
3914  >>> n.sort()
3915  BitVec(24)
3916  >>> v0 = BitVecVal(2, 2)
3917  >>> v0
3918  2
3919  >>> v0.size()
3920  2
3921  >>> v = simplify(SignExt(6, v0))
3922  >>> v
3923  254
3924  >>> v.size()
3925  8
3926  >>> print("%.x" % v.as_long())
3927  fe
3928  """
3929  if __debug__:
3930  _z3_assert(_is_int(n), "First argument must be an integer")
3931  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3932  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3933 
3934 def ZeroExt(n, a):
3935  """Return a bit-vector expression with `n` extra zero-bits.
3936 
3937  >>> x = BitVec('x', 16)
3938  >>> n = ZeroExt(8, x)
3939  >>> n.size()
3940  24
3941  >>> n
3942  ZeroExt(8, x)
3943  >>> n.sort()
3944  BitVec(24)
3945  >>> v0 = BitVecVal(2, 2)
3946  >>> v0
3947  2
3948  >>> v0.size()
3949  2
3950  >>> v = simplify(ZeroExt(6, v0))
3951  >>> v
3952  2
3953  >>> v.size()
3954  8
3955  """
3956  if __debug__:
3957  _z3_assert(_is_int(n), "First argument must be an integer")
3958  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3959  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
3960 
3961 def RepeatBitVec(n, a):
3962  """Return an expression representing `n` copies of `a`.
3963 
3964  >>> x = BitVec('x', 8)
3965  >>> n = RepeatBitVec(4, x)
3966  >>> n
3967  RepeatBitVec(4, x)
3968  >>> n.size()
3969  32
3970  >>> v0 = BitVecVal(10, 4)
3971  >>> print("%.x" % v0.as_long())
3972  a
3973  >>> v = simplify(RepeatBitVec(4, v0))
3974  >>> v.size()
3975  16
3976  >>> print("%.x" % v.as_long())
3977  aaaa
3978  """
3979  if __debug__:
3980  _z3_assert(_is_int(n), "First argument must be an integer")
3981  _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
3982  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
3983 
3984 def BVRedAnd(a):
3985  """Return the reduction-and expression of `a`."""
3986  if __debug__:
3987  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3988  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
3989 
3990 def BVRedOr(a):
3991  """Return the reduction-or expression of `a`."""
3992  if __debug__:
3993  _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
3994  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
3995 
3996 def BVAddNoOverflow(a, b, signed):
3997  """A predicate the determines that bit-vector addition does not overflow"""
3998  _check_bv_args(a, b)
3999  a, b = _coerce_exprs(a, b)
4000  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4001 
4002 def BVAddNoUnderflow(a, b):
4003  """A predicate the determines that signed bit-vector addition does not underflow"""
4004  _check_bv_args(a, b)
4005  a, b = _coerce_exprs(a, b)
4006  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4007 
4008 def BVSubNoOverflow(a, b):
4009  """A predicate the determines that bit-vector subtraction does not overflow"""
4010  _check_bv_args(a, b)
4011  a, b = _coerce_exprs(a, b)
4012  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4013 
4014 
4015 def BVSubNoUnderflow(a, b, signed):
4016  """A predicate the determines that bit-vector subtraction does not underflow"""
4017  _check_bv_args(a, b)
4018  a, b = _coerce_exprs(a, b)
4019  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4020 
4021 def BVSDivNoOverflow(a, b):
4022  """A predicate the determines that bit-vector signed division does not overflow"""
4023  _check_bv_args(a, b)
4024  a, b = _coerce_exprs(a, b)
4025  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4026 
4027 def BVSNegNoOverflow(a):
4028  """A predicate the determines that bit-vector unary negation does not overflow"""
4029  if __debug__:
4030  _z3_assert(is_bv(a), "Argument should be a bit-vector")
4031  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4032 
4033 def BVMulNoOverflow(a, b, signed):
4034  """A predicate the determines that bit-vector multiplication does not overflow"""
4035  _check_bv_args(a, b)
4036  a, b = _coerce_exprs(a, b)
4037  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4038 
4039 
4040 def BVMulNoUnderflow(a, b):
4041  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4042  _check_bv_args(a, b)
4043  a, b = _coerce_exprs(a, b)
4044  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4045 
4046 
4047 
4048 #########################################
4049 #
4050 # Arrays
4051 #
4052 #########################################
4053 
4054 class ArraySortRef(SortRef):
4055  """Array sorts."""
4056 
4057  def domain(self):
4058  """Return the domain of the array sort `self`.
4059 
4060  >>> A = ArraySort(IntSort(), BoolSort())
4061  >>> A.domain()
4062  Int
4063  """
4064  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4065 
4066  def range(self):
4067  """Return the range of the array sort `self`.
4068 
4069  >>> A = ArraySort(IntSort(), BoolSort())
4070  >>> A.range()
4071  Bool
4072  """
4073  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4074 
4075 class ArrayRef(ExprRef):
4076  """Array expressions. """
4077 
4078  def sort(self):
4079  """Return the array sort of the array expression `self`.
4080 
4081  >>> a = Array('a', IntSort(), BoolSort())
4082  >>> a.sort()
4083  Array(Int, Bool)
4084  """
4085  return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4086 
4087  def domain(self):
4088  """Shorthand for `self.sort().domain()`.
4089 
4090  >>> a = Array('a', IntSort(), BoolSort())
4091  >>> a.domain()
4092  Int
4093  """
4094  return self.sort().domain()
4095 
4096  def range(self):
4097  """Shorthand for `self.sort().range()`.
4098 
4099  >>> a = Array('a', IntSort(), BoolSort())
4100  >>> a.range()
4101  Bool
4102  """
4103  return self.sort().range()
4104 
4105  def __getitem__(self, arg):
4106  """Return the Z3 expression `self[arg]`.
4107 
4108  >>> a = Array('a', IntSort(), BoolSort())
4109  >>> i = Int('i')
4110  >>> a[i]
4111  a[i]
4112  >>> a[i].sexpr()
4113  '(select a i)'
4114  """
4115  arg = self.domain().cast(arg)
4116  return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
4117 
4118  def default(self):
4119  return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4120 
4121 
4122 def is_array(a):
4123  """Return `True` if `a` is a Z3 array expression.
4124 
4125  >>> a = Array('a', IntSort(), IntSort())
4126  >>> is_array(a)
4127  True
4128  >>> is_array(Store(a, 0, 1))
4129  True
4130  >>> is_array(a[0])
4131  False
4132  """
4133  return isinstance(a, ArrayRef)
4134 
4135 def is_const_array(a):
4136  """Return `True` if `a` is a Z3 constant array.
4137 
4138  >>> a = K(IntSort(), 10)
4139  >>> is_const_array(a)
4140  True
4141  >>> a = Array('a', IntSort(), IntSort())
4142  >>> is_const_array(a)
4143  False
4144  """
4145  return is_app_of(a, Z3_OP_CONST_ARRAY)
4146 
4147 def is_K(a):
4148  """Return `True` if `a` is a Z3 constant array.
4149 
4150  >>> a = K(IntSort(), 10)
4151  >>> is_K(a)
4152  True
4153  >>> a = Array('a', IntSort(), IntSort())
4154  >>> is_K(a)
4155  False
4156  """
4157  return is_app_of(a, Z3_OP_CONST_ARRAY)
4158 
4159 def is_map(a):
4160  """Return `True` if `a` is a Z3 map array expression.
4161 
4162  >>> f = Function('f', IntSort(), IntSort())
4163  >>> b = Array('b', IntSort(), IntSort())
4164  >>> a = Map(f, b)
4165  >>> a
4166  Map(f, b)
4167  >>> is_map(a)
4168  True
4169  >>> is_map(b)
4170  False
4171  """
4172  return is_app_of(a, Z3_OP_ARRAY_MAP)
4173 
4174 def is_default(a):
4175  """Return `True` if `a` is a Z3 default array expression.
4176  >>> d = Default(K(IntSort(), 10))
4177  >>> is_default(d)
4178  True
4179  """
4180  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4181 
4182 def get_map_func(a):
4183  """Return the function declaration associated with a Z3 map array expression.
4184 
4185  >>> f = Function('f', IntSort(), IntSort())
4186  >>> b = Array('b', IntSort(), IntSort())
4187  >>> a = Map(f, b)
4188  >>> eq(f, get_map_func(a))
4189  True
4190  >>> get_map_func(a)
4191  f
4192  >>> get_map_func(a)(0)
4193  f(0)
4194  """
4195  if __debug__:
4196  _z3_assert(is_map(a), "Z3 array map expression expected.")
4197  return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4198 
4199 def ArraySort(d, r):
4200  """Return the Z3 array sort with the given domain and range sorts.
4201 
4202  >>> A = ArraySort(IntSort(), BoolSort())
4203  >>> A
4204  Array(Int, Bool)
4205  >>> A.domain()
4206  Int
4207  >>> A.range()
4208  Bool
4209  >>> AA = ArraySort(IntSort(), A)
4210  >>> AA
4211  Array(Int, Array(Int, Bool))
4212  """
4213  if __debug__:
4214  _z3_assert(is_sort(d), "Z3 sort expected")
4215  _z3_assert(is_sort(r), "Z3 sort expected")
4216  _z3_assert(d.ctx == r.ctx, "Context mismatch")
4217  ctx = d.ctx
4218  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4219 
4220 def Array(name, dom, rng):
4221  """Return an array constant named `name` with the given domain and range sorts.
4222 
4223  >>> a = Array('a', IntSort(), IntSort())
4224  >>> a.sort()
4225  Array(Int, Int)
4226  >>> a[0]
4227  a[0]
4228  """
4229  s = ArraySort(dom, rng)
4230  ctx = s.ctx
4231  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4232 
4233 def Update(a, i, v):
4234  """Return a Z3 store array expression.
4235 
4236  >>> a = Array('a', IntSort(), IntSort())
4237  >>> i, v = Ints('i v')
4238  >>> s = Update(a, i, v)
4239  >>> s.sort()
4240  Array(Int, Int)
4241  >>> prove(s[i] == v)
4242  proved
4243  >>> j = Int('j')
4244  >>> prove(Implies(i != j, s[j] == a[j]))
4245  proved
4246  """
4247  if __debug__:
4248  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4249  i = a.domain().cast(i)
4250  v = a.range().cast(v)
4251  ctx = a.ctx
4252  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4253 
4254 def Default(a):
4255  """ Return a default value for array expression.
4256  >>> b = K(IntSort(), 1)
4257  >>> prove(Default(b) == 1)
4258  proved
4259  """
4260  if __debug__:
4261  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4262  return a.default()
4263 
4264 
4265 def Store(a, i, v):
4266  """Return a Z3 store array expression.
4267 
4268  >>> a = Array('a', IntSort(), IntSort())
4269  >>> i, v = Ints('i v')
4270  >>> s = Store(a, i, v)
4271  >>> s.sort()
4272  Array(Int, Int)
4273  >>> prove(s[i] == v)
4274  proved
4275  >>> j = Int('j')
4276  >>> prove(Implies(i != j, s[j] == a[j]))
4277  proved
4278  """
4279  return Update(a, i, v)
4280 
4281 def Select(a, i):
4282  """Return a Z3 select array expression.
4283 
4284  >>> a = Array('a', IntSort(), IntSort())
4285  >>> i = Int('i')
4286  >>> Select(a, i)
4287  a[i]
4288  >>> eq(Select(a, i), a[i])
4289  True
4290  """
4291  if __debug__:
4292  _z3_assert(is_array(a), "First argument must be a Z3 array expression")
4293  return a[i]
4294 
4295 
4296 def Map(f, *args):
4297  """Return a Z3 map array expression.
4298 
4299  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4300  >>> a1 = Array('a1', IntSort(), IntSort())
4301  >>> a2 = Array('a2', IntSort(), IntSort())
4302  >>> b = Map(f, a1, a2)
4303  >>> b
4304  Map(f, a1, a2)
4305  >>> prove(b[0] == f(a1[0], a2[0]))
4306  proved
4307  """
4308  args = _get_args(args)
4309  if __debug__:
4310  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4311  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4312  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4313  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4314  _args, sz = _to_ast_array(args)
4315  ctx = f.ctx
4316  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4317 
4318 def K(dom, v):
4319  """Return a Z3 constant array expression.
4320 
4321  >>> a = K(IntSort(), 10)
4322  >>> a
4323  K(Int, 10)
4324  >>> a.sort()
4325  Array(Int, Int)
4326  >>> i = Int('i')
4327  >>> a[i]
4328  K(Int, 10)[i]
4329  >>> simplify(a[i])
4330  10
4331  """
4332  if __debug__:
4333  _z3_assert(is_sort(dom), "Z3 sort expected")
4334  ctx = dom.ctx
4335  if not is_expr(v):
4336  v = _py2expr(v, ctx)
4337  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4338 
4339 def Ext(a, b):
4340  """Return extensionality index for arrays.
4341  """
4342  if __debug__:
4343  _z3_assert(is_array(a) and is_array(b))
4344  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
4345 
4346 def is_select(a):
4347  """Return `True` if `a` is a Z3 array select application.
4348 
4349  >>> a = Array('a', IntSort(), IntSort())
4350  >>> is_select(a)
4351  False
4352  >>> i = Int('i')
4353  >>> is_select(a[i])
4354  True
4355  """
4356  return is_app_of(a, Z3_OP_SELECT)
4357 
4358 def is_store(a):
4359  """Return `True` if `a` is a Z3 array store application.
4360 
4361  >>> a = Array('a', IntSort(), IntSort())
4362  >>> is_store(a)
4363  False
4364  >>> is_store(Store(a, 0, 1))
4365  True
4366  """
4367  return is_app_of(a, Z3_OP_STORE)
4368 
4369 #########################################
4370 #
4371 # Datatypes
4372 #
4373 #########################################
4374 
4375 def _valid_accessor(acc):
4376  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4377  return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4378 
4379 class Datatype:
4380  """Helper class for declaring Z3 datatypes.
4381 
4382  >>> List = Datatype('List')
4383  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4384  >>> List.declare('nil')
4385  >>> List = List.create()
4386  >>> # List is now a Z3 declaration
4387  >>> List.nil
4388  nil
4389  >>> List.cons(10, List.nil)
4390  cons(10, nil)
4391  >>> List.cons(10, List.nil).sort()
4392  List
4393  >>> cons = List.cons
4394  >>> nil = List.nil
4395  >>> car = List.car
4396  >>> cdr = List.cdr
4397  >>> n = cons(1, cons(0, nil))
4398  >>> n
4399  cons(1, cons(0, nil))
4400  >>> simplify(cdr(n))
4401  cons(0, nil)
4402  >>> simplify(car(n))
4403  1
4404  """
4405  def __init__(self, name, ctx=None):
4406  self.ctx = _get_ctx(ctx)
4407  self.name = name
4408  self.constructors = []
4409 
4410  def __deepcopy__(self, memo={}):
4411  r = Datatype(self.name, self.ctx)
4412  r.constructors = copy.deepcopy(self.constructors)
4413  return r
4414 
4415  def declare_core(self, name, rec_name, *args):
4416  if __debug__:
4417  _z3_assert(isinstance(name, str), "String expected")
4418  _z3_assert(isinstance(rec_name, str), "String expected")
4419  _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)")
4420  self.constructors.append((name, rec_name, args))
4421 
4422  def declare(self, name, *args):
4423  """Declare constructor named `name` with the given accessors `args`.
4424  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.
4425 
4426  In the followin example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4427  declares the constructor named `cons` that builds a new List using an integer and a List.
4428  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4429  and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4430  the actual datatype in Z3.
4431 
4432  >>> List = Datatype('List')
4433  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4434  >>> List.declare('nil')
4435  >>> List = List.create()
4436  """
4437  if __debug__:
4438  _z3_assert(isinstance(name, str), "String expected")
4439  _z3_assert(name != "", "Constructor name cannot be empty")
4440  return self.declare_core(name, "is_" + name, *args)
4441 
4442  def __repr__(self):
4443  return "Datatype(%s, %s)" % (self.name, self.constructors)
4444 
4445  def create(self):
4446  """Create a Z3 datatype based on the constructors declared using the mehtod `declare()`.
4447 
4448  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4449 
4450  >>> List = Datatype('List')
4451  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4452  >>> List.declare('nil')
4453  >>> List = List.create()
4454  >>> List.nil
4455  nil
4456  >>> List.cons(10, List.nil)
4457  cons(10, nil)
4458  """
4459  return CreateDatatypes([self])[0]
4460 
4461 class ScopedConstructor:
4462  """Auxiliary object used to create Z3 datatypes."""
4463  def __init__(self, c, ctx):
4464  self.c = c
4465  self.ctx = ctx
4466  def __del__(self):
4467  if self.ctx.ref() is not None:
4468  Z3_del_constructor(self.ctx.ref(), self.c)
4469 
4470 class ScopedConstructorList:
4471  """Auxiliary object used to create Z3 datatypes."""
4472  def __init__(self, c, ctx):
4473  self.c = c
4474  self.ctx = ctx
4475  def __del__(self):
4476  if self.ctx.ref() is not None:
4477  Z3_del_constructor_list(self.ctx.ref(), self.c)
4478 
4479 def CreateDatatypes(*ds):
4480  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4481 
4482  In the following example we define a Tree-List using two mutually recursive datatypes.
4483 
4484  >>> TreeList = Datatype('TreeList')
4485  >>> Tree = Datatype('Tree')
4486  >>> # Tree has two constructors: leaf and node
4487  >>> Tree.declare('leaf', ('val', IntSort()))
4488  >>> # a node contains a list of trees
4489  >>> Tree.declare('node', ('children', TreeList))
4490  >>> TreeList.declare('nil')
4491  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4492  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4493  >>> Tree.val(Tree.leaf(10))
4494  val(leaf(10))
4495  >>> simplify(Tree.val(Tree.leaf(10)))
4496  10
4497  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4498  >>> n1
4499  node(cons(leaf(10), cons(leaf(20), nil)))
4500  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4501  >>> simplify(n2 == n1)
4502  False
4503  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4504  True
4505  """
4506  ds = _get_args(ds)
4507  if __debug__:
4508  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4509  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4510  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4511  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4512  ctx = ds[0].ctx
4513  num = len(ds)
4514  names = (Symbol * num)()
4515  out = (Sort * num)()
4516  clists = (ConstructorList * num)()
4517  to_delete = []
4518  for i in range(num):
4519  d = ds[i]
4520  names[i] = to_symbol(d.name, ctx)
4521  num_cs = len(d.constructors)
4522  cs = (Constructor * num_cs)()
4523  for j in range(num_cs):
4524  c = d.constructors[j]
4525  cname = to_symbol(c[0], ctx)
4526  rname = to_symbol(c[1], ctx)
4527  fs = c[2]
4528  num_fs = len(fs)
4529  fnames = (Symbol * num_fs)()
4530  sorts = (Sort * num_fs)()
4531  refs = (ctypes.c_uint * num_fs)()
4532  for k in range(num_fs):
4533  fname = fs[k][0]
4534  ftype = fs[k][1]
4535  fnames[k] = to_symbol(fname, ctx)
4536  if isinstance(ftype, Datatype):
4537  if __debug__:
4538  _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4539  sorts[k] = None
4540  refs[k] = ds.index(ftype)
4541  else:
4542  if __debug__:
4543  _z3_assert(is_sort(ftype), "Z3 sort expected")
4544  sorts[k] = ftype.ast
4545  refs[k] = 0
4546  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4547  to_delete.append(ScopedConstructor(cs[j], ctx))
4548  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4549  to_delete.append(ScopedConstructorList(clists[i], ctx))
4550  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4551  result = []
4552  ## Create a field for every constructor, recognizer and accessor
4553  for i in range(num):
4554  dref = DatatypeSortRef(out[i], ctx)
4555  num_cs = dref.num_constructors()
4556  for j in range(num_cs):
4557  cref = dref.constructor(j)
4558  cref_name = cref.name()
4559  cref_arity = cref.arity()
4560  if cref.arity() == 0:
4561  cref = cref()
4562  setattr(dref, cref_name, cref)
4563  rref = dref.recognizer(j)
4564  setattr(dref, rref.name(), rref)
4565  for k in range(cref_arity):
4566  aref = dref.accessor(j, k)
4567  setattr(dref, aref.name(), aref)
4568  result.append(dref)
4569  return tuple(result)
4570 
4571 class DatatypeSortRef(SortRef):
4572  """Datatype sorts."""
4573  def num_constructors(self):
4574  """Return the number of constructors in the given Z3 datatype.
4575 
4576  >>> List = Datatype('List')
4577  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4578  >>> List.declare('nil')
4579  >>> List = List.create()
4580  >>> # List is now a Z3 declaration
4581  >>> List.num_constructors()
4582  2
4583  """
4584  return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4585 
4586  def constructor(self, idx):
4587  """Return a constructor of the datatype `self`.
4588 
4589  >>> List = Datatype('List')
4590  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4591  >>> List.declare('nil')
4592  >>> List = List.create()
4593  >>> # List is now a Z3 declaration
4594  >>> List.num_constructors()
4595  2
4596  >>> List.constructor(0)
4597  cons
4598  >>> List.constructor(1)
4599  nil
4600  """
4601  if __debug__:
4602  _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4603  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4604 
4605  def recognizer(self, idx):
4606  """In Z3, each constructor has an associated recognizer predicate.
4607 
4608  If the constructor is named `name`, then the recognizer `is_name`.
4609 
4610  >>> List = Datatype('List')
4611  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4612  >>> List.declare('nil')
4613  >>> List = List.create()
4614  >>> # List is now a Z3 declaration
4615  >>> List.num_constructors()
4616  2
4617  >>> List.recognizer(0)
4618  is_cons
4619  >>> List.recognizer(1)
4620  is_nil
4621  >>> simplify(List.is_nil(List.cons(10, List.nil)))
4622  False
4623  >>> simplify(List.is_cons(List.cons(10, List.nil)))
4624  True
4625  >>> l = Const('l', List)
4626  >>> simplify(List.is_cons(l))
4627  is_cons(l)
4628  """
4629  if __debug__:
4630  _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4631  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4632 
4633  def accessor(self, i, j):
4634  """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4635 
4636  >>> List = Datatype('List')
4637  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4638  >>> List.declare('nil')
4639  >>> List = List.create()
4640  >>> List.num_constructors()
4641  2
4642  >>> List.constructor(0)
4643  cons
4644  >>> num_accs = List.constructor(0).arity()
4645  >>> num_accs
4646  2
4647  >>> List.accessor(0, 0)
4648  car
4649  >>> List.accessor(0, 1)
4650  cdr
4651  >>> List.constructor(1)
4652  nil
4653  >>> num_accs = List.constructor(1).arity()
4654  >>> num_accs
4655  0
4656  """
4657  if __debug__:
4658  _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4659  _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4660  return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4661 
4662 class DatatypeRef(ExprRef):
4663  """Datatype expressions."""
4664  def sort(self):
4665  """Return the datatype sort of the datatype expression `self`."""
4666  return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4667 
4668 def EnumSort(name, values, ctx=None):
4669  """Return a new enumeration sort named `name` containing the given values.
4670 
4671  The result is a pair (sort, list of constants).
4672  Example:
4673  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
4674  """
4675  if __debug__:
4676  _z3_assert(isinstance(name, str), "Name must be a string")
4677  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
4678  _z3_assert(len(values) > 0, "At least one value expected")
4679  ctx = _get_ctx(ctx)
4680  num = len(values)
4681  _val_names = (Symbol * num)()
4682  for i in range(num):
4683  _val_names[i] = to_symbol(values[i])
4684  _values = (FuncDecl * num)()
4685  _testers = (FuncDecl * num)()
4686  name = to_symbol(name)
4687  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
4688  V = []
4689  for i in range(num):
4690  V.append(FuncDeclRef(_values[i], ctx))
4691  V = [a() for a in V]
4692  return S, V
4693 
4694 #########################################
4695 #
4696 # Parameter Sets
4697 #
4698 #########################################
4699 
4700 class ParamsRef:
4701  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
4702 
4703  Consider using the function `args2params` to create instances of this object.
4704  """
4705  def __init__(self, ctx=None, params=None):
4706  self.ctx = _get_ctx(ctx)
4707  if params is None:
4708  self.params = Z3_mk_params(self.ctx.ref())
4709  else:
4710  self.params = params
4711  Z3_params_inc_ref(self.ctx.ref(), self.params)
4712 
4713  def __deepcopy__(self, memo={}):
4714  return ParamsRef(self.ctx, self.params)
4715 
4716  def __del__(self):
4717  if self.ctx.ref() is not None:
4718  Z3_params_dec_ref(self.ctx.ref(), self.params)
4719 
4720  def set(self, name, val):
4721  """Set parameter name with value val."""
4722  if __debug__:
4723  _z3_assert(isinstance(name, str), "parameter name must be a string")
4724  name_sym = to_symbol(name, self.ctx)
4725  if isinstance(val, bool):
4726  Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
4727  elif _is_int(val):
4728  Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
4729  elif isinstance(val, float):
4730  Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
4731  elif isinstance(val, str):
4732  Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
4733  else:
4734  if __debug__:
4735  _z3_assert(False, "invalid parameter value")
4736 
4737  def __repr__(self):
4738  return Z3_params_to_string(self.ctx.ref(), self.params)
4739 
4740  def validate(self, ds):
4741  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
4742  Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
4743 
4744 def args2params(arguments, keywords, ctx=None):
4745  """Convert python arguments into a Z3_params object.
4746  A ':' is added to the keywords, and '_' is replaced with '-'
4747 
4748  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
4749  (params model true relevancy 2 elim_and true)
4750  """
4751  if __debug__:
4752  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
4753  prev = None
4754  r = ParamsRef(ctx)
4755  for a in arguments:
4756  if prev is None:
4757  prev = a
4758  else:
4759  r.set(prev, a)
4760  prev = None
4761  for k in keywords:
4762  v = keywords[k]
4763  r.set(k, v)
4764  return r
4765 
4766 class ParamDescrsRef:
4767  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
4768  """
4769  def __init__(self, descr, ctx=None):
4770  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
4771  self.ctx = _get_ctx(ctx)
4772  self.descr = descr
4773  Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
4774 
4775  def __deepcopy__(self, memo={}):
4776  return ParamsDescrsRef(self.descr, self.ctx)
4777 
4778  def __del__(self):
4779  if self.ctx.ref() is not None:
4780  Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
4781 
4782  def size(self):
4783  """Return the size of in the parameter description `self`.
4784  """
4785  return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
4786 
4787  def __len__(self):
4788  """Return the size of in the parameter description `self`.
4789  """
4790  return self.size()
4791 
4792  def get_name(self, i):
4793  """Return the i-th parameter name in the parameter description `self`.
4794  """
4795  return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
4796 
4797  def get_kind(self, n):
4798  """Return the kind of the parameter named `n`.
4799  """
4800  return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4801 
4802  def get_documentation(self, n):
4803  """Return the documentation string of the parameter named `n`.
4804  """
4805  return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
4806 
4807  def __getitem__(self, arg):
4808  if _is_int(arg):
4809  return self.get_name(arg)
4810  else:
4811  return self.get_kind(arg)
4812 
4813  def __repr__(self):
4814  return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
4815 
4816 #########################################
4817 #
4818 # Goals
4819 #
4820 #########################################
4821 
4822 class Goal(Z3PPObject):
4823  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
4824 
4825  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
4826  A goal has a solution if one of its subgoals has a solution.
4827  A goal is unsatisfiable if all subgoals are unsatisfiable.
4828  """
4829 
4830  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
4831  if __debug__:
4832  _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
4833  self.ctx = _get_ctx(ctx)
4834  self.goal = goal
4835  if self.goal is None:
4836  self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
4837  Z3_goal_inc_ref(self.ctx.ref(), self.goal)
4838 
4839  def __deepcopy__(self, memo={}):
4840  return Goal(False, False, False, self.ctx, self.goal)
4841 
4842  def __del__(self):
4843  if self.goal is not None and self.ctx.ref() is not None:
4844  Z3_goal_dec_ref(self.ctx.ref(), self.goal)
4845 
4846  def depth(self):
4847  """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
4848 
4849  >>> x, y = Ints('x y')
4850  >>> g = Goal()
4851  >>> g.add(x == 0, y >= x + 1)
4852  >>> g.depth()
4853  0
4854  >>> r = Then('simplify', 'solve-eqs')(g)
4855  >>> # r has 1 subgoal
4856  >>> len(r)
4857  1
4858  >>> r[0].depth()
4859  2
4860  """
4861  return int(Z3_goal_depth(self.ctx.ref(), self.goal))
4862 
4863  def inconsistent(self):
4864  """Return `True` if `self` contains the `False` constraints.
4865 
4866  >>> x, y = Ints('x y')
4867  >>> g = Goal()
4868  >>> g.inconsistent()
4869  False
4870  >>> g.add(x == 0, x == 1)
4871  >>> g
4872  [x == 0, x == 1]
4873  >>> g.inconsistent()
4874  False
4875  >>> g2 = Tactic('propagate-values')(g)[0]
4876  >>> g2.inconsistent()
4877  True
4878  """
4879  return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
4880 
4881  def prec(self):
4882  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
4883 
4884  >>> g = Goal()
4885  >>> g.prec() == Z3_GOAL_PRECISE
4886  True
4887  >>> x, y = Ints('x y')
4888  >>> g.add(x == y + 1)
4889  >>> g.prec() == Z3_GOAL_PRECISE
4890  True
4891  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
4892  >>> g2 = t(g)[0]
4893  >>> g2
4894  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
4895  >>> g2.prec() == Z3_GOAL_PRECISE
4896  False
4897  >>> g2.prec() == Z3_GOAL_UNDER
4898  True
4899  """
4900  return Z3_goal_precision(self.ctx.ref(), self.goal)
4901 
4902  def precision(self):
4903  """Alias for `prec()`.
4904 
4905  >>> g = Goal()
4906  >>> g.precision() == Z3_GOAL_PRECISE
4907  True
4908  """
4909  return self.prec()
4910 
4911  def size(self):
4912  """Return the number of constraints in the goal `self`.
4913 
4914  >>> g = Goal()
4915  >>> g.size()
4916  0
4917  >>> x, y = Ints('x y')
4918  >>> g.add(x == 0, y > x)
4919  >>> g.size()
4920  2
4921  """
4922  return int(Z3_goal_size(self.ctx.ref(), self.goal))
4923 
4924  def __len__(self):
4925  """Return the number of constraints in the goal `self`.
4926 
4927  >>> g = Goal()
4928  >>> len(g)
4929  0
4930  >>> x, y = Ints('x y')
4931  >>> g.add(x == 0, y > x)
4932  >>> len(g)
4933  2
4934  """
4935  return self.size()
4936 
4937  def get(self, i):
4938  """Return a constraint in the goal `self`.
4939 
4940  >>> g = Goal()
4941  >>> x, y = Ints('x y')
4942  >>> g.add(x == 0, y > x)
4943  >>> g.get(0)
4944  x == 0
4945  >>> g.get(1)
4946  y > x
4947  """
4948  return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
4949 
4950  def __getitem__(self, arg):
4951  """Return a constraint in the goal `self`.
4952 
4953  >>> g = Goal()
4954  >>> x, y = Ints('x y')
4955  >>> g.add(x == 0, y > x)
4956  >>> g[0]
4957  x == 0
4958  >>> g[1]
4959  y > x
4960  """
4961  if arg >= len(self):
4962  raise IndexError
4963  return self.get(arg)
4964 
4965  def assert_exprs(self, *args):
4966  """Assert constraints into the goal.
4967 
4968  >>> x = Int('x')
4969  >>> g = Goal()
4970  >>> g.assert_exprs(x > 0, x < 2)
4971  >>> g
4972  [x > 0, x < 2]
4973  """
4974  args = _get_args(args)
4975  s = BoolSort(self.ctx)
4976  for arg in args:
4977  arg = s.cast(arg)
4978  Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
4979 
4980  def append(self, *args):
4981  """Add constraints.
4982 
4983  >>> x = Int('x')
4984  >>> g = Goal()
4985  >>> g.append(x > 0, x < 2)
4986  >>> g
4987  [x > 0, x < 2]
4988  """
4989  self.assert_exprs(*args)
4990 
4991  def insert(self, *args):
4992  """Add constraints.
4993 
4994  >>> x = Int('x')
4995  >>> g = Goal()
4996  >>> g.insert(x > 0, x < 2)
4997  >>> g
4998  [x > 0, x < 2]
4999  """
5000  self.assert_exprs(*args)
5001 
5002  def add(self, *args):
5003  """Add constraints.
5004 
5005  >>> x = Int('x')
5006  >>> g = Goal()
5007  >>> g.add(x > 0, x < 2)
5008  >>> g
5009  [x > 0, x < 2]
5010  """
5011  self.assert_exprs(*args)
5012 
5013  def __repr__(self):
5014  return obj_to_string(self)
5015 
5016  def sexpr(self):
5017  """Return a textual representation of the s-expression representing the goal."""
5018  return Z3_goal_to_string(self.ctx.ref(), self.goal)
5019 
5020  def translate(self, target):
5021  """Copy goal `self` to context `target`.
5022 
5023  >>> x = Int('x')
5024  >>> g = Goal()
5025  >>> g.add(x > 10)
5026  >>> g
5027  [x > 10]
5028  >>> c2 = Context()
5029  >>> g2 = g.translate(c2)
5030  >>> g2
5031  [x > 10]
5032  >>> g.ctx == main_ctx()
5033  True
5034  >>> g2.ctx == c2
5035  True
5036  >>> g2.ctx == main_ctx()
5037  False
5038  """
5039  if __debug__:
5040  _z3_assert(isinstance(target, Context), "target must be a context")
5041  return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5042 
5043  def simplify(self, *arguments, **keywords):
5044  """Return a new simplified goal.
5045 
5046  This method is essentially invoking the simplify tactic.
5047 
5048  >>> g = Goal()
5049  >>> x = Int('x')
5050  >>> g.add(x + 1 >= 2)
5051  >>> g
5052  [x + 1 >= 2]
5053  >>> g2 = g.simplify()
5054  >>> g2
5055  [x >= 1]
5056  >>> # g was not modified
5057  >>> g
5058  [x + 1 >= 2]
5059  """
5060  t = Tactic('simplify')
5061  return t.apply(self, *arguments, **keywords)[0]
5062 
5063  def as_expr(self):
5064  """Return goal `self` as a single Z3 expression.
5065 
5066  >>> x = Int('x')
5067  >>> g = Goal()
5068  >>> g.as_expr()
5069  True
5070  >>> g.add(x > 1)
5071  >>> g.as_expr()
5072  x > 1
5073  >>> g.add(x < 10)
5074  >>> g.as_expr()
5075  And(x > 1, x < 10)
5076  """
5077  sz = len(self)
5078  if sz == 0:
5079  return BoolVal(True, self.ctx)
5080  elif sz == 1:
5081  return self.get(0)
5082  else:
5083  return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5084 
5085 #########################################
5086 #
5087 # AST Vector
5088 #
5089 #########################################
5090 class AstVector(Z3PPObject):
5091  """A collection (vector) of ASTs."""
5092 
5093  def __init__(self, v=None, ctx=None):
5094  self.vector = None
5095  if v is None:
5096  self.ctx = _get_ctx(ctx)
5097  self.vector = Z3_mk_ast_vector(self.ctx.ref())
5098  else:
5099  self.vector = v
5100  assert ctx is not None
5101  self.ctx = ctx
5102  Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5103 
5104  def __deepcopy__(self, memo={}):
5105  return AstVector(self.vector, self.ctx)
5106 
5107  def __del__(self):
5108  if self.vector is not None and self.ctx.ref() is not None:
5109  Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5110 
5111  def __len__(self):
5112  """Return the size of the vector `self`.
5113 
5114  >>> A = AstVector()
5115  >>> len(A)
5116  0
5117  >>> A.push(Int('x'))
5118  >>> A.push(Int('x'))
5119  >>> len(A)
5120  2
5121  """
5122  return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5123 
5124  def __getitem__(self, i):
5125  """Return the AST at position `i`.
5126 
5127  >>> A = AstVector()
5128  >>> A.push(Int('x') + 1)
5129  >>> A.push(Int('y'))
5130  >>> A[0]
5131  x + 1
5132  >>> A[1]
5133  y
5134  """
5135  if i >= self.__len__():
5136  raise IndexError
5137  return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5138 
5139  def __setitem__(self, i, v):
5140  """Update AST at position `i`.
5141 
5142  >>> A = AstVector()
5143  >>> A.push(Int('x') + 1)
5144  >>> A.push(Int('y'))
5145  >>> A[0]
5146  x + 1
5147  >>> A[0] = Int('x')
5148  >>> A[0]
5149  x
5150  """
5151  if i >= self.__len__():
5152  raise IndexError
5153  Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5154 
5155  def push(self, v):
5156  """Add `v` in the end of the vector.
5157 
5158  >>> A = AstVector()
5159  >>> len(A)
5160  0
5161  >>> A.push(Int('x'))
5162  >>> len(A)
5163  1
5164  """
5165  Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5166 
5167  def resize(self, sz):
5168  """Resize the vector to `sz` elements.
5169 
5170  >>> A = AstVector()
5171  >>> A.resize(10)
5172  >>> len(A)
5173  10
5174  >>> for i in range(10): A[i] = Int('x')
5175  >>> A[5]
5176  x
5177  """
5178  Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5179 
5180  def __contains__(self, item):
5181  """Return `True` if the vector contains `item`.
5182 
5183  >>> x = Int('x')
5184  >>> A = AstVector()
5185  >>> x in A
5186  False
5187  >>> A.push(x)
5188  >>> x in A
5189  True
5190  >>> (x+1) in A
5191  False
5192  >>> A.push(x+1)
5193  >>> (x+1) in A
5194  True
5195  >>> A
5196  [x, x + 1]
5197  """
5198  for elem in self:
5199  if elem.eq(item):
5200  return True
5201  return False
5202 
5203  def translate(self, other_ctx):
5204  """Copy vector `self` to context `other_ctx`.
5205 
5206  >>> x = Int('x')
5207  >>> A = AstVector()
5208  >>> A.push(x)
5209  >>> c2 = Context()
5210  >>> B = A.translate(c2)
5211  >>> B
5212  [x]
5213  """
5214  return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5215 
5216  def __repr__(self):
5217  return obj_to_string(self)
5218 
5219  def sexpr(self):
5220  """Return a textual representation of the s-expression representing the vector."""
5221  return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5222 
5223 #########################################
5224 #
5225 # AST Map
5226 #
5227 #########################################
5228 class AstMap:
5229  """A mapping from ASTs to ASTs."""
5230 
5231  def __init__(self, m=None, ctx=None):
5232  self.map = None
5233  if m is None:
5234  self.ctx = _get_ctx(ctx)
5235  self.map = Z3_mk_ast_map(self.ctx.ref())
5236  else:
5237  self.map = m
5238  assert ctx is not None
5239  self.ctx = ctx
5240  Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5241 
5242  def __deepcopy__(self, memo={}):
5243  return AstMap(self.map, self.ctx)
5244 
5245  def __del__(self):
5246  if self.map is not None and self.ctx.ref() is not None:
5247  Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5248 
5249  def __len__(self):
5250  """Return the size of the map.
5251 
5252  >>> M = AstMap()
5253  >>> len(M)
5254  0
5255  >>> x = Int('x')
5256  >>> M[x] = IntVal(1)
5257  >>> len(M)
5258  1
5259  """
5260  return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5261 
5262  def __contains__(self, key):
5263  """Return `True` if the map contains key `key`.
5264 
5265  >>> M = AstMap()
5266  >>> x = Int('x')
5267  >>> M[x] = x + 1
5268  >>> x in M
5269  True
5270  >>> x+1 in M
5271  False
5272  """
5273  return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5274 
5275  def __getitem__(self, key):
5276  """Retrieve the value associated with key `key`.
5277 
5278  >>> M = AstMap()
5279  >>> x = Int('x')
5280  >>> M[x] = x + 1
5281  >>> M[x]
5282  x + 1
5283  """
5284  return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5285 
5286  def __setitem__(self, k, v):
5287  """Add/Update key `k` with value `v`.
5288 
5289  >>> M = AstMap()
5290  >>> x = Int('x')
5291  >>> M[x] = x + 1
5292  >>> len(M)
5293  1
5294  >>> M[x]
5295  x + 1
5296  >>> M[x] = IntVal(1)
5297  >>> M[x]
5298  1
5299  """
5300  Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5301 
5302  def __repr__(self):
5303  return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5304 
5305  def erase(self, k):
5306  """Remove the entry associated with key `k`.
5307 
5308  >>> M = AstMap()
5309  >>> x = Int('x')
5310  >>> M[x] = x + 1
5311  >>> len(M)
5312  1
5313  >>> M.erase(x)
5314  >>> len(M)
5315  0
5316  """
5317  Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5318 
5319  def reset(self):
5320  """Remove all entries from the map.
5321 
5322  >>> M = AstMap()
5323  >>> x = Int('x')
5324  >>> M[x] = x + 1
5325  >>> M[x+x] = IntVal(1)
5326  >>> len(M)
5327  2
5328  >>> M.reset()
5329  >>> len(M)
5330  0
5331  """
5332  Z3_ast_map_reset(self.ctx.ref(), self.map)
5333 
5334  def keys(self):
5335  """Return an AstVector containing all keys in the map.
5336 
5337  >>> M = AstMap()
5338  >>> x = Int('x')
5339  >>> M[x] = x + 1
5340  >>> M[x+x] = IntVal(1)
5341  >>> M.keys()
5342  [x, x + x]
5343  """
5344  return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5345 
5346 #########################################
5347 #
5348 # Model
5349 #
5350 #########################################
5351 
5352 class FuncEntry:
5353  """Store the value of the interpretation of a function in a particular point."""
5354 
5355  def __init__(self, entry, ctx):
5356  self.entry = entry
5357  self.ctx = ctx
5358  Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5359 
5360  def __deepcopy__(self, memo={}):
5361  return FuncEntry(self.entry, self.ctx)
5362 
5363  def __del__(self):
5364  if self.ctx.ref() is not None:
5365  Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5366 
5367  def num_args(self):
5368  """Return the number of arguments in the given entry.
5369 
5370  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5371  >>> s = Solver()
5372  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5373  >>> s.check()
5374  sat
5375  >>> m = s.model()
5376  >>> f_i = m[f]
5377  >>> f_i.num_entries()
5378  3
5379  >>> e = f_i.entry(0)
5380  >>> e.num_args()
5381  2
5382  """
5383  return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5384 
5385  def arg_value(self, idx):
5386  """Return the value of argument `idx`.
5387 
5388  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5389  >>> s = Solver()
5390  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5391  >>> s.check()
5392  sat
5393  >>> m = s.model()
5394  >>> f_i = m[f]
5395  >>> f_i.num_entries()
5396  3
5397  >>> e = f_i.entry(0)
5398  >>> e
5399  [0, 1, 10]
5400  >>> e.num_args()
5401  2
5402  >>> e.arg_value(0)
5403  0
5404  >>> e.arg_value(1)
5405  1
5406  >>> try:
5407  ... e.arg_value(2)
5408  ... except IndexError:
5409  ... print("index error")
5410  index error
5411  """
5412  if idx >= self.num_args():
5413  raise IndexError
5414  return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5415 
5416  def value(self):
5417  """Return the value of the function at point `self`.
5418 
5419  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5420  >>> s = Solver()
5421  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5422  >>> s.check()
5423  sat
5424  >>> m = s.model()
5425  >>> f_i = m[f]
5426  >>> f_i.num_entries()
5427  3
5428  >>> e = f_i.entry(0)
5429  >>> e
5430  [0, 1, 10]
5431  >>> e.num_args()
5432  2
5433  >>> e.value()
5434  10
5435  """
5436  return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5437 
5438  def as_list(self):
5439  """Return entry `self` as a Python list.
5440  >>> f = Function('f', IntSort(), IntSort(), IntSort())
5441  >>> s = Solver()
5442  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5443  >>> s.check()
5444  sat
5445  >>> m = s.model()
5446  >>> f_i = m[f]
5447  >>> f_i.num_entries()
5448  3
5449  >>> e = f_i.entry(0)
5450  >>> e.as_list()
5451  [0, 1, 10]
5452  """
5453  args = [ self.arg_value(i) for i in range(self.num_args())]
5454  args.append(self.value())
5455  return args
5456 
5457  def __repr__(self):
5458  return repr(self.as_list())
5459 
5460 class FuncInterp(Z3PPObject):
5461  """Stores the interpretation of a function in a Z3 model."""
5462 
5463  def __init__(self, f, ctx):
5464  self.f = f
5465  self.ctx = ctx
5466  if self.f is not None:
5467  Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5468 
5469  def __deepcopy__(self, memo={}):
5470  return FuncInterp(self.f, self.ctx)
5471 
5472  def __del__(self):
5473  if self.f is not None and self.ctx.ref() is not None:
5474  Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5475 
5476  def else_value(self):
5477  """
5478  Return the `else` value for a function interpretation.
5479  Return None if Z3 did not specify the `else` value for
5480  this object.
5481 
5482  >>> f = Function('f', IntSort(), IntSort())
5483  >>> s = Solver()
5484  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5485  >>> s.check()
5486  sat
5487  >>> m = s.model()
5488  >>> m[f]
5489  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5490  >>> m[f].else_value()
5491  1
5492  """
5493  r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5494  if r:
5495  return _to_expr_ref(r, self.ctx)
5496  else:
5497  return None
5498 
5499  def num_entries(self):
5500  """Return the number of entries/points in the function interpretation `self`.
5501 
5502  >>> f = Function('f', IntSort(), IntSort())
5503  >>> s = Solver()
5504  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5505  >>> s.check()
5506  sat
5507  >>> m = s.model()
5508  >>> m[f]
5509  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5510  >>> m[f].num_entries()
5511  3
5512  """
5513  return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5514 
5515  def arity(self):
5516  """Return the number of arguments for each entry in the function interpretation `self`.
5517 
5518  >>> f = Function('f', IntSort(), IntSort())
5519  >>> s = Solver()
5520  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5521  >>> s.check()
5522  sat
5523  >>> m = s.model()
5524  >>> m[f].arity()
5525  1
5526  """
5527  return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5528 
5529  def entry(self, idx):
5530  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5531 
5532  >>> f = Function('f', IntSort(), IntSort())
5533  >>> s = Solver()
5534  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5535  >>> s.check()
5536  sat
5537  >>> m = s.model()
5538  >>> m[f]
5539  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5540  >>> m[f].num_entries()
5541  3
5542  >>> m[f].entry(0)
5543  [0, 1]
5544  >>> m[f].entry(1)
5545  [1, 1]
5546  >>> m[f].entry(2)
5547  [2, 0]
5548  """
5549  if idx >= self.num_entries():
5550  raise IndexError
5551  return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5552 
5553  def as_list(self):
5554  """Return the function interpretation as a Python list.
5555  >>> f = Function('f', IntSort(), IntSort())
5556  >>> s = Solver()
5557  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5558  >>> s.check()
5559  sat
5560  >>> m = s.model()
5561  >>> m[f]
5562  [0 -> 1, 1 -> 1, 2 -> 0, else -> 1]
5563  >>> m[f].as_list()
5564  [[0, 1], [1, 1], [2, 0], 1]
5565  """
5566  r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5567  r.append(self.else_value())
5568  return r
5569 
5570  def __repr__(self):
5571  return obj_to_string(self)
5572 
5573 class ModelRef(Z3PPObject):
5574  """Model/Solution of a satisfiability problem (aka system of constraints)."""
5575 
5576  def __init__(self, m, ctx):
5577  assert ctx is not None
5578  self.model = m
5579  self.ctx = ctx
5580  Z3_model_inc_ref(self.ctx.ref(), self.model)
5581 
5582  def __deepcopy__(self, memo={}):
5583  return ModelRef(self.m, self.ctx)
5584 
5585  def __del__(self):
5586  if self.ctx.ref() is not None:
5587  Z3_model_dec_ref(self.ctx.ref(), self.model)
5588 
5589  def __repr__(self):
5590  return obj_to_string(self)
5591 
5592  def sexpr(self):
5593  """Return a textual representation of the s-expression representing the model."""
5594  return Z3_model_to_string(self.ctx.ref(), self.model)
5595 
5596  def eval(self, t, model_completion=False):
5597  """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`.
5598 
5599  >>> x = Int('x')
5600  >>> s = Solver()
5601  >>> s.add(x > 0, x < 2)
5602  >>> s.check()
5603  sat
5604  >>> m = s.model()
5605  >>> m.eval(x + 1)
5606  2
5607  >>> m.eval(x == 1)
5608  True
5609  >>> y = Int('y')
5610  >>> m.eval(y + x)
5611  1 + y
5612  >>> m.eval(y)
5613  y
5614  >>> m.eval(y, model_completion=True)
5615  0
5616  >>> # Now, m contains an interpretation for y
5617  >>> m.eval(y + x)
5618  1
5619  """
5620  r = (Ast * 1)()
5621  if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
5622  return _to_expr_ref(r[0], self.ctx)
5623  raise Z3Exception("failed to evaluate expression in the model")
5624 
5625  def evaluate(self, t, model_completion=False):
5626  """Alias for `eval`.
5627 
5628  >>> x = Int('x')
5629  >>> s = Solver()
5630  >>> s.add(x > 0, x < 2)
5631  >>> s.check()
5632  sat
5633  >>> m = s.model()
5634  >>> m.evaluate(x + 1)
5635  2
5636  >>> m.evaluate(x == 1)
5637  True
5638  >>> y = Int('y')
5639  >>> m.evaluate(y + x)
5640  1 + y
5641  >>> m.evaluate(y)
5642  y
5643  >>> m.evaluate(y, model_completion=True)
5644  0
5645  >>> # Now, m contains an interpretation for y
5646  >>> m.evaluate(y + x)
5647  1
5648  """
5649  return self.eval(t, model_completion)
5650 
5651  def __len__(self):
5652  """Return the number of constant and function declarations in the model `self`.
5653 
5654  >>> f = Function('f', IntSort(), IntSort())
5655  >>> x = Int('x')
5656  >>> s = Solver()
5657  >>> s.add(x > 0, f(x) != x)
5658  >>> s.check()
5659  sat
5660  >>> m = s.model()
5661  >>> len(m)
5662  2
5663  """
5664  return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
5665 
5666  def get_interp(self, decl):
5667  """Return the interpretation for a given declaration or constant.
5668 
5669  >>> f = Function('f', IntSort(), IntSort())
5670  >>> x = Int('x')
5671  >>> s = Solver()
5672  >>> s.add(x > 0, x < 2, f(x) == 0)
5673  >>> s.check()
5674  sat
5675  >>> m = s.model()
5676  >>> m[x]
5677  1
5678  >>> m[f]
5679  [1 -> 0, else -> 0]
5680  """
5681  if __debug__:
5682  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
5683  if is_const(decl):
5684  decl = decl.decl()
5685  try:
5686  if decl.arity() == 0:
5687  _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
5688  if _r.value is None:
5689  return None
5690  r = _to_expr_ref(_r, self.ctx)
5691  if is_as_array(r):
5692  return self.get_interp(get_as_array_func(r))
5693  else:
5694  return r
5695  else:
5696  return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
5697  except Z3Exception:
5698  return None
5699 
5700  def num_sorts(self):
5701  """Return the number of unintepreted sorts that contain an interpretation in the model `self`.
5702 
5703  >>> A = DeclareSort('A')
5704  >>> a, b = Consts('a b', A)
5705  >>> s = Solver()
5706  >>> s.add(a != b)
5707  >>> s.check()
5708  sat
5709  >>> m = s.model()
5710  >>> m.num_sorts()
5711  1
5712  """
5713  return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
5714 
5715  def get_sort(self, idx):
5716  """Return the unintepreted sort at position `idx` < self.num_sorts().
5717 
5718  >>> A = DeclareSort('A')
5719  >>> B = DeclareSort('B')
5720  >>> a1, a2 = Consts('a1 a2', A)
5721  >>> b1, b2 = Consts('b1 b2', B)
5722  >>> s = Solver()
5723  >>> s.add(a1 != a2, b1 != b2)
5724  >>> s.check()
5725  sat
5726  >>> m = s.model()
5727  >>> m.num_sorts()
5728  2
5729  >>> m.get_sort(0)
5730  A
5731  >>> m.get_sort(1)
5732  B
5733  """
5734  if idx >= self.num_sorts():
5735  raise IndexError
5736  return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
5737 
5738  def sorts(self):
5739  """Return all uninterpreted sorts that have an interpretation in the model `self`.
5740 
5741  >>> A = DeclareSort('A')
5742  >>> B = DeclareSort('B')
5743  >>> a1, a2 = Consts('a1 a2', A)
5744  >>> b1, b2 = Consts('b1 b2', B)
5745  >>> s = Solver()
5746  >>> s.add(a1 != a2, b1 != b2)
5747  >>> s.check()
5748  sat
5749  >>> m = s.model()
5750  >>> m.sorts()
5751  [A, B]
5752  """
5753  return [ self.get_sort(i) for i in range(self.num_sorts()) ]
5754 
5755  def get_universe(self, s):
5756  """Return the intepretation for the uninterpreted sort `s` in the model `self`.
5757 
5758  >>> A = DeclareSort('A')
5759  >>> a, b = Consts('a b', A)
5760  >>> s = Solver()
5761  >>> s.add(a != b)
5762  >>> s.check()
5763  sat
5764  >>> m = s.model()
5765  >>> m.get_universe(A)
5766  [A!val!0, A!val!1]
5767  """
5768  if __debug__:
5769  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
5770  try:
5771  return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
5772  except Z3Exception:
5773  return None
5774 
5775  def __getitem__(self, idx):
5776  """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.
5777 
5778  The elements can be retrieved using position or the actual declaration.
5779 
5780  >>> f = Function('f', IntSort(), IntSort())
5781  >>> x = Int('x')
5782  >>> s = Solver()
5783  >>> s.add(x > 0, x < 2, f(x) == 0)
5784  >>> s.check()
5785  sat
5786  >>> m = s.model()
5787  >>> len(m)
5788  2
5789  >>> m[0]
5790  x
5791  >>> m[1]
5792  f
5793  >>> m[x]
5794  1
5795  >>> m[f]
5796  [1 -> 0, else -> 0]
5797  >>> for d in m: print("%s -> %s" % (d, m[d]))
5798  x -> 1
5799  f -> [1 -> 0, else -> 0]
5800  """
5801  if _is_int(idx):
5802  if idx >= len(self):
5803  raise IndexError
5804  num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
5805  if (idx < num_consts):
5806  return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
5807  else:
5808  return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
5809  if isinstance(idx, FuncDeclRef):
5810  return self.get_interp(idx)
5811  if is_const(idx):
5812  return self.get_interp(idx.decl())
5813  if isinstance(idx, SortRef):
5814  return self.get_universe(idx)
5815  if __debug__:
5816  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
5817  return None
5818 
5819  def decls(self):
5820  """Return a list with all symbols that have an interpreation in the model `self`.
5821  >>> f = Function('f', IntSort(), IntSort())
5822  >>> x = Int('x')
5823  >>> s = Solver()
5824  >>> s.add(x > 0, x < 2, f(x) == 0)
5825  >>> s.check()
5826  sat
5827  >>> m = s.model()
5828  >>> m.decls()
5829  [x, f]
5830  """
5831  r = []
5832  for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
5833  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
5834  for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
5835  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
5836  return r
5837 
5838 def is_as_array(n):
5839  """Return true if n is a Z3 expression of the form (_ as-array f)."""
5840  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
5841 
5842 def get_as_array_func(n):
5843  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
5844  if __debug__:
5845  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
5846  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
5847 
5848 #########################################
5849 #
5850 # Statistics
5851 #
5852 #########################################
5853 class Statistics:
5854  """Statistics for `Solver.check()`."""
5855 
5856  def __init__(self, stats, ctx):
5857  self.stats = stats
5858  self.ctx = ctx
5859  Z3_stats_inc_ref(self.ctx.ref(), self.stats)
5860 
5861  def __deepcopy__(self, memo={}):
5862  return Statistics(self.stats, self.ctx)
5863 
5864  def __del__(self):
5865  if self.ctx.ref() is not None:
5866  Z3_stats_dec_ref(self.ctx.ref(), self.stats)
5867 
5868  def __repr__(self):
5869  if in_html_mode():
5870  out = io.StringIO()
5871  even = True
5872  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
5873  for k, v in self:
5874  if even:
5875  out.write(u('<tr style="background-color:#CFCFCF">'))
5876  even = False
5877  else:
5878  out.write(u('<tr>'))
5879  even = True
5880  out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
5881  out.write(u('</table>'))
5882  return out.getvalue()
5883  else:
5884  return Z3_stats_to_string(self.ctx.ref(), self.stats)
5885 
5886  def __len__(self):
5887  """Return the number of statistical counters.
5888 
5889  >>> x = Int('x')
5890  >>> s = Then('simplify', 'nlsat').solver()
5891  >>> s.add(x > 0)
5892  >>> s.check()
5893  sat
5894  >>> st = s.statistics()
5895  >>> len(st)
5896  6
5897  """
5898  return int(Z3_stats_size(self.ctx.ref(), self.stats))
5899 
5900  def __getitem__(self, idx):
5901  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
5902 
5903  >>> x = Int('x')
5904  >>> s = Then('simplify', 'nlsat').solver()
5905  >>> s.add(x > 0)
5906  >>> s.check()
5907  sat
5908  >>> st = s.statistics()
5909  >>> len(st)
5910  6
5911  >>> st[0]
5912  ('nlsat propagations', 2)
5913  >>> st[1]
5914  ('nlsat stages', 2)
5915  """
5916  if idx >= len(self):
5917  raise IndexError
5918  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5919  val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5920  else:
5921  val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5922  return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
5923 
5924  def keys(self):
5925  """Return the list of statistical counters.
5926 
5927  >>> x = Int('x')
5928  >>> s = Then('simplify', 'nlsat').solver()
5929  >>> s.add(x > 0)
5930  >>> s.check()
5931  sat
5932  >>> st = s.statistics()
5933  """
5934  return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
5935 
5936  def get_key_value(self, key):
5937  """Return the value of a particular statistical counter.
5938 
5939  >>> x = Int('x')
5940  >>> s = Then('simplify', 'nlsat').solver()
5941  >>> s.add(x > 0)
5942  >>> s.check()
5943  sat
5944  >>> st = s.statistics()
5945  >>> st.get_key_value('nlsat propagations')
5946  2
5947  """
5948  for idx in range(len(self)):
5949  if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
5950  if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
5951  return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
5952  else:
5953  return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
5954  raise Z3Exception("unknown key")
5955 
5956  def __getattr__(self, name):
5957  """Access the value of statistical using attributes.
5958 
5959  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
5960  we should use '_' (e.g., 'nlsat_propagations').
5961 
5962  >>> x = Int('x')
5963  >>> s = Then('simplify', 'nlsat').solver()
5964  >>> s.add(x > 0)
5965  >>> s.check()
5966  sat
5967  >>> st = s.statistics()
5968  >>> st.nlsat_propagations
5969  2
5970  >>> st.nlsat_stages
5971  2
5972  """
5973  key = name.replace('_', ' ')
5974  try:
5975  return self.get_key_value(key)
5976  except Z3Exception:
5977  raise AttributeError
5978 
5979 #########################################
5980 #
5981 # Solver
5982 #
5983 #########################################
5984 class CheckSatResult:
5985  """Represents the result of a satisfiability check: sat, unsat, unknown.
5986 
5987  >>> s = Solver()
5988  >>> s.check()
5989  sat
5990  >>> r = s.check()
5991  >>> isinstance(r, CheckSatResult)
5992  True
5993  """
5994 
5995  def __init__(self, r):
5996  self.r = r
5997 
5998  def __deepcopy__(self, memo={}):
5999  return CheckSatResult(self.r)
6000 
6001  def __eq__(self, other):
6002  return isinstance(other, CheckSatResult) and self.r == other.r
6003 
6004  def __ne__(self, other):
6005  return not self.__eq__(other)
6006 
6007  def __repr__(self):
6008  if in_html_mode():
6009  if self.r == Z3_L_TRUE:
6010  return "<b>sat</b>"
6011  elif self.r == Z3_L_FALSE:
6012  return "<b>unsat</b>"
6013  else:
6014  return "<b>unknown</b>"
6015  else:
6016  if self.r == Z3_L_TRUE:
6017  return "sat"
6018  elif self.r == Z3_L_FALSE:
6019  return "unsat"
6020  else:
6021  return "unknown"
6022 
6023 sat = CheckSatResult(Z3_L_TRUE)
6024 unsat = CheckSatResult(Z3_L_FALSE)
6025 unknown = CheckSatResult(Z3_L_UNDEF)
6026 
6027 class Solver(Z3PPObject):
6028  """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6029 
6030  def __init__(self, solver=None, ctx=None):
6031  assert solver is None or ctx is not None
6032  self.ctx = _get_ctx(ctx)
6033  self.solver = None
6034  if solver is None:
6035  self.solver = Z3_mk_solver(self.ctx.ref())
6036  else:
6037  self.solver = solver
6038  Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6039 
6040  def __deepcopy__(self, memo={}):
6041  return Solver(self.solver, self.ctx)
6042 
6043  def __del__(self):
6044  if self.solver is not None and self.ctx.ref() is not None:
6045  Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6046 
6047  def set(self, *args, **keys):
6048  """Set a configuration option. The method `help()` return a string containing all available options.
6049 
6050  >>> s = Solver()
6051  >>> # The option MBQI can be set using three different approaches.
6052  >>> s.set(mbqi=True)
6053  >>> s.set('MBQI', True)
6054  >>> s.set(':mbqi', True)
6055  """
6056  p = args2params(args, keys, self.ctx)
6057  Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6058 
6059  def push(self):
6060  """Create a backtracking point.
6061 
6062  >>> x = Int('x')
6063  >>> s = Solver()
6064  >>> s.add(x > 0)
6065  >>> s
6066  [x > 0]
6067  >>> s.push()
6068  >>> s.add(x < 1)
6069  >>> s
6070  [x > 0, x < 1]
6071  >>> s.check()
6072  unsat
6073  >>> s.pop()
6074  >>> s.check()
6075  sat
6076  >>> s
6077  [x > 0]
6078  """
6079  Z3_solver_push(self.ctx.ref(), self.solver)
6080 
6081  def pop(self, num=1):
6082  """Backtrack \c num backtracking points.
6083 
6084  >>> x = Int('x')
6085  >>> s = Solver()
6086  >>> s.add(x > 0)
6087  >>> s
6088  [x > 0]
6089  >>> s.push()
6090  >>> s.add(x < 1)
6091  >>> s
6092  [x > 0, x < 1]
6093  >>> s.check()
6094  unsat
6095  >>> s.pop()
6096  >>> s.check()
6097  sat
6098  >>> s
6099  [x > 0]
6100  """
6101  Z3_solver_pop(self.ctx.ref(), self.solver, num)
6102 
6103  def num_scopes(self):
6104  """Return the current number of backtracking points.
6105 
6106  >>> s = Solver()
6107  >>> s.num_scopes()
6108  0L
6109  >>> s.push()
6110  >>> s.num_scopes()
6111  1L
6112  >>> s.push()
6113  >>> s.num_scopes()
6114  2L
6115  >>> s.pop()
6116  >>> s.num_scopes()
6117  1L
6118  """
6119  return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6120 
6121  def reset(self):
6122  """Remove all asserted constraints and backtracking points created using `push()`.
6123 
6124  >>> x = Int('x')
6125  >>> s = Solver()
6126  >>> s.add(x > 0)
6127  >>> s
6128  [x > 0]
6129  >>> s.reset()
6130  >>> s
6131  []
6132  """
6133  Z3_solver_reset(self.ctx.ref(), self.solver)
6134 
6135  def assert_exprs(self, *args):
6136  """Assert constraints into the solver.
6137 
6138  >>> x = Int('x')
6139  >>> s = Solver()
6140  >>> s.assert_exprs(x > 0, x < 2)
6141  >>> s
6142  [x > 0, x < 2]
6143  """
6144  args = _get_args(args)
6145  s = BoolSort(self.ctx)
6146  for arg in args:
6147  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6148  for f in arg:
6149  Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6150  else:
6151  arg = s.cast(arg)
6152  Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6153 
6154  def add(self, *args):
6155  """Assert constraints into the solver.
6156 
6157  >>> x = Int('x')
6158  >>> s = Solver()
6159  >>> s.add(x > 0, x < 2)
6160  >>> s
6161  [x > 0, x < 2]
6162  """
6163  self.assert_exprs(*args)
6164 
6165  def __iadd__(self, fml):
6166  self.add(fml)
6167  return self
6168 
6169  def append(self, *args):
6170  """Assert constraints into the solver.
6171 
6172  >>> x = Int('x')
6173  >>> s = Solver()
6174  >>> s.append(x > 0, x < 2)
6175  >>> s
6176  [x > 0, x < 2]
6177  """
6178  self.assert_exprs(*args)
6179 
6180  def insert(self, *args):
6181  """Assert constraints into the solver.
6182 
6183  >>> x = Int('x')
6184  >>> s = Solver()
6185  >>> s.insert(x > 0, x < 2)
6186  >>> s
6187  [x > 0, x < 2]
6188  """
6189  self.assert_exprs(*args)
6190 
6191  def assert_and_track(self, a, p):
6192  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6193 
6194  If `p` is a string, it will be automatically converted into a Boolean constant.
6195 
6196  >>> x = Int('x')
6197  >>> p3 = Bool('p3')
6198  >>> s = Solver()
6199  >>> s.set(unsat_core=True)
6200  >>> s.assert_and_track(x > 0, 'p1')
6201  >>> s.assert_and_track(x != 1, 'p2')
6202  >>> s.assert_and_track(x < 0, p3)
6203  >>> print(s.check())
6204  unsat
6205  >>> c = s.unsat_core()
6206  >>> len(c)
6207  2
6208  >>> Bool('p1') in c
6209  True
6210  >>> Bool('p2') in c
6211  False
6212  >>> p3 in c
6213  True
6214  """
6215  if isinstance(p, str):
6216  p = Bool(p, self.ctx)
6217  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6218  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6219  Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6220 
6221  def check(self, *assumptions):
6222  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6223 
6224  >>> x = Int('x')
6225  >>> s = Solver()
6226  >>> s.check()
6227  sat
6228  >>> s.add(x > 0, x < 2)
6229  >>> s.check()
6230  sat
6231  >>> s.model()
6232  [x = 1]
6233  >>> s.add(x < 1)
6234  >>> s.check()
6235  unsat
6236  >>> s.reset()
6237  >>> s.add(2**x == 4)
6238  >>> s.check()
6239  unknown
6240  """
6241  assumptions = _get_args(assumptions)
6242  num = len(assumptions)
6243  _assumptions = (Ast * num)()
6244  for i in range(num):
6245  _assumptions[i] = assumptions[i].as_ast()
6246  r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6247  return CheckSatResult(r)
6248 
6249  def model(self):
6250  """Return a model for the last `check()`.
6251 
6252  This function raises an exception if
6253  a model is not available (e.g., last `check()` returned unsat).
6254 
6255  >>> s = Solver()
6256  >>> a = Int('a')
6257  >>> s.add(a + 2 == 0)
6258  >>> s.check()
6259  sat
6260  >>> s.model()
6261  [a = -2]
6262  """
6263  try:
6264  return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6265  except Z3Exception:
6266  raise Z3Exception("model is not available")
6267 
6268  def unsat_core(self):
6269  """Return a subset (as an AST vector) of the assumptions provided to the last check().
6270 
6271  These are the assumptions Z3 used in the unsatisfiability proof.
6272  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6273  They may be also used to "retract" assumptions. Note that, assumptions are not really
6274  "soft constraints", but they can be used to implement them.
6275 
6276  >>> p1, p2, p3 = Bools('p1 p2 p3')
6277  >>> x, y = Ints('x y')
6278  >>> s = Solver()
6279  >>> s.add(Implies(p1, x > 0))
6280  >>> s.add(Implies(p2, y > x))
6281  >>> s.add(Implies(p2, y < 1))
6282  >>> s.add(Implies(p3, y > -3))
6283  >>> s.check(p1, p2, p3)
6284  unsat
6285  >>> core = s.unsat_core()
6286  >>> len(core)
6287  2
6288  >>> p1 in core
6289  True
6290  >>> p2 in core
6291  True
6292  >>> p3 in core
6293  False
6294  >>> # "Retracting" p2
6295  >>> s.check(p1, p3)
6296  sat
6297  """
6298  return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6299 
6300  def consequences(self, assumptions, variables):
6301  """Determine fixed values for the variables based on the solver state and assumptions.
6302  >>> s = Solver()
6303  >>> a, b, c, d = Bools('a b c d')
6304  >>> s.add(Implies(a,b), Implies(b, c))
6305  >>> s.consequences([a],[b,c,d])
6306  (sat, [Implies(a, b), Implies(a, c)])
6307  >>> s.consequences([Not(c),d],[a,b,c,d])
6308  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6309  """
6310  if isinstance(assumptions, list):
6311  _asms = AstVector(None, self.ctx)
6312  for a in assumptions:
6313  _asms.push(a)
6314  assumptions = _asms
6315  if isinstance(variables, list):
6316  _vars = AstVector(None, self.ctx)
6317  for a in variables:
6318  _vars.push(a)
6319  variables = _vars
6320  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6321  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6322  consequences = AstVector(None, self.ctx)
6323  r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6324  sz = len(consequences)
6325  consequences = [ consequences[i] for i in range(sz) ]
6326  return CheckSatResult(r), consequences
6327 
6328  def from_file(self, filename):
6329  """Parse assertions from a file"""
6330  try:
6331  Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6332  except Z3Exception as e:
6333  _handle_parse_error(e, self.ctx)
6334 
6335  def from_string(self, s):
6336  """Parse assertions from a string"""
6337  try:
6338  Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6339  except Z3Exception as e:
6340  _handle_parse_error(e, self.ctx)
6341 
6342  def proof(self):
6343  """Return a proof for the last `check()`. Proof construction must be enabled."""
6344  return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6345 
6346  def assertions(self):
6347  """Return an AST vector containing all added constraints.
6348 
6349  >>> s = Solver()
6350  >>> s.assertions()
6351  []
6352  >>> a = Int('a')
6353  >>> s.add(a > 0)
6354  >>> s.add(a < 10)
6355  >>> s.assertions()
6356  [a > 0, a < 10]
6357  """
6358  return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6359 
6360  def statistics(self):
6361  """Return statistics for the last `check()`.
6362 
6363  >>> s = SimpleSolver()
6364  >>> x = Int('x')
6365  >>> s.add(x > 0)
6366  >>> s.check()
6367  sat
6368  >>> st = s.statistics()
6369  >>> st.get_key_value('final checks')
6370  1
6371  >>> len(st) > 0
6372  True
6373  >>> st[0] != 0
6374  True
6375  """
6376  return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6377 
6378  def reason_unknown(self):
6379  """Return a string describing why the last `check()` returned `unknown`.
6380 
6381  >>> x = Int('x')
6382  >>> s = SimpleSolver()
6383  >>> s.add(2**x == 4)
6384  >>> s.check()
6385  unknown
6386  >>> s.reason_unknown()
6387  '(incomplete (theory arithmetic))'
6388  """
6389  return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6390 
6391  def help(self):
6392  """Display a string describing all available options."""
6393  print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6394 
6395  def param_descrs(self):
6396  """Return the parameter description set."""
6397  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6398 
6399  def __repr__(self):
6400  """Return a formatted string with all added constraints."""
6401  return obj_to_string(self)
6402 
6403  def translate(self, target):
6404  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6405 
6406  >>> c1 = Context()
6407  >>> c2 = Context()
6408  >>> s1 = Solver(ctx=c1)
6409  >>> s2 = s1.translate(c2)
6410  """
6411  if __debug__:
6412  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6413  solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6414  return Solver(solver, target)
6415 
6416  def sexpr(self):
6417  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6418 
6419  >>> x = Int('x')
6420  >>> s = Solver()
6421  >>> s.add(x > 0)
6422  >>> s.add(x < 2)
6423  >>> r = s.sexpr()
6424  """
6425  return Z3_solver_to_string(self.ctx.ref(), self.solver)
6426 
6427  def to_smt2(self):
6428  """return SMTLIB2 formatted benchmark for solver's assertions"""
6429  es = self.assertions()
6430  sz = len(es)
6431  sz1 = sz
6432  if sz1 > 0:
6433  sz1 -= 1
6434  v = (Ast * sz1)()
6435  for i in range(sz1):
6436  v[i] = es[i].as_ast()
6437  if sz > 0:
6438  e = es[sz1].as_ast()
6439  else:
6440  e = BoolVal(True, self.ctx).as_ast()
6441  return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6442 
6443 def SolverFor(logic, ctx=None):
6444  """Create a solver customized for the given logic.
6445 
6446  The parameter `logic` is a string. It should be contains
6447  the name of a SMT-LIB logic.
6448  See http://www.smtlib.org/ for the name of all available logics.
6449 
6450  >>> s = SolverFor("QF_LIA")
6451  >>> x = Int('x')
6452  >>> s.add(x > 0)
6453  >>> s.add(x < 2)
6454  >>> s.check()
6455  sat
6456  >>> s.model()
6457  [x = 1]
6458  """
6459  ctx = _get_ctx(ctx)
6460  logic = to_symbol(logic)
6461  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
6462 
6463 def SimpleSolver(ctx=None):
6464  """Return a simple general purpose solver with limited amount of preprocessing.
6465 
6466  >>> s = SimpleSolver()
6467  >>> x = Int('x')
6468  >>> s.add(x > 0)
6469  >>> s.check()
6470  sat
6471  """
6472  ctx = _get_ctx(ctx)
6473  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
6474 
6475 
6480 
6482  """Fixedpoint API provides methods for solving with recursive predicates"""
6483 
6484  def __init__(self, fixedpoint=None, ctx=None):
6485  assert fixedpoint is None or ctx is not None
6486  self.ctx = _get_ctx(ctx)
6487  self.fixedpoint = None
6488  if fixedpoint is None:
6489  self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6490  else:
6491  self.fixedpoint = fixedpoint
6492  Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6493  self.vars = []
6494 
6495  def __deepcopy__(self, memo={}):
6496  return FixedPoint(self.fixedpoint, self.ctx)
6497 
6498  def __del__(self):
6499  if self.fixedpoint is not None and self.ctx.ref() is not None:
6500  Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6501 
6502  def set(self, *args, **keys):
6503  """Set a configuration option. The method `help()` return a string containing all available options.
6504  """
6505  p = args2params(args, keys, self.ctx)
6506  Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6507 
6508  def help(self):
6509  """Display a string describing all available options."""
6510  print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6511 
6512  def param_descrs(self):
6513  """Return the parameter description set."""
6514  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6515 
6516  def assert_exprs(self, *args):
6517  """Assert constraints as background axioms for the fixedpoint solver."""
6518  args = _get_args(args)
6519  s = BoolSort(self.ctx)
6520  for arg in args:
6521  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6522  for f in arg:
6523  f = self.abstract(f)
6524  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6525  else:
6526  arg = s.cast(arg)
6527  arg = self.abstract(arg)
6528  Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6529 
6530  def add(self, *args):
6531  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6532  self.assert_exprs(*args)
6533 
6534  def __iadd__(self, fml):
6535  self.add(fml)
6536  return self
6537 
6538  def append(self, *args):
6539  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6540  self.assert_exprs(*args)
6541 
6542  def insert(self, *args):
6543  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
6544  self.assert_exprs(*args)
6545 
6546  def add_rule(self, head, body = None, name = None):
6547  """Assert rules defining recursive predicates to the fixedpoint solver.
6548  >>> a = Bool('a')
6549  >>> b = Bool('b')
6550  >>> s = Fixedpoint()
6551  >>> s.register_relation(a.decl())
6552  >>> s.register_relation(b.decl())
6553  >>> s.fact(a)
6554  >>> s.rule(b, a)
6555  >>> s.query(b)
6556  sat
6557  """
6558  if name is None:
6559  name = ""
6560  name = to_symbol(name, self.ctx)
6561  if body is None:
6562  head = self.abstract(head)
6563  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
6564  else:
6565  body = _get_args(body)
6566  f = self.abstract(Implies(And(body, self.ctx),head))
6567  Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6568 
6569  def rule(self, head, body = None, name = None):
6570  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6571  self.add_rule(head, body, name)
6572 
6573  def fact(self, head, name = None):
6574  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
6575  self.add_rule(head, None, name)
6576 
6577  def query(self, *query):
6578  """Query the fixedpoint engine whether formula is derivable.
6579  You can also pass an tuple or list of recursive predicates.
6580  """
6581  query = _get_args(query)
6582  sz = len(query)
6583  if sz >= 1 and isinstance(query[0], FuncDeclRef):
6584  _decls = (FuncDecl * sz)()
6585  i = 0
6586  for q in query:
6587  _decls[i] = q.ast
6588  i = i + 1
6589  r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
6590  else:
6591  if sz == 1:
6592  query = query[0]
6593  else:
6594  query = And(query, self.ctx)
6595  query = self.abstract(query, False)
6596  r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
6597  return CheckSatResult(r)
6598 
6599  def query_from_lvl (self, lvl, *query):
6600  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
6601  """
6602  query = _get_args(query)
6603  sz = len(query)
6604  if sz >= 1 and isinstance(query[0], FuncDecl):
6605  _z3_assert (False, "unsupported")
6606  else:
6607  if sz == 1:
6608  query = query[0]
6609  else:
6610  query = And(query)
6611  query = self.abstract(query, False)
6612  r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
6613  return CheckSatResult(r)
6614 
6615  def push(self):
6616  """create a backtracking point for added rules, facts and assertions"""
6617  Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
6618 
6619  def pop(self):
6620  """restore to previously created backtracking point"""
6621  Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
6622 
6623  def update_rule(self, head, body, name):
6624  """update rule"""
6625  if name is None:
6626  name = ""
6627  name = to_symbol(name, self.ctx)
6628  body = _get_args(body)
6629  f = self.abstract(Implies(And(body, self.ctx),head))
6630  Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
6631 
6632  def get_answer(self):
6633  """Retrieve answer from last query call."""
6634  r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
6635  return _to_expr_ref(r, self.ctx)
6636 
6638  """Retrieve a ground cex from last query call."""
6639  r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
6640  return _to_expr_ref(r, self.ctx)
6641 
6643  """retrieve rules along the counterexample trace"""
6644  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
6645 
6647  """retrieve rule names along the counterexample trace"""
6648  # this is a hack as I don't know how to return a list of symbols from C++;
6649  # obtain names as a single string separated by semicolons
6650  names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
6651  # split into individual names
6652  return names.split (';')
6653 
6654  def get_num_levels(self, predicate):
6655  """Retrieve number of levels used for predicate in PDR engine"""
6656  return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
6657 
6658  def get_cover_delta(self, level, predicate):
6659  """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
6660  r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
6661  return _to_expr_ref(r, self.ctx)
6662 
6663  def add_cover(self, level, predicate, property):
6664  """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
6665  Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
6666 
6667  def register_relation(self, *relations):
6668  """Register relation as recursive"""
6669  relations = _get_args(relations)
6670  for f in relations:
6671  Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
6672 
6673  def set_predicate_representation(self, f, *representations):
6674  """Control how relation is represented"""
6675  representations = _get_args(representations)
6676  representations = [to_symbol(s) for s in representations]
6677  sz = len(representations)
6678  args = (Symbol * sz)()
6679  for i in range(sz):
6680  args[i] = representations[i]
6681  Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
6682 
6683  def parse_string(self, s):
6684  """Parse rules and queries from a string"""
6685  try:
6686  return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
6687  except Z3Exception as e:
6688  _handle_parse_error(e, self.ctx)
6689 
6690  def parse_file(self, f):
6691  """Parse rules and queries from a file"""
6692  try:
6693  return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
6694  except Z3Exception as e:
6695  _handle_parse_error(e, self.ctx)
6696 
6697  def get_rules(self):
6698  """retrieve rules that have been added to fixedpoint context"""
6699  return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
6700 
6701  def get_assertions(self):
6702  """retrieve assertions that have been added to fixedpoint context"""
6703  return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
6704 
6705  def __repr__(self):
6706  """Return a formatted string with all added rules and constraints."""
6707  return self.sexpr()
6708 
6709  def sexpr(self):
6710  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6711  """
6712  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
6713 
6714  def to_string(self, queries):
6715  """Return a formatted string (in Lisp-like format) with all added constraints.
6716  We say the string is in s-expression format.
6717  Include also queries.
6718  """
6719  args, len = _to_ast_array(queries)
6720  return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
6721 
6722  def statistics(self):
6723  """Return statistics for the last `query()`.
6724  """
6725  return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
6726 
6727  def reason_unknown(self):
6728  """Return a string describing why the last `query()` returned `unknown`.
6729  """
6730  return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
6731 
6732  def declare_var(self, *vars):
6733  """Add variable or several variables.
6734  The added variable or variables will be bound in the rules
6735  and queries
6736  """
6737  vars = _get_args(vars)
6738  for v in vars:
6739  self.vars += [v]
6740 
6741  def abstract(self, fml, is_forall=True):
6742  if self.vars == []:
6743  return fml
6744  if is_forall:
6745  return ForAll(self.vars, fml)
6746  else:
6747  return Exists(self.vars, fml)
6748 
6749 
6750 
6755 
6757  """Finite domain sort."""
6758 
6759  def size(self):
6760  """Return the size of the finite domain sort"""
6761  r = (ctype.c_ulonglong * 1)()
6762  if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast(), r):
6763  return r[0]
6764  else:
6765  raise Z3Exception("Failed to retrieve finite domain sort size")
6766 
6767 def FiniteDomainSort(name, sz, ctx=None):
6768  """Create a named finite domain sort of a given size sz"""
6769  if not isinstance(name, Symbol):
6770  name = to_symbol(name)
6771  ctx = _get_ctx(ctx)
6772  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
6773 
6775  """Return True if `s` is a Z3 finite-domain sort.
6776 
6777  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
6778  True
6779  >>> is_finite_domain_sort(IntSort())
6780  False
6781  """
6782  return isinstance(s, FiniteDomainSortRef)
6783 
6784 
6786  """Finite-domain expressions."""
6787 
6788  def sort(self):
6789  """Return the sort of the finite-domain expression `self`."""
6790  return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
6791 
6792  def as_string(self):
6793  """Return a Z3 floating point expression as a Python string."""
6794  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
6795 
6797  """Return `True` if `a` is a Z3 finite-domain expression.
6798 
6799  >>> s = FiniteDomainSort('S', 100)
6800  >>> b = Const('b', s)
6801  >>> is_finite_domain(b)
6802  True
6803  >>> is_finite_domain(Int('x'))
6804  False
6805  """
6806  return isinstance(a, FiniteDomainRef)
6807 
6808 
6810  """Integer values."""
6811 
6812  def as_long(self):
6813  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
6814 
6815  >>> s = FiniteDomainSort('S', 100)
6816  >>> v = FiniteDomainVal(3, s)
6817  >>> v
6818  3
6819  >>> v.as_long() + 1
6820  4
6821  """
6822  return int(self.as_string())
6823 
6824  def as_string(self):
6825  """Return a Z3 finite-domain numeral as a Python string.
6826 
6827  >>> s = FiniteDomainSort('S', 100)
6828  >>> v = FiniteDomainVal(42, s)
6829  >>> v.as_string()
6830  '42'
6831  """
6832  return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
6833 
6834 
6835 def FiniteDomainVal(val, sort, ctx=None):
6836  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
6837 
6838  >>> s = FiniteDomainSort('S', 256)
6839  >>> FiniteDomainVal(255, s)
6840  255
6841  >>> FiniteDomainVal('100', s)
6842  100
6843  """
6844  if __debug__:
6845  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
6846  ctx = sort.ctx
6847  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
6848 
6850  """Return `True` if `a` is a Z3 finite-domain value.
6851 
6852  >>> s = FiniteDomainSort('S', 100)
6853  >>> b = Const('b', s)
6854  >>> is_finite_domain_value(b)
6855  False
6856  >>> b = FiniteDomainVal(10, s)
6857  >>> b
6858  10
6859  >>> is_finite_domain_value(b)
6860  True
6861  """
6862  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
6863 
6864 
6865 
6870 
6872  def __init__(self, opt, value, is_max):
6873  self._opt = opt
6874  self._value = value
6875  self._is_max = is_max
6876 
6877  def lower(self):
6878  opt = self._opt
6879  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6880 
6881  def upper(self):
6882  opt = self._opt
6883  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6884 
6885  def lower_values(self):
6886  opt = self._opt
6887  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6888 
6889  def upper_values(self):
6890  opt = self._opt
6891  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
6892 
6893  def value(self):
6894  if self._is_max:
6895  return self.upper()
6896  else:
6897  return self.lower()
6898 
6899  def __str__(self):
6900  return "%s:%s" % (self._value, self._is_max)
6901 
6902 
6904  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
6905 
6906  def __init__(self, ctx=None):
6907  self.ctx = _get_ctx(ctx)
6908  self.optimize = Z3_mk_optimize(self.ctx.ref())
6909  Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
6910 
6911  def __deepcopy__(self, memo={}):
6912  return Optimize(self.optimize, self.ctx)
6913 
6914  def __del__(self):
6915  if self.optimize is not None and self.ctx.ref() is not None:
6916  Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
6917 
6918  def set(self, *args, **keys):
6919  """Set a configuration option. The method `help()` return a string containing all available options.
6920  """
6921  p = args2params(args, keys, self.ctx)
6922  Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
6923 
6924  def help(self):
6925  """Display a string describing all available options."""
6926  print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
6927 
6928  def param_descrs(self):
6929  """Return the parameter description set."""
6930  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
6931 
6932  def assert_exprs(self, *args):
6933  """Assert constraints as background axioms for the optimize solver."""
6934  args = _get_args(args)
6935  for arg in args:
6936  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6937  for f in arg:
6938  Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
6939  else:
6940  Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
6941 
6942  def add(self, *args):
6943  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
6944  self.assert_exprs(*args)
6945 
6946  def __iadd__(self, fml):
6947  self.add(fml)
6948  return self
6949 
6950  def add_soft(self, arg, weight = "1", id = None):
6951  """Add soft constraint with optional weight and optional identifier.
6952  If no weight is supplied, then the penalty for violating the soft constraint
6953  is 1.
6954  Soft constraints are grouped by identifiers. Soft constraints that are
6955  added without identifiers are grouped by default.
6956  """
6957  if _is_int(weight):
6958  weight = "%d" % weight
6959  elif isinstance(weight, float):
6960  weight = "%f" % weight
6961  if not isinstance(weight, str):
6962  raise Z3Exception("weight should be a string or an integer")
6963  if id is None:
6964  id = ""
6965  id = to_symbol(id, self.ctx)
6966  v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
6967  return OptimizeObjective(self, v, False)
6968 
6969  def maximize(self, arg):
6970  """Add objective function to maximize."""
6971  return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
6972 
6973  def minimize(self, arg):
6974  """Add objective function to minimize."""
6975  return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
6976 
6977  def push(self):
6978  """create a backtracking point for added rules, facts and assertions"""
6979  Z3_optimize_push(self.ctx.ref(), self.optimize)
6980 
6981  def pop(self):
6982  """restore to previously created backtracking point"""
6983  Z3_optimize_pop(self.ctx.ref(), self.optimize)
6984 
6985  def check(self):
6986  """Check satisfiability while optimizing objective functions."""
6987  return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize))
6988 
6989  def reason_unknown(self):
6990  """Return a string that describes why the last `check()` returned `unknown`."""
6991  return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
6992 
6993  def model(self):
6994  """Return a model for the last check()."""
6995  try:
6996  return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
6997  except Z3Exception:
6998  raise Z3Exception("model is not available")
6999 
7000  def lower(self, obj):
7001  if not isinstance(obj, OptimizeObjective):
7002  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7003  return obj.lower()
7004 
7005  def upper(self, obj):
7006  if not isinstance(obj, OptimizeObjective):
7007  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7008  return obj.upper()
7009 
7010  def lower_values(self, obj):
7011  if not isinstance(obj, OptimizeObjective):
7012  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7013  return obj.lower_values()
7014 
7015  def upper_values(self, obj):
7016  if not isinstance(obj, OptimizeObjective):
7017  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7018  return obj.upper_values()
7019 
7020  def from_file(self, filename):
7021  """Parse assertions and objectives from a file"""
7022  try:
7023  Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7024  except Z3Exception as e:
7025  _handle_parse_error(e, self.ctx)
7026 
7027  def from_string(self, s):
7028  """Parse assertions and objectives from a string"""
7029  try:
7030  Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7031  except Z3Exception as e:
7032  _handle_parse_error(e, self.ctx)
7033 
7034  def assertions(self):
7035  """Return an AST vector containing all added constraints."""
7036  return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7037 
7038  def objectives(self):
7039  """returns set of objective functions"""
7040  return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7041 
7042  def __repr__(self):
7043  """Return a formatted string with all added rules and constraints."""
7044  return self.sexpr()
7045 
7046  def sexpr(self):
7047  """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7048  """
7049  return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7050 
7051  def statistics(self):
7052  """Return statistics for the last check`.
7053  """
7054  return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7055 
7056 
7057 
7058 
7059 
7065  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7066 
7067  def __init__(self, result, ctx):
7068  self.result = result
7069  self.ctx = ctx
7070  Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7071 
7072  def __deepcopy__(self, memo={}):
7073  return ApplyResult(self.result, self.ctx)
7074 
7075  def __del__(self):
7076  if self.ctx.ref() is not None:
7077  Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7078 
7079  def __len__(self):
7080  """Return the number of subgoals in `self`.
7081 
7082  >>> a, b = Ints('a b')
7083  >>> g = Goal()
7084  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7085  >>> t = Tactic('split-clause')
7086  >>> r = t(g)
7087  >>> len(r)
7088  2
7089  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7090  >>> len(t(g))
7091  4
7092  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7093  >>> len(t(g))
7094  1
7095  """
7096  return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7097 
7098  def __getitem__(self, idx):
7099  """Return one of the subgoals stored in ApplyResult object `self`.
7100 
7101  >>> a, b = Ints('a b')
7102  >>> g = Goal()
7103  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7104  >>> t = Tactic('split-clause')
7105  >>> r = t(g)
7106  >>> r[0]
7107  [a == 0, Or(b == 0, b == 1), a > b]
7108  >>> r[1]
7109  [a == 1, Or(b == 0, b == 1), a > b]
7110  """
7111  if idx >= len(self):
7112  raise IndexError
7113  return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7114 
7115  def __repr__(self):
7116  return obj_to_string(self)
7117 
7118  def sexpr(self):
7119  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7120  return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7121 
7122  def convert_model(self, model, idx=0):
7123  """Convert a model for a subgoal into a model for the original goal.
7124 
7125  >>> a, b = Ints('a b')
7126  >>> g = Goal()
7127  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7128  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
7129  >>> r = t(g)
7130  >>> r[0]
7131  [Or(b == 0, b == 1), Not(0 <= b)]
7132  >>> r[1]
7133  [Or(b == 0, b == 1), Not(1 <= b)]
7134  >>> # Remark: the subgoal r[0] is unsatisfiable
7135  >>> # Creating a solver for solving the second subgoal
7136  >>> s = Solver()
7137  >>> s.add(r[1])
7138  >>> s.check()
7139  sat
7140  >>> s.model()
7141  [b = 0]
7142  >>> # Model s.model() does not assign a value to `a`
7143  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
7144  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
7145  >>> r.convert_model(s.model(), 1)
7146  [b = 0, a = 1]
7147  """
7148  if __debug__:
7149  _z3_assert(idx < len(self), "index out of bounds")
7150  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
7151  return ModelRef(Z3_apply_result_convert_model(self.ctx.ref(), self.result, idx, model.model), self.ctx)
7152 
7153  def as_expr(self):
7154  """Return a Z3 expression consisting of all subgoals.
7155 
7156  >>> x = Int('x')
7157  >>> g = Goal()
7158  >>> g.add(x > 1)
7159  >>> g.add(Or(x == 2, x == 3))
7160  >>> r = Tactic('simplify')(g)
7161  >>> r
7162  [[Not(x <= 1), Or(x == 2, x == 3)]]
7163  >>> r.as_expr()
7164  And(Not(x <= 1), Or(x == 2, x == 3))
7165  >>> r = Tactic('split-clause')(g)
7166  >>> r
7167  [[x > 1, x == 2], [x > 1, x == 3]]
7168  >>> r.as_expr()
7169  Or(And(x > 1, x == 2), And(x > 1, x == 3))
7170  """
7171  sz = len(self)
7172  if sz == 0:
7173  return BoolVal(False, self.ctx)
7174  elif sz == 1:
7175  return self[0].as_expr()
7176  else:
7177  return Or([ self[i].as_expr() for i in range(len(self)) ])
7178 
7179 
7184 class Tactic:
7185  """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7186 
7187  Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7188  """
7189  def __init__(self, tactic, ctx=None):
7190  self.ctx = _get_ctx(ctx)
7191  self.tactic = None
7192  if isinstance(tactic, TacticObj):
7193  self.tactic = tactic
7194  else:
7195  if __debug__:
7196  _z3_assert(isinstance(tactic, str), "tactic name expected")
7197  try:
7198  self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7199  except Z3Exception:
7200  raise Z3Exception("unknown tactic '%s'" % tactic)
7201  Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7202 
7203  def __deepcopy__(self, memo={}):
7204  return Tactic(self.tactic, self.ctx)
7205 
7206  def __del__(self):
7207  if self.tactic is not None and self.ctx.ref() is not None:
7208  Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7209 
7210  def solver(self):
7211  """Create a solver using the tactic `self`.
7212 
7213  The solver supports the methods `push()` and `pop()`, but it
7214  will always solve each `check()` from scratch.
7215 
7216  >>> t = Then('simplify', 'nlsat')
7217  >>> s = t.solver()
7218  >>> x = Real('x')
7219  >>> s.add(x**2 == 2, x > 0)
7220  >>> s.check()
7221  sat
7222  >>> s.model()
7223  [x = 1.4142135623?]
7224  """
7225  return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
7226 
7227  def apply(self, goal, *arguments, **keywords):
7228  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7229 
7230  >>> x, y = Ints('x y')
7231  >>> t = Tactic('solve-eqs')
7232  >>> t.apply(And(x == 0, y >= x + 1))
7233  [[y >= 1]]
7234  """
7235  if __debug__:
7236  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7237  goal = _to_goal(goal)
7238  if len(arguments) > 0 or len(keywords) > 0:
7239  p = args2params(arguments, keywords, self.ctx)
7240  return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7241  else:
7242  return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7243 
7244  def __call__(self, goal, *arguments, **keywords):
7245  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7246 
7247  >>> x, y = Ints('x y')
7248  >>> t = Tactic('solve-eqs')
7249  >>> t(And(x == 0, y >= x + 1))
7250  [[y >= 1]]
7251  """
7252  return self.apply(goal, *arguments, **keywords)
7253 
7254  def help(self):
7255  """Display a string containing a description of the available options for the `self` tactic."""
7256  print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7257 
7258  def param_descrs(self):
7259  """Return the parameter description set."""
7260  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7261 
7262 def _to_goal(a):
7263  if isinstance(a, BoolRef):
7264  goal = Goal(ctx = a.ctx)
7265  goal.add(a)
7266  return goal
7267  else:
7268  return a
7269 
7270 def _to_tactic(t, ctx=None):
7271  if isinstance(t, Tactic):
7272  return t
7273  else:
7274  return Tactic(t, ctx)
7275 
7276 def _and_then(t1, t2, ctx=None):
7277  t1 = _to_tactic(t1, ctx)
7278  t2 = _to_tactic(t2, ctx)
7279  if __debug__:
7280  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7281  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7282 
7283 def _or_else(t1, t2, ctx=None):
7284  t1 = _to_tactic(t1, ctx)
7285  t2 = _to_tactic(t2, ctx)
7286  if __debug__:
7287  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7288  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7289 
7290 def AndThen(*ts, **ks):
7291  """Return a tactic that applies the tactics in `*ts` in sequence.
7292 
7293  >>> x, y = Ints('x y')
7294  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7295  >>> t(And(x == 0, y > x + 1))
7296  [[Not(y <= 1)]]
7297  >>> t(And(x == 0, y > x + 1)).as_expr()
7298  Not(y <= 1)
7299  """
7300  if __debug__:
7301  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7302  ctx = ks.get('ctx', None)
7303  num = len(ts)
7304  r = ts[0]
7305  for i in range(num - 1):
7306  r = _and_then(r, ts[i+1], ctx)
7307  return r
7308 
7309 def Then(*ts, **ks):
7310  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7311 
7312  >>> x, y = Ints('x y')
7313  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7314  >>> t(And(x == 0, y > x + 1))
7315  [[Not(y <= 1)]]
7316  >>> t(And(x == 0, y > x + 1)).as_expr()
7317  Not(y <= 1)
7318  """
7319  return AndThen(*ts, **ks)
7320 
7321 def OrElse(*ts, **ks):
7322  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7323 
7324  >>> x = Int('x')
7325  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7326  >>> # Tactic split-clause fails if there is no clause in the given goal.
7327  >>> t(x == 0)
7328  [[x == 0]]
7329  >>> t(Or(x == 0, x == 1))
7330  [[x == 0], [x == 1]]
7331  """
7332  if __debug__:
7333  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7334  ctx = ks.get('ctx', None)
7335  num = len(ts)
7336  r = ts[0]
7337  for i in range(num - 1):
7338  r = _or_else(r, ts[i+1], ctx)
7339  return r
7340 
7341 def ParOr(*ts, **ks):
7342  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7343 
7344  >>> x = Int('x')
7345  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7346  >>> t(x + 1 == 2)
7347  [[x == 1]]
7348  """
7349  if __debug__:
7350  _z3_assert(len(ts) >= 2, "At least two arguments expected")
7351  ctx = _get_ctx(ks.get('ctx', None))
7352  ts = [ _to_tactic(t, ctx) for t in ts ]
7353  sz = len(ts)
7354  _args = (TacticObj * sz)()
7355  for i in range(sz):
7356  _args[i] = ts[i].tactic
7357  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7358 
7359 def ParThen(t1, t2, ctx=None):
7360  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7361 
7362  >>> x, y = Ints('x y')
7363  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7364  >>> t(And(Or(x == 1, x == 2), y == x + 1))
7365  [[x == 1, y == 2], [x == 2, y == 3]]
7366  """
7367  t1 = _to_tactic(t1, ctx)
7368  t2 = _to_tactic(t2, ctx)
7369  if __debug__:
7370  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7371  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7372 
7373 def ParAndThen(t1, t2, ctx=None):
7374  """Alias for ParThen(t1, t2, ctx)."""
7375  return ParThen(t1, t2, ctx)
7376 
7377 def With(t, *args, **keys):
7378  """Return a tactic that applies tactic `t` using the given configuration options.
7379 
7380  >>> x, y = Ints('x y')
7381  >>> t = With(Tactic('simplify'), som=True)
7382  >>> t((x + 1)*(y + 2) == 0)
7383  [[2*x + y + x*y == -2]]
7384  """
7385  ctx = keys.pop('ctx', None)
7386  t = _to_tactic(t, ctx)
7387  p = args2params(args, keys, t.ctx)
7388  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7389 
7390 def Repeat(t, max=4294967295, ctx=None):
7391  """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7392 
7393  >>> x, y = Ints('x y')
7394  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7395  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7396  >>> r = t(c)
7397  >>> for subgoal in r: print(subgoal)
7398  [x == 0, y == 0, x > y]
7399  [x == 0, y == 1, x > y]
7400  [x == 1, y == 0, x > y]
7401  [x == 1, y == 1, x > y]
7402  >>> t = Then(t, Tactic('propagate-values'))
7403  >>> t(c)
7404  [[x == 1, y == 0]]
7405  """
7406  t = _to_tactic(t, ctx)
7407  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7408 
7409 def TryFor(t, ms, ctx=None):
7410  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7411 
7412  If `t` does not terminate in `ms` milliseconds, then it fails.
7413  """
7414  t = _to_tactic(t, ctx)
7415  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7416 
7417 def tactics(ctx=None):
7418  """Return a list of all available tactics in Z3.
7419 
7420  >>> l = tactics()
7421  >>> l.count('simplify') == 1
7422  True
7423  """
7424  ctx = _get_ctx(ctx)
7425  return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7426 
7427 def tactic_description(name, ctx=None):
7428  """Return a short description for the tactic named `name`.
7429 
7430  >>> d = tactic_description('simplify')
7431  """
7432  ctx = _get_ctx(ctx)
7433  return Z3_tactic_get_descr(ctx.ref(), name)
7434 
7436  """Display a (tabular) description of all available tactics in Z3."""
7437  if in_html_mode():
7438  even = True
7439  print('<table border="1" cellpadding="2" cellspacing="0">')
7440  for t in tactics():
7441  if even:
7442  print('<tr style="background-color:#CFCFCF">')
7443  even = False
7444  else:
7445  print('<tr>')
7446  even = True
7447  print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7448  print('</table>')
7449  else:
7450  for t in tactics():
7451  print('%s : %s' % (t, tactic_description(t)))
7452 
7453 class Probe:
7454  """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."""
7455  def __init__(self, probe, ctx=None):
7456  self.ctx = _get_ctx(ctx)
7457  self.probe = None
7458  if isinstance(probe, ProbeObj):
7459  self.probe = probe
7460  elif isinstance(probe, float):
7461  self.probe = Z3_probe_const(self.ctx.ref(), probe)
7462  elif _is_int(probe):
7463  self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7464  elif isinstance(probe, bool):
7465  if probe:
7466  self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7467  else:
7468  self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7469  else:
7470  if __debug__:
7471  _z3_assert(isinstance(probe, str), "probe name expected")
7472  try:
7473  self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7474  except Z3Exception:
7475  raise Z3Exception("unknown probe '%s'" % probe)
7476  Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7477 
7478  def __deepcopy__(self, memo={}):
7479  return Probe(self.probe, self.ctx)
7480 
7481  def __del__(self):
7482  if self.probe is not None and self.ctx.ref() is not None:
7483  Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7484 
7485  def __lt__(self, other):
7486  """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7487 
7488  >>> p = Probe('size') < 10
7489  >>> x = Int('x')
7490  >>> g = Goal()
7491  >>> g.add(x > 0)
7492  >>> g.add(x < 10)
7493  >>> p(g)
7494  1.0
7495  """
7496  return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7497 
7498  def __gt__(self, other):
7499  """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7500 
7501  >>> p = Probe('size') > 10
7502  >>> x = Int('x')
7503  >>> g = Goal()
7504  >>> g.add(x > 0)
7505  >>> g.add(x < 10)
7506  >>> p(g)
7507  0.0
7508  """
7509  return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7510 
7511  def __le__(self, other):
7512  """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7513 
7514  >>> p = Probe('size') <= 2
7515  >>> x = Int('x')
7516  >>> g = Goal()
7517  >>> g.add(x > 0)
7518  >>> g.add(x < 10)
7519  >>> p(g)
7520  1.0
7521  """
7522  return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7523 
7524  def __ge__(self, other):
7525  """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7526 
7527  >>> p = Probe('size') >= 2
7528  >>> x = Int('x')
7529  >>> g = Goal()
7530  >>> g.add(x > 0)
7531  >>> g.add(x < 10)
7532  >>> p(g)
7533  1.0
7534  """
7535  return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7536 
7537  def __eq__(self, other):
7538  """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
7539 
7540  >>> p = Probe('size') == 2
7541  >>> x = Int('x')
7542  >>> g = Goal()
7543  >>> g.add(x > 0)
7544  >>> g.add(x < 10)
7545  >>> p(g)
7546  1.0
7547  """
7548  return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7549 
7550  def __ne__(self, other):
7551  """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
7552 
7553  >>> p = Probe('size') != 2
7554  >>> x = Int('x')
7555  >>> g = Goal()
7556  >>> g.add(x > 0)
7557  >>> g.add(x < 10)
7558  >>> p(g)
7559  0.0
7560  """
7561  p = self.__eq__(other)
7562  return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
7563 
7564  def __call__(self, goal):
7565  """Evaluate the probe `self` in the given goal.
7566 
7567  >>> p = Probe('size')
7568  >>> x = Int('x')
7569  >>> g = Goal()
7570  >>> g.add(x > 0)
7571  >>> g.add(x < 10)
7572  >>> p(g)
7573  2.0
7574  >>> g.add(x < 20)
7575  >>> p(g)
7576  3.0
7577  >>> p = Probe('num-consts')
7578  >>> p(g)
7579  1.0
7580  >>> p = Probe('is-propositional')
7581  >>> p(g)
7582  0.0
7583  >>> p = Probe('is-qflia')
7584  >>> p(g)
7585  1.0
7586  """
7587  if __debug__:
7588  _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
7589  goal = _to_goal(goal)
7590  return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
7591 
7592 def is_probe(p):
7593  """Return `True` if `p` is a Z3 probe.
7594 
7595  >>> is_probe(Int('x'))
7596  False
7597  >>> is_probe(Probe('memory'))
7598  True
7599  """
7600  return isinstance(p, Probe)
7601 
7602 def _to_probe(p, ctx=None):
7603  if is_probe(p):
7604  return p
7605  else:
7606  return Probe(p, ctx)
7607 
7608 def probes(ctx=None):
7609  """Return a list of all available probes in Z3.
7610 
7611  >>> l = probes()
7612  >>> l.count('memory') == 1
7613  True
7614  """
7615  ctx = _get_ctx(ctx)
7616  return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
7617 
7618 def probe_description(name, ctx=None):
7619  """Return a short description for the probe named `name`.
7620 
7621  >>> d = probe_description('memory')
7622  """
7623  ctx = _get_ctx(ctx)
7624  return Z3_probe_get_descr(ctx.ref(), name)
7625 
7627  """Display a (tabular) description of all available probes in Z3."""
7628  if in_html_mode():
7629  even = True
7630  print('<table border="1" cellpadding="2" cellspacing="0">')
7631  for p in probes():
7632  if even:
7633  print('<tr style="background-color:#CFCFCF">')
7634  even = False
7635  else:
7636  print('<tr>')
7637  even = True
7638  print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
7639  print('</table>')
7640  else:
7641  for p in probes():
7642  print('%s : %s' % (p, probe_description(p)))
7643 
7644 def _probe_nary(f, args, ctx):
7645  if __debug__:
7646  _z3_assert(len(args) > 0, "At least one argument expected")
7647  num = len(args)
7648  r = _to_probe(args[0], ctx)
7649  for i in range(num - 1):
7650  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
7651  return r
7652 
7653 def _probe_and(args, ctx):
7654  return _probe_nary(Z3_probe_and, args, ctx)
7655 
7656 def _probe_or(args, ctx):
7657  return _probe_nary(Z3_probe_or, args, ctx)
7658 
7659 def FailIf(p, ctx=None):
7660  """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7661 
7662  In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
7663 
7664  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
7665  >>> x, y = Ints('x y')
7666  >>> g = Goal()
7667  >>> g.add(x > 0)
7668  >>> g.add(y > 0)
7669  >>> t(g)
7670  [[x > 0, y > 0]]
7671  >>> g.add(x == y + 1)
7672  >>> t(g)
7673  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7674  """
7675  p = _to_probe(p, ctx)
7676  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
7677 
7678 def When(p, t, ctx=None):
7679  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
7680 
7681  >>> t = When(Probe('size') > 2, Tactic('simplify'))
7682  >>> x, y = Ints('x y')
7683  >>> g = Goal()
7684  >>> g.add(x > 0)
7685  >>> g.add(y > 0)
7686  >>> t(g)
7687  [[x > 0, y > 0]]
7688  >>> g.add(x == y + 1)
7689  >>> t(g)
7690  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
7691  """
7692  p = _to_probe(p, ctx)
7693  t = _to_tactic(t, ctx)
7694  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
7695 
7696 def Cond(p, t1, t2, ctx=None):
7697  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
7698 
7699  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
7700  """
7701  p = _to_probe(p, ctx)
7702  t1 = _to_tactic(t1, ctx)
7703  t2 = _to_tactic(t2, ctx)
7704  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
7705 
7706 
7711 
7712 def simplify(a, *arguments, **keywords):
7713  """Simplify the expression `a` using the given options.
7714 
7715  This function has many options. Use `help_simplify` to obtain the complete list.
7716 
7717  >>> x = Int('x')
7718  >>> y = Int('y')
7719  >>> simplify(x + 1 + y + x + 1)
7720  2 + 2*x + y
7721  >>> simplify((x + 1)*(y + 1), som=True)
7722  1 + x + y + x*y
7723  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
7724  And(Not(x == y), Not(x == 1), Not(y == 1))
7725  >>> simplify(And(x == 0, y == 1), elim_and=True)
7726  Not(Or(Not(x == 0), Not(y == 1)))
7727  """
7728  if __debug__:
7729  _z3_assert(is_expr(a), "Z3 expression expected")
7730  if len(arguments) > 0 or len(keywords) > 0:
7731  p = args2params(arguments, keywords, a.ctx)
7732  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
7733  else:
7734  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
7735 
7737  """Return a string describing all options available for Z3 `simplify` procedure."""
7738  print(Z3_simplify_get_help(main_ctx().ref()))
7739 
7741  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
7743 
7744 def substitute(t, *m):
7745  """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.
7746 
7747  >>> x = Int('x')
7748  >>> y = Int('y')
7749  >>> substitute(x + 1, (x, y + 1))
7750  y + 1 + 1
7751  >>> f = Function('f', IntSort(), IntSort())
7752  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
7753  1 + 1
7754  """
7755  if isinstance(m, tuple):
7756  m1 = _get_args(m)
7757  if isinstance(m1, list):
7758  m = m1
7759  if __debug__:
7760  _z3_assert(is_expr(t), "Z3 expression expected")
7761  _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.")
7762  num = len(m)
7763  _from = (Ast * num)()
7764  _to = (Ast * num)()
7765  for i in range(num):
7766  _from[i] = m[i][0].as_ast()
7767  _to[i] = m[i][1].as_ast()
7768  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
7769 
7770 def substitute_vars(t, *m):
7771  """Substitute the free variables in t with the expression in m.
7772 
7773  >>> v0 = Var(0, IntSort())
7774  >>> v1 = Var(1, IntSort())
7775  >>> x = Int('x')
7776  >>> f = Function('f', IntSort(), IntSort(), IntSort())
7777  >>> # replace v0 with x+1 and v1 with x
7778  >>> substitute_vars(f(v0, v1), x + 1, x)
7779  f(x + 1, x)
7780  """
7781  if __debug__:
7782  _z3_assert(is_expr(t), "Z3 expression expected")
7783  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
7784  num = len(m)
7785  _to = (Ast * num)()
7786  for i in range(num):
7787  _to[i] = m[i].as_ast()
7788  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
7789 
7790 def Sum(*args):
7791  """Create the sum of the Z3 expressions.
7792 
7793  >>> a, b, c = Ints('a b c')
7794  >>> Sum(a, b, c)
7795  a + b + c
7796  >>> Sum([a, b, c])
7797  a + b + c
7798  >>> A = IntVector('a', 5)
7799  >>> Sum(A)
7800  a__0 + a__1 + a__2 + a__3 + a__4
7801  """
7802  args = _get_args(args)
7803  if len(args) == 0:
7804  return 0
7805  ctx = _ctx_from_ast_arg_list(args)
7806  if ctx is None:
7807  return _reduce(lambda a, b: a + b, args, 0)
7808  args = _coerce_expr_list(args, ctx)
7809  if is_bv(args[0]):
7810  return _reduce(lambda a, b: a + b, args, 0)
7811  else:
7812  _args, sz = _to_ast_array(args)
7813  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
7814 
7815 
7816 def Product(*args):
7817  """Create the product of the Z3 expressions.
7818 
7819  >>> a, b, c = Ints('a b c')
7820  >>> Product(a, b, c)
7821  a*b*c
7822  >>> Product([a, b, c])
7823  a*b*c
7824  >>> A = IntVector('a', 5)
7825  >>> Product(A)
7826  a__0*a__1*a__2*a__3*a__4
7827  """
7828  args = _get_args(args)
7829  if len(args) == 0:
7830  return 1
7831  ctx = _ctx_from_ast_arg_list(args)
7832  if ctx is None:
7833  return _reduce(lambda a, b: a * b, args, 1)
7834  args = _coerce_expr_list(args, ctx)
7835  if is_bv(args[0]):
7836  return _reduce(lambda a, b: a * b, args, 1)
7837  else:
7838  _args, sz = _to_ast_array(args)
7839  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
7840 
7841 def AtMost(*args):
7842  """Create an at-most Pseudo-Boolean k constraint.
7843 
7844  >>> a, b, c = Bools('a b c')
7845  >>> f = AtMost(a, b, c, 2)
7846  """
7847  args = _get_args(args)
7848  if __debug__:
7849  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7850  ctx = _ctx_from_ast_arg_list(args)
7851  if __debug__:
7852  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7853  args1 = _coerce_expr_list(args[:-1], ctx)
7854  k = args[-1]
7855  _args, sz = _to_ast_array(args1)
7856  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
7857 
7858 def AtLeast(*args):
7859  """Create an at-most Pseudo-Boolean k constraint.
7860 
7861  >>> a, b, c = Bools('a b c')
7862  >>> f = AtLeast(a, b, c, 2)
7863  """
7864  args = _get_args(args)
7865  if __debug__:
7866  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
7867  ctx = _ctx_from_ast_arg_list(args)
7868  if __debug__:
7869  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7870  args1 = _coerce_expr_list(args[:-1], ctx)
7871  k = args[-1]
7872  _args, sz = _to_ast_array(args1)
7873  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
7874 
7875 
7876 def _pb_args_coeffs(args):
7877  args = _get_args(args)
7878  args, coeffs = zip(*args)
7879  if __debug__:
7880  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
7881  ctx = _ctx_from_ast_arg_list(args)
7882  if __debug__:
7883  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
7884  args = _coerce_expr_list(args, ctx)
7885  _args, sz = _to_ast_array(args)
7886  _coeffs = (ctypes.c_int * len(coeffs))()
7887  for i in range(len(coeffs)):
7888  _coeffs[i] = coeffs[i]
7889  return ctx, sz, _args, _coeffs
7890 
7891 def PbLe(args, k):
7892  """Create a Pseudo-Boolean inequality k constraint.
7893 
7894  >>> a, b, c = Bools('a b c')
7895  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
7896  """
7897  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7898  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
7899 
7900 def PbGe(args, k):
7901  """Create a Pseudo-Boolean inequality k constraint.
7902 
7903  >>> a, b, c = Bools('a b c')
7904  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
7905  """
7906  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7907  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
7908 
7909 def PbEq(args, k):
7910  """Create a Pseudo-Boolean inequality k constraint.
7911 
7912  >>> a, b, c = Bools('a b c')
7913  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
7914  """
7915  ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
7916  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
7917 
7918 
7919 def solve(*args, **keywords):
7920  """Solve the constraints `*args`.
7921 
7922  This is a simple function for creating demonstrations. It creates a solver,
7923  configure it using the options in `keywords`, adds the constraints
7924  in `args`, and invokes check.
7925 
7926  >>> a = Int('a')
7927  >>> solve(a > 0, a < 2)
7928  [a = 1]
7929  """
7930  s = Solver()
7931  s.set(**keywords)
7932  s.add(*args)
7933  if keywords.get('show', False):
7934  print(s)
7935  r = s.check()
7936  if r == unsat:
7937  print("no solution")
7938  elif r == unknown:
7939  print("failed to solve")
7940  try:
7941  print(s.model())
7942  except Z3Exception:
7943  return
7944  else:
7945  print(s.model())
7946 
7947 def solve_using(s, *args, **keywords):
7948  """Solve the constraints `*args` using solver `s`.
7949 
7950  This is a simple function for creating demonstrations. It is similar to `solve`,
7951  but it uses the given solver `s`.
7952  It configures solver `s` using the options in `keywords`, adds the constraints
7953  in `args`, and invokes check.
7954  """
7955  if __debug__:
7956  _z3_assert(isinstance(s, Solver), "Solver object expected")
7957  s.set(**keywords)
7958  s.add(*args)
7959  if keywords.get('show', False):
7960  print("Problem:")
7961  print(s)
7962  r = s.check()
7963  if r == unsat:
7964  print("no solution")
7965  elif r == unknown:
7966  print("failed to solve")
7967  try:
7968  print(s.model())
7969  except Z3Exception:
7970  return
7971  else:
7972  if keywords.get('show', False):
7973  print("Solution:")
7974  print(s.model())
7975 
7976 def prove(claim, **keywords):
7977  """Try to prove the given claim.
7978 
7979  This is a simple function for creating demonstrations. It tries to prove
7980  `claim` by showing the negation is unsatisfiable.
7981 
7982  >>> p, q = Bools('p q')
7983  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
7984  proved
7985  """
7986  if __debug__:
7987  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
7988  s = Solver()
7989  s.set(**keywords)
7990  s.add(Not(claim))
7991  if keywords.get('show', False):
7992  print(s)
7993  r = s.check()
7994  if r == unsat:
7995  print("proved")
7996  elif r == unknown:
7997  print("failed to prove")
7998  print(s.model())
7999  else:
8000  print("counterexample")
8001  print(s.model())
8002 
8003 def _solve_html(*args, **keywords):
8004  """Version of funcion `solve` used in RiSE4Fun."""
8005  s = Solver()
8006  s.set(**keywords)
8007  s.add(*args)
8008  if keywords.get('show', False):
8009  print("<b>Problem:</b>")
8010  print(s)
8011  r = s.check()
8012  if r == unsat:
8013  print("<b>no solution</b>")
8014  elif r == unknown:
8015  print("<b>failed to solve</b>")
8016  try:
8017  print(s.model())
8018  except Z3Exception:
8019  return
8020  else:
8021  if keywords.get('show', False):
8022  print("<b>Solution:</b>")
8023  print(s.model())
8024 
8025 def _solve_using_html(s, *args, **keywords):
8026  """Version of funcion `solve_using` used in RiSE4Fun."""
8027  if __debug__:
8028  _z3_assert(isinstance(s, Solver), "Solver object expected")
8029  s.set(**keywords)
8030  s.add(*args)
8031  if keywords.get('show', False):
8032  print("<b>Problem:</b>")
8033  print(s)
8034  r = s.check()
8035  if r == unsat:
8036  print("<b>no solution</b>")
8037  elif r == unknown:
8038  print("<b>failed to solve</b>")
8039  try:
8040  print(s.model())
8041  except Z3Exception:
8042  return
8043  else:
8044  if keywords.get('show', False):
8045  print("<b>Solution:</b>")
8046  print(s.model())
8047 
8048 def _prove_html(claim, **keywords):
8049  """Version of funcion `prove` used in RiSE4Fun."""
8050  if __debug__:
8051  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8052  s = Solver()
8053  s.set(**keywords)
8054  s.add(Not(claim))
8055  if keywords.get('show', False):
8056  print(s)
8057  r = s.check()
8058  if r == unsat:
8059  print("<b>proved</b>")
8060  elif r == unknown:
8061  print("<b>failed to prove</b>")
8062  print(s.model())
8063  else:
8064  print("<b>counterexample</b>")
8065  print(s.model())
8066 
8067 def _dict2sarray(sorts, ctx):
8068  sz = len(sorts)
8069  _names = (Symbol * sz)()
8070  _sorts = (Sort * sz) ()
8071  i = 0
8072  for k in sorts:
8073  v = sorts[k]
8074  if __debug__:
8075  _z3_assert(isinstance(k, str), "String expected")
8076  _z3_assert(is_sort(v), "Z3 sort expected")
8077  _names[i] = to_symbol(k, ctx)
8078  _sorts[i] = v.ast
8079  i = i + 1
8080  return sz, _names, _sorts
8081 
8082 def _dict2darray(decls, ctx):
8083  sz = len(decls)
8084  _names = (Symbol * sz)()
8085  _decls = (FuncDecl * sz) ()
8086  i = 0
8087  for k in decls:
8088  v = decls[k]
8089  if __debug__:
8090  _z3_assert(isinstance(k, str), "String expected")
8091  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8092  _names[i] = to_symbol(k, ctx)
8093  if is_const(v):
8094  _decls[i] = v.decl().ast
8095  else:
8096  _decls[i] = v.ast
8097  i = i + 1
8098  return sz, _names, _decls
8099 
8100 def _handle_parse_error(ex, ctx):
8101  msg = Z3_get_parser_error(ctx.ref())
8102  if msg != "":
8103  raise Z3Exception(msg)
8104  raise ex
8105 
8106 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8107  """Parse a string in SMT 2.0 format using the given sorts and decls.
8108 
8109  The arguments sorts and decls are Python dictionaries used to initialize
8110  the symbol table used for the SMT 2.0 parser.
8111 
8112  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8113  And(x > 0, x < 10)
8114  >>> x, y = Ints('x y')
8115  >>> f = Function('f', IntSort(), IntSort())
8116  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8117  x + f(y) > 0
8118  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8119  a > 0
8120  """
8121  ctx = _get_ctx(ctx)
8122  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8123  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8124  try:
8125  return _to_expr_ref(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8126  except Z3Exception as e:
8127  _handle_parse_error(e, ctx)
8128 
8129 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8130  """Parse a file in SMT 2.0 format using the given sorts and decls.
8131 
8132  This function is similar to parse_smt2_string().
8133  """
8134  ctx = _get_ctx(ctx)
8135  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8136  dsz, dnames, ddecls = _dict2darray(decls, ctx)
8137  try:
8138  return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8139  except Z3Exception as e:
8140  _handle_parse_error(e, ctx)
8141 
8142 def Interpolant(a,ctx=None):
8143  """Create an interpolation operator.
8144 
8145  The argument is an interpolation pattern (see tree_interpolant).
8146 
8147  >>> x = Int('x')
8148  >>> print(Interpolant(x>0))
8149  interp(x > 0)
8150  """
8151  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
8152  s = BoolSort(ctx)
8153  a = s.cast(a)
8154  return BoolRef(Z3_mk_interpolant(ctx.ref(), a.as_ast()), ctx)
8155 
8156 def tree_interpolant(pat,p=None,ctx=None):
8157  """Compute interpolant for a tree of formulas.
8158 
8159  The input is an interpolation pattern over a set of formulas C.
8160  The pattern pat is a formula combining the formulas in C using
8161  logical conjunction and the "interp" operator (see Interp). This
8162  interp operator is logically the identity operator. It marks the
8163  sub-formulas of the pattern for which interpolants should be
8164  computed. The interpolant is a map sigma from marked subformulas
8165  to formulas, such that, for each marked subformula phi of pat
8166  (where phi sigma is phi with sigma(psi) substituted for each
8167  subformula psi of phi such that psi in dom(sigma)):
8168 
8169  1) phi sigma implies sigma(phi), and
8170 
8171  2) sigma(phi) is in the common uninterpreted vocabulary between
8172  the formulas of C occurring in phi and those not occurring in
8173  phi
8174 
8175  and moreover pat sigma implies false. In the simplest case
8176  an interpolant for the pattern "(and (interp A) B)" maps A
8177  to an interpolant for A /\ B.
8178 
8179  The return value is a vector of formulas representing sigma. This
8180  vector contains sigma(phi) for each marked subformula of pat, in
8181  pre-order traversal. This means that subformulas of phi occur before phi
8182  in the vector. Also, subformulas that occur multiply in pat will
8183  occur multiply in the result vector.
8184 
8185  If pat is satisfiable, raises an object of class ModelRef
8186  that represents a model of pat.
8187 
8188  If neither a proof of unsatisfiability nor a model is obtained
8189  (for example, because of a timeout, or because models are disabled)
8190  then None is returned.
8191 
8192  If parameters p are supplied, these are used in creating the
8193  solver that determines satisfiability.
8194 
8195  >>> x = Int('x')
8196  >>> y = Int('y')
8197  >>> print(tree_interpolant(And(Interpolant(x < 0), Interpolant(y > 2), x == y)))
8198  [Not(x >= 0), Not(y <= 2)]
8199 
8200  # >>> g = And(Interpolant(x<0),x<2)
8201  # >>> try:
8202  # ... print tree_interpolant(g).sexpr()
8203  # ... except ModelRef as m:
8204  # ... print m.sexpr()
8205  (define-fun x () Int
8206  (- 1))
8207  """
8208  f = pat
8209  ctx = _get_ctx(_ctx_from_ast_arg_list([f], ctx))
8210  ptr = (AstVectorObj * 1)()
8211  mptr = (Model * 1)()
8212  if p is None:
8213  p = ParamsRef(ctx)
8214  res = Z3_compute_interpolant(ctx.ref(),f.as_ast(),p.params,ptr,mptr)
8215  if res == Z3_L_FALSE:
8216  return AstVector(ptr[0],ctx)
8217  if mptr[0]:
8218  raise ModelRef(mptr[0], ctx)
8219  return None
8220 
8221 def binary_interpolant(a,b,p=None,ctx=None):
8222  """Compute an interpolant for a binary conjunction.
8223 
8224  If a & b is unsatisfiable, returns an interpolant for a & b.
8225  This is a formula phi such that
8226 
8227  1) a implies phi
8228  2) b implies not phi
8229  3) All the uninterpreted symbols of phi occur in both a and b.
8230 
8231  If a & b is satisfiable, raises an object of class ModelRef
8232  that represents a model of a &b.
8233 
8234  If neither a proof of unsatisfiability nor a model is obtained
8235  (for example, because of a timeout, or because models are disabled)
8236  then None is returned.
8237 
8238  If parameters p are supplied, these are used in creating the
8239  solver that determines satisfiability.
8240 
8241  x = Int('x')
8242  print(binary_interpolant(x<0,x>2))
8243  Not(x >= 0)
8244  """
8245  f = And(Interpolant(a),b)
8246  ti = tree_interpolant(f,p,ctx)
8247  return ti[0] if ti is not None else None
8248 
8249 def sequence_interpolant(v,p=None,ctx=None):
8250  """Compute interpolant for a sequence of formulas.
8251 
8252  If len(v) == N, and if the conjunction of the formulas in v is
8253  unsatisfiable, the interpolant is a sequence of formulas w
8254  such that len(w) = N-1 and v[0] implies w[0] and for i in 0..N-1:
8255 
8256  1) w[i] & v[i+1] implies w[i+1] (or false if i+1 = N)
8257  2) All uninterpreted symbols in w[i] occur in both v[0]..v[i]
8258  and v[i+1]..v[n]
8259 
8260  Requires len(v) >= 1.
8261 
8262  If a & b is satisfiable, raises an object of class ModelRef
8263  that represents a model of a & b.
8264 
8265  If neither a proof of unsatisfiability nor a model is obtained
8266  (for example, because of a timeout, or because models are disabled)
8267  then None is returned.
8268 
8269  If parameters p are supplied, these are used in creating the
8270  solver that determines satisfiability.
8271 
8272  x = Int('x')
8273  y = Int('y')
8274  print(sequence_interpolant([x < 0, y == x , y > 2]))
8275  [Not(x >= 0), Not(y >= 0)]
8276  """
8277  f = v[0]
8278  for i in range(1,len(v)):
8279  f = And(Interpolant(f),v[i])
8280  return tree_interpolant(f,p,ctx)
8281 
8282 
8283 #########################################
8284 #
8285 # Floating-Point Arithmetic
8286 #
8287 #########################################
8288 
8289 
8290 # Global default rounding mode
8291 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8292 _dflt_fpsort_ebits = 11
8293 _dflt_fpsort_sbits = 53
8294 
8295 def get_default_rounding_mode(ctx=None):
8296  """Retrieves the global default rounding mode."""
8297  global _dflt_rounding_mode
8298  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8299  return RTZ(ctx)
8300  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8301  return RTN(ctx)
8302  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8303  return RTP(ctx)
8304  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8305  return RNE(ctx)
8306  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8307  return RNA(ctx)
8308 
8309 def set_default_rounding_mode(rm, ctx=None):
8310  global _dflt_rounding_mode
8311  if is_fprm_value(rm):
8312  _dflt_rounding_mode = rm.decl().kind()
8313  else:
8314  _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8315  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8316  _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8317  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8318  _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8319  "illegal rounding mode")
8320  _dflt_rounding_mode = rm
8321 
8322 def get_default_fp_sort(ctx=None):
8323  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8324 
8325 def set_default_fp_sort(ebits, sbits, ctx=None):
8326  global _dflt_fpsort_ebits
8327  global _dflt_fpsort_sbits
8328  _dflt_fpsort_ebits = ebits
8329  _dflt_fpsort_sbits = sbits
8330 
8331 def _dflt_rm(ctx=None):
8332  return get_default_rounding_mode(ctx)
8333 
8334 def _dflt_fps(ctx=None):
8335  return get_default_fp_sort(ctx)
8336 
8337 def _coerce_fp_expr_list(alist, ctx):
8338  first_fp_sort = None
8339  for a in alist:
8340  if is_fp(a):
8341  if first_fp_sort is None:
8342  first_fp_sort = a.sort()
8343  elif first_fp_sort == a.sort():
8344  pass # OK, same as before
8345  else:
8346  # we saw at least 2 different float sorts; something will
8347  # throw a sort mismatch later, for now assume None.
8348  first_fp_sort = None
8349  break
8350 
8351  r = []
8352  for i in range(len(alist)):
8353  a = alist[i]
8354  if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8355  r.append(FPVal(a, None, first_fp_sort, ctx))
8356  else:
8357  r.append(a)
8358  return _coerce_expr_list(r, ctx)
8359 
8360 
8361 ### FP Sorts
8362 
8363 class FPSortRef(SortRef):
8364  """Floating-point sort."""
8365 
8366  def ebits(self):
8367  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8368  >>> b = FPSort(8, 24)
8369  >>> b.ebits()
8370  8
8371  """
8372  return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8373 
8374  def sbits(self):
8375  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8376  >>> b = FPSort(8, 24)
8377  >>> b.sbits()
8378  24
8379  """
8380  return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8381 
8382  def cast(self, val):
8383  """Try to cast `val` as a floating-point expression.
8384  >>> b = FPSort(8, 24)
8385  >>> b.cast(1.0)
8386  1
8387  >>> b.cast(1.0).sexpr()
8388  '(fp #b0 #x7f #b00000000000000000000000)'
8389  """
8390  if is_expr(val):
8391  if __debug__:
8392  _z3_assert(self.ctx == val.ctx, "Context mismatch")
8393  return val
8394  else:
8395  return FPVal(val, None, self, self.ctx)
8396 
8397 
8398 def Float16(ctx=None):
8399  """Floating-point 16-bit (half) sort."""
8400  ctx = _get_ctx(ctx)
8401  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8402 
8403 def FloatHalf(ctx=None):
8404  """Floating-point 16-bit (half) sort."""
8405  ctx = _get_ctx(ctx)
8406  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8407 
8408 def Float32(ctx=None):
8409  """Floating-point 32-bit (single) sort."""
8410  ctx = _get_ctx(ctx)
8411  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8412 
8413 def FloatSingle(ctx=None):
8414  """Floating-point 32-bit (single) sort."""
8415  ctx = _get_ctx(ctx)
8416  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8417 
8418 def Float64(ctx=None):
8419  """Floating-point 64-bit (double) sort."""
8420  ctx = _get_ctx(ctx)
8421  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8422 
8423 def FloatDouble(ctx=None):
8424  """Floating-point 64-bit (double) sort."""
8425  ctx = _get_ctx(ctx)
8426  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8427 
8428 def Float128(ctx=None):
8429  """Floating-point 128-bit (quadruple) sort."""
8430  ctx = _get_ctx(ctx)
8431  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8432 
8433 def FloatQuadruple(ctx=None):
8434  """Floating-point 128-bit (quadruple) sort."""
8435  ctx = _get_ctx(ctx)
8436  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8437 
8438 class FPRMSortRef(SortRef):
8439  """"Floating-point rounding mode sort."""
8440 
8441 
8442 def is_fp_sort(s):
8443  """Return True if `s` is a Z3 floating-point sort.
8444 
8445  >>> is_fp_sort(FPSort(8, 24))
8446  True
8447  >>> is_fp_sort(IntSort())
8448  False
8449  """
8450  return isinstance(s, FPSortRef)
8451 
8452 def is_fprm_sort(s):
8453  """Return True if `s` is a Z3 floating-point rounding mode sort.
8454 
8455  >>> is_fprm_sort(FPSort(8, 24))
8456  False
8457  >>> is_fprm_sort(RNE().sort())
8458  True
8459  """
8460  return isinstance(s, FPRMSortRef)
8461 
8462 ### FP Expressions
8463 
8464 class FPRef(ExprRef):
8465  """Floating-point expressions."""
8466 
8467  def sort(self):
8468  """Return the sort of the floating-point expression `self`.
8469 
8470  >>> x = FP('1.0', FPSort(8, 24))
8471  >>> x.sort()
8472  FPSort(8, 24)
8473  >>> x.sort() == FPSort(8, 24)
8474  True
8475  """
8476  return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8477 
8478  def ebits(self):
8479  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8480  >>> b = FPSort(8, 24)
8481  >>> b.ebits()
8482  8
8483  """
8484  return self.sort().ebits();
8485 
8486  def sbits(self):
8487  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8488  >>> b = FPSort(8, 24)
8489  >>> b.sbits()
8490  24
8491  """
8492  return self.sort().sbits();
8493 
8494  def as_string(self):
8495  """Return a Z3 floating point expression as a Python string."""
8496  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8497 
8498  def __le__(self, other):
8499  return fpLEQ(self, other, self.ctx)
8500 
8501  def __lt__(self, other):
8502  return fpLT(self, other, self.ctx)
8503 
8504  def __ge__(self, other):
8505  return fpGEQ(self, other, self.ctx)
8506 
8507  def __gt__(self, other):
8508  return fpGT(self, other, self.ctx)
8509 
8510  def __add__(self, other):
8511  """Create the Z3 expression `self + other`.
8512 
8513  >>> x = FP('x', FPSort(8, 24))
8514  >>> y = FP('y', FPSort(8, 24))
8515  >>> x + y
8516  x + y
8517  >>> (x + y).sort()
8518  FPSort(8, 24)
8519  """
8520  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8521  return fpAdd(_dflt_rm(), a, b, self.ctx)
8522 
8523  def __radd__(self, other):
8524  """Create the Z3 expression `other + self`.
8525 
8526  >>> x = FP('x', FPSort(8, 24))
8527  >>> 10 + x
8528  1.25*(2**3) + x
8529  """
8530  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8531  return fpAdd(_dflt_rm(), a, b, self.ctx)
8532 
8533  def __sub__(self, other):
8534  """Create the Z3 expression `self - other`.
8535 
8536  >>> x = FP('x', FPSort(8, 24))
8537  >>> y = FP('y', FPSort(8, 24))
8538  >>> x - y
8539  x - y
8540  >>> (x - y).sort()
8541  FPSort(8, 24)
8542  """
8543  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8544  return fpSub(_dflt_rm(), a, b, self.ctx)
8545 
8546  def __rsub__(self, other):
8547  """Create the Z3 expression `other - self`.
8548 
8549  >>> x = FP('x', FPSort(8, 24))
8550  >>> 10 - x
8551  1.25*(2**3) - x
8552  """
8553  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8554  return fpSub(_dflt_rm(), a, b, self.ctx)
8555 
8556  def __mul__(self, other):
8557  """Create the Z3 expression `self * other`.
8558 
8559  >>> x = FP('x', FPSort(8, 24))
8560  >>> y = FP('y', FPSort(8, 24))
8561  >>> x * y
8562  x * y
8563  >>> (x * y).sort()
8564  FPSort(8, 24)
8565  >>> 10 * y
8566  1.25*(2**3) * y
8567  """
8568  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8569  return fpMul(_dflt_rm(), a, b, self.ctx)
8570 
8571  def __rmul__(self, other):
8572  """Create the Z3 expression `other * self`.
8573 
8574  >>> x = FP('x', FPSort(8, 24))
8575  >>> y = FP('y', FPSort(8, 24))
8576  >>> x * y
8577  x * y
8578  >>> x * 10
8579  x * 1.25*(2**3)
8580  """
8581  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8582  return fpMul(_dflt_rm(), a, b, self.ctx)
8583 
8584  def __pos__(self):
8585  """Create the Z3 expression `+self`."""
8586  return self
8587 
8588  def __neg__(self):
8589  """Create the Z3 expression `-self`.
8590 
8591  >>> x = FP('x', Float32())
8592  >>> -x
8593  -x
8594  """
8595  return fpNeg(self)
8596 
8597  def __div__(self, other):
8598  """Create the Z3 expression `self / other`.
8599 
8600  >>> x = FP('x', FPSort(8, 24))
8601  >>> y = FP('y', FPSort(8, 24))
8602  >>> x / y
8603  x / y
8604  >>> (x / y).sort()
8605  FPSort(8, 24)
8606  >>> 10 / y
8607  1.25*(2**3) / y
8608  """
8609  [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8610  return fpDiv(_dflt_rm(), a, b, self.ctx)
8611 
8612  def __rdiv__(self, other):
8613  """Create the Z3 expression `other / self`.
8614 
8615  >>> x = FP('x', FPSort(8, 24))
8616  >>> y = FP('y', FPSort(8, 24))
8617  >>> x / y
8618  x / y
8619  >>> x / 10
8620  x / 1.25*(2**3)
8621  """
8622  [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8623  return fpDiv(_dflt_rm(), a, b, self.ctx)
8624 
8625  if not sys.version < '3':
8626  def __truediv__(self, other):
8627  """Create the Z3 expression division `self / other`."""
8628  return self.__div__(other)
8629 
8630  def __rtruediv__(self, other):
8631  """Create the Z3 expression division `other / self`."""
8632  return self.__rdiv__(other)
8633 
8634  def __mod__(self, other):
8635  """Create the Z3 expression mod `self % other`."""
8636  return fpRem(self, other)
8637 
8638  def __rmod__(self, other):
8639  """Create the Z3 expression mod `other % self`."""
8640  return fpRem(other, self)
8641 
8642 class FPRMRef(ExprRef):
8643  """Floating-point rounding mode expressions"""
8644 
8645  def as_string(self):
8646  """Return a Z3 floating point expression as a Python string."""
8647  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8648 
8649 
8650 def RoundNearestTiesToEven(ctx=None):
8651  ctx = _get_ctx(ctx)
8652  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8653 
8654 def RNE (ctx=None):
8655  ctx = _get_ctx(ctx)
8656  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8657 
8658 def RoundNearestTiesToAway(ctx=None):
8659  ctx = _get_ctx(ctx)
8660  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8661 
8662 def RNA (ctx=None):
8663  ctx = _get_ctx(ctx)
8664  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8665 
8666 def RoundTowardPositive(ctx=None):
8667  ctx = _get_ctx(ctx)
8668  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8669 
8670 def RTP(ctx=None):
8671  ctx = _get_ctx(ctx)
8672  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8673 
8674 def RoundTowardNegative(ctx=None):
8675  ctx = _get_ctx(ctx)
8676  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8677 
8678 def RTN(ctx=None):
8679  ctx = _get_ctx(ctx)
8680  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
8681 
8682 def RoundTowardZero(ctx=None):
8683  ctx = _get_ctx(ctx)
8684  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8685 
8686 def RTZ(ctx=None):
8687  ctx = _get_ctx(ctx)
8688  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
8689 
8690 def is_fprm(a):
8691  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
8692 
8693  >>> rm = RNE()
8694  >>> is_fprm(rm)
8695  True
8696  >>> rm = 1.0
8697  >>> is_fprm(rm)
8698  False
8699  """
8700  return isinstance(a, FPRMRef)
8701 
8702 def is_fprm_value(a):
8703  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
8704  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
8705 
8706 ### FP Numerals
8707 
8708 class FPNumRef(FPRef):
8709  """The sign of the numeral.
8710 
8711  >>> x = FPVal(+1.0, FPSort(8, 24))
8712  >>> x.sign()
8713  False
8714  >>> x = FPVal(-1.0, FPSort(8, 24))
8715  >>> x.sign()
8716  True
8717  """
8718  def sign(self):
8719  l = (ctypes.c_int)()
8720  if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
8721  raise Z3Exception("error retrieving the sign of a numeral.")
8722  return l.value != 0
8723 
8724  """The sign of a floating-point numeral as a bit-vector expression.
8725 
8726  Remark: NaN's are invalid arguments.
8727  """
8728  def sign_as_bv(self):
8729  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8730 
8731  """The significand of the numeral.
8732 
8733  >>> x = FPVal(2.5, FPSort(8, 24))
8734  >>> x.significand()
8735  1.25
8736  """
8737  def significand(self):
8738  return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
8739 
8740  """The significand of the numeral as a long.
8741 
8742  >>> x = FPVal(2.5, FPSort(8, 24))
8743  >>> x.significand_as_long()
8744  1.25
8745  """
8746  def significand_as_long(self):
8747  return Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast())
8748 
8749  """The significand of the numeral as a bit-vector expression.
8750 
8751  Remark: NaN are invalid arguments.
8752  """
8753  def significand_as_bv(self):
8754  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
8755 
8756  """The exponent of the numeral.
8757 
8758  >>> x = FPVal(2.5, FPSort(8, 24))
8759  >>> x.exponent()
8760  1
8761  """
8762  def exponent(self, biased=True):
8763  return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
8764 
8765  """The exponent of the numeral as a long.
8766 
8767  >>> x = FPVal(2.5, FPSort(8, 24))
8768  >>> x.exponent_as_long()
8769  1
8770  """
8771  def exponent_as_long(self, biased=True):
8772  ptr = (ctypes.c_longlong * 1)()
8773  if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
8774  raise Z3Exception("error retrieving the exponent of a numeral.")
8775  return ptr[0]
8776 
8777  """The exponent of the numeral as a bit-vector expression.
8778 
8779  Remark: NaNs are invalid arguments.
8780  """
8781  def exponent_as_bv(self, biased=True):
8782  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
8783 
8784  """Indicates whether the numeral is a NaN."""
8785  def isNaN(self):
8786  return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
8787 
8788  """Indicates whether the numeral is +oo or -oo."""
8789  def isInf(self):
8790  return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
8791 
8792  """Indicates whether the numeral is +zero or -zero."""
8793  def isZero(self):
8794  return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
8795 
8796  """Indicates whether the numeral is normal."""
8797  def isNormal(self):
8798  return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
8799 
8800  """Indicates whether the numeral is subnormal."""
8801  def isSubnormal(self):
8802  return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
8803 
8804  """Indicates whether the numeral is postitive."""
8805  def isPositive(self):
8806  return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
8807 
8808  """Indicates whether the numeral is negative."""
8809  def isNegative(self):
8810  return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
8811 
8812  """
8813  The string representation of the numeral.
8814 
8815  >>> x = FPVal(20, FPSort(8, 24))
8816  >>> x.as_string()
8817  1.25*(2**4)
8818  """
8819  def as_string(self):
8820  s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
8821  return ("FPVal(%s, %s)" % (s, self.sort()))
8822 
8823 def is_fp(a):
8824  """Return `True` if `a` is a Z3 floating-point expression.
8825 
8826  >>> b = FP('b', FPSort(8, 24))
8827  >>> is_fp(b)
8828  True
8829  >>> is_fp(b + 1.0)
8830  True
8831  >>> is_fp(Int('x'))
8832  False
8833  """
8834  return isinstance(a, FPRef)
8835 
8836 def is_fp_value(a):
8837  """Return `True` if `a` is a Z3 floating-point numeral value.
8838 
8839  >>> b = FP('b', FPSort(8, 24))
8840  >>> is_fp_value(b)
8841  False
8842  >>> b = FPVal(1.0, FPSort(8, 24))
8843  >>> b
8844  1
8845  >>> is_fp_value(b)
8846  True
8847  """
8848  return is_fp(a) and _is_numeral(a.ctx, a.ast)
8849 
8850 def FPSort(ebits, sbits, ctx=None):
8851  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
8852 
8853  >>> Single = FPSort(8, 24)
8854  >>> Double = FPSort(11, 53)
8855  >>> Single
8856  FPSort(8, 24)
8857  >>> x = Const('x', Single)
8858  >>> eq(x, FP('x', FPSort(8, 24)))
8859  True
8860  """
8861  ctx = _get_ctx(ctx)
8862  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
8863 
8864 def _to_float_str(val, exp=0):
8865  if isinstance(val, float):
8866  if math.isnan(val):
8867  res = "NaN"
8868  elif val == 0.0:
8869  sone = math.copysign(1.0, val)
8870  if sone < 0.0:
8871  return "-0.0"
8872  else:
8873  return "+0.0"
8874  elif val == float("+inf"):
8875  res = "+oo"
8876  elif val == float("-inf"):
8877  res = "-oo"
8878  else:
8879  v = val.as_integer_ratio()
8880  num = v[0]
8881  den = v[1]
8882  rvs = str(num) + '/' + str(den)
8883  res = rvs + 'p' + _to_int_str(exp)
8884  elif isinstance(val, bool):
8885  if val:
8886  res = "1.0"
8887  else:
8888  res = "0.0"
8889  elif _is_int(val):
8890  res = str(val)
8891  elif isinstance(val, str):
8892  inx = val.find('*(2**')
8893  if inx == -1:
8894  res = val
8895  elif val[-1] == ')':
8896  res = val[0:inx]
8897  exp = str(int(val[inx+5:-1]) + int(exp))
8898  else:
8899  _z3_assert(False, "String does not have floating-point numeral form.")
8900  elif __debug__:
8901  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
8902  if exp == 0:
8903  return res
8904  else:
8905  return res + 'p' + exp
8906 
8907 
8908 def fpNaN(s):
8909  """Create a Z3 floating-point NaN term.
8910 
8911  >>> s = FPSort(8, 24)
8912  >>> set_fpa_pretty(True)
8913  >>> fpNaN(s)
8914  NaN
8915  >>> pb = get_fpa_pretty()
8916  >>> set_fpa_pretty(False)
8917  >>> fpNaN(s)
8918  fpNaN(FPSort(8, 24))
8919  >>> set_fpa_pretty(pb)
8920  """
8921  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8922  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
8923 
8924 def fpPlusInfinity(s):
8925  """Create a Z3 floating-point +oo term.
8926 
8927  >>> s = FPSort(8, 24)
8928  >>> pb = get_fpa_pretty()
8929  >>> set_fpa_pretty(True)
8930  >>> fpPlusInfinity(s)
8931  +oo
8932  >>> set_fpa_pretty(False)
8933  >>> fpPlusInfinity(s)
8934  fpPlusInfinity(FPSort(8, 24))
8935  >>> set_fpa_pretty(pb)
8936  """
8937  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8938  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
8939 
8940 def fpMinusInfinity(s):
8941  """Create a Z3 floating-point -oo term."""
8942  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8943  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
8944 
8945 def fpInfinity(s, negative):
8946  """Create a Z3 floating-point +oo or -oo term."""
8947  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8948  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
8949  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
8950 
8951 def fpPlusZero(s):
8952  """Create a Z3 floating-point +0.0 term."""
8953  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8954  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
8955 
8956 def fpMinusZero(s):
8957  """Create a Z3 floating-point -0.0 term."""
8958  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8959  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
8960 
8961 def fpZero(s, negative):
8962  """Create a Z3 floating-point +0.0 or -0.0 term."""
8963  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
8964  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
8965  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
8966 
8967 def FPVal(sig, exp=None, fps=None, ctx=None):
8968  """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
8969 
8970  >>> v = FPVal(20.0, FPSort(8, 24))
8971  >>> v
8972  1.25*(2**4)
8973  >>> print("0x%.8x" % v.exponent_as_long(False))
8974  0x00000004
8975  >>> v = FPVal(2.25, FPSort(8, 24))
8976  >>> v
8977  1.125*(2**1)
8978  >>> v = FPVal(-2.25, FPSort(8, 24))
8979  >>> v
8980  -1.125*(2**1)
8981  >>> FPVal(-0.0, FPSort(8, 24))
8982  -0.0
8983  >>> FPVal(0.0, FPSort(8, 24))
8984  +0.0
8985  >>> FPVal(+0.0, FPSort(8, 24))
8986  +0.0
8987  """
8988  ctx = _get_ctx(ctx)
8989  if is_fp_sort(exp):
8990  fps = exp
8991  exp = None
8992  elif fps is None:
8993  fps = _dflt_fps(ctx)
8994  _z3_assert(is_fp_sort(fps), "sort mismatch")
8995  if exp is None:
8996  exp = 0
8997  val = _to_float_str(sig)
8998  if val == "NaN" or val == "nan":
8999  return fpNaN(fps)
9000  elif val == "-0.0":
9001  return fpMinusZero(fps)
9002  elif val == "0.0" or val == "+0.0":
9003  return fpPlusZero(fps)
9004  elif val == "+oo" or val == "+inf" or val == "+Inf":
9005  return fpPlusInfinity(fps)
9006  elif val == "-oo" or val == "-inf" or val == "-Inf":
9007  return fpMinusInfinity(fps)
9008  else:
9009  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9010 
9011 def FP(name, fpsort, ctx=None):
9012  """Return a floating-point constant named `name`.
9013  `fpsort` is the floating-point sort.
9014  If `ctx=None`, then the global context is used.
9015 
9016  >>> x = FP('x', FPSort(8, 24))
9017  >>> is_fp(x)
9018  True
9019  >>> x.ebits()
9020  8
9021  >>> x.sort()
9022  FPSort(8, 24)
9023  >>> word = FPSort(8, 24)
9024  >>> x2 = FP('x', word)
9025  >>> eq(x, x2)
9026  True
9027  """
9028  if isinstance(fpsort, FPSortRef) and ctx is None:
9029  ctx = fpsort.ctx
9030  else:
9031  ctx = _get_ctx(ctx)
9032  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9033 
9034 def FPs(names, fpsort, ctx=None):
9035  """Return an array of floating-point constants.
9036 
9037  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9038  >>> x.sort()
9039  FPSort(8, 24)
9040  >>> x.sbits()
9041  24
9042  >>> x.ebits()
9043  8
9044  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9045  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9046  """
9047  ctx = _get_ctx(ctx)
9048  if isinstance(names, str):
9049  names = names.split(" ")
9050  return [FP(name, fpsort, ctx) for name in names]
9051 
9052 def fpAbs(a, ctx=None):
9053  """Create a Z3 floating-point absolute value expression.
9054 
9055  >>> s = FPSort(8, 24)
9056  >>> rm = RNE()
9057  >>> x = FPVal(1.0, s)
9058  >>> fpAbs(x)
9059  fpAbs(1)
9060  >>> y = FPVal(-20.0, s)
9061  >>> y
9062  -1.25*(2**4)
9063  >>> fpAbs(y)
9064  fpAbs(-1.25*(2**4))
9065  >>> fpAbs(-1.25*(2**4))
9066  fpAbs(-1.25*(2**4))
9067  >>> fpAbs(x).sort()
9068  FPSort(8, 24)
9069  """
9070  ctx = _get_ctx(ctx)
9071  [a] = _coerce_fp_expr_list([a], ctx)
9072  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9073 
9074 def fpNeg(a, ctx=None):
9075  """Create a Z3 floating-point addition expression.
9076 
9077  >>> s = FPSort(8, 24)
9078  >>> rm = RNE()
9079  >>> x = FP('x', s)
9080  >>> fpNeg(x)
9081  -x
9082  >>> fpNeg(x).sort()
9083  FPSort(8, 24)
9084  """
9085  ctx = _get_ctx(ctx)
9086  [a] = _coerce_fp_expr_list([a], ctx)
9087  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9088 
9089 def _mk_fp_unary(f, rm, a, ctx):
9090  ctx = _get_ctx(ctx)
9091  [a] = _coerce_fp_expr_list([a], ctx)
9092  if __debug__:
9093  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9094  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9095  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9096 
9097 def _mk_fp_unary_norm(f, a, ctx):
9098  ctx = _get_ctx(ctx)
9099  [a] = _coerce_fp_expr_list([a], ctx)
9100  if __debug__:
9101  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9102  return FPRef(f(ctx.ref(), a.as_ast()), ctx)
9103 
9104 def _mk_fp_unary_pred(f, a, ctx):
9105  ctx = _get_ctx(ctx)
9106  [a] = _coerce_fp_expr_list([a], ctx)
9107  if __debug__:
9108  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9109  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9110 
9111 def _mk_fp_bin(f, rm, a, b, ctx):
9112  ctx = _get_ctx(ctx)
9113  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9114  if __debug__:
9115  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9116  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9117  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9118 
9119 def _mk_fp_bin_norm(f, a, b, ctx):
9120  ctx = _get_ctx(ctx)
9121  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9122  if __debug__:
9123  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9124  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9125 
9126 def _mk_fp_bin_pred(f, a, b, ctx):
9127  ctx = _get_ctx(ctx)
9128  [a, b] = _coerce_fp_expr_list([a, b], ctx)
9129  if __debug__:
9130  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9131  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9132 
9133 def _mk_fp_tern(f, rm, a, b, c, ctx):
9134  ctx = _get_ctx(ctx)
9135  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9136  if __debug__:
9137  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9138  _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression")
9139  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9140 
9141 def fpAdd(rm, a, b, ctx=None):
9142  """Create a Z3 floating-point addition expression.
9143 
9144  >>> s = FPSort(8, 24)
9145  >>> rm = RNE()
9146  >>> x = FP('x', s)
9147  >>> y = FP('y', s)
9148  >>> fpAdd(rm, x, y)
9149  fpAdd(RNE(), x, y)
9150  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9151  x + y
9152  >>> fpAdd(rm, x, y).sort()
9153  FPSort(8, 24)
9154  """
9155  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9156 
9157 def fpSub(rm, a, b, ctx=None):
9158  """Create a Z3 floating-point subtraction expression.
9159 
9160  >>> s = FPSort(8, 24)
9161  >>> rm = RNE()
9162  >>> x = FP('x', s)
9163  >>> y = FP('y', s)
9164  >>> fpSub(rm, x, y)
9165  fpSub(RNE(), x, y)
9166  >>> fpSub(rm, x, y).sort()
9167  FPSort(8, 24)
9168  """
9169  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9170 
9171 def fpMul(rm, a, b, ctx=None):
9172  """Create a Z3 floating-point multiplication expression.
9173 
9174  >>> s = FPSort(8, 24)
9175  >>> rm = RNE()
9176  >>> x = FP('x', s)
9177  >>> y = FP('y', s)
9178  >>> fpMul(rm, x, y)
9179  fpMul(RNE(), x, y)
9180  >>> fpMul(rm, x, y).sort()
9181  FPSort(8, 24)
9182  """
9183  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9184 
9185 def fpDiv(rm, a, b, ctx=None):
9186  """Create a Z3 floating-point divison expression.
9187 
9188  >>> s = FPSort(8, 24)
9189  >>> rm = RNE()
9190  >>> x = FP('x', s)
9191  >>> y = FP('y', s)
9192  >>> fpDiv(rm, x, y)
9193  fpDiv(RNE(), x, y)
9194  >>> fpDiv(rm, x, y).sort()
9195  FPSort(8, 24)
9196  """
9197  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9198 
9199 def fpRem(a, b, ctx=None):
9200  """Create a Z3 floating-point remainder expression.
9201 
9202  >>> s = FPSort(8, 24)
9203  >>> x = FP('x', s)
9204  >>> y = FP('y', s)
9205  >>> fpRem(x, y)
9206  fpRem(x, y)
9207  >>> fpRem(x, y).sort()
9208  FPSort(8, 24)
9209  """
9210  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9211 
9212 def fpMin(a, b, ctx=None):
9213  """Create a Z3 floating-point minimium expression.
9214 
9215  >>> s = FPSort(8, 24)
9216  >>> rm = RNE()
9217  >>> x = FP('x', s)
9218  >>> y = FP('y', s)
9219  >>> fpMin(x, y)
9220  fpMin(x, y)
9221  >>> fpMin(x, y).sort()
9222  FPSort(8, 24)
9223  """
9224  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9225 
9226 def fpMax(a, b, ctx=None):
9227  """Create a Z3 floating-point maximum expression.
9228 
9229  >>> s = FPSort(8, 24)
9230  >>> rm = RNE()
9231  >>> x = FP('x', s)
9232  >>> y = FP('y', s)
9233  >>> fpMax(x, y)
9234  fpMax(x, y)
9235  >>> fpMax(x, y).sort()
9236  FPSort(8, 24)
9237  """
9238  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9239 
9240 def fpFMA(rm, a, b, c, ctx=None):
9241  """Create a Z3 floating-point fused multiply-add expression.
9242  """
9243  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9244 
9245 def fpSqrt(rm, a, ctx=None):
9246  """Create a Z3 floating-point square root expression.
9247  """
9248  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9249 
9250 def fpRoundToIntegral(rm, a, ctx=None):
9251  """Create a Z3 floating-point roundToIntegral expression.
9252  """
9253  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9254 
9255 def fpIsNaN(a, ctx=None):
9256  """Create a Z3 floating-point isNaN expression.
9257 
9258  >>> s = FPSort(8, 24)
9259  >>> x = FP('x', s)
9260  >>> y = FP('y', s)
9261  >>> fpIsNaN(x)
9262  fpIsNaN(x)
9263  """
9264  return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
9265 
9266 def fpIsInf(a, ctx=None):
9267  """Create a Z3 floating-point isInfinite expression.
9268 
9269  >>> s = FPSort(8, 24)
9270  >>> x = FP('x', s)
9271  >>> fpIsInf(x)
9272  fpIsInf(x)
9273  """
9274  return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
9275 
9276 def fpIsZero(a, ctx=None):
9277  """Create a Z3 floating-point isZero expression.
9278  """
9279  return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
9280 
9281 def fpIsNormal(a, ctx=None):
9282  """Create a Z3 floating-point isNormal expression.
9283  """
9284  return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
9285 
9286 def fpIsSubnormal(a, ctx=None):
9287  """Create a Z3 floating-point isSubnormal expression.
9288  """
9289  return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
9290 
9291 def fpIsNegative(a, ctx=None):
9292  """Create a Z3 floating-point isNegative expression.
9293  """
9294  return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
9295 
9296 def fpIsPositive(a, ctx=None):
9297  """Create a Z3 floating-point isPositive expression.
9298  """
9299  return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
9300  return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
9301 
9302 def _check_fp_args(a, b):
9303  if __debug__:
9304  _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9305 
9306 def fpLT(a, b, ctx=None):
9307  """Create the Z3 floating-point expression `other < self`.
9308 
9309  >>> x, y = FPs('x y', FPSort(8, 24))
9310  >>> fpLT(x, y)
9311  x < y
9312  >>> (x < y).sexpr()
9313  '(fp.lt x y)'
9314  """
9315  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9316 
9317 def fpLEQ(a, b, ctx=None):
9318  """Create the Z3 floating-point expression `other <= self`.
9319 
9320  >>> x, y = FPs('x y', FPSort(8, 24))
9321  >>> fpLEQ(x, y)
9322  x <= y
9323  >>> (x <= y).sexpr()
9324  '(fp.leq x y)'
9325  """
9326  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9327 
9328 def fpGT(a, b, ctx=None):
9329  """Create the Z3 floating-point expression `other > self`.
9330 
9331  >>> x, y = FPs('x y', FPSort(8, 24))
9332  >>> fpGT(x, y)
9333  x > y
9334  >>> (x > y).sexpr()
9335  '(fp.gt x y)'
9336  """
9337  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9338 
9339 def fpGEQ(a, b, ctx=None):
9340  """Create the Z3 floating-point expression `other >= self`.
9341 
9342  >>> x, y = FPs('x y', FPSort(8, 24))
9343  >>> fpGEQ(x, y)
9344  x >= y
9345  >>> (x >= y).sexpr()
9346  '(fp.geq x y)'
9347  """
9348  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9349 
9350 def fpEQ(a, b, ctx=None):
9351  """Create the Z3 floating-point expression `fpEQ(other, self)`.
9352 
9353  >>> x, y = FPs('x y', FPSort(8, 24))
9354  >>> fpEQ(x, y)
9355  fpEQ(x, y)
9356  >>> fpEQ(x, y).sexpr()
9357  '(fp.eq x y)'
9358  """
9359  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9360 
9361 def fpNEQ(a, b, ctx=None):
9362  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9363 
9364  >>> x, y = FPs('x y', FPSort(8, 24))
9365  >>> fpNEQ(x, y)
9366  Not(fpEQ(x, y))
9367  >>> (x != y).sexpr()
9368  '(distinct x y)'
9369  """
9370  return Not(fpEQ(a, b, ctx))
9371 
9372 def fpFP(sgn, exp, sig, ctx=None):
9373  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9374 
9375  >>> s = FPSort(8, 24)
9376  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9377  >>> print(x)
9378  fpFP(1, 127, 4194304)
9379  >>> xv = FPVal(-1.5, s)
9380  >>> print(xv)
9381  -1.5
9382  >>> slvr = Solver()
9383  >>> slvr.add(fpEQ(x, xv))
9384  >>> slvr.check()
9385  sat
9386  >>> xv = FPVal(+1.5, s)
9387  >>> print(xv)
9388  1.5
9389  >>> slvr = Solver()
9390  >>> slvr.add(fpEQ(x, xv))
9391  >>> slvr.check()
9392  unsat
9393  """
9394  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9395  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9396  ctx = _get_ctx(ctx)
9397  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9398  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9399 
9400 def fpToFP(a1, a2=None, a3=None, ctx=None):
9401  """Create a Z3 floating-point conversion expression from other term sorts
9402  to floating-point.
9403 
9404  From a bit-vector term in IEEE 754-2008 format:
9405  >>> x = FPVal(1.0, Float32())
9406  >>> x_bv = fpToIEEEBV(x)
9407  >>> simplify(fpToFP(x_bv, Float32()))
9408  1
9409 
9410  From a floating-point term with different precision:
9411  >>> x = FPVal(1.0, Float32())
9412  >>> x_db = fpToFP(RNE(), x, Float64())
9413  >>> x_db.sort()
9414  FPSort(11, 53)
9415 
9416  From a real term:
9417  >>> x_r = RealVal(1.5)
9418  >>> simplify(fpToFP(RNE(), x_r, Float32()))
9419  1.5
9420 
9421  From a signed bit-vector term:
9422  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9423  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9424  -1.25*(2**2)
9425  """
9426  ctx = _get_ctx(ctx)
9427  if is_bv(a1) and is_fp_sort(a2):
9428  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9429  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9430  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9431  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9432  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9433  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9434  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9435  else:
9436  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9437 
9438 def fpBVToFP(v, sort, ctx=None):
9439  """Create a Z3 floating-point conversion expression that represents the
9440  conversion from a bit-vector term to a floating-point term.
9441 
9442  >>> x_bv = BitVecVal(0x3F800000, 32)
9443  >>> x_fp = fpBVToFP(x_bv, Float32())
9444  >>> x_fp
9445  fpToFP(1065353216)
9446  >>> simplify(x_fp)
9447  1
9448  """
9449  _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9450  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9451  ctx = _get_ctx(ctx)
9452  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9453 
9454 def fpFPToFP(rm, v, sort, ctx=None):
9455  """Create a Z3 floating-point conversion expression that represents the
9456  conversion from a floating-point term to a floating-point term of different precision.
9457 
9458  >>> x_sgl = FPVal(1.0, Float32())
9459  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9460  >>> x_dbl
9461  fpToFP(RNE(), 1)
9462  >>> simplify(x_dbl)
9463  1
9464  >>> x_dbl.sort()
9465  FPSort(11, 53)
9466  """
9467  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9468  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9469  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9470  ctx = _get_ctx(ctx)
9471  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9472 
9473 def fpRealToFP(rm, v, sort, ctx=None):
9474  """Create a Z3 floating-point conversion expression that represents the
9475  conversion from a real term to a floating-point term.
9476 
9477  >>> x_r = RealVal(1.5)
9478  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9479  >>> x_fp
9480  fpToFP(RNE(), 3/2)
9481  >>> simplify(x_fp)
9482  1.5
9483  """
9484  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9485  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9486  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9487  ctx = _get_ctx(ctx)
9488  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9489 
9490 def fpSignedToFP(rm, v, sort, ctx=None):
9491  """Create a Z3 floating-point conversion expression that represents the
9492  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9493 
9494  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9495  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9496  >>> x_fp
9497  fpToFP(RNE(), 4294967291)
9498  >>> simplify(x_fp)
9499  -1.25*(2**2)
9500  """
9501  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9502  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9503  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9504  ctx = _get_ctx(ctx)
9505  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9506 
9507 def fpUnsignedToFP(rm, v, sort, ctx=None):
9508  """Create a Z3 floating-point conversion expression that represents the
9509  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9510 
9511  >>> x_signed = BitVecVal(-5, BitVecSort(32))
9512  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9513  >>> x_fp
9514  fpToFPUnsigned(RNE(), 4294967291)
9515  >>> simplify(x_fp)
9516  1*(2**32)
9517  """
9518  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9519  _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9520  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9521  ctx = _get_ctx(ctx)
9522  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9523 
9524 def fpToFPUnsigned(rm, x, s, ctx=None):
9525  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9526  if __debug__:
9527  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9528  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9529  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9530  ctx = _get_ctx(ctx)
9531  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9532 
9533 def fpToSBV(rm, x, s, ctx=None):
9534  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9535 
9536  >>> x = FP('x', FPSort(8, 24))
9537  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9538  >>> print(is_fp(x))
9539  True
9540  >>> print(is_bv(y))
9541  True
9542  >>> print(is_fp(y))
9543  False
9544  >>> print(is_bv(x))
9545  False
9546  """
9547  if __debug__:
9548  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9549  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9550  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9551  ctx = _get_ctx(ctx)
9552  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9553 
9554 def fpToUBV(rm, x, s, ctx=None):
9555  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9556 
9557  >>> x = FP('x', FPSort(8, 24))
9558  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9559  >>> print(is_fp(x))
9560  True
9561  >>> print(is_bv(y))
9562  True
9563  >>> print(is_fp(y))
9564  False
9565  >>> print(is_bv(x))
9566  False
9567  """
9568  if __debug__:
9569  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9570  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9571  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9572  ctx = _get_ctx(ctx)
9573  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9574 
9575 def fpToReal(x, ctx=None):
9576  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9577 
9578  >>> x = FP('x', FPSort(8, 24))
9579  >>> y = fpToReal(x)
9580  >>> print(is_fp(x))
9581  True
9582  >>> print(is_real(y))
9583  True
9584  >>> print(is_fp(y))
9585  False
9586  >>> print(is_real(x))
9587  False
9588  """
9589  if __debug__:
9590  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9591  ctx = _get_ctx(ctx)
9592  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9593 
9594 def fpToIEEEBV(x, ctx=None):
9595  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9596 
9597  The size of the resulting bit-vector is automatically determined.
9598 
9599  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9600  knows only one NaN and it will always produce the same bit-vector represenatation of
9601  that NaN.
9602 
9603  >>> x = FP('x', FPSort(8, 24))
9604  >>> y = fpToIEEEBV(x)
9605  >>> print(is_fp(x))
9606  True
9607  >>> print(is_bv(y))
9608  True
9609  >>> print(is_fp(y))
9610  False
9611  >>> print(is_bv(x))
9612  False
9613  """
9614  if __debug__:
9615  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9616  ctx = _get_ctx(ctx)
9617  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9618 
9619 
9620 
9621 #########################################
9622 #
9623 # Strings, Sequences and Regular expressions
9624 #
9625 #########################################
9626 
9627 class SeqSortRef(SortRef):
9628  """Sequence sort."""
9629 
9630  def is_string(self):
9631  """Determine if sort is a string
9632  >>> s = StringSort()
9633  >>> s.is_string()
9634  True
9635  >>> s = SeqSort(IntSort())
9636  >>> s.is_string()
9637  False
9638  """
9639  return Z3_is_string_sort(self.ctx_ref(), self.ast)
9640 
9641 
9642 def StringSort(ctx=None):
9643  """Create a string sort
9644  >>> s = StringSort()
9645  >>> print(s)
9646  String
9647  """
9648  ctx = _get_ctx(ctx)
9649  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9650 
9651 
9652 def SeqSort(s):
9653  """Create a sequence sort over elements provided in the argument
9654  >>> s = SeqSort(IntSort())
9655  >>> s == Unit(IntVal(1)).sort()
9656  True
9657  """
9658  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9659 
9660 class SeqRef(ExprRef):
9661  """Sequence expression."""
9662 
9663  def sort(self):
9664  return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
9665 
9666  def __add__(self, other):
9667  return Concat(self, other)
9668 
9669  def __radd__(self, other):
9670  return Concat(other, self)
9671 
9672  def __getitem__(self, i):
9673  if _is_int(i):
9674  i = IntVal(i, self.ctx)
9675  return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
9676 
9677  def is_string(self):
9678  return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
9679 
9680  def is_string_value(self):
9681  return Z3_is_string(self.ctx_ref(), self.as_ast())
9682 
9683  def as_string(self):
9684  """Return a string representation of sequence expression."""
9685  return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
9686 
9687 
9688 def _coerce_seq(s, ctx=None):
9689  if isinstance(s, str):
9690  ctx = _get_ctx(ctx)
9691  s = StringVal(s, ctx)
9692  if not is_expr(s):
9693  raise Z3Exception("Non-expression passed as a sequence")
9694  if not is_seq(s):
9695  raise Z3Exception("Non-sequence passed as a sequence")
9696  return s
9697 
9698 def _get_ctx2(a, b, ctx=None):
9699  if is_expr(a):
9700  return a.ctx
9701  if is_expr(b):
9702  return b.ctx
9703  if ctx is None:
9704  ctx = main_ctx()
9705  return ctx
9706 
9707 def is_seq(a):
9708  """Return `True` if `a` is a Z3 sequence expression.
9709  >>> print (is_seq(Unit(IntVal(0))))
9710  True
9711  >>> print (is_seq(StringVal("abc")))
9712  True
9713  """
9714  return isinstance(a, SeqRef)
9715 
9716 def is_string(a):
9717  """Return `True` if `a` is a Z3 string expression.
9718  >>> print (is_string(StringVal("ab")))
9719  True
9720  """
9721  return isinstance(a, SeqRef) and a.is_string()
9722 
9723 def is_string_value(a):
9724  """return 'True' if 'a' is a Z3 string constant expression.
9725  >>> print (is_string_value(StringVal("a")))
9726  True
9727  >>> print (is_string_value(StringVal("a") + StringVal("b")))
9728  False
9729  """
9730  return isinstance(a, SeqRef) and a.is_string_value()
9731 
9732 
9733 def StringVal(s, ctx=None):
9734  """create a string expression"""
9735  ctx = _get_ctx(ctx)
9736  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
9737 
9738 def String(name, ctx=None):
9739  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
9740 
9741  >>> x = String('x')
9742  """
9743  ctx = _get_ctx(ctx)
9744  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
9745 
9746 def Strings(names, ctx=None):
9747  """Return a tuple of String constants. """
9748  ctx = _get_ctx(ctx)
9749  if isinstance(names, str):
9750  names = names.split(" ")
9751  return [String(name, ctx) for name in names]
9752 
9753 def Empty(s):
9754  """Create the empty sequence of the given sort
9755  >>> e = Empty(StringSort())
9756  >>> print(e)
9757  ""
9758  >>> e2 = StringVal("")
9759  >>> print(e.eq(e2))
9760  True
9761  >>> e3 = Empty(SeqSort(IntSort()))
9762  >>> print(e3)
9763  seq.empty
9764  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
9765  >>> print(e4)
9766  re.empty
9767  """
9768  if isinstance(s, SeqSortRef):
9769  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
9770  if isinstance(s, ReSortRef):
9771  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
9772  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
9773 
9774 def Full(s):
9775  """Create the regular expression that accepts the universal langauge
9776  >>> e = Full(ReSort(SeqSort(IntSort())))
9777  >>> print(e)
9778  re.all
9779  >>> e1 = Full(ReSort(StringSort()))
9780  >>> print(e1)
9781  re.allchar
9782  """
9783  if isinstance(s, ReSortRef):
9784  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
9785  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
9786 
9787 
9788 def Unit(a):
9789  """Create a singleton sequence"""
9790  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
9791 
9792 def PrefixOf(a, b):
9793  """Check if 'a' is a prefix of 'b'
9794  >>> s1 = PrefixOf("ab", "abc")
9795  >>> simplify(s1)
9796  True
9797  >>> s2 = PrefixOf("bc", "abc")
9798  >>> simplify(s2)
9799  False
9800  """
9801  ctx = _get_ctx2(a, b)
9802  a = _coerce_seq(a, ctx)
9803  b = _coerce_seq(b, ctx)
9804  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9805 
9806 def SuffixOf(a, b):
9807  """Check if 'a' is a suffix of 'b'
9808  >>> s1 = SuffixOf("ab", "abc")
9809  >>> simplify(s1)
9810  False
9811  >>> s2 = SuffixOf("bc", "abc")
9812  >>> simplify(s2)
9813  True
9814  """
9815  ctx = _get_ctx2(a, b)
9816  a = _coerce_seq(a, ctx)
9817  b = _coerce_seq(b, ctx)
9818  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9819 
9820 def Contains(a, b):
9821  """Check if 'a' contains 'b'
9822  >>> s1 = Contains("abc", "ab")
9823  >>> simplify(s1)
9824  True
9825  >>> s2 = Contains("abc", "bc")
9826  >>> simplify(s2)
9827  True
9828  >>> x, y, z = Strings('x y z')
9829  >>> s3 = Contains(Concat(x,y,z), y)
9830  >>> simplify(s3)
9831  True
9832  """
9833  ctx = _get_ctx2(a, b)
9834  a = _coerce_seq(a, ctx)
9835  b = _coerce_seq(b, ctx)
9836  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
9837 
9838 
9839 def Replace(s, src, dst):
9840  """Replace the first occurrence of 'src' by 'dst' in 's'
9841  >>> r = Replace("aaa", "a", "b")
9842  >>> simplify(r)
9843  "baa"
9844  """
9845  ctx = _get_ctx2(dst, s)
9846  if ctx is None and is_expr(src):
9847  ctx = src.ctx
9848  src = _coerce_seq(src, ctx)
9849  dst = _coerce_seq(dst, ctx)
9850  s = _coerce_seq(s, ctx)
9851  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
9852 
9853 def IndexOf(s, substr):
9854  return IndexOf(s, substr, IntVal(0))
9855 
9856 def IndexOf(s, substr, offset):
9857  """Retrieve the index of substring within a string starting at a specified offset.
9858  >>> simplify(IndexOf("abcabc", "bc", 0))
9859  1
9860  >>> simplify(IndexOf("abcabc", "bc", 2))
9861  4
9862  """
9863  ctx = None
9864  if is_expr(offset):
9865  ctx = offset.ctx
9866  ctx = _get_ctx2(s, substr, ctx)
9867  s = _coerce_seq(s, ctx)
9868  substr = _coerce_seq(substr, ctx)
9869  if _is_int(offset):
9870  offset = IntVal(offset, ctx)
9871  return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
9872 
9873 def Length(s):
9874  """Obtain the length of a sequence 's'
9875  >>> l = Length(StringVal("abc"))
9876  >>> simplify(l)
9877  3
9878  """
9879  s = _coerce_seq(s)
9880  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
9881 
9882 def StrToInt(s):
9883  """Convert string expression to integer
9884  >>> a = StrToInt("1")
9885  >>> simplify(1 == a)
9886  True
9887  >>> b = StrToInt("2")
9888  >>> simplify(1 == b)
9889  False
9890  >>> c = StrToInt(IntToStr(2))
9891  >>> simplify(1 == c)
9892  False
9893  """
9894  s = _coerce_seq(s)
9895  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
9896 
9897 
9898 def IntToStr(s):
9899  """Convert integer expression to string"""
9900  if not is_expr(s):
9901  s = _py2expr(s)
9902  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
9903 
9904 
9905 def Re(s, ctx=None):
9906  """The regular expression that accepts sequence 's'
9907  >>> s1 = Re("ab")
9908  >>> s2 = Re(StringVal("ab"))
9909  >>> s3 = Re(Unit(BoolVal(True)))
9910  """
9911  s = _coerce_seq(s, ctx)
9912  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
9913 
9914 
9915 
9916 
9917 ## Regular expressions
9918 
9919 class ReSortRef(SortRef):
9920  """Regular expression sort."""
9921 
9922 
9923 def ReSort(s):
9924  if is_ast(s):
9925  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
9926  if s is None or isinstance(s, Context):
9927  ctx = _get_ctx(s)
9928  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
9929  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
9930 
9931 
9932 class ReRef(ExprRef):
9933  """Regular expressions."""
9934 
9935  def __add__(self, other):
9936  return Union(self, other)
9937 
9938 
9939 def is_re(s):
9940  return isinstance(s, ReRef)
9941 
9942 
9943 def InRe(s, re):
9944  """Create regular expression membership test
9945  >>> re = Union(Re("a"),Re("b"))
9946  >>> print (simplify(InRe("a", re)))
9947  True
9948  >>> print (simplify(InRe("b", re)))
9949  True
9950  >>> print (simplify(InRe("c", re)))
9951  False
9952  """
9953  s = _coerce_seq(s, re.ctx)
9954  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
9955 
9956 def Union(*args):
9957  """Create union of regular expressions.
9958  >>> re = Union(Re("a"), Re("b"), Re("c"))
9959  >>> print (simplify(InRe("d", re)))
9960  False
9961  """
9962  args = _get_args(args)
9963  sz = len(args)
9964  if __debug__:
9965  _z3_assert(sz > 0, "At least one argument expected.")
9966  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
9967  if sz == 1:
9968  return args[0]
9969  ctx = args[0].ctx
9970  v = (Ast * sz)()
9971  for i in range(sz):
9972  v[i] = args[i].as_ast()
9973  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
9974 
9975 def Plus(re):
9976  """Create the regular expression accepting one or more repetitions of argument.
9977  >>> re = Plus(Re("a"))
9978  >>> print(simplify(InRe("aa", re)))
9979  True
9980  >>> print(simplify(InRe("ab", re)))
9981  False
9982  >>> print(simplify(InRe("", re)))
9983  False
9984  """
9985  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
9986 
9987 def Option(re):
9988  """Create the regular expression that optionally accepts the argument.
9989  >>> re = Option(Re("a"))
9990  >>> print(simplify(InRe("a", re)))
9991  True
9992  >>> print(simplify(InRe("", re)))
9993  True
9994  >>> print(simplify(InRe("aa", re)))
9995  False
9996  """
9997  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
9998 
9999 def Complement(re):
10000  """Create the complement regular expression."""
10001  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10002 
10003 def Star(re):
10004  """Create the regular expression accepting zero or more repetitions of argument.
10005  >>> re = Star(Re("a"))
10006  >>> print(simplify(InRe("aa", re)))
10007  True
10008  >>> print(simplify(InRe("ab", re)))
10009  False
10010  >>> print(simplify(InRe("", re)))
10011  True
10012  """
10013  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10014 
10015 def Loop(re, lo, hi=0):
10016  """Create the regular expression accepting between a lower and upper bound repetitions
10017  >>> re = Loop(Re("a"), 1, 3)
10018  >>> print(simplify(InRe("aa", re)))
10019  True
10020  >>> print(simplify(InRe("aaaa", re)))
10021  False
10022  >>> print(simplify(InRe("", re)))
10023  False
10024  """
10025  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
def param_descrs(self)
Definition: z3py.py:6928
def value(self)
Definition: z3py.py:6893
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
def lower(self, obj)
Definition: z3py.py:7000
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
def name(self)
Definition: z3py.py:638
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9594
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
def is_lt(a)
Definition: z3py.py:2519
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
def simplify(a, arguments, keywords)
Utils.
Definition: z3py.py:7712
def __ge__(self, other)
Definition: z3py.py:7524
Z3_bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:2936
def is_distinct(a)
Definition: z3py.py:1424
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
def __gt__(self, other)
Definition: z3py.py:7498
def Then(ts, ks)
Definition: z3py.py:7309
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def PbEq(args, k)
Definition: z3py.py:7909
def SignExt(n, a)
Definition: z3py.py:3905
def update_rule(self, head, body, name)
Definition: z3py.py:6623
def SeqSort(s)
Definition: z3py.py:9652
Fixedpoint.
Definition: z3py.py:6481
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
def upper(self)
Definition: z3py.py:6881
def OrElse(ts, ks)
Definition: z3py.py:7321
def is_fprm_sort(s)
Definition: z3py.py:8452
def get_version_string()
Definition: z3py.py:68
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
Quantifiers.
Definition: z3py.py:1714
def AtLeast(args)
Definition: z3py.py:7858
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:4744
def entry(self, idx)
Definition: z3py.py:5529
def get_cover_delta(self, level, predicate)
Definition: z3py.py:6658
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def upper_values(self, obj)
Definition: z3py.py:7015
def RatVal(a, b, ctx=None)
Definition: z3py.py:2822
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].
def add(self, args)
Definition: z3py.py:6942
def __getitem__(self, idx)
Definition: z3py.py:7098
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Function Declarations.
Definition: z3py.py:622
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:2923
Booleans.
Definition: z3py.py:1283
def Product(args)
Definition: z3py.py:7816
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def prec(self)
Definition: z3py.py:4881
def IsInt(a)
Definition: z3py.py:2983
def Sum(args)
Definition: z3py.py:7790
def __repr__(self)
Definition: z3py.py:292
def is_arith_sort(s)
Definition: z3py.py:2021
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
Z3_bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
def ReSort(s)
Definition: z3py.py:9923
def push(self)
Definition: z3py.py:6615
def Function(name, sig)
Definition: z3py.py:760
def RTZ(ctx=None)
Definition: z3py.py:8686
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
def as_ast(self)
Definition: z3py.py:801
def __iadd__(self, fml)
Definition: z3py.py:6946
def RealSort(ctx=None)
Definition: z3py.py:2762
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:2813
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9438
Z3_model Z3_API Z3_apply_result_convert_model(Z3_context c, Z3_apply_result r, unsigned i, Z3_model m)
Convert a model for the subgoal Z3_apply_result_get_subgoal(c, r, i) into a model for the original go...
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o)
Check consistency and produce optimal values.
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9034
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:8967
def get_rules(self)
Definition: z3py.py:6697
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
def RealVarVector(n, ctx=None)
Definition: z3py.py:1266
def sort(self)
Definition: z3py.py:6788
def AndThen(ts, ks)
Definition: z3py.py:7290
def ZeroExt(n, a)
Definition: z3py.py:3934
def assertions(self)
Definition: z3py.py:7034
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def substitute_vars(t, m)
Definition: z3py.py:7770
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
def is_int(self)
Definition: z3py.py:1967
def Var(idx, s)
Definition: z3py.py:1244
def __del__(self)
Definition: z3py.py:7481
def is_bool(self)
Definition: z3py.py:1313
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def probes(ctx=None)
Definition: z3py.py:7608
def to_symbol(s, ctx=None)
Definition: z3py.py:101
def help(self)
Definition: z3py.py:6391
def reset_params()
Definition: z3py.py:241
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def declare(self, name, args)
Definition: z3py.py:4422
def is_string_value(a)
Definition: z3py.py:9723
def as_ast(self)
Definition: z3py.py:323
def assert_exprs(self, args)
Definition: z3py.py:6932
def LShR(a, b)
Definition: z3py.py:3844
def is_default(a)
Definition: z3py.py:4174
def set_option(args, kws)
Definition: z3py.py:246
Z3_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs. The result is the new AST. The arrays from and to must have size num_exprs. For every i smaller than num_exprs, we must have that sort of from[i] must be equal to sort of to[i].
Bit-Vectors.
Definition: z3py.py:3029
def Consts(names, sort)
Definition: z3py.py:1230
def use_pp(self)
Definition: z3py.py:272
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
def IntVal(val, ctx=None)
Definition: z3py.py:2793
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
def __nonzero__(self)
Definition: z3py.py:301
def is_and(a)
Definition: z3py.py:1382
def ref(self)
Definition: z3py.py:177
def push(self)
Definition: z3py.py:6059
def fpGT(a, b, ctx=None)
Definition: z3py.py:9328
def sort(self)
Definition: z3py.py:1319
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8106
def ULT(a, b)
Definition: z3py.py:3733
def fpIsInf(a, ctx=None)
Definition: z3py.py:9266
Arithmetic.
Definition: z3py.py:1950
FP Expressions.
Definition: z3py.py:8464
def __init__(self, ctx=None)
Definition: z3py.py:6906
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
def minimize(self, arg)
Definition: z3py.py:6973
def help(self)
Definition: z3py.py:6924
def sort(self)
Definition: z3py.py:2039
Z3_bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
def is_to_real(a)
Definition: z3py.py:2563
def as_ast(self)
Definition: z3py.py:478
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9400
def assert_exprs(self, args)
Definition: z3py.py:6516
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
def Float64(ctx=None)
Definition: z3py.py:8418
def param_descrs(self)
Definition: z3py.py:6512
def is_select(a)
Definition: z3py.py:4346
def is_real(self)
Definition: z3py.py:2063
Z3_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
def is_int(self)
Definition: z3py.py:2049
ASTs base class.
Definition: z3py.py:270
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
def __ne__(self, other)
Definition: z3py.py:851
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9507
def is_gt(a)
Definition: z3py.py:2541
def lower_values(self, obj)
Definition: z3py.py:7010
def pop(self)
Definition: z3py.py:6981
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
def sexpr(self)
Definition: z3py.py:7118
def set_param(args, kws)
Definition: z3py.py:218
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
def __eq__(self, other)
Definition: z3py.py:830
def domain(self, i)
Definition: z3py.py:658
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
def as_string(self)
Definition: z3py.py:6792
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:1923
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
def Loop(re, lo, hi=0)
Definition: z3py.py:10015
def AtMost(args)
Definition: z3py.py:7841
def __deepcopy__(self, memo={})
Definition: z3py.py:7072
def register_relation(self, relations)
Definition: z3py.py:6667
def IndexOf(s, substr)
Definition: z3py.py:9853
def is_app(a)
Definition: z3py.py:1055
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9554
def __len__(self)
Definition: z3py.py:7079
def StringSort(ctx=None)
Definition: z3py.py:9642
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
def And(args)
Definition: z3py.py:1578
def open_log(fname)
Definition: z3py.py:93
def __deepcopy__(self, memo={})
Definition: z3py.py:7203
def solver(self)
Definition: z3py.py:7210
def PrefixOf(a, b)
Definition: z3py.py:9792
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9339
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def rule(self, head, body=None, name=None)
Definition: z3py.py:6569
def range(self)
Definition: z3py.py:4096
def __repr__(self)
Definition: z3py.py:7115
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
def fpRem(a, b, ctx=None)
Definition: z3py.py:9199
def Cbrt(a, ctx=None)
Definition: z3py.py:3011
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
def disable_trace(msg)
Definition: z3py.py:65
def RotateRight(a, b)
Definition: z3py.py:3890
def sort(self)
Definition: z3py.py:3074
def is_ge(a)
Definition: z3py.py:2530
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
def is_K(a)
Definition: z3py.py:4147
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
def sort_kind(self)
Definition: z3py.py:819
def tactics(ctx=None)
Definition: z3py.py:7417
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Brujin bound variable.
def is_const(a)
Definition: z3py.py:1080
def Star(re)
Definition: z3py.py:10003
def InRe(s, re)
Definition: z3py.py:9943
def is_finite_domain_sort(s)
Definition: z3py.py:6774
def push(self)
Definition: z3py.py:6977
def z3_error_handler(c, e)
Definition: z3py.py:137
def RotateLeft(a, b)
Definition: z3py.py:3875
def Const(name, sort)
Definition: z3py.py:1219
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1496
def substitute(t, m)
Definition: z3py.py:7744
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
def Array(name, dom, rng)
Definition: z3py.py:4220
def main_ctx()
Definition: z3py.py:192
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def If(a, b, c, ctx=None)
Definition: z3py.py:1166
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3585
def get_id(self)
Definition: z3py.py:632
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
def is_array(a)
Definition: z3py.py:4122
def is_pattern(a)
Definition: z3py.py:1658
Statistics.
Definition: z3py.py:5853
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:7696
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
def is_fp_value(a)
Definition: z3py.py:8836
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
def help_simplify()
Definition: z3py.py:7736
def fpMax(a, b, ctx=None)
Definition: z3py.py:9226
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
def upper(self, obj)
Definition: z3py.py:7005
def get_rule_names_along_trace(self)
Definition: z3py.py:6646
def Int(name, ctx=None)
Definition: z3py.py:2849
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6484
def __repr__(self)
Definition: z3py.py:7042
def __repr__(self)
Definition: z3py.py:6705
Arrays.
Definition: z3py.py:4054
def simplify_param_descrs()
Definition: z3py.py:7740
def is_map(a)
Definition: z3py.py:4159
def is_or(a)
Definition: z3py.py:1393
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9524
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9171
Patterns.
Definition: z3py.py:1647
def fpAbs(a, ctx=None)
Definition: z3py.py:9052
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9350
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3601
def is_int_value(a)
Definition: z3py.py:2380
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
def __hash__(self)
Definition: z3py.py:557
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expresson value associated with an expression parameter.
def Default(a)
Definition: z3py.py:4254
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:6767
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
def CreateDatatypes(ds)
Definition: z3py.py:4479
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
def URem(a, b)
Definition: z3py.py:3804
def PbGe(args, k)
Definition: z3py.py:7900
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def binary_interpolant(a, b, p=None, ctx=None)
Definition: z3py.py:8221
def Union(args)
Definition: z3py.py:9956
def SuffixOf(a, b)
Definition: z3py.py:9806
def __eq__(self, other)
Definition: z3py.py:295
def __mul__(self, other)
Definition: z3py.py:1325
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9490
def is_mod(a)
Definition: z3py.py:2497
def fact(self, head, name=None)
Definition: z3py.py:6573
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, __uint64 size)
Create a named finite domain sort.
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
def UGE(a, b)
Definition: z3py.py:3750
def Replace(s, src, dst)
Definition: z3py.py:9839
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs...
def Real(name, ctx=None)
Definition: z3py.py:2897
def __init__(self, args, kws)
Definition: z3py.py:153
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective.
def lower_values(self)
Definition: z3py.py:6885
def cast(self, val)
Definition: z3py.py:508
def Length(s)
Definition: z3py.py:9873
def decl(self)
Definition: z3py.py:872
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7373
def Bools(names, ctx=None)
Definition: z3py.py:1481
def is_eq(a)
Definition: z3py.py:1415
def __del__(self)
Definition: z3py.py:172
def Float32(ctx=None)
Definition: z3py.py:8408
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9255
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
def statistics(self)
Definition: z3py.py:7051
def depth(self)
Definition: z3py.py:4846
def __str__(self)
Definition: z3py.py:6899
def sort(self)
Definition: z3py.py:807
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def is_real(a)
Definition: z3py.py:2356
def RealVal(val, ctx=None)
Definition: z3py.py:2804
def PbLe(args, k)
Definition: z3py.py:7891
def get_id(self)
Definition: z3py.py:804
def Extract(high, low, a)
Definition: z3py.py:3689
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def RealVar(idx, ctx=None)
Definition: z3py.py:1256
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:1904
def solve_using(s, args, keywords)
Definition: z3py.py:7947
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def set_predicate_representation(self, f, representations)
Definition: z3py.py:6673
def maximize(self, arg)
Definition: z3py.py:6969
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
def eq(a, b)
Definition: z3py.py:398
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def help(self)
Definition: z3py.py:7254
def __bool__(self)
Definition: z3py.py:304
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:6950
def sexpr(self)
Definition: z3py.py:7046
def is_le(a)
Definition: z3py.py:2508
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def __deepcopy__(self, memo={})
Definition: z3py.py:286
def is_not(a)
Definition: z3py.py:1404
def get_map_func(a)
Definition: z3py.py:4182
def Implies(a, b, ctx=None)
Definition: z3py.py:1523
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7189
def __deepcopy__(self, memo={})
Definition: z3py.py:6911
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def apply(self, goal, arguments, keywords)
Definition: z3py.py:7227
def solve(args, keywords)
Definition: z3py.py:7919
def is_arith(a)
Definition: z3py.py:2318
def __del__(self)
Definition: z3py.py:7206
def is_sort(s)
Definition: z3py.py:561
def objectives(self)
Definition: z3py.py:7038
def Or(args)
Definition: z3py.py:1611
def __init__(self, opt, value, is_max)
Definition: z3py.py:6872
def num_sorts(self)
Definition: z3py.py:5700
def add(self, args)
Definition: z3py.py:6530
def hash(self)
Definition: z3py.py:368
def is_int(a)
Definition: z3py.py:2338
def check(self, assumptions)
Definition: z3py.py:6221
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
def fpPlusInfinity(s)
Definition: z3py.py:8924
def insert(self, args)
Definition: z3py.py:6542
def is_quantifier(a)
Definition: z3py.py:1861
def as_string(self)
Definition: z3py.py:6824
def is_string(a)
Definition: z3py.py:9716
def StringVal(s, ctx=None)
Definition: z3py.py:9733
def Plus(re)
Definition: z3py.py:9975
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def StrToInt(s)
Definition: z3py.py:9882
def __call__(self, goal, arguments, keywords)
Definition: z3py.py:7244
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:6835
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0...
def params(self)
Definition: z3py.py:869
def num_args(self)
Definition: z3py.py:887
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:8850
def __del__(self)
Definition: z3py.py:7075
def prove(claim, keywords)
Definition: z3py.py:7976
def DeclareSort(name, ctx=None)
Definition: z3py.py:598
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def Ints(names, ctx=None)
Definition: z3py.py:2861
def parse_file(self, f)
Definition: z3py.py:6690
def Interpolant(a, ctx=None)
Definition: z3py.py:8142
def pop(self)
Definition: z3py.py:6619
def is_true(a)
Definition: z3py.py:1352
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def Contains(a, b)
Definition: z3py.py:9820
def is_finite_domain_value(a)
Definition: z3py.py:6849
def is_real(self)
Definition: z3py.py:1953
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a string of a numeric constant term.
def FreshBool(prefix='b', ctx=None)
Definition: z3py.py:1510
def Bool(name, ctx=None)
Definition: z3py.py:1470
def probe_description(name, ctx=None)
Definition: z3py.py:7618
def get_rules_along_trace(self)
Definition: z3py.py:6642
def __deepcopy__(self, memo={})
Definition: z3py.py:6495
def __del__(self)
Definition: z3py.py:6914
def tactic_description(name, ctx=None)
Definition: z3py.py:7427
def param_descrs(self)
Definition: z3py.py:7258
def RNE(ctx=None)
Definition: z3py.py:8654
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
def is_store(a)
Definition: z3py.py:4358
def get_version()
Definition: z3py.py:76
def from_string(self, s)
Definition: z3py.py:7027
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def SRem(a, b)
Definition: z3py.py:3824
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9011
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:9533
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9185
def eq(self, other)
Definition: z3py.py:335
def get_id(self)
Definition: z3py.py:481
def ToReal(a)
Definition: z3py.py:2949
def is_bv_value(a)
Definition: z3py.py:3535
def range(self)
Definition: z3py.py:671
def is_idiv(a)
Definition: z3py.py:2486
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3624
def translate(self, target)
Definition: z3py.py:352
def from_file(self, filename)
Definition: z3py.py:7020
def __init__(self, probe, ctx=None)
Definition: z3py.py:7455
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate. ...
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expresson value associated with an expression parameter.
def query_from_lvl(self, lvl, query)
Definition: z3py.py:6599
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
def __ne__(self, other)
Definition: z3py.py:546
def __le__(self, other)
Definition: z3py.py:7511
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
def cast(self, val)
Definition: z3py.py:1285
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality. Thus, two ast nodes created by the same context and having the same children and same function symbols have the same identifiers. Ast nodes created in the same context, but having different children or different functions have different identifiers. Variables and quantifiers are also assigned different identifiers according to their structure.
def as_func_decl(self)
Definition: z3py.py:635
def size(self)
Definition: z3py.py:3085
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def to_string(self, queries)
Definition: z3py.py:6714
def assertions(self)
Definition: z3py.py:6346
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
def Strings(names, ctx=None)
Definition: z3py.py:9746
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
def get_id(self)
Definition: z3py.py:327
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9157
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9372
def __lt__(self, other)
Definition: z3py.py:7485
def ArraySort(d, r)
Definition: z3py.py:4199
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
def create(self)
Definition: z3py.py:4445
def Full(s)
Definition: z3py.py:9774
def is_const_array(a)
Definition: z3py.py:4135
def fpNaN(s)
Definition: z3py.py:8908
def cast(self, val)
Definition: z3py.py:1985
def as_long(self)
Definition: z3py.py:6812
def sexpr(self)
Definition: z3py.py:314
def reason_unknown(self)
Definition: z3py.py:6989
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
def kind(self)
Definition: z3py.py:484
def IntSort(ctx=None)
Definition: z3py.py:2746
def Unit(a)
Definition: z3py.py:9788
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def parse_string(self, s)
Definition: z3py.py:6683
def is_rational_value(a)
Definition: z3py.py:2403
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
def is_finite_domain(a)
Definition: z3py.py:6796
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
def fpNeg(a, ctx=None)
Definition: z3py.py:9074
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:9317
def get_ground_sat_answer(self)
Definition: z3py.py:6637
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4668
def sexpr(self)
Definition: z3py.py:6709
def __ne__(self, other)
Definition: z3py.py:7550
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
def declare_var(self, vars)
Definition: z3py.py:6732
def arg(self, idx)
Definition: z3py.py:903
def sort(self)
Definition: z3py.py:8467
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
def IntToStr(s)
Definition: z3py.py:9898
def Xor(a, b, ctx=None)
Definition: z3py.py:1538
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def Select(a, i)
Definition: z3py.py:4281
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:6546
def __rmul__(self, other)
Definition: z3py.py:1322
def params(self)
Definition: z3py.py:692
def query(self, query)
Definition: z3py.py:6577
def get_var_index(a)
Definition: z3py.py:1122
def Not(a, ctx=None)
Definition: z3py.py:1553
def MultiPattern(args)
Definition: z3py.py:1677
def BoolVal(val, ctx=None)
Definition: z3py.py:1452
def upper_values(self)
Definition: z3py.py:6889
def model(self)
Definition: z3py.py:6993
def is_div(a)
Definition: z3py.py:2470
FP Numerals.
Definition: z3py.py:8708
FP Sorts.
Definition: z3py.py:8363
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
def ctx_ref(self)
Definition: z3py.py:331
def help(self)
Definition: z3py.py:6508
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
def Re(s, ctx=None)
Definition: z3py.py:9905
def fpMin(a, b, ctx=None)
Definition: z3py.py:9212
def is_fp_sort(s)
Definition: z3py.py:8442
Expressions.
Definition: z3py.py:791
def is_app_of(a, k)
Definition: z3py.py:1154
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def is_probe(p)
Definition: z3py.py:7592
def is_mul(a)
Definition: z3py.py:2448
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:2884
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
def subsort(self, other)
Definition: z3py.py:500
def kind(self)
Definition: z3py.py:680
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:3061
def Update(a, i, v)
Definition: z3py.py:4233
def With(t, args, keys)
Definition: z3py.py:7377
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
def append_log(s)
Definition: z3py.py:97
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
def statistics(self)
Definition: z3py.py:6722
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
def is_add(a)
Definition: z3py.py:2437
def ParOr(ts, ks)
Definition: z3py.py:7341
def K(dom, v)
Definition: z3py.py:4318
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3571
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def __hash__(self)
Definition: z3py.py:847
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:2873
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9141
def get_assertions(self)
Definition: z3py.py:6701
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def get_num_levels(self, predicate)
Definition: z3py.py:6654
def UGT(a, b)
Definition: z3py.py:3767
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
def get_answer(self)
Definition: z3py.py:6632
def children(self)
Definition: z3py.py:924
def BV2Int(a, is_signed=False)
Definition: z3py.py:3549
def arity(self)
Definition: z3py.py:5515
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def Store(a, i, v)
Definition: z3py.py:4265
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7409
def numerator(self)
Definition: z3py.py:2618
def __str__(self)
Definition: z3py.py:289
def is_int(self)
Definition: z3py.py:1310
def is_ast(a)
Definition: z3py.py:378
def sequence_interpolant(v, p=None, ctx=None)
Definition: z3py.py:8249
Z3_string Z3_API Z3_get_parser_error(Z3_context c)
Retrieve that last error message information generated from parsing.
def domain(self)
Definition: z3py.py:4087
def Empty(s)
Definition: z3py.py:9753
def __init__(self, ast, ctx=None)
Definition: z3py.py:277
def UDiv(a, b)
Definition: z3py.py:3784
def convert_model(self, model, idx=0)
Definition: z3py.py:7122
def is_expr(a)
Definition: z3py.py:1033
def __init__(self, result, ctx)
Definition: z3py.py:7067
def abstract(self, fml, is_forall=True)
Definition: z3py.py:6741
def set(self, args, keys)
Definition: z3py.py:6502
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
def fpToReal(x, ctx=None)
Definition: z3py.py:9575
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i&#39;th optimization objective.
def Map(f, args)
Definition: z3py.py:4296
def __call__(self, args)
Definition: z3py.py:716
def else_value(self)
Definition: z3py.py:5476
def subsort(self, other)
Definition: z3py.py:1307
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
def describe_probes()
Definition: z3py.py:7626
def add_cover(self, level, predicate, property)
Definition: z3py.py:6663
def describe_tactics()
Definition: z3py.py:7435
def is_bool(a)
Definition: z3py.py:1335
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
def Distinct(args)
Definition: z3py.py:1188
def __call__(self, goal)
Definition: z3py.py:7564
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
def body(self)
Definition: z3py.py:1795
def as_list(self)
Definition: z3py.py:5553
def check(self)
Definition: z3py.py:6985
def arity(self)
Definition: z3py.py:649
def Reals(names, ctx=None)
Definition: z3py.py:2909
def is_bv(a)
Definition: z3py.py:3522
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
def is_var(a)
Definition: z3py.py:1098
def as_expr(self)
Definition: z3py.py:7153
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9454
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9361
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:7390
def RepeatBitVec(n, a)
Definition: z3py.py:3961
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i&#39;th optimization objective. The returned vector ...
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
def SolverFor(logic, ctx=None)
Definition: z3py.py:6443
def get_full_version()
Definition: z3py.py:84
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7359
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
def lower(self)
Definition: z3py.py:6877
def as_ast(self)
Definition: z3py.py:629
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def is_false(a)
Definition: z3py.py:1369
def set(self, args, keys)
Definition: z3py.py:6918
def ULE(a, b)
Definition: z3py.py:3716
def is_is_int(a)
Definition: z3py.py:2552
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
def enable_trace(msg)
Definition: z3py.py:62
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
def name(self)
Definition: z3py.py:523
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9473
def is_fprm(a)
Definition: z3py.py:8690
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
def __iadd__(self, fml)
Definition: z3py.py:6534
def Option(re)
Definition: z3py.py:9987
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
def as_signed_long(self)
Definition: z3py.py:3497
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def __del__(self)
Definition: z3py.py:6498
def is_func_decl(a)
Definition: z3py.py:748
def interrupt(self)
Definition: z3py.py:181
def is_sub(a)
Definition: z3py.py:2459
def Concat(args)
Definition: z3py.py:3644
def FailIf(p, ctx=None)
Definition: z3py.py:7659
def __hash__(self)
Definition: z3py.py:298
def append(self, args)
Definition: z3py.py:6538
def When(p, t, ctx=None)
Definition: z3py.py:7678
def is_seq(a)
Definition: z3py.py:9707
def is_algebraic_value(a)
Definition: z3py.py:2424
def BoolSort(ctx=None)
Definition: z3py.py:1435
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def get_param(name)
Definition: z3py.py:251
def is_to_int(a)
Definition: z3py.py:2577
def __eq__(self, other)
Definition: z3py.py:7537
def Q(a, b, ctx=None)
Definition: z3py.py:2837
def __deepcopy__(self, memo={})
Definition: z3py.py:7478
def String(name, ctx=None)
Definition: z3py.py:9738
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, __uint64 *r)
Store the size of the sort in r. Return Z3_FALSE if the call failed. That is, Z3_get_sort_kind(s) == ...
def reason_unknown(self)
Definition: z3py.py:6727
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
def ToInt(a)
Definition: z3py.py:2966
def num_entries(self)
Definition: z3py.py:5499
def tree_interpolant(pat, p=None, ctx=None)
Definition: z3py.py:8156
def __del__(self)
Definition: z3py.py:282
def is_fp(a)
Definition: z3py.py:8823
def __eq__(self, other)
Definition: z3py.py:533
def Sqrt(a, ctx=None)
Definition: z3py.py:2999
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives. Add the parsed constraints and objectives to the optimization context.
def fpLT(a, b, ctx=None)
Definition: z3py.py:9306
def SimpleSolver(ctx=None)
Definition: z3py.py:6463