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