Z3
z3py.py
Go to the documentation of this file.
1 
8 
9 """Z3 is a high performance theorem prover developed at Microsoft Research.
10 
11 Z3 is used in many applications such as: software/hardware verification and testing,
12 constraint solving, analysis of hybrid systems, security, biology (in silico analysis),
13 and geometrical problems.
14 
15 
16 Please send feedback, comments and/or corrections on the Issue tracker for
17 https://github.com/Z3prover/z3.git. Your comments are very valuable.
18 
19 Small example:
20 
21 >>> x = Int('x')
22 >>> y = Int('y')
23 >>> s = Solver()
24 >>> s.add(x > 0)
25 >>> s.add(x < 2)
26 >>> s.add(y == x + 1)
27 >>> s.check()
28 sat
29 >>> m = s.model()
30 >>> m[x]
31 1
32 >>> m[y]
33 2
34 
35 Z3 exceptions:
36 
37 >>> try:
38 ... x = BitVec('x', 32)
39 ... y = Bool('y')
40 ... # the expression x + y is type incorrect
41 ... n = x + y
42 ... except Z3Exception as ex:
43 ... print("failed: %s" % ex)
44 failed: sort mismatch
45 """
46 from . import z3core
47 from .z3core import *
48 from .z3types import *
49 from .z3consts import *
50 from .z3printer import *
51 from fractions import Fraction
52 import sys
53 import io
54 import math
55 import copy
56 if sys.version_info.major >= 3:
57  from typing import Iterable
58 
59 Z3_DEBUG = __debug__
60 
61 
62 def z3_debug():
63  global Z3_DEBUG
64  return Z3_DEBUG
65 
66 
67 if sys.version_info.major < 3:
68  def _is_int(v):
69  return isinstance(v, (int, long))
70 else:
71  def _is_int(v):
72  return isinstance(v, int)
73 
74 
75 def enable_trace(msg):
76  Z3_enable_trace(msg)
77 
78 
79 def disable_trace(msg):
80  Z3_disable_trace(msg)
81 
82 
84  major = ctypes.c_uint(0)
85  minor = ctypes.c_uint(0)
86  build = ctypes.c_uint(0)
87  rev = ctypes.c_uint(0)
88  Z3_get_version(major, minor, build, rev)
89  return "%s.%s.%s" % (major.value, minor.value, build.value)
90 
91 
93  major = ctypes.c_uint(0)
94  minor = ctypes.c_uint(0)
95  build = ctypes.c_uint(0)
96  rev = ctypes.c_uint(0)
97  Z3_get_version(major, minor, build, rev)
98  return (major.value, minor.value, build.value, rev.value)
99 
100 
102  return Z3_get_full_version()
103 
104 
105 def _z3_assert(cond, msg):
106  if not cond:
107  raise Z3Exception(msg)
108 
109 
110 def _z3_check_cint_overflow(n, name):
111  _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
112 
113 
114 def open_log(fname):
115  """Log interaction to a file. This function must be invoked immediately after init(). """
116  Z3_open_log(fname)
117 
118 
119 def append_log(s):
120  """Append user-defined string to interaction log. """
121  Z3_append_log(s)
122 
123 
124 def to_symbol(s, ctx=None):
125  """Convert an integer or string into a Z3 symbol."""
126  if _is_int(s):
127  return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
128  else:
129  return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
130 
131 
132 def _symbol2py(ctx, s):
133  """Convert a Z3 symbol back into a Python object. """
134  if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
135  return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
136  else:
137  return Z3_get_symbol_string(ctx.ref(), s)
138 
139 # Hack for having nary functions that can receive one argument that is the
140 # list of arguments.
141 # Use this when function takes a single list of arguments
142 
143 
144 def _get_args(args):
145  try:
146  if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
147  return args[0]
148  elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
149  return [arg for arg in args[0]]
150  else:
151  return args
152  except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?)
153  return args
154 
155 # Use this when function takes multiple arguments
156 
157 
158 def _get_args_ast_list(args):
159  try:
160  if isinstance(args, (set, AstVector, tuple)):
161  return [arg for arg in args]
162  else:
163  return args
164  except Exception:
165  return args
166 
167 
168 def _to_param_value(val):
169  if isinstance(val, bool):
170  return "true" if val else "false"
171  return str(val)
172 
173 
175  # Do nothing error handler, just avoid exit(0)
176  # The wrappers in z3core.py will raise a Z3Exception if an error is detected
177  return
178 
179 
180 class Context:
181  """A Context manages all other Z3 objects, global configuration options, etc.
182 
183  Z3Py uses a default global context. For most applications this is sufficient.
184  An application may use multiple Z3 contexts. Objects created in one context
185  cannot be used in another one. However, several objects may be "translated" from
186  one context to another. It is not safe to access Z3 objects from multiple threads.
187  The only exception is the method `interrupt()` that can be used to interrupt() a long
188  computation.
189  The initialization method receives global configuration options for the new context.
190  """
191 
192  def __init__(self, *args, **kws):
193  if z3_debug():
194  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
195  conf = Z3_mk_config()
196  for key in kws:
197  value = kws[key]
198  Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
199  prev = None
200  for a in args:
201  if prev is None:
202  prev = a
203  else:
204  Z3_set_param_value(conf, str(prev), _to_param_value(a))
205  prev = None
206  self.ctxctx = Z3_mk_context_rc(conf)
207  self.eheh = Z3_set_error_handler(self.ctxctx, z3_error_handler)
208  Z3_set_ast_print_mode(self.ctxctx, Z3_PRINT_SMTLIB2_COMPLIANT)
209  Z3_del_config(conf)
210 
211  def __del__(self):
212  Z3_del_context(self.ctxctx)
213  self.ctxctx = None
214  self.eheh = None
215 
216  def ref(self):
217  """Return a reference to the actual C pointer to the Z3 context."""
218  return self.ctxctx
219 
220  def interrupt(self):
221  """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
222 
223  This method can be invoked from a thread different from the one executing the
224  interruptible procedure.
225  """
226  Z3_interrupt(self.refref())
227 
228 
229 # Global Z3 context
230 _main_ctx = None
231 
232 
233 def main_ctx():
234  """Return a reference to the global Z3 context.
235 
236  >>> x = Real('x')
237  >>> x.ctx == main_ctx()
238  True
239  >>> c = Context()
240  >>> c == main_ctx()
241  False
242  >>> x2 = Real('x', c)
243  >>> x2.ctx == c
244  True
245  >>> eq(x, x2)
246  False
247  """
248  global _main_ctx
249  if _main_ctx is None:
250  _main_ctx = Context()
251  return _main_ctx
252 
253 
254 def _get_ctx(ctx):
255  if ctx is None:
256  return main_ctx()
257  else:
258  return ctx
259 
260 
261 def get_ctx(ctx):
262  return _get_ctx(ctx)
263 
264 
265 def set_param(*args, **kws):
266  """Set Z3 global (or module) parameters.
267 
268  >>> set_param(precision=10)
269  """
270  if z3_debug():
271  _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
272  new_kws = {}
273  for k in kws:
274  v = kws[k]
275  if not set_pp_option(k, v):
276  new_kws[k] = v
277  for key in new_kws:
278  value = new_kws[key]
279  Z3_global_param_set(str(key).upper(), _to_param_value(value))
280  prev = None
281  for a in args:
282  if prev is None:
283  prev = a
284  else:
285  Z3_global_param_set(str(prev), _to_param_value(a))
286  prev = None
287 
288 
290  """Reset all global (or module) parameters.
291  """
293 
294 
295 def set_option(*args, **kws):
296  """Alias for 'set_param' for backward compatibility.
297  """
298  return set_param(*args, **kws)
299 
300 
301 def get_param(name):
302  """Return the value of a Z3 global (or module) parameter
303 
304  >>> get_param('nlsat.reorder')
305  'true'
306  """
307  ptr = (ctypes.c_char_p * 1)()
308  if Z3_global_param_get(str(name), ptr):
309  r = z3core._to_pystr(ptr[0])
310  return r
311  raise Z3Exception("failed to retrieve value for '%s'" % name)
312 
313 
318 
319 # Mark objects that use pretty printer
320 
321 
323  """Superclass for all Z3 objects that have support for pretty printing."""
324 
325  def use_pp(self):
326  return True
327 
328  def _repr_html_(self):
329  in_html = in_html_mode()
330  set_html_mode(True)
331  res = repr(self)
332  set_html_mode(in_html)
333  return res
334 
335 
337  """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
338 
339  def __init__(self, ast, ctx=None):
340  self.astast = ast
341  self.ctxctx = _get_ctx(ctx)
342  Z3_inc_ref(self.ctxctx.ref(), self.as_astas_ast())
343 
344  def __del__(self):
345  if self.ctxctx.ref() is not None and self.astast is not None:
346  Z3_dec_ref(self.ctxctx.ref(), self.as_astas_ast())
347  self.astast = None
348 
349  def __deepcopy__(self, memo={}):
350  return _to_ast_ref(self.astast, self.ctxctx)
351 
352  def __str__(self):
353  return obj_to_string(self)
354 
355  def __repr__(self):
356  return obj_to_string(self)
357 
358  def __eq__(self, other):
359  return self.eqeq(other)
360 
361  def __hash__(self):
362  return self.hashhash()
363 
364  def __nonzero__(self):
365  return self.__bool____bool__()
366 
367  def __bool__(self):
368  if is_true(self):
369  return True
370  elif is_false(self):
371  return False
372  elif is_eq(self) and self.num_args() == 2:
373  return self.arg(0).eq(self.arg(1))
374  else:
375  raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
376 
377  def sexpr(self):
378  """Return a string representing the AST node in s-expression notation.
379 
380  >>> x = Int('x')
381  >>> ((x + 1)*x).sexpr()
382  '(* (+ x 1) x)'
383  """
384  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_ast())
385 
386  def as_ast(self):
387  """Return a pointer to the corresponding C Z3_ast object."""
388  return self.astast
389 
390  def get_id(self):
391  """Return unique identifier for object. It can be used for hash-tables and maps."""
392  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_ast())
393 
394  def ctx_ref(self):
395  """Return a reference to the C context where this AST node is stored."""
396  return self.ctxctx.ref()
397 
398  def eq(self, other):
399  """Return `True` if `self` and `other` are structurally identical.
400 
401  >>> x = Int('x')
402  >>> n1 = x + 1
403  >>> n2 = 1 + x
404  >>> n1.eq(n2)
405  False
406  >>> n1 = simplify(n1)
407  >>> n2 = simplify(n2)
408  >>> n1.eq(n2)
409  True
410  """
411  if z3_debug():
412  _z3_assert(is_ast(other), "Z3 AST expected")
413  return Z3_is_eq_ast(self.ctx_refctx_ref(), self.as_astas_ast(), other.as_ast())
414 
415  def translate(self, target):
416  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
417 
418  >>> c1 = Context()
419  >>> c2 = Context()
420  >>> x = Int('x', c1)
421  >>> y = Int('y', c2)
422  >>> # Nodes in different contexts can't be mixed.
423  >>> # However, we can translate nodes from one context to another.
424  >>> x.translate(c2) + y
425  x + y
426  """
427  if z3_debug():
428  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
429  return _to_ast_ref(Z3_translate(self.ctxctx.ref(), self.as_astas_ast(), target.ref()), target)
430 
431  def __copy__(self):
432  return self.translatetranslate(self.ctxctx)
433 
434  def hash(self):
435  """Return a hashcode for the `self`.
436 
437  >>> n1 = simplify(Int('x') + 1)
438  >>> n2 = simplify(2 + Int('x') - 1)
439  >>> n1.hash() == n2.hash()
440  True
441  """
442  return Z3_get_ast_hash(self.ctx_refctx_ref(), self.as_astas_ast())
443 
444 
445 def is_ast(a):
446  """Return `True` if `a` is an AST node.
447 
448  >>> is_ast(10)
449  False
450  >>> is_ast(IntVal(10))
451  True
452  >>> is_ast(Int('x'))
453  True
454  >>> is_ast(BoolSort())
455  True
456  >>> is_ast(Function('f', IntSort(), IntSort()))
457  True
458  >>> is_ast("x")
459  False
460  >>> is_ast(Solver())
461  False
462  """
463  return isinstance(a, AstRef)
464 
465 
466 def eq(a, b):
467  """Return `True` if `a` and `b` are structurally identical AST nodes.
468 
469  >>> x = Int('x')
470  >>> y = Int('y')
471  >>> eq(x, y)
472  False
473  >>> eq(x + 1, x + 1)
474  True
475  >>> eq(x + 1, 1 + x)
476  False
477  >>> eq(simplify(x + 1), simplify(1 + x))
478  True
479  """
480  if z3_debug():
481  _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
482  return a.eq(b)
483 
484 
485 def _ast_kind(ctx, a):
486  if is_ast(a):
487  a = a.as_ast()
488  return Z3_get_ast_kind(ctx.ref(), a)
489 
490 
491 def _ctx_from_ast_arg_list(args, default_ctx=None):
492  ctx = None
493  for a in args:
494  if is_ast(a) or is_probe(a):
495  if ctx is None:
496  ctx = a.ctx
497  else:
498  if z3_debug():
499  _z3_assert(ctx == a.ctx, "Context mismatch")
500  if ctx is None:
501  ctx = default_ctx
502  return ctx
503 
504 
505 def _ctx_from_ast_args(*args):
506  return _ctx_from_ast_arg_list(args)
507 
508 
509 def _to_func_decl_array(args):
510  sz = len(args)
511  _args = (FuncDecl * sz)()
512  for i in range(sz):
513  _args[i] = args[i].as_func_decl()
514  return _args, sz
515 
516 
517 def _to_ast_array(args):
518  sz = len(args)
519  _args = (Ast * sz)()
520  for i in range(sz):
521  _args[i] = args[i].as_ast()
522  return _args, sz
523 
524 
525 def _to_ref_array(ref, args):
526  sz = len(args)
527  _args = (ref * sz)()
528  for i in range(sz):
529  _args[i] = args[i].as_ast()
530  return _args, sz
531 
532 
533 def _to_ast_ref(a, ctx):
534  k = _ast_kind(ctx, a)
535  if k == Z3_SORT_AST:
536  return _to_sort_ref(a, ctx)
537  elif k == Z3_FUNC_DECL_AST:
538  return _to_func_decl_ref(a, ctx)
539  else:
540  return _to_expr_ref(a, ctx)
541 
542 
543 
548 
549 def _sort_kind(ctx, s):
550  return Z3_get_sort_kind(ctx.ref(), s)
551 
552 
554  """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
555 
556  def as_ast(self):
557  return Z3_sort_to_ast(self.ctx_refctx_ref(), self.astast)
558 
559  def get_id(self):
560  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_ast())
561 
562  def kind(self):
563  """Return the Z3 internal kind of a sort.
564  This method can be used to test if `self` is one of the Z3 builtin sorts.
565 
566  >>> b = BoolSort()
567  >>> b.kind() == Z3_BOOL_SORT
568  True
569  >>> b.kind() == Z3_INT_SORT
570  False
571  >>> A = ArraySort(IntSort(), IntSort())
572  >>> A.kind() == Z3_ARRAY_SORT
573  True
574  >>> A.kind() == Z3_INT_SORT
575  False
576  """
577  return _sort_kind(self.ctxctx, self.astast)
578 
579  def subsort(self, other):
580  """Return `True` if `self` is a subsort of `other`.
581 
582  >>> IntSort().subsort(RealSort())
583  True
584  """
585  return False
586 
587  def cast(self, val):
588  """Try to cast `val` as an element of sort `self`.
589 
590  This method is used in Z3Py to convert Python objects such as integers,
591  floats, longs and strings into Z3 expressions.
592 
593  >>> x = Int('x')
594  >>> RealSort().cast(x)
595  ToReal(x)
596  """
597  if z3_debug():
598  _z3_assert(is_expr(val), "Z3 expression expected")
599  _z3_assert(self.eqeq(val.sort()), "Sort mismatch")
600  return val
601 
602  def name(self):
603  """Return the name (string) of sort `self`.
604 
605  >>> BoolSort().name()
606  'Bool'
607  >>> ArraySort(IntSort(), IntSort()).name()
608  'Array'
609  """
610  return _symbol2py(self.ctxctx, Z3_get_sort_name(self.ctx_refctx_ref(), self.astast))
611 
612  def __eq__(self, other):
613  """Return `True` if `self` and `other` are the same Z3 sort.
614 
615  >>> p = Bool('p')
616  >>> p.sort() == BoolSort()
617  True
618  >>> p.sort() == IntSort()
619  False
620  """
621  if other is None:
622  return False
623  return Z3_is_eq_sort(self.ctx_refctx_ref(), self.astast, other.ast)
624 
625  def __ne__(self, other):
626  """Return `True` if `self` and `other` are not the same Z3 sort.
627 
628  >>> p = Bool('p')
629  >>> p.sort() != BoolSort()
630  False
631  >>> p.sort() != IntSort()
632  True
633  """
634  return not Z3_is_eq_sort(self.ctx_refctx_ref(), self.astast, other.ast)
635 
636  def __hash__(self):
637  """ Hash code. """
638  return AstRef.__hash__(self)
639 
640 
641 def is_sort(s):
642  """Return `True` if `s` is a Z3 sort.
643 
644  >>> is_sort(IntSort())
645  True
646  >>> is_sort(Int('x'))
647  False
648  >>> is_expr(Int('x'))
649  True
650  """
651  return isinstance(s, SortRef)
652 
653 
654 def _to_sort_ref(s, ctx):
655  if z3_debug():
656  _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
657  k = _sort_kind(ctx, s)
658  if k == Z3_BOOL_SORT:
659  return BoolSortRef(s, ctx)
660  elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
661  return ArithSortRef(s, ctx)
662  elif k == Z3_BV_SORT:
663  return BitVecSortRef(s, ctx)
664  elif k == Z3_ARRAY_SORT:
665  return ArraySortRef(s, ctx)
666  elif k == Z3_DATATYPE_SORT:
667  return DatatypeSortRef(s, ctx)
668  elif k == Z3_FINITE_DOMAIN_SORT:
669  return FiniteDomainSortRef(s, ctx)
670  elif k == Z3_FLOATING_POINT_SORT:
671  return FPSortRef(s, ctx)
672  elif k == Z3_ROUNDING_MODE_SORT:
673  return FPRMSortRef(s, ctx)
674  elif k == Z3_RE_SORT:
675  return ReSortRef(s, ctx)
676  elif k == Z3_SEQ_SORT:
677  return SeqSortRef(s, ctx)
678  elif k == Z3_CHAR_SORT:
679  return CharSortRef(s, ctx)
680  return SortRef(s, ctx)
681 
682 
683 def _sort(ctx, a):
684  return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
685 
686 
687 def DeclareSort(name, ctx=None):
688  """Create a new uninterpreted sort named `name`.
689 
690  If `ctx=None`, then the new sort is declared in the global Z3Py context.
691 
692  >>> A = DeclareSort('A')
693  >>> a = Const('a', A)
694  >>> b = Const('b', A)
695  >>> a.sort() == A
696  True
697  >>> b.sort() == A
698  True
699  >>> a == b
700  a == b
701  """
702  ctx = _get_ctx(ctx)
703  return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
704 
705 
710 
711 
713  """Function declaration. Every constant and function have an associated declaration.
714 
715  The declaration assigns a name, a sort (i.e., type), and for function
716  the sort (i.e., type) of each of its arguments. Note that, in Z3,
717  a constant is a function with 0 arguments.
718  """
719 
720  def as_ast(self):
721  return Z3_func_decl_to_ast(self.ctx_refctx_ref(), self.astast)
722 
723  def get_id(self):
724  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_ast())
725 
726  def as_func_decl(self):
727  return self.astast
728 
729  def name(self):
730  """Return the name of the function declaration `self`.
731 
732  >>> f = Function('f', IntSort(), IntSort())
733  >>> f.name()
734  'f'
735  >>> isinstance(f.name(), str)
736  True
737  """
738  return _symbol2py(self.ctxctx, Z3_get_decl_name(self.ctx_refctx_ref(), self.astast))
739 
740  def arity(self):
741  """Return the number of arguments of a function declaration.
742  If `self` is a constant, then `self.arity()` is 0.
743 
744  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
745  >>> f.arity()
746  2
747  """
748  return int(Z3_get_arity(self.ctx_refctx_ref(), self.astast))
749 
750  def domain(self, i):
751  """Return the sort of the argument `i` of a function declaration.
752  This method assumes that `0 <= i < self.arity()`.
753 
754  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
755  >>> f.domain(0)
756  Int
757  >>> f.domain(1)
758  Real
759  """
760  if z3_debug():
761  _z3_assert(i < self.arityarity(), "Index out of bounds")
762  return _to_sort_ref(Z3_get_domain(self.ctx_refctx_ref(), self.astast, i), self.ctxctx)
763 
764  def range(self):
765  """Return the sort of the range of a function declaration.
766  For constants, this is the sort of the constant.
767 
768  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
769  >>> f.range()
770  Bool
771  """
772  return _to_sort_ref(Z3_get_range(self.ctx_refctx_ref(), self.astast), self.ctxctx)
773 
774  def kind(self):
775  """Return the internal kind of a function declaration.
776  It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
777 
778  >>> x = Int('x')
779  >>> d = (x + 1).decl()
780  >>> d.kind() == Z3_OP_ADD
781  True
782  >>> d.kind() == Z3_OP_MUL
783  False
784  """
785  return Z3_get_decl_kind(self.ctx_refctx_ref(), self.astast)
786 
787  def params(self):
788  ctx = self.ctxctx
789  n = Z3_get_decl_num_parameters(self.ctx_refctx_ref(), self.astast)
790  result = [None for i in range(n)]
791  for i in range(n):
792  k = Z3_get_decl_parameter_kind(self.ctx_refctx_ref(), self.astast, i)
793  if k == Z3_PARAMETER_INT:
794  result[i] = Z3_get_decl_int_parameter(self.ctx_refctx_ref(), self.astast, i)
795  elif k == Z3_PARAMETER_DOUBLE:
796  result[i] = Z3_get_decl_double_parameter(self.ctx_refctx_ref(), self.astast, i)
797  elif k == Z3_PARAMETER_RATIONAL:
798  result[i] = Z3_get_decl_rational_parameter(self.ctx_refctx_ref(), self.astast, i)
799  elif k == Z3_PARAMETER_SYMBOL:
800  result[i] = Z3_get_decl_symbol_parameter(self.ctx_refctx_ref(), self.astast, i)
801  elif k == Z3_PARAMETER_SORT:
802  result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_refctx_ref(), self.astast, i), ctx)
803  elif k == Z3_PARAMETER_AST:
804  result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_refctx_ref(), self.astast, i), ctx)
805  elif k == Z3_PARAMETER_FUNC_DECL:
806  result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_refctx_ref(), self.astast, i), ctx)
807  else:
808  assert(False)
809  return result
810 
811  def __call__(self, *args):
812  """Create a Z3 application expression using the function `self`, and the given arguments.
813 
814  The arguments must be Z3 expressions. This method assumes that
815  the sorts of the elements in `args` match the sorts of the
816  domain. Limited coercion is supported. For example, if
817  args[0] is a Python integer, and the function expects a Z3
818  integer, then the argument is automatically converted into a
819  Z3 integer.
820 
821  >>> f = Function('f', IntSort(), RealSort(), BoolSort())
822  >>> x = Int('x')
823  >>> y = Real('y')
824  >>> f(x, y)
825  f(x, y)
826  >>> f(x, x)
827  f(x, ToReal(x))
828  """
829  args = _get_args(args)
830  num = len(args)
831  if z3_debug():
832  _z3_assert(num == self.arityarity(), "Incorrect number of arguments to %s" % self)
833  _args = (Ast * num)()
834  saved = []
835  for i in range(num):
836  # self.domain(i).cast(args[i]) may create a new Z3 expression,
837  # then we must save in 'saved' to prevent it from being garbage collected.
838  tmp = self.domaindomain(i).cast(args[i])
839  saved.append(tmp)
840  _args[i] = tmp.as_ast()
841  return _to_expr_ref(Z3_mk_app(self.ctx_refctx_ref(), self.astast, len(args), _args), self.ctxctx)
842 
843 
845  """Return `True` if `a` is a Z3 function declaration.
846 
847  >>> f = Function('f', IntSort(), IntSort())
848  >>> is_func_decl(f)
849  True
850  >>> x = Real('x')
851  >>> is_func_decl(x)
852  False
853  """
854  return isinstance(a, FuncDeclRef)
855 
856 
857 def Function(name, *sig):
858  """Create a new Z3 uninterpreted function with the given sorts.
859 
860  >>> f = Function('f', IntSort(), IntSort())
861  >>> f(f(0))
862  f(f(0))
863  """
864  sig = _get_args(sig)
865  if z3_debug():
866  _z3_assert(len(sig) > 0, "At least two arguments expected")
867  arity = len(sig) - 1
868  rng = sig[arity]
869  if z3_debug():
870  _z3_assert(is_sort(rng), "Z3 sort expected")
871  dom = (Sort * arity)()
872  for i in range(arity):
873  if z3_debug():
874  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
875  dom[i] = sig[i].ast
876  ctx = rng.ctx
877  return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
878 
879 
880 def FreshFunction(*sig):
881  """Create a new fresh Z3 uninterpreted function with the given sorts.
882  """
883  sig = _get_args(sig)
884  if z3_debug():
885  _z3_assert(len(sig) > 0, "At least two arguments expected")
886  arity = len(sig) - 1
887  rng = sig[arity]
888  if z3_debug():
889  _z3_assert(is_sort(rng), "Z3 sort expected")
890  dom = (z3.Sort * arity)()
891  for i in range(arity):
892  if z3_debug():
893  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
894  dom[i] = sig[i].ast
895  ctx = rng.ctx
896  return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
897 
898 
899 def _to_func_decl_ref(a, ctx):
900  return FuncDeclRef(a, ctx)
901 
902 
903 def RecFunction(name, *sig):
904  """Create a new Z3 recursive with the given sorts."""
905  sig = _get_args(sig)
906  if z3_debug():
907  _z3_assert(len(sig) > 0, "At least two arguments expected")
908  arity = len(sig) - 1
909  rng = sig[arity]
910  if z3_debug():
911  _z3_assert(is_sort(rng), "Z3 sort expected")
912  dom = (Sort * arity)()
913  for i in range(arity):
914  if z3_debug():
915  _z3_assert(is_sort(sig[i]), "Z3 sort expected")
916  dom[i] = sig[i].ast
917  ctx = rng.ctx
918  return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
919 
920 
921 def RecAddDefinition(f, args, body):
922  """Set the body of a recursive function.
923  Recursive definitions can be simplified if they are applied to ground
924  arguments.
925  >>> ctx = Context()
926  >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
927  >>> n = Int('n', ctx)
928  >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
929  >>> simplify(fac(5))
930  120
931  >>> s = Solver(ctx=ctx)
932  >>> s.add(fac(n) < 3)
933  >>> s.check()
934  sat
935  >>> s.model().eval(fac(5))
936  120
937  """
938  if is_app(args):
939  args = [args]
940  ctx = body.ctx
941  args = _get_args(args)
942  n = len(args)
943  _args = (Ast * n)()
944  for i in range(n):
945  _args[i] = args[i].ast
946  Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
947 
948 
953 
954 
956  """Constraints, formulas and terms are expressions in Z3.
957 
958  Expressions are ASTs. Every expression has a sort.
959  There are three main kinds of expressions:
960  function applications, quantifiers and bounded variables.
961  A constant is a function application with 0 arguments.
962  For quantifier free problems, all expressions are
963  function applications.
964  """
965 
966  def as_ast(self):
967  return self.astast
968 
969  def get_id(self):
970  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_ast())
971 
972  def sort(self):
973  """Return the sort of expression `self`.
974 
975  >>> x = Int('x')
976  >>> (x + 1).sort()
977  Int
978  >>> y = Real('y')
979  >>> (x + y).sort()
980  Real
981  """
982  return _sort(self.ctxctx, self.as_astas_astas_ast())
983 
984  def sort_kind(self):
985  """Shorthand for `self.sort().kind()`.
986 
987  >>> a = Array('a', IntSort(), IntSort())
988  >>> a.sort_kind() == Z3_ARRAY_SORT
989  True
990  >>> a.sort_kind() == Z3_INT_SORT
991  False
992  """
993  return self.sortsort().kind()
994 
995  def __eq__(self, other):
996  """Return a Z3 expression that represents the constraint `self == other`.
997 
998  If `other` is `None`, then this method simply returns `False`.
999 
1000  >>> a = Int('a')
1001  >>> b = Int('b')
1002  >>> a == b
1003  a == b
1004  >>> a is None
1005  False
1006  """
1007  if other is None:
1008  return False
1009  a, b = _coerce_exprs(self, other)
1010  return BoolRef(Z3_mk_eq(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
1011 
1012  def __hash__(self):
1013  """ Hash code. """
1014  return AstRef.__hash__(self)
1015 
1016  def __ne__(self, other):
1017  """Return a Z3 expression that represents the constraint `self != other`.
1018 
1019  If `other` is `None`, then this method simply returns `True`.
1020 
1021  >>> a = Int('a')
1022  >>> b = Int('b')
1023  >>> a != b
1024  a != b
1025  >>> a is not None
1026  True
1027  """
1028  if other is None:
1029  return True
1030  a, b = _coerce_exprs(self, other)
1031  _args, sz = _to_ast_array((a, b))
1032  return BoolRef(Z3_mk_distinct(self.ctx_refctx_ref(), 2, _args), self.ctxctx)
1033 
1034  def params(self):
1035  return self.decldecl().params()
1036 
1037  def decl(self):
1038  """Return the Z3 function declaration associated with a Z3 application.
1039 
1040  >>> f = Function('f', IntSort(), IntSort())
1041  >>> a = Int('a')
1042  >>> t = f(a)
1043  >>> eq(t.decl(), f)
1044  True
1045  >>> (a + 1).decl()
1046  +
1047  """
1048  if z3_debug():
1049  _z3_assert(is_app(self), "Z3 application expected")
1050  return FuncDeclRef(Z3_get_app_decl(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
1051 
1052  def num_args(self):
1053  """Return the number of arguments of a Z3 application.
1054 
1055  >>> a = Int('a')
1056  >>> b = Int('b')
1057  >>> (a + b).num_args()
1058  2
1059  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1060  >>> t = f(a, b, 0)
1061  >>> t.num_args()
1062  3
1063  """
1064  if z3_debug():
1065  _z3_assert(is_app(self), "Z3 application expected")
1066  return int(Z3_get_app_num_args(self.ctx_refctx_ref(), self.as_astas_astas_ast()))
1067 
1068  def arg(self, idx):
1069  """Return argument `idx` of the application `self`.
1070 
1071  This method assumes that `self` is a function application with at least `idx+1` arguments.
1072 
1073  >>> a = Int('a')
1074  >>> b = Int('b')
1075  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1076  >>> t = f(a, b, 0)
1077  >>> t.arg(0)
1078  a
1079  >>> t.arg(1)
1080  b
1081  >>> t.arg(2)
1082  0
1083  """
1084  if z3_debug():
1085  _z3_assert(is_app(self), "Z3 application expected")
1086  _z3_assert(idx < self.num_argsnum_args(), "Invalid argument index")
1087  return _to_expr_ref(Z3_get_app_arg(self.ctx_refctx_ref(), self.as_astas_astas_ast(), idx), self.ctxctx)
1088 
1089  def children(self):
1090  """Return a list containing the children of the given expression
1091 
1092  >>> a = Int('a')
1093  >>> b = Int('b')
1094  >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1095  >>> t = f(a, b, 0)
1096  >>> t.children()
1097  [a, b, 0]
1098  """
1099  if is_app(self):
1100  return [self.argarg(i) for i in range(self.num_argsnum_args())]
1101  else:
1102  return []
1103 
1104  def from_string(self, s):
1105  pass
1106 
1107  def serialize(self):
1108  s = Solver()
1109  f = Function('F', self.sort(), BoolSort(self.ctx))
1110  s.add(f(self))
1111  return s.sexpr()
1112 
1113 def deserialize(st):
1114  """inverse function to the serialize method on ExprRef.
1115  It is made available to make it easier for users to serialize expressions back and forth between
1116  strings. Solvers can be serialized using the 'sexpr()' method.
1117  """
1118  s = Solver()
1119  s.from_string(st)
1120  if len(s.assertions()) != 1:
1121  raise Z3Exception("single assertion expected")
1122  fml = s.assertions()[0]
1123  if fml.num_args() != 1:
1124  raise Z3Exception("dummy function 'F' expected")
1125  return fml.arg(0)
1126 
1127 def _to_expr_ref(a, ctx):
1128  if isinstance(a, Pattern):
1129  return PatternRef(a, ctx)
1130  ctx_ref = ctx.ref()
1131  k = Z3_get_ast_kind(ctx_ref, a)
1132  if k == Z3_QUANTIFIER_AST:
1133  return QuantifierRef(a, ctx)
1134  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1135  if sk == Z3_BOOL_SORT:
1136  return BoolRef(a, ctx)
1137  if sk == Z3_INT_SORT:
1138  if k == Z3_NUMERAL_AST:
1139  return IntNumRef(a, ctx)
1140  return ArithRef(a, ctx)
1141  if sk == Z3_REAL_SORT:
1142  if k == Z3_NUMERAL_AST:
1143  return RatNumRef(a, ctx)
1144  if _is_algebraic(ctx, a):
1145  return AlgebraicNumRef(a, ctx)
1146  return ArithRef(a, ctx)
1147  if sk == Z3_BV_SORT:
1148  if k == Z3_NUMERAL_AST:
1149  return BitVecNumRef(a, ctx)
1150  else:
1151  return BitVecRef(a, ctx)
1152  if sk == Z3_ARRAY_SORT:
1153  return ArrayRef(a, ctx)
1154  if sk == Z3_DATATYPE_SORT:
1155  return DatatypeRef(a, ctx)
1156  if sk == Z3_FLOATING_POINT_SORT:
1157  if k == Z3_APP_AST and _is_numeral(ctx, a):
1158  return FPNumRef(a, ctx)
1159  else:
1160  return FPRef(a, ctx)
1161  if sk == Z3_FINITE_DOMAIN_SORT:
1162  if k == Z3_NUMERAL_AST:
1163  return FiniteDomainNumRef(a, ctx)
1164  else:
1165  return FiniteDomainRef(a, ctx)
1166  if sk == Z3_ROUNDING_MODE_SORT:
1167  return FPRMRef(a, ctx)
1168  if sk == Z3_SEQ_SORT:
1169  return SeqRef(a, ctx)
1170  if sk == Z3_CHAR_SORT:
1171  return CharRef(a, ctx)
1172  if sk == Z3_RE_SORT:
1173  return ReRef(a, ctx)
1174  return ExprRef(a, ctx)
1175 
1176 
1177 def _coerce_expr_merge(s, a):
1178  if is_expr(a):
1179  s1 = a.sort()
1180  if s is None:
1181  return s1
1182  if s1.eq(s):
1183  return s
1184  elif s.subsort(s1):
1185  return s1
1186  elif s1.subsort(s):
1187  return s
1188  else:
1189  if z3_debug():
1190  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1191  _z3_assert(False, "sort mismatch")
1192  else:
1193  return s
1194 
1195 
1196 def _coerce_exprs(a, b, ctx=None):
1197  if not is_expr(a) and not is_expr(b):
1198  a = _py2expr(a, ctx)
1199  b = _py2expr(b, ctx)
1200  if isinstance(a, str) and isinstance(b, SeqRef):
1201  a = StringVal(a, b.ctx)
1202  if isinstance(b, str) and isinstance(a, SeqRef):
1203  b = StringVal(b, a.ctx)
1204  s = None
1205  s = _coerce_expr_merge(s, a)
1206  s = _coerce_expr_merge(s, b)
1207  a = s.cast(a)
1208  b = s.cast(b)
1209  return (a, b)
1210 
1211 
1212 def _reduce(func, sequence, initial):
1213  result = initial
1214  for element in sequence:
1215  result = func(result, element)
1216  return result
1217 
1218 
1219 def _coerce_expr_list(alist, ctx=None):
1220  has_expr = False
1221  for a in alist:
1222  if is_expr(a):
1223  has_expr = True
1224  break
1225  if not has_expr:
1226  alist = [_py2expr(a, ctx) for a in alist]
1227  s = _reduce(_coerce_expr_merge, alist, None)
1228  return [s.cast(a) for a in alist]
1229 
1230 
1231 def is_expr(a):
1232  """Return `True` if `a` is a Z3 expression.
1233 
1234  >>> a = Int('a')
1235  >>> is_expr(a)
1236  True
1237  >>> is_expr(a + 1)
1238  True
1239  >>> is_expr(IntSort())
1240  False
1241  >>> is_expr(1)
1242  False
1243  >>> is_expr(IntVal(1))
1244  True
1245  >>> x = Int('x')
1246  >>> is_expr(ForAll(x, x >= 0))
1247  True
1248  >>> is_expr(FPVal(1.0))
1249  True
1250  """
1251  return isinstance(a, ExprRef)
1252 
1253 
1254 def is_app(a):
1255  """Return `True` if `a` is a Z3 function application.
1256 
1257  Note that, constants are function applications with 0 arguments.
1258 
1259  >>> a = Int('a')
1260  >>> is_app(a)
1261  True
1262  >>> is_app(a + 1)
1263  True
1264  >>> is_app(IntSort())
1265  False
1266  >>> is_app(1)
1267  False
1268  >>> is_app(IntVal(1))
1269  True
1270  >>> x = Int('x')
1271  >>> is_app(ForAll(x, x >= 0))
1272  False
1273  """
1274  if not isinstance(a, ExprRef):
1275  return False
1276  k = _ast_kind(a.ctx, a)
1277  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1278 
1279 
1280 def is_const(a):
1281  """Return `True` if `a` is Z3 constant/variable expression.
1282 
1283  >>> a = Int('a')
1284  >>> is_const(a)
1285  True
1286  >>> is_const(a + 1)
1287  False
1288  >>> is_const(1)
1289  False
1290  >>> is_const(IntVal(1))
1291  True
1292  >>> x = Int('x')
1293  >>> is_const(ForAll(x, x >= 0))
1294  False
1295  """
1296  return is_app(a) and a.num_args() == 0
1297 
1298 
1299 def is_var(a):
1300  """Return `True` if `a` is variable.
1301 
1302  Z3 uses de-Bruijn indices for representing bound variables in
1303  quantifiers.
1304 
1305  >>> x = Int('x')
1306  >>> is_var(x)
1307  False
1308  >>> is_const(x)
1309  True
1310  >>> f = Function('f', IntSort(), IntSort())
1311  >>> # Z3 replaces x with bound variables when ForAll is executed.
1312  >>> q = ForAll(x, f(x) == x)
1313  >>> b = q.body()
1314  >>> b
1315  f(Var(0)) == Var(0)
1316  >>> b.arg(1)
1317  Var(0)
1318  >>> is_var(b.arg(1))
1319  True
1320  """
1321  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1322 
1323 
1325  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1326 
1327  >>> x = Int('x')
1328  >>> y = Int('y')
1329  >>> is_var(x)
1330  False
1331  >>> is_const(x)
1332  True
1333  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1334  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1335  >>> q = ForAll([x, y], f(x, y) == x + y)
1336  >>> q.body()
1337  f(Var(1), Var(0)) == Var(1) + Var(0)
1338  >>> b = q.body()
1339  >>> b.arg(0)
1340  f(Var(1), Var(0))
1341  >>> v1 = b.arg(0).arg(0)
1342  >>> v2 = b.arg(0).arg(1)
1343  >>> v1
1344  Var(1)
1345  >>> v2
1346  Var(0)
1347  >>> get_var_index(v1)
1348  1
1349  >>> get_var_index(v2)
1350  0
1351  """
1352  if z3_debug():
1353  _z3_assert(is_var(a), "Z3 bound variable expected")
1354  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1355 
1356 
1357 def is_app_of(a, k):
1358  """Return `True` if `a` is an application of the given kind `k`.
1359 
1360  >>> x = Int('x')
1361  >>> n = x + 1
1362  >>> is_app_of(n, Z3_OP_ADD)
1363  True
1364  >>> is_app_of(n, Z3_OP_MUL)
1365  False
1366  """
1367  return is_app(a) and a.decl().kind() == k
1368 
1369 
1370 def If(a, b, c, ctx=None):
1371  """Create a Z3 if-then-else expression.
1372 
1373  >>> x = Int('x')
1374  >>> y = Int('y')
1375  >>> max = If(x > y, x, y)
1376  >>> max
1377  If(x > y, x, y)
1378  >>> simplify(max)
1379  If(x <= y, y, x)
1380  """
1381  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1382  return Cond(a, b, c, ctx)
1383  else:
1384  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1385  s = BoolSort(ctx)
1386  a = s.cast(a)
1387  b, c = _coerce_exprs(b, c, ctx)
1388  if z3_debug():
1389  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1390  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1391 
1392 
1393 def Distinct(*args):
1394  """Create a Z3 distinct expression.
1395 
1396  >>> x = Int('x')
1397  >>> y = Int('y')
1398  >>> Distinct(x, y)
1399  x != y
1400  >>> z = Int('z')
1401  >>> Distinct(x, y, z)
1402  Distinct(x, y, z)
1403  >>> simplify(Distinct(x, y, z))
1404  Distinct(x, y, z)
1405  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1406  And(Not(x == y), Not(x == z), Not(y == z))
1407  """
1408  args = _get_args(args)
1409  ctx = _ctx_from_ast_arg_list(args)
1410  if z3_debug():
1411  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1412  args = _coerce_expr_list(args, ctx)
1413  _args, sz = _to_ast_array(args)
1414  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1415 
1416 
1417 def _mk_bin(f, a, b):
1418  args = (Ast * 2)()
1419  if z3_debug():
1420  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1421  args[0] = a.as_ast()
1422  args[1] = b.as_ast()
1423  return f(a.ctx.ref(), 2, args)
1424 
1425 
1426 def Const(name, sort):
1427  """Create a constant of the given sort.
1428 
1429  >>> Const('x', IntSort())
1430  x
1431  """
1432  if z3_debug():
1433  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1434  ctx = sort.ctx
1435  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1436 
1437 
1438 def Consts(names, sort):
1439  """Create several constants of the given sort.
1440 
1441  `names` is a string containing the names of all constants to be created.
1442  Blank spaces separate the names of different constants.
1443 
1444  >>> x, y, z = Consts('x y z', IntSort())
1445  >>> x + y + z
1446  x + y + z
1447  """
1448  if isinstance(names, str):
1449  names = names.split(" ")
1450  return [Const(name, sort) for name in names]
1451 
1452 
1453 def FreshConst(sort, prefix="c"):
1454  """Create a fresh constant of a specified sort"""
1455  ctx = _get_ctx(sort.ctx)
1456  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1457 
1458 
1459 def Var(idx, s):
1460  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1461 
1462  >>> Var(0, IntSort())
1463  Var(0)
1464  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1465  False
1466  """
1467  if z3_debug():
1468  _z3_assert(is_sort(s), "Z3 sort expected")
1469  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1470 
1471 
1472 def RealVar(idx, ctx=None):
1473  """
1474  Create a real free variable. Free variables are used to create quantified formulas.
1475  They are also used to create polynomials.
1476 
1477  >>> RealVar(0)
1478  Var(0)
1479  """
1480  return Var(idx, RealSort(ctx))
1481 
1482 
1483 def RealVarVector(n, ctx=None):
1484  """
1485  Create a list of Real free variables.
1486  The variables have ids: 0, 1, ..., n-1
1487 
1488  >>> x0, x1, x2, x3 = RealVarVector(4)
1489  >>> x2
1490  Var(2)
1491  """
1492  return [RealVar(i, ctx) for i in range(n)]
1493 
1494 
1499 
1500 
1502  """Boolean sort."""
1503 
1504  def cast(self, val):
1505  """Try to cast `val` as a Boolean.
1506 
1507  >>> x = BoolSort().cast(True)
1508  >>> x
1509  True
1510  >>> is_expr(x)
1511  True
1512  >>> is_expr(True)
1513  False
1514  >>> x.sort()
1515  Bool
1516  """
1517  if isinstance(val, bool):
1518  return BoolVal(val, self.ctxctx)
1519  if z3_debug():
1520  if not is_expr(val):
1521  msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1522  _z3_assert(is_expr(val), msg % (val, type(val)))
1523  if not self.eqeq(val.sort()):
1524  _z3_assert(self.eqeq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1525  return val
1526 
1527  def subsort(self, other):
1528  return isinstance(other, ArithSortRef)
1529 
1530  def is_int(self):
1531  return True
1532 
1533  def is_bool(self):
1534  return True
1535 
1536 
1538  """All Boolean expressions are instances of this class."""
1539 
1540  def sort(self):
1541  return BoolSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
1542 
1543  def __rmul__(self, other):
1544  return self * other
1545 
1546  def __mul__(self, other):
1547  """Create the Z3 expression `self * other`.
1548  """
1549  if other == 1:
1550  return self
1551  if other == 0:
1552  return 0
1553  return If(self, other, 0)
1554 
1555 
1556 def is_bool(a):
1557  """Return `True` if `a` is a Z3 Boolean expression.
1558 
1559  >>> p = Bool('p')
1560  >>> is_bool(p)
1561  True
1562  >>> q = Bool('q')
1563  >>> is_bool(And(p, q))
1564  True
1565  >>> x = Real('x')
1566  >>> is_bool(x)
1567  False
1568  >>> is_bool(x == 0)
1569  True
1570  """
1571  return isinstance(a, BoolRef)
1572 
1573 
1574 def is_true(a):
1575  """Return `True` if `a` is the Z3 true expression.
1576 
1577  >>> p = Bool('p')
1578  >>> is_true(p)
1579  False
1580  >>> is_true(simplify(p == p))
1581  True
1582  >>> x = Real('x')
1583  >>> is_true(x == 0)
1584  False
1585  >>> # True is a Python Boolean expression
1586  >>> is_true(True)
1587  False
1588  """
1589  return is_app_of(a, Z3_OP_TRUE)
1590 
1591 
1592 def is_false(a):
1593  """Return `True` if `a` is the Z3 false expression.
1594 
1595  >>> p = Bool('p')
1596  >>> is_false(p)
1597  False
1598  >>> is_false(False)
1599  False
1600  >>> is_false(BoolVal(False))
1601  True
1602  """
1603  return is_app_of(a, Z3_OP_FALSE)
1604 
1605 
1606 def is_and(a):
1607  """Return `True` if `a` is a Z3 and expression.
1608 
1609  >>> p, q = Bools('p q')
1610  >>> is_and(And(p, q))
1611  True
1612  >>> is_and(Or(p, q))
1613  False
1614  """
1615  return is_app_of(a, Z3_OP_AND)
1616 
1617 
1618 def is_or(a):
1619  """Return `True` if `a` is a Z3 or expression.
1620 
1621  >>> p, q = Bools('p q')
1622  >>> is_or(Or(p, q))
1623  True
1624  >>> is_or(And(p, q))
1625  False
1626  """
1627  return is_app_of(a, Z3_OP_OR)
1628 
1629 
1630 def is_implies(a):
1631  """Return `True` if `a` is a Z3 implication expression.
1632 
1633  >>> p, q = Bools('p q')
1634  >>> is_implies(Implies(p, q))
1635  True
1636  >>> is_implies(And(p, q))
1637  False
1638  """
1639  return is_app_of(a, Z3_OP_IMPLIES)
1640 
1641 
1642 def is_not(a):
1643  """Return `True` if `a` is a Z3 not expression.
1644 
1645  >>> p = Bool('p')
1646  >>> is_not(p)
1647  False
1648  >>> is_not(Not(p))
1649  True
1650  """
1651  return is_app_of(a, Z3_OP_NOT)
1652 
1653 
1654 def is_eq(a):
1655  """Return `True` if `a` is a Z3 equality expression.
1656 
1657  >>> x, y = Ints('x y')
1658  >>> is_eq(x == y)
1659  True
1660  """
1661  return is_app_of(a, Z3_OP_EQ)
1662 
1663 
1665  """Return `True` if `a` is a Z3 distinct expression.
1666 
1667  >>> x, y, z = Ints('x y z')
1668  >>> is_distinct(x == y)
1669  False
1670  >>> is_distinct(Distinct(x, y, z))
1671  True
1672  """
1673  return is_app_of(a, Z3_OP_DISTINCT)
1674 
1675 
1676 def BoolSort(ctx=None):
1677  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1678 
1679  >>> BoolSort()
1680  Bool
1681  >>> p = Const('p', BoolSort())
1682  >>> is_bool(p)
1683  True
1684  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1685  >>> r(0, 1)
1686  r(0, 1)
1687  >>> is_bool(r(0, 1))
1688  True
1689  """
1690  ctx = _get_ctx(ctx)
1691  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1692 
1693 
1694 def BoolVal(val, ctx=None):
1695  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1696 
1697  >>> BoolVal(True)
1698  True
1699  >>> is_true(BoolVal(True))
1700  True
1701  >>> is_true(True)
1702  False
1703  >>> is_false(BoolVal(False))
1704  True
1705  """
1706  ctx = _get_ctx(ctx)
1707  if val:
1708  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1709  else:
1710  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1711 
1712 
1713 def Bool(name, ctx=None):
1714  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1715 
1716  >>> p = Bool('p')
1717  >>> q = Bool('q')
1718  >>> And(p, q)
1719  And(p, q)
1720  """
1721  ctx = _get_ctx(ctx)
1722  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1723 
1724 
1725 def Bools(names, ctx=None):
1726  """Return a tuple of Boolean constants.
1727 
1728  `names` is a single string containing all names separated by blank spaces.
1729  If `ctx=None`, then the global context is used.
1730 
1731  >>> p, q, r = Bools('p q r')
1732  >>> And(p, Or(q, r))
1733  And(p, Or(q, r))
1734  """
1735  ctx = _get_ctx(ctx)
1736  if isinstance(names, str):
1737  names = names.split(" ")
1738  return [Bool(name, ctx) for name in names]
1739 
1740 
1741 def BoolVector(prefix, sz, ctx=None):
1742  """Return a list of Boolean constants of size `sz`.
1743 
1744  The constants are named using the given prefix.
1745  If `ctx=None`, then the global context is used.
1746 
1747  >>> P = BoolVector('p', 3)
1748  >>> P
1749  [p__0, p__1, p__2]
1750  >>> And(P)
1751  And(p__0, p__1, p__2)
1752  """
1753  return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1754 
1755 
1756 def FreshBool(prefix="b", ctx=None):
1757  """Return a fresh Boolean constant in the given context using the given prefix.
1758 
1759  If `ctx=None`, then the global context is used.
1760 
1761  >>> b1 = FreshBool()
1762  >>> b2 = FreshBool()
1763  >>> eq(b1, b2)
1764  False
1765  """
1766  ctx = _get_ctx(ctx)
1767  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1768 
1769 
1770 def Implies(a, b, ctx=None):
1771  """Create a Z3 implies expression.
1772 
1773  >>> p, q = Bools('p q')
1774  >>> Implies(p, q)
1775  Implies(p, q)
1776  """
1777  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1778  s = BoolSort(ctx)
1779  a = s.cast(a)
1780  b = s.cast(b)
1781  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1782 
1783 
1784 def Xor(a, b, ctx=None):
1785  """Create a Z3 Xor expression.
1786 
1787  >>> p, q = Bools('p q')
1788  >>> Xor(p, q)
1789  Xor(p, q)
1790  >>> simplify(Xor(p, q))
1791  Not(p == q)
1792  """
1793  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1794  s = BoolSort(ctx)
1795  a = s.cast(a)
1796  b = s.cast(b)
1797  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1798 
1799 
1800 def Not(a, ctx=None):
1801  """Create a Z3 not expression or probe.
1802 
1803  >>> p = Bool('p')
1804  >>> Not(Not(p))
1805  Not(Not(p))
1806  >>> simplify(Not(Not(p)))
1807  p
1808  """
1809  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1810  if is_probe(a):
1811  # Not is also used to build probes
1812  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1813  else:
1814  s = BoolSort(ctx)
1815  a = s.cast(a)
1816  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1817 
1818 
1819 def mk_not(a):
1820  if is_not(a):
1821  return a.arg(0)
1822  else:
1823  return Not(a)
1824 
1825 
1826 def _has_probe(args):
1827  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1828  for arg in args:
1829  if is_probe(arg):
1830  return True
1831  return False
1832 
1833 
1834 def And(*args):
1835  """Create a Z3 and-expression or and-probe.
1836 
1837  >>> p, q, r = Bools('p q r')
1838  >>> And(p, q, r)
1839  And(p, q, r)
1840  >>> P = BoolVector('p', 5)
1841  >>> And(P)
1842  And(p__0, p__1, p__2, p__3, p__4)
1843  """
1844  last_arg = None
1845  if len(args) > 0:
1846  last_arg = args[len(args) - 1]
1847  if isinstance(last_arg, Context):
1848  ctx = args[len(args) - 1]
1849  args = args[:len(args) - 1]
1850  elif len(args) == 1 and isinstance(args[0], AstVector):
1851  ctx = args[0].ctx
1852  args = [a for a in args[0]]
1853  else:
1854  ctx = None
1855  args = _get_args(args)
1856  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1857  if z3_debug():
1858  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1859  if _has_probe(args):
1860  return _probe_and(args, ctx)
1861  else:
1862  args = _coerce_expr_list(args, ctx)
1863  _args, sz = _to_ast_array(args)
1864  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1865 
1866 
1867 def Or(*args):
1868  """Create a Z3 or-expression or or-probe.
1869 
1870  >>> p, q, r = Bools('p q r')
1871  >>> Or(p, q, r)
1872  Or(p, q, r)
1873  >>> P = BoolVector('p', 5)
1874  >>> Or(P)
1875  Or(p__0, p__1, p__2, p__3, p__4)
1876  """
1877  last_arg = None
1878  if len(args) > 0:
1879  last_arg = args[len(args) - 1]
1880  if isinstance(last_arg, Context):
1881  ctx = args[len(args) - 1]
1882  args = args[:len(args) - 1]
1883  elif len(args) == 1 and isinstance(args[0], AstVector):
1884  ctx = args[0].ctx
1885  args = [a for a in args[0]]
1886  else:
1887  ctx = None
1888  args = _get_args(args)
1889  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1890  if z3_debug():
1891  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1892  if _has_probe(args):
1893  return _probe_or(args, ctx)
1894  else:
1895  args = _coerce_expr_list(args, ctx)
1896  _args, sz = _to_ast_array(args)
1897  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1898 
1899 
1904 
1905 
1907  """Patterns are hints for quantifier instantiation.
1908 
1909  """
1910 
1911  def as_ast(self):
1912  return Z3_pattern_to_ast(self.ctx_refctx_ref(), self.astast)
1913 
1914  def get_id(self):
1915  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_astas_ast())
1916 
1917 
1918 def is_pattern(a):
1919  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1920 
1921  >>> f = Function('f', IntSort(), IntSort())
1922  >>> x = Int('x')
1923  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1924  >>> q
1925  ForAll(x, f(x) == 0)
1926  >>> q.num_patterns()
1927  1
1928  >>> is_pattern(q.pattern(0))
1929  True
1930  >>> q.pattern(0)
1931  f(Var(0))
1932  """
1933  return isinstance(a, PatternRef)
1934 
1935 
1936 def MultiPattern(*args):
1937  """Create a Z3 multi-pattern using the given expressions `*args`
1938 
1939  >>> f = Function('f', IntSort(), IntSort())
1940  >>> g = Function('g', IntSort(), IntSort())
1941  >>> x = Int('x')
1942  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1943  >>> q
1944  ForAll(x, f(x) != g(x))
1945  >>> q.num_patterns()
1946  1
1947  >>> is_pattern(q.pattern(0))
1948  True
1949  >>> q.pattern(0)
1950  MultiPattern(f(Var(0)), g(Var(0)))
1951  """
1952  if z3_debug():
1953  _z3_assert(len(args) > 0, "At least one argument expected")
1954  _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1955  ctx = args[0].ctx
1956  args, sz = _to_ast_array(args)
1957  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1958 
1959 
1960 def _to_pattern(arg):
1961  if is_pattern(arg):
1962  return arg
1963  else:
1964  return MultiPattern(arg)
1965 
1966 
1971 
1972 
1974  """Universally and Existentially quantified formulas."""
1975 
1976  def as_ast(self):
1977  return self.astast
1978 
1979  def get_id(self):
1980  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_astas_ast())
1981 
1982  def sort(self):
1983  """Return the Boolean sort or sort of Lambda."""
1984  if self.is_lambdais_lambda():
1985  return _sort(self.ctxctx, self.as_astas_astas_astas_ast())
1986  return BoolSort(self.ctxctx)
1987 
1988  def is_forall(self):
1989  """Return `True` if `self` is a universal quantifier.
1990 
1991  >>> f = Function('f', IntSort(), IntSort())
1992  >>> x = Int('x')
1993  >>> q = ForAll(x, f(x) == 0)
1994  >>> q.is_forall()
1995  True
1996  >>> q = Exists(x, f(x) != 0)
1997  >>> q.is_forall()
1998  False
1999  """
2000  return Z3_is_quantifier_forall(self.ctx_refctx_ref(), self.astast)
2001 
2002  def is_exists(self):
2003  """Return `True` if `self` is an existential quantifier.
2004 
2005  >>> f = Function('f', IntSort(), IntSort())
2006  >>> x = Int('x')
2007  >>> q = ForAll(x, f(x) == 0)
2008  >>> q.is_exists()
2009  False
2010  >>> q = Exists(x, f(x) != 0)
2011  >>> q.is_exists()
2012  True
2013  """
2014  return Z3_is_quantifier_exists(self.ctx_refctx_ref(), self.astast)
2015 
2016  def is_lambda(self):
2017  """Return `True` if `self` is a lambda expression.
2018 
2019  >>> f = Function('f', IntSort(), IntSort())
2020  >>> x = Int('x')
2021  >>> q = Lambda(x, f(x))
2022  >>> q.is_lambda()
2023  True
2024  >>> q = Exists(x, f(x) != 0)
2025  >>> q.is_lambda()
2026  False
2027  """
2028  return Z3_is_lambda(self.ctx_refctx_ref(), self.astast)
2029 
2030  def __getitem__(self, arg):
2031  """Return the Z3 expression `self[arg]`.
2032  """
2033  if z3_debug():
2034  _z3_assert(self.is_lambdais_lambda(), "quantifier should be a lambda expression")
2035  return _array_select(self, arg)
2036 
2037  def weight(self):
2038  """Return the weight annotation of `self`.
2039 
2040  >>> f = Function('f', IntSort(), IntSort())
2041  >>> x = Int('x')
2042  >>> q = ForAll(x, f(x) == 0)
2043  >>> q.weight()
2044  1
2045  >>> q = ForAll(x, f(x) == 0, weight=10)
2046  >>> q.weight()
2047  10
2048  """
2049  return int(Z3_get_quantifier_weight(self.ctx_refctx_ref(), self.astast))
2050 
2051  def num_patterns(self):
2052  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2053 
2054  >>> f = Function('f', IntSort(), IntSort())
2055  >>> g = Function('g', IntSort(), IntSort())
2056  >>> x = Int('x')
2057  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2058  >>> q.num_patterns()
2059  2
2060  """
2061  return int(Z3_get_quantifier_num_patterns(self.ctx_refctx_ref(), self.astast))
2062 
2063  def pattern(self, idx):
2064  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2065 
2066  >>> f = Function('f', IntSort(), IntSort())
2067  >>> g = Function('g', IntSort(), IntSort())
2068  >>> x = Int('x')
2069  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2070  >>> q.num_patterns()
2071  2
2072  >>> q.pattern(0)
2073  f(Var(0))
2074  >>> q.pattern(1)
2075  g(Var(0))
2076  """
2077  if z3_debug():
2078  _z3_assert(idx < self.num_patternsnum_patterns(), "Invalid pattern idx")
2079  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2080 
2081  def num_no_patterns(self):
2082  """Return the number of no-patterns."""
2083  return Z3_get_quantifier_num_no_patterns(self.ctx_refctx_ref(), self.astast)
2084 
2085  def no_pattern(self, idx):
2086  """Return a no-pattern."""
2087  if z3_debug():
2088  _z3_assert(idx < self.num_no_patternsnum_no_patterns(), "Invalid no-pattern idx")
2089  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2090 
2091  def body(self):
2092  """Return the expression being quantified.
2093 
2094  >>> f = Function('f', IntSort(), IntSort())
2095  >>> x = Int('x')
2096  >>> q = ForAll(x, f(x) == 0)
2097  >>> q.body()
2098  f(Var(0)) == 0
2099  """
2100  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_refctx_ref(), self.astast), self.ctxctx)
2101 
2102  def num_vars(self):
2103  """Return the number of variables bounded by this quantifier.
2104 
2105  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2106  >>> x = Int('x')
2107  >>> y = Int('y')
2108  >>> q = ForAll([x, y], f(x, y) >= x)
2109  >>> q.num_vars()
2110  2
2111  """
2112  return int(Z3_get_quantifier_num_bound(self.ctx_refctx_ref(), self.astast))
2113 
2114  def var_name(self, idx):
2115  """Return a string representing a name used when displaying the quantifier.
2116 
2117  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2118  >>> x = Int('x')
2119  >>> y = Int('y')
2120  >>> q = ForAll([x, y], f(x, y) >= x)
2121  >>> q.var_name(0)
2122  'x'
2123  >>> q.var_name(1)
2124  'y'
2125  """
2126  if z3_debug():
2127  _z3_assert(idx < self.num_varsnum_vars(), "Invalid variable idx")
2128  return _symbol2py(self.ctxctx, Z3_get_quantifier_bound_name(self.ctx_refctx_ref(), self.astast, idx))
2129 
2130  def var_sort(self, idx):
2131  """Return the sort of a bound variable.
2132 
2133  >>> f = Function('f', IntSort(), RealSort(), IntSort())
2134  >>> x = Int('x')
2135  >>> y = Real('y')
2136  >>> q = ForAll([x, y], f(x, y) >= x)
2137  >>> q.var_sort(0)
2138  Int
2139  >>> q.var_sort(1)
2140  Real
2141  """
2142  if z3_debug():
2143  _z3_assert(idx < self.num_varsnum_vars(), "Invalid variable idx")
2144  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2145 
2146  def children(self):
2147  """Return a list containing a single element self.body()
2148 
2149  >>> f = Function('f', IntSort(), IntSort())
2150  >>> x = Int('x')
2151  >>> q = ForAll(x, f(x) == 0)
2152  >>> q.children()
2153  [f(Var(0)) == 0]
2154  """
2155  return [self.bodybody()]
2156 
2157 
2159  """Return `True` if `a` is a Z3 quantifier.
2160 
2161  >>> f = Function('f', IntSort(), IntSort())
2162  >>> x = Int('x')
2163  >>> q = ForAll(x, f(x) == 0)
2164  >>> is_quantifier(q)
2165  True
2166  >>> is_quantifier(f(x))
2167  False
2168  """
2169  return isinstance(a, QuantifierRef)
2170 
2171 
2172 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2173  if z3_debug():
2174  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2175  _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2176  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2177  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2178  if is_app(vs):
2179  ctx = vs.ctx
2180  vs = [vs]
2181  else:
2182  ctx = vs[0].ctx
2183  if not is_expr(body):
2184  body = BoolVal(body, ctx)
2185  num_vars = len(vs)
2186  if num_vars == 0:
2187  return body
2188  _vs = (Ast * num_vars)()
2189  for i in range(num_vars):
2190  # TODO: Check if is constant
2191  _vs[i] = vs[i].as_ast()
2192  patterns = [_to_pattern(p) for p in patterns]
2193  num_pats = len(patterns)
2194  _pats = (Pattern * num_pats)()
2195  for i in range(num_pats):
2196  _pats[i] = patterns[i].ast
2197  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2198  qid = to_symbol(qid, ctx)
2199  skid = to_symbol(skid, ctx)
2200  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2201  num_vars, _vs,
2202  num_pats, _pats,
2203  num_no_pats, _no_pats,
2204  body.as_ast()), ctx)
2205 
2206 
2207 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2208  """Create a Z3 forall formula.
2209 
2210  The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2211 
2212  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2213  >>> x = Int('x')
2214  >>> y = Int('y')
2215  >>> ForAll([x, y], f(x, y) >= x)
2216  ForAll([x, y], f(x, y) >= x)
2217  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2218  ForAll([x, y], f(x, y) >= x)
2219  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2220  ForAll([x, y], f(x, y) >= x)
2221  """
2222  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2223 
2224 
2225 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2226  """Create a Z3 exists formula.
2227 
2228  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2229 
2230 
2231  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2232  >>> x = Int('x')
2233  >>> y = Int('y')
2234  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2235  >>> q
2236  Exists([x, y], f(x, y) >= x)
2237  >>> is_quantifier(q)
2238  True
2239  >>> r = Tactic('nnf')(q).as_expr()
2240  >>> is_quantifier(r)
2241  False
2242  """
2243  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2244 
2245 
2246 def Lambda(vs, body):
2247  """Create a Z3 lambda expression.
2248 
2249  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2250  >>> mem0 = Array('mem0', IntSort(), IntSort())
2251  >>> lo, hi, e, i = Ints('lo hi e i')
2252  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2253  >>> mem1
2254  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2255  """
2256  ctx = body.ctx
2257  if is_app(vs):
2258  vs = [vs]
2259  num_vars = len(vs)
2260  _vs = (Ast * num_vars)()
2261  for i in range(num_vars):
2262  # TODO: Check if is constant
2263  _vs[i] = vs[i].as_ast()
2264  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2265 
2266 
2271 
2272 
2274  """Real and Integer sorts."""
2275 
2276  def is_real(self):
2277  """Return `True` if `self` is of the sort Real.
2278 
2279  >>> x = Real('x')
2280  >>> x.is_real()
2281  True
2282  >>> (x + 1).is_real()
2283  True
2284  >>> x = Int('x')
2285  >>> x.is_real()
2286  False
2287  """
2288  return self.kindkind() == Z3_REAL_SORT
2289 
2290  def is_int(self):
2291  """Return `True` if `self` is of the sort Integer.
2292 
2293  >>> x = Int('x')
2294  >>> x.is_int()
2295  True
2296  >>> (x + 1).is_int()
2297  True
2298  >>> x = Real('x')
2299  >>> x.is_int()
2300  False
2301  """
2302  return self.kindkind() == Z3_INT_SORT
2303 
2304  def is_bool(self):
2305  return False
2306 
2307  def subsort(self, other):
2308  """Return `True` if `self` is a subsort of `other`."""
2309  return self.is_intis_int() and is_arith_sort(other) and other.is_real()
2310 
2311  def cast(self, val):
2312  """Try to cast `val` as an Integer or Real.
2313 
2314  >>> IntSort().cast(10)
2315  10
2316  >>> is_int(IntSort().cast(10))
2317  True
2318  >>> is_int(10)
2319  False
2320  >>> RealSort().cast(10)
2321  10
2322  >>> is_real(RealSort().cast(10))
2323  True
2324  """
2325  if is_expr(val):
2326  if z3_debug():
2327  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
2328  val_s = val.sort()
2329  if self.eqeq(val_s):
2330  return val
2331  if val_s.is_int() and self.is_realis_real():
2332  return ToReal(val)
2333  if val_s.is_bool() and self.is_intis_int():
2334  return If(val, 1, 0)
2335  if val_s.is_bool() and self.is_realis_real():
2336  return ToReal(If(val, 1, 0))
2337  if z3_debug():
2338  _z3_assert(False, "Z3 Integer/Real expression expected")
2339  else:
2340  if self.is_intis_int():
2341  return IntVal(val, self.ctxctxctx)
2342  if self.is_realis_real():
2343  return RealVal(val, self.ctxctxctx)
2344  if z3_debug():
2345  msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2346  _z3_assert(False, msg % self)
2347 
2348 
2350  """Return `True` if s is an arithmetical sort (type).
2351 
2352  >>> is_arith_sort(IntSort())
2353  True
2354  >>> is_arith_sort(RealSort())
2355  True
2356  >>> is_arith_sort(BoolSort())
2357  False
2358  >>> n = Int('x') + 1
2359  >>> is_arith_sort(n.sort())
2360  True
2361  """
2362  return isinstance(s, ArithSortRef)
2363 
2364 
2366  """Integer and Real expressions."""
2367 
2368  def sort(self):
2369  """Return the sort (type) of the arithmetical expression `self`.
2370 
2371  >>> Int('x').sort()
2372  Int
2373  >>> (Real('x') + 1).sort()
2374  Real
2375  """
2376  return ArithSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2377 
2378  def is_int(self):
2379  """Return `True` if `self` is an integer expression.
2380 
2381  >>> x = Int('x')
2382  >>> x.is_int()
2383  True
2384  >>> (x + 1).is_int()
2385  True
2386  >>> y = Real('y')
2387  >>> (x + y).is_int()
2388  False
2389  """
2390  return self.sortsortsort().is_int()
2391 
2392  def is_real(self):
2393  """Return `True` if `self` is an real expression.
2394 
2395  >>> x = Real('x')
2396  >>> x.is_real()
2397  True
2398  >>> (x + 1).is_real()
2399  True
2400  """
2401  return self.sortsortsort().is_real()
2402 
2403  def __add__(self, other):
2404  """Create the Z3 expression `self + other`.
2405 
2406  >>> x = Int('x')
2407  >>> y = Int('y')
2408  >>> x + y
2409  x + y
2410  >>> (x + y).sort()
2411  Int
2412  """
2413  a, b = _coerce_exprs(self, other)
2414  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctxctx)
2415 
2416  def __radd__(self, other):
2417  """Create the Z3 expression `other + self`.
2418 
2419  >>> x = Int('x')
2420  >>> 10 + x
2421  10 + x
2422  """
2423  a, b = _coerce_exprs(self, other)
2424  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctxctx)
2425 
2426  def __mul__(self, other):
2427  """Create the Z3 expression `self * other`.
2428 
2429  >>> x = Real('x')
2430  >>> y = Real('y')
2431  >>> x * y
2432  x*y
2433  >>> (x * y).sort()
2434  Real
2435  """
2436  if isinstance(other, BoolRef):
2437  return If(other, self, 0)
2438  a, b = _coerce_exprs(self, other)
2439  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctxctx)
2440 
2441  def __rmul__(self, other):
2442  """Create the Z3 expression `other * self`.
2443 
2444  >>> x = Real('x')
2445  >>> 10 * x
2446  10*x
2447  """
2448  a, b = _coerce_exprs(self, other)
2449  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctxctx)
2450 
2451  def __sub__(self, other):
2452  """Create the Z3 expression `self - other`.
2453 
2454  >>> x = Int('x')
2455  >>> y = Int('y')
2456  >>> x - y
2457  x - y
2458  >>> (x - y).sort()
2459  Int
2460  """
2461  a, b = _coerce_exprs(self, other)
2462  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctxctx)
2463 
2464  def __rsub__(self, other):
2465  """Create the Z3 expression `other - self`.
2466 
2467  >>> x = Int('x')
2468  >>> 10 - x
2469  10 - x
2470  """
2471  a, b = _coerce_exprs(self, other)
2472  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctxctx)
2473 
2474  def __pow__(self, other):
2475  """Create the Z3 expression `self**other` (** is the power operator).
2476 
2477  >>> x = Real('x')
2478  >>> x**3
2479  x**3
2480  >>> (x**3).sort()
2481  Real
2482  >>> simplify(IntVal(2)**8)
2483  256
2484  """
2485  a, b = _coerce_exprs(self, other)
2486  return ArithRef(Z3_mk_power(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2487 
2488  def __rpow__(self, other):
2489  """Create the Z3 expression `other**self` (** is the power operator).
2490 
2491  >>> x = Real('x')
2492  >>> 2**x
2493  2**x
2494  >>> (2**x).sort()
2495  Real
2496  >>> simplify(2**IntVal(8))
2497  256
2498  """
2499  a, b = _coerce_exprs(self, other)
2500  return ArithRef(Z3_mk_power(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2501 
2502  def __div__(self, other):
2503  """Create the Z3 expression `other/self`.
2504 
2505  >>> x = Int('x')
2506  >>> y = Int('y')
2507  >>> x/y
2508  x/y
2509  >>> (x/y).sort()
2510  Int
2511  >>> (x/y).sexpr()
2512  '(div x y)'
2513  >>> x = Real('x')
2514  >>> y = Real('y')
2515  >>> x/y
2516  x/y
2517  >>> (x/y).sort()
2518  Real
2519  >>> (x/y).sexpr()
2520  '(/ x y)'
2521  """
2522  a, b = _coerce_exprs(self, other)
2523  return ArithRef(Z3_mk_div(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2524 
2525  def __truediv__(self, other):
2526  """Create the Z3 expression `other/self`."""
2527  return self.__div____div__(other)
2528 
2529  def __rdiv__(self, other):
2530  """Create the Z3 expression `other/self`.
2531 
2532  >>> x = Int('x')
2533  >>> 10/x
2534  10/x
2535  >>> (10/x).sexpr()
2536  '(div 10 x)'
2537  >>> x = Real('x')
2538  >>> 10/x
2539  10/x
2540  >>> (10/x).sexpr()
2541  '(/ 10.0 x)'
2542  """
2543  a, b = _coerce_exprs(self, other)
2544  return ArithRef(Z3_mk_div(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2545 
2546  def __rtruediv__(self, other):
2547  """Create the Z3 expression `other/self`."""
2548  return self.__rdiv____rdiv__(other)
2549 
2550  def __mod__(self, other):
2551  """Create the Z3 expression `other%self`.
2552 
2553  >>> x = Int('x')
2554  >>> y = Int('y')
2555  >>> x % y
2556  x%y
2557  >>> simplify(IntVal(10) % IntVal(3))
2558  1
2559  """
2560  a, b = _coerce_exprs(self, other)
2561  if z3_debug():
2562  _z3_assert(a.is_int(), "Z3 integer expression expected")
2563  return ArithRef(Z3_mk_mod(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2564 
2565  def __rmod__(self, other):
2566  """Create the Z3 expression `other%self`.
2567 
2568  >>> x = Int('x')
2569  >>> 10 % x
2570  10%x
2571  """
2572  a, b = _coerce_exprs(self, other)
2573  if z3_debug():
2574  _z3_assert(a.is_int(), "Z3 integer expression expected")
2575  return ArithRef(Z3_mk_mod(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2576 
2577  def __neg__(self):
2578  """Return an expression representing `-self`.
2579 
2580  >>> x = Int('x')
2581  >>> -x
2582  -x
2583  >>> simplify(-(-x))
2584  x
2585  """
2586  return ArithRef(Z3_mk_unary_minus(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2587 
2588  def __pos__(self):
2589  """Return `self`.
2590 
2591  >>> x = Int('x')
2592  >>> +x
2593  x
2594  """
2595  return self
2596 
2597  def __le__(self, other):
2598  """Create the Z3 expression `other <= self`.
2599 
2600  >>> x, y = Ints('x y')
2601  >>> x <= y
2602  x <= y
2603  >>> y = Real('y')
2604  >>> x <= y
2605  ToReal(x) <= y
2606  """
2607  a, b = _coerce_exprs(self, other)
2608  return BoolRef(Z3_mk_le(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2609 
2610  def __lt__(self, other):
2611  """Create the Z3 expression `other < self`.
2612 
2613  >>> x, y = Ints('x y')
2614  >>> x < y
2615  x < y
2616  >>> y = Real('y')
2617  >>> x < y
2618  ToReal(x) < y
2619  """
2620  a, b = _coerce_exprs(self, other)
2621  return BoolRef(Z3_mk_lt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2622 
2623  def __gt__(self, other):
2624  """Create the Z3 expression `other > self`.
2625 
2626  >>> x, y = Ints('x y')
2627  >>> x > y
2628  x > y
2629  >>> y = Real('y')
2630  >>> x > y
2631  ToReal(x) > y
2632  """
2633  a, b = _coerce_exprs(self, other)
2634  return BoolRef(Z3_mk_gt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2635 
2636  def __ge__(self, other):
2637  """Create the Z3 expression `other >= self`.
2638 
2639  >>> x, y = Ints('x y')
2640  >>> x >= y
2641  x >= y
2642  >>> y = Real('y')
2643  >>> x >= y
2644  ToReal(x) >= y
2645  """
2646  a, b = _coerce_exprs(self, other)
2647  return BoolRef(Z3_mk_ge(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2648 
2649 
2650 def is_arith(a):
2651  """Return `True` if `a` is an arithmetical expression.
2652 
2653  >>> x = Int('x')
2654  >>> is_arith(x)
2655  True
2656  >>> is_arith(x + 1)
2657  True
2658  >>> is_arith(1)
2659  False
2660  >>> is_arith(IntVal(1))
2661  True
2662  >>> y = Real('y')
2663  >>> is_arith(y)
2664  True
2665  >>> is_arith(y + 1)
2666  True
2667  """
2668  return isinstance(a, ArithRef)
2669 
2670 
2671 def is_int(a):
2672  """Return `True` if `a` is an integer expression.
2673 
2674  >>> x = Int('x')
2675  >>> is_int(x + 1)
2676  True
2677  >>> is_int(1)
2678  False
2679  >>> is_int(IntVal(1))
2680  True
2681  >>> y = Real('y')
2682  >>> is_int(y)
2683  False
2684  >>> is_int(y + 1)
2685  False
2686  """
2687  return is_arith(a) and a.is_int()
2688 
2689 
2690 def is_real(a):
2691  """Return `True` if `a` is a real expression.
2692 
2693  >>> x = Int('x')
2694  >>> is_real(x + 1)
2695  False
2696  >>> y = Real('y')
2697  >>> is_real(y)
2698  True
2699  >>> is_real(y + 1)
2700  True
2701  >>> is_real(1)
2702  False
2703  >>> is_real(RealVal(1))
2704  True
2705  """
2706  return is_arith(a) and a.is_real()
2707 
2708 
2709 def _is_numeral(ctx, a):
2710  return Z3_is_numeral_ast(ctx.ref(), a)
2711 
2712 
2713 def _is_algebraic(ctx, a):
2714  return Z3_is_algebraic_number(ctx.ref(), a)
2715 
2716 
2718  """Return `True` if `a` is an integer value of sort Int.
2719 
2720  >>> is_int_value(IntVal(1))
2721  True
2722  >>> is_int_value(1)
2723  False
2724  >>> is_int_value(Int('x'))
2725  False
2726  >>> n = Int('x') + 1
2727  >>> n
2728  x + 1
2729  >>> n.arg(1)
2730  1
2731  >>> is_int_value(n.arg(1))
2732  True
2733  >>> is_int_value(RealVal("1/3"))
2734  False
2735  >>> is_int_value(RealVal(1))
2736  False
2737  """
2738  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2739 
2740 
2742  """Return `True` if `a` is rational value of sort Real.
2743 
2744  >>> is_rational_value(RealVal(1))
2745  True
2746  >>> is_rational_value(RealVal("3/5"))
2747  True
2748  >>> is_rational_value(IntVal(1))
2749  False
2750  >>> is_rational_value(1)
2751  False
2752  >>> n = Real('x') + 1
2753  >>> n.arg(1)
2754  1
2755  >>> is_rational_value(n.arg(1))
2756  True
2757  >>> is_rational_value(Real('x'))
2758  False
2759  """
2760  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2761 
2762 
2764  """Return `True` if `a` is an algebraic value of sort Real.
2765 
2766  >>> is_algebraic_value(RealVal("3/5"))
2767  False
2768  >>> n = simplify(Sqrt(2))
2769  >>> n
2770  1.4142135623?
2771  >>> is_algebraic_value(n)
2772  True
2773  """
2774  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2775 
2776 
2777 def is_add(a):
2778  """Return `True` if `a` is an expression of the form b + c.
2779 
2780  >>> x, y = Ints('x y')
2781  >>> is_add(x + y)
2782  True
2783  >>> is_add(x - y)
2784  False
2785  """
2786  return is_app_of(a, Z3_OP_ADD)
2787 
2788 
2789 def is_mul(a):
2790  """Return `True` if `a` is an expression of the form b * c.
2791 
2792  >>> x, y = Ints('x y')
2793  >>> is_mul(x * y)
2794  True
2795  >>> is_mul(x - y)
2796  False
2797  """
2798  return is_app_of(a, Z3_OP_MUL)
2799 
2800 
2801 def is_sub(a):
2802  """Return `True` if `a` is an expression of the form b - c.
2803 
2804  >>> x, y = Ints('x y')
2805  >>> is_sub(x - y)
2806  True
2807  >>> is_sub(x + y)
2808  False
2809  """
2810  return is_app_of(a, Z3_OP_SUB)
2811 
2812 
2813 def is_div(a):
2814  """Return `True` if `a` is an expression of the form b / c.
2815 
2816  >>> x, y = Reals('x y')
2817  >>> is_div(x / y)
2818  True
2819  >>> is_div(x + y)
2820  False
2821  >>> x, y = Ints('x y')
2822  >>> is_div(x / y)
2823  False
2824  >>> is_idiv(x / y)
2825  True
2826  """
2827  return is_app_of(a, Z3_OP_DIV)
2828 
2829 
2830 def is_idiv(a):
2831  """Return `True` if `a` is an expression of the form b div c.
2832 
2833  >>> x, y = Ints('x y')
2834  >>> is_idiv(x / y)
2835  True
2836  >>> is_idiv(x + y)
2837  False
2838  """
2839  return is_app_of(a, Z3_OP_IDIV)
2840 
2841 
2842 def is_mod(a):
2843  """Return `True` if `a` is an expression of the form b % c.
2844 
2845  >>> x, y = Ints('x y')
2846  >>> is_mod(x % y)
2847  True
2848  >>> is_mod(x + y)
2849  False
2850  """
2851  return is_app_of(a, Z3_OP_MOD)
2852 
2853 
2854 def is_le(a):
2855  """Return `True` if `a` is an expression of the form b <= c.
2856 
2857  >>> x, y = Ints('x y')
2858  >>> is_le(x <= y)
2859  True
2860  >>> is_le(x < y)
2861  False
2862  """
2863  return is_app_of(a, Z3_OP_LE)
2864 
2865 
2866 def is_lt(a):
2867  """Return `True` if `a` is an expression of the form b < c.
2868 
2869  >>> x, y = Ints('x y')
2870  >>> is_lt(x < y)
2871  True
2872  >>> is_lt(x == y)
2873  False
2874  """
2875  return is_app_of(a, Z3_OP_LT)
2876 
2877 
2878 def is_ge(a):
2879  """Return `True` if `a` is an expression of the form b >= c.
2880 
2881  >>> x, y = Ints('x y')
2882  >>> is_ge(x >= y)
2883  True
2884  >>> is_ge(x == y)
2885  False
2886  """
2887  return is_app_of(a, Z3_OP_GE)
2888 
2889 
2890 def is_gt(a):
2891  """Return `True` if `a` is an expression of the form b > c.
2892 
2893  >>> x, y = Ints('x y')
2894  >>> is_gt(x > y)
2895  True
2896  >>> is_gt(x == y)
2897  False
2898  """
2899  return is_app_of(a, Z3_OP_GT)
2900 
2901 
2902 def is_is_int(a):
2903  """Return `True` if `a` is an expression of the form IsInt(b).
2904 
2905  >>> x = Real('x')
2906  >>> is_is_int(IsInt(x))
2907  True
2908  >>> is_is_int(x)
2909  False
2910  """
2911  return is_app_of(a, Z3_OP_IS_INT)
2912 
2913 
2914 def is_to_real(a):
2915  """Return `True` if `a` is an expression of the form ToReal(b).
2916 
2917  >>> x = Int('x')
2918  >>> n = ToReal(x)
2919  >>> n
2920  ToReal(x)
2921  >>> is_to_real(n)
2922  True
2923  >>> is_to_real(x)
2924  False
2925  """
2926  return is_app_of(a, Z3_OP_TO_REAL)
2927 
2928 
2929 def is_to_int(a):
2930  """Return `True` if `a` is an expression of the form ToInt(b).
2931 
2932  >>> x = Real('x')
2933  >>> n = ToInt(x)
2934  >>> n
2935  ToInt(x)
2936  >>> is_to_int(n)
2937  True
2938  >>> is_to_int(x)
2939  False
2940  """
2941  return is_app_of(a, Z3_OP_TO_INT)
2942 
2943 
2945  """Integer values."""
2946 
2947  def as_long(self):
2948  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2949 
2950  >>> v = IntVal(1)
2951  >>> v + 1
2952  1 + 1
2953  >>> v.as_long() + 1
2954  2
2955  """
2956  if z3_debug():
2957  _z3_assert(self.is_intis_int(), "Integer value expected")
2958  return int(self.as_stringas_string())
2959 
2960  def as_string(self):
2961  """Return a Z3 integer numeral as a Python string.
2962  >>> v = IntVal(100)
2963  >>> v.as_string()
2964  '100'
2965  """
2966  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
2967 
2968  def as_binary_string(self):
2969  """Return a Z3 integer numeral as a Python binary string.
2970  >>> v = IntVal(10)
2971  >>> v.as_binary_string()
2972  '1010'
2973  """
2974  return Z3_get_numeral_binary_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
2975 
2976 
2978  """Rational values."""
2979 
2980  def numerator(self):
2981  """ Return the numerator of a Z3 rational numeral.
2982 
2983  >>> is_rational_value(RealVal("3/5"))
2984  True
2985  >>> n = RealVal("3/5")
2986  >>> n.numerator()
2987  3
2988  >>> is_rational_value(Q(3,5))
2989  True
2990  >>> Q(3,5).numerator()
2991  3
2992  """
2993  return IntNumRef(Z3_get_numerator(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2994 
2995  def denominator(self):
2996  """ Return the denominator of a Z3 rational numeral.
2997 
2998  >>> is_rational_value(Q(3,5))
2999  True
3000  >>> n = Q(3,5)
3001  >>> n.denominator()
3002  5
3003  """
3004  return IntNumRef(Z3_get_denominator(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3005 
3007  """ Return the numerator as a Python long.
3008 
3009  >>> v = RealVal(10000000000)
3010  >>> v
3011  10000000000
3012  >>> v + 1
3013  10000000000 + 1
3014  >>> v.numerator_as_long() + 1 == 10000000001
3015  True
3016  """
3017  return self.numeratornumerator().as_long()
3018 
3020  """ Return the denominator as a Python long.
3021 
3022  >>> v = RealVal("1/3")
3023  >>> v
3024  1/3
3025  >>> v.denominator_as_long()
3026  3
3027  """
3028  return self.denominatordenominator().as_long()
3029 
3030  def is_int(self):
3031  return False
3032 
3033  def is_real(self):
3034  return True
3035 
3036  def is_int_value(self):
3037  return self.denominatordenominator().is_int() and self.denominator_as_longdenominator_as_long() == 1
3038 
3039  def as_long(self):
3040  _z3_assert(self.is_int_valueis_int_value(), "Expected integer fraction")
3041  return self.numerator_as_longnumerator_as_long()
3042 
3043  def as_decimal(self, prec):
3044  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3045 
3046  >>> v = RealVal("1/5")
3047  >>> v.as_decimal(3)
3048  '0.2'
3049  >>> v = RealVal("1/3")
3050  >>> v.as_decimal(3)
3051  '0.333?'
3052  """
3053  return Z3_get_numeral_decimal_string(self.ctx_refctx_ref(), self.as_astas_astas_ast(), prec)
3054 
3055  def as_string(self):
3056  """Return a Z3 rational numeral as a Python string.
3057 
3058  >>> v = Q(3,6)
3059  >>> v.as_string()
3060  '1/2'
3061  """
3062  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3063 
3064  def as_fraction(self):
3065  """Return a Z3 rational as a Python Fraction object.
3066 
3067  >>> v = RealVal("1/5")
3068  >>> v.as_fraction()
3069  Fraction(1, 5)
3070  """
3071  return Fraction(self.numerator_as_longnumerator_as_long(), self.denominator_as_longdenominator_as_long())
3072 
3073 
3075  """Algebraic irrational values."""
3076 
3077  def approx(self, precision=10):
3078  """Return a Z3 rational number that approximates the algebraic number `self`.
3079  The result `r` is such that |r - self| <= 1/10^precision
3080 
3081  >>> x = simplify(Sqrt(2))
3082  >>> x.approx(20)
3083  6838717160008073720548335/4835703278458516698824704
3084  >>> x.approx(5)
3085  2965821/2097152
3086  """
3087  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_refctx_ref(), self.as_astas_astas_ast(), precision), self.ctxctx)
3088 
3089  def as_decimal(self, prec):
3090  """Return a string representation of the algebraic number `self` in decimal notation
3091  using `prec` decimal places.
3092 
3093  >>> x = simplify(Sqrt(2))
3094  >>> x.as_decimal(10)
3095  '1.4142135623?'
3096  >>> x.as_decimal(20)
3097  '1.41421356237309504880?'
3098  """
3099  return Z3_get_numeral_decimal_string(self.ctx_refctx_ref(), self.as_astas_astas_ast(), prec)
3100 
3101  def poly(self):
3102  return AstVector(Z3_algebraic_get_poly(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3103 
3104  def index(self):
3105  return Z3_algebraic_get_i(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3106 
3107 
3108 def _py2expr(a, ctx=None):
3109  if isinstance(a, bool):
3110  return BoolVal(a, ctx)
3111  if _is_int(a):
3112  return IntVal(a, ctx)
3113  if isinstance(a, float):
3114  return RealVal(a, ctx)
3115  if isinstance(a, str):
3116  return StringVal(a, ctx)
3117  if is_expr(a):
3118  return a
3119  if z3_debug():
3120  _z3_assert(False, "Python bool, int, long or float expected")
3121 
3122 
3123 def IntSort(ctx=None):
3124  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3125 
3126  >>> IntSort()
3127  Int
3128  >>> x = Const('x', IntSort())
3129  >>> is_int(x)
3130  True
3131  >>> x.sort() == IntSort()
3132  True
3133  >>> x.sort() == BoolSort()
3134  False
3135  """
3136  ctx = _get_ctx(ctx)
3137  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3138 
3139 
3140 def RealSort(ctx=None):
3141  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3142 
3143  >>> RealSort()
3144  Real
3145  >>> x = Const('x', RealSort())
3146  >>> is_real(x)
3147  True
3148  >>> is_int(x)
3149  False
3150  >>> x.sort() == RealSort()
3151  True
3152  """
3153  ctx = _get_ctx(ctx)
3154  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3155 
3156 
3157 def _to_int_str(val):
3158  if isinstance(val, float):
3159  return str(int(val))
3160  elif isinstance(val, bool):
3161  if val:
3162  return "1"
3163  else:
3164  return "0"
3165  elif _is_int(val):
3166  return str(val)
3167  elif isinstance(val, str):
3168  return val
3169  if z3_debug():
3170  _z3_assert(False, "Python value cannot be used as a Z3 integer")
3171 
3172 
3173 def IntVal(val, ctx=None):
3174  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3175 
3176  >>> IntVal(1)
3177  1
3178  >>> IntVal("100")
3179  100
3180  """
3181  ctx = _get_ctx(ctx)
3182  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3183 
3184 
3185 def RealVal(val, ctx=None):
3186  """Return a Z3 real value.
3187 
3188  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3189  If `ctx=None`, then the global context is used.
3190 
3191  >>> RealVal(1)
3192  1
3193  >>> RealVal(1).sort()
3194  Real
3195  >>> RealVal("3/5")
3196  3/5
3197  >>> RealVal("1.5")
3198  3/2
3199  """
3200  ctx = _get_ctx(ctx)
3201  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3202 
3203 
3204 def RatVal(a, b, ctx=None):
3205  """Return a Z3 rational a/b.
3206 
3207  If `ctx=None`, then the global context is used.
3208 
3209  >>> RatVal(3,5)
3210  3/5
3211  >>> RatVal(3,5).sort()
3212  Real
3213  """
3214  if z3_debug():
3215  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3216  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3217  return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3218 
3219 
3220 def Q(a, b, ctx=None):
3221  """Return a Z3 rational a/b.
3222 
3223  If `ctx=None`, then the global context is used.
3224 
3225  >>> Q(3,5)
3226  3/5
3227  >>> Q(3,5).sort()
3228  Real
3229  """
3230  return simplify(RatVal(a, b, ctx=ctx))
3231 
3232 
3233 def Int(name, ctx=None):
3234  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3235 
3236  >>> x = Int('x')
3237  >>> is_int(x)
3238  True
3239  >>> is_int(x + 1)
3240  True
3241  """
3242  ctx = _get_ctx(ctx)
3243  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3244 
3245 
3246 def Ints(names, ctx=None):
3247  """Return a tuple of Integer constants.
3248 
3249  >>> x, y, z = Ints('x y z')
3250  >>> Sum(x, y, z)
3251  x + y + z
3252  """
3253  ctx = _get_ctx(ctx)
3254  if isinstance(names, str):
3255  names = names.split(" ")
3256  return [Int(name, ctx) for name in names]
3257 
3258 
3259 def IntVector(prefix, sz, ctx=None):
3260  """Return a list of integer constants of size `sz`.
3261 
3262  >>> X = IntVector('x', 3)
3263  >>> X
3264  [x__0, x__1, x__2]
3265  >>> Sum(X)
3266  x__0 + x__1 + x__2
3267  """
3268  ctx = _get_ctx(ctx)
3269  return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3270 
3271 
3272 def FreshInt(prefix="x", ctx=None):
3273  """Return a fresh integer constant in the given context using the given prefix.
3274 
3275  >>> x = FreshInt()
3276  >>> y = FreshInt()
3277  >>> eq(x, y)
3278  False
3279  >>> x.sort()
3280  Int
3281  """
3282  ctx = _get_ctx(ctx)
3283  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3284 
3285 
3286 def Real(name, ctx=None):
3287  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3288 
3289  >>> x = Real('x')
3290  >>> is_real(x)
3291  True
3292  >>> is_real(x + 1)
3293  True
3294  """
3295  ctx = _get_ctx(ctx)
3296  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3297 
3298 
3299 def Reals(names, ctx=None):
3300  """Return a tuple of real constants.
3301 
3302  >>> x, y, z = Reals('x y z')
3303  >>> Sum(x, y, z)
3304  x + y + z
3305  >>> Sum(x, y, z).sort()
3306  Real
3307  """
3308  ctx = _get_ctx(ctx)
3309  if isinstance(names, str):
3310  names = names.split(" ")
3311  return [Real(name, ctx) for name in names]
3312 
3313 
3314 def RealVector(prefix, sz, ctx=None):
3315  """Return a list of real constants of size `sz`.
3316 
3317  >>> X = RealVector('x', 3)
3318  >>> X
3319  [x__0, x__1, x__2]
3320  >>> Sum(X)
3321  x__0 + x__1 + x__2
3322  >>> Sum(X).sort()
3323  Real
3324  """
3325  ctx = _get_ctx(ctx)
3326  return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3327 
3328 
3329 def FreshReal(prefix="b", ctx=None):
3330  """Return a fresh real constant in the given context using the given prefix.
3331 
3332  >>> x = FreshReal()
3333  >>> y = FreshReal()
3334  >>> eq(x, y)
3335  False
3336  >>> x.sort()
3337  Real
3338  """
3339  ctx = _get_ctx(ctx)
3340  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3341 
3342 
3343 def ToReal(a):
3344  """ Return the Z3 expression ToReal(a).
3345 
3346  >>> x = Int('x')
3347  >>> x.sort()
3348  Int
3349  >>> n = ToReal(x)
3350  >>> n
3351  ToReal(x)
3352  >>> n.sort()
3353  Real
3354  """
3355  if z3_debug():
3356  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3357  ctx = a.ctx
3358  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3359 
3360 
3361 def ToInt(a):
3362  """ Return the Z3 expression ToInt(a).
3363 
3364  >>> x = Real('x')
3365  >>> x.sort()
3366  Real
3367  >>> n = ToInt(x)
3368  >>> n
3369  ToInt(x)
3370  >>> n.sort()
3371  Int
3372  """
3373  if z3_debug():
3374  _z3_assert(a.is_real(), "Z3 real expression expected.")
3375  ctx = a.ctx
3376  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3377 
3378 
3379 def IsInt(a):
3380  """ Return the Z3 predicate IsInt(a).
3381 
3382  >>> x = Real('x')
3383  >>> IsInt(x + "1/2")
3384  IsInt(x + 1/2)
3385  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3386  [x = 1/2]
3387  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3388  no solution
3389  """
3390  if z3_debug():
3391  _z3_assert(a.is_real(), "Z3 real expression expected.")
3392  ctx = a.ctx
3393  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3394 
3395 
3396 def Sqrt(a, ctx=None):
3397  """ Return a Z3 expression which represents the square root of a.
3398 
3399  >>> x = Real('x')
3400  >>> Sqrt(x)
3401  x**(1/2)
3402  """
3403  if not is_expr(a):
3404  ctx = _get_ctx(ctx)
3405  a = RealVal(a, ctx)
3406  return a ** "1/2"
3407 
3408 
3409 def Cbrt(a, ctx=None):
3410  """ Return a Z3 expression which represents the cubic root of a.
3411 
3412  >>> x = Real('x')
3413  >>> Cbrt(x)
3414  x**(1/3)
3415  """
3416  if not is_expr(a):
3417  ctx = _get_ctx(ctx)
3418  a = RealVal(a, ctx)
3419  return a ** "1/3"
3420 
3421 
3426 
3427 
3429  """Bit-vector sort."""
3430 
3431  def size(self):
3432  """Return the size (number of bits) of the bit-vector sort `self`.
3433 
3434  >>> b = BitVecSort(32)
3435  >>> b.size()
3436  32
3437  """
3438  return int(Z3_get_bv_sort_size(self.ctx_refctx_ref(), self.astast))
3439 
3440  def subsort(self, other):
3441  return is_bv_sort(other) and self.sizesize() < other.size()
3442 
3443  def cast(self, val):
3444  """Try to cast `val` as a Bit-Vector.
3445 
3446  >>> b = BitVecSort(32)
3447  >>> b.cast(10)
3448  10
3449  >>> b.cast(10).sexpr()
3450  '#x0000000a'
3451  """
3452  if is_expr(val):
3453  if z3_debug():
3454  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
3455  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3456  return val
3457  else:
3458  return BitVecVal(val, self)
3459 
3460 
3461 def is_bv_sort(s):
3462  """Return True if `s` is a Z3 bit-vector sort.
3463 
3464  >>> is_bv_sort(BitVecSort(32))
3465  True
3466  >>> is_bv_sort(IntSort())
3467  False
3468  """
3469  return isinstance(s, BitVecSortRef)
3470 
3471 
3473  """Bit-vector expressions."""
3474 
3475  def sort(self):
3476  """Return the sort of the bit-vector expression `self`.
3477 
3478  >>> x = BitVec('x', 32)
3479  >>> x.sort()
3480  BitVec(32)
3481  >>> x.sort() == BitVecSort(32)
3482  True
3483  """
3484  return BitVecSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3485 
3486  def size(self):
3487  """Return the number of bits of the bit-vector expression `self`.
3488 
3489  >>> x = BitVec('x', 32)
3490  >>> (x + 1).size()
3491  32
3492  >>> Concat(x, x).size()
3493  64
3494  """
3495  return self.sortsortsort().size()
3496 
3497  def __add__(self, other):
3498  """Create the Z3 expression `self + other`.
3499 
3500  >>> x = BitVec('x', 32)
3501  >>> y = BitVec('y', 32)
3502  >>> x + y
3503  x + y
3504  >>> (x + y).sort()
3505  BitVec(32)
3506  """
3507  a, b = _coerce_exprs(self, other)
3508  return BitVecRef(Z3_mk_bvadd(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3509 
3510  def __radd__(self, other):
3511  """Create the Z3 expression `other + self`.
3512 
3513  >>> x = BitVec('x', 32)
3514  >>> 10 + x
3515  10 + x
3516  """
3517  a, b = _coerce_exprs(self, other)
3518  return BitVecRef(Z3_mk_bvadd(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3519 
3520  def __mul__(self, other):
3521  """Create the Z3 expression `self * other`.
3522 
3523  >>> x = BitVec('x', 32)
3524  >>> y = BitVec('y', 32)
3525  >>> x * y
3526  x*y
3527  >>> (x * y).sort()
3528  BitVec(32)
3529  """
3530  a, b = _coerce_exprs(self, other)
3531  return BitVecRef(Z3_mk_bvmul(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3532 
3533  def __rmul__(self, other):
3534  """Create the Z3 expression `other * self`.
3535 
3536  >>> x = BitVec('x', 32)
3537  >>> 10 * x
3538  10*x
3539  """
3540  a, b = _coerce_exprs(self, other)
3541  return BitVecRef(Z3_mk_bvmul(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3542 
3543  def __sub__(self, other):
3544  """Create the Z3 expression `self - other`.
3545 
3546  >>> x = BitVec('x', 32)
3547  >>> y = BitVec('y', 32)
3548  >>> x - y
3549  x - y
3550  >>> (x - y).sort()
3551  BitVec(32)
3552  """
3553  a, b = _coerce_exprs(self, other)
3554  return BitVecRef(Z3_mk_bvsub(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3555 
3556  def __rsub__(self, other):
3557  """Create the Z3 expression `other - self`.
3558 
3559  >>> x = BitVec('x', 32)
3560  >>> 10 - x
3561  10 - x
3562  """
3563  a, b = _coerce_exprs(self, other)
3564  return BitVecRef(Z3_mk_bvsub(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3565 
3566  def __or__(self, other):
3567  """Create the Z3 expression bitwise-or `self | other`.
3568 
3569  >>> x = BitVec('x', 32)
3570  >>> y = BitVec('y', 32)
3571  >>> x | y
3572  x | y
3573  >>> (x | y).sort()
3574  BitVec(32)
3575  """
3576  a, b = _coerce_exprs(self, other)
3577  return BitVecRef(Z3_mk_bvor(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3578 
3579  def __ror__(self, other):
3580  """Create the Z3 expression bitwise-or `other | self`.
3581 
3582  >>> x = BitVec('x', 32)
3583  >>> 10 | x
3584  10 | x
3585  """
3586  a, b = _coerce_exprs(self, other)
3587  return BitVecRef(Z3_mk_bvor(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3588 
3589  def __and__(self, other):
3590  """Create the Z3 expression bitwise-and `self & other`.
3591 
3592  >>> x = BitVec('x', 32)
3593  >>> y = BitVec('y', 32)
3594  >>> x & y
3595  x & y
3596  >>> (x & y).sort()
3597  BitVec(32)
3598  """
3599  a, b = _coerce_exprs(self, other)
3600  return BitVecRef(Z3_mk_bvand(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3601 
3602  def __rand__(self, other):
3603  """Create the Z3 expression bitwise-or `other & self`.
3604 
3605  >>> x = BitVec('x', 32)
3606  >>> 10 & x
3607  10 & x
3608  """
3609  a, b = _coerce_exprs(self, other)
3610  return BitVecRef(Z3_mk_bvand(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3611 
3612  def __xor__(self, other):
3613  """Create the Z3 expression bitwise-xor `self ^ other`.
3614 
3615  >>> x = BitVec('x', 32)
3616  >>> y = BitVec('y', 32)
3617  >>> x ^ y
3618  x ^ y
3619  >>> (x ^ y).sort()
3620  BitVec(32)
3621  """
3622  a, b = _coerce_exprs(self, other)
3623  return BitVecRef(Z3_mk_bvxor(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3624 
3625  def __rxor__(self, other):
3626  """Create the Z3 expression bitwise-xor `other ^ self`.
3627 
3628  >>> x = BitVec('x', 32)
3629  >>> 10 ^ x
3630  10 ^ x
3631  """
3632  a, b = _coerce_exprs(self, other)
3633  return BitVecRef(Z3_mk_bvxor(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3634 
3635  def __pos__(self):
3636  """Return `self`.
3637 
3638  >>> x = BitVec('x', 32)
3639  >>> +x
3640  x
3641  """
3642  return self
3643 
3644  def __neg__(self):
3645  """Return an expression representing `-self`.
3646 
3647  >>> x = BitVec('x', 32)
3648  >>> -x
3649  -x
3650  >>> simplify(-(-x))
3651  x
3652  """
3653  return BitVecRef(Z3_mk_bvneg(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3654 
3655  def __invert__(self):
3656  """Create the Z3 expression bitwise-not `~self`.
3657 
3658  >>> x = BitVec('x', 32)
3659  >>> ~x
3660  ~x
3661  >>> simplify(~(~x))
3662  x
3663  """
3664  return BitVecRef(Z3_mk_bvnot(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3665 
3666  def __div__(self, other):
3667  """Create the Z3 expression (signed) division `self / other`.
3668 
3669  Use the function UDiv() for unsigned division.
3670 
3671  >>> x = BitVec('x', 32)
3672  >>> y = BitVec('y', 32)
3673  >>> x / y
3674  x/y
3675  >>> (x / y).sort()
3676  BitVec(32)
3677  >>> (x / y).sexpr()
3678  '(bvsdiv x y)'
3679  >>> UDiv(x, y).sexpr()
3680  '(bvudiv x y)'
3681  """
3682  a, b = _coerce_exprs(self, other)
3683  return BitVecRef(Z3_mk_bvsdiv(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3684 
3685  def __truediv__(self, other):
3686  """Create the Z3 expression (signed) division `self / other`."""
3687  return self.__div____div__(other)
3688 
3689  def __rdiv__(self, other):
3690  """Create the Z3 expression (signed) division `other / self`.
3691 
3692  Use the function UDiv() for unsigned division.
3693 
3694  >>> x = BitVec('x', 32)
3695  >>> 10 / x
3696  10/x
3697  >>> (10 / x).sexpr()
3698  '(bvsdiv #x0000000a x)'
3699  >>> UDiv(10, x).sexpr()
3700  '(bvudiv #x0000000a x)'
3701  """
3702  a, b = _coerce_exprs(self, other)
3703  return BitVecRef(Z3_mk_bvsdiv(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3704 
3705  def __rtruediv__(self, other):
3706  """Create the Z3 expression (signed) division `other / self`."""
3707  return self.__rdiv____rdiv__(other)
3708 
3709  def __mod__(self, other):
3710  """Create the Z3 expression (signed) mod `self % other`.
3711 
3712  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3713 
3714  >>> x = BitVec('x', 32)
3715  >>> y = BitVec('y', 32)
3716  >>> x % y
3717  x%y
3718  >>> (x % y).sort()
3719  BitVec(32)
3720  >>> (x % y).sexpr()
3721  '(bvsmod x y)'
3722  >>> URem(x, y).sexpr()
3723  '(bvurem x y)'
3724  >>> SRem(x, y).sexpr()
3725  '(bvsrem x y)'
3726  """
3727  a, b = _coerce_exprs(self, other)
3728  return BitVecRef(Z3_mk_bvsmod(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3729 
3730  def __rmod__(self, other):
3731  """Create the Z3 expression (signed) mod `other % self`.
3732 
3733  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3734 
3735  >>> x = BitVec('x', 32)
3736  >>> 10 % x
3737  10%x
3738  >>> (10 % x).sexpr()
3739  '(bvsmod #x0000000a x)'
3740  >>> URem(10, x).sexpr()
3741  '(bvurem #x0000000a x)'
3742  >>> SRem(10, x).sexpr()
3743  '(bvsrem #x0000000a x)'
3744  """
3745  a, b = _coerce_exprs(self, other)
3746  return BitVecRef(Z3_mk_bvsmod(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3747 
3748  def __le__(self, other):
3749  """Create the Z3 expression (signed) `other <= self`.
3750 
3751  Use the function ULE() for unsigned less than or equal to.
3752 
3753  >>> x, y = BitVecs('x y', 32)
3754  >>> x <= y
3755  x <= y
3756  >>> (x <= y).sexpr()
3757  '(bvsle x y)'
3758  >>> ULE(x, y).sexpr()
3759  '(bvule x y)'
3760  """
3761  a, b = _coerce_exprs(self, other)
3762  return BoolRef(Z3_mk_bvsle(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3763 
3764  def __lt__(self, other):
3765  """Create the Z3 expression (signed) `other < self`.
3766 
3767  Use the function ULT() for unsigned less than.
3768 
3769  >>> x, y = BitVecs('x y', 32)
3770  >>> x < y
3771  x < y
3772  >>> (x < y).sexpr()
3773  '(bvslt x y)'
3774  >>> ULT(x, y).sexpr()
3775  '(bvult x y)'
3776  """
3777  a, b = _coerce_exprs(self, other)
3778  return BoolRef(Z3_mk_bvslt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3779 
3780  def __gt__(self, other):
3781  """Create the Z3 expression (signed) `other > self`.
3782 
3783  Use the function UGT() for unsigned greater than.
3784 
3785  >>> x, y = BitVecs('x y', 32)
3786  >>> x > y
3787  x > y
3788  >>> (x > y).sexpr()
3789  '(bvsgt x y)'
3790  >>> UGT(x, y).sexpr()
3791  '(bvugt x y)'
3792  """
3793  a, b = _coerce_exprs(self, other)
3794  return BoolRef(Z3_mk_bvsgt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3795 
3796  def __ge__(self, other):
3797  """Create the Z3 expression (signed) `other >= self`.
3798 
3799  Use the function UGE() for unsigned greater than or equal to.
3800 
3801  >>> x, y = BitVecs('x y', 32)
3802  >>> x >= y
3803  x >= y
3804  >>> (x >= y).sexpr()
3805  '(bvsge x y)'
3806  >>> UGE(x, y).sexpr()
3807  '(bvuge x y)'
3808  """
3809  a, b = _coerce_exprs(self, other)
3810  return BoolRef(Z3_mk_bvsge(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3811 
3812  def __rshift__(self, other):
3813  """Create the Z3 expression (arithmetical) right shift `self >> other`
3814 
3815  Use the function LShR() for the right logical shift
3816 
3817  >>> x, y = BitVecs('x y', 32)
3818  >>> x >> y
3819  x >> y
3820  >>> (x >> y).sexpr()
3821  '(bvashr x y)'
3822  >>> LShR(x, y).sexpr()
3823  '(bvlshr x y)'
3824  >>> BitVecVal(4, 3)
3825  4
3826  >>> BitVecVal(4, 3).as_signed_long()
3827  -4
3828  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3829  -2
3830  >>> simplify(BitVecVal(4, 3) >> 1)
3831  6
3832  >>> simplify(LShR(BitVecVal(4, 3), 1))
3833  2
3834  >>> simplify(BitVecVal(2, 3) >> 1)
3835  1
3836  >>> simplify(LShR(BitVecVal(2, 3), 1))
3837  1
3838  """
3839  a, b = _coerce_exprs(self, other)
3840  return BitVecRef(Z3_mk_bvashr(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3841 
3842  def __lshift__(self, other):
3843  """Create the Z3 expression left shift `self << other`
3844 
3845  >>> x, y = BitVecs('x y', 32)
3846  >>> x << y
3847  x << y
3848  >>> (x << y).sexpr()
3849  '(bvshl x y)'
3850  >>> simplify(BitVecVal(2, 3) << 1)
3851  4
3852  """
3853  a, b = _coerce_exprs(self, other)
3854  return BitVecRef(Z3_mk_bvshl(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3855 
3856  def __rrshift__(self, other):
3857  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3858 
3859  Use the function LShR() for the right logical shift
3860 
3861  >>> x = BitVec('x', 32)
3862  >>> 10 >> x
3863  10 >> x
3864  >>> (10 >> x).sexpr()
3865  '(bvashr #x0000000a x)'
3866  """
3867  a, b = _coerce_exprs(self, other)
3868  return BitVecRef(Z3_mk_bvashr(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3869 
3870  def __rlshift__(self, other):
3871  """Create the Z3 expression left shift `other << self`.
3872 
3873  Use the function LShR() for the right logical shift
3874 
3875  >>> x = BitVec('x', 32)
3876  >>> 10 << x
3877  10 << x
3878  >>> (10 << x).sexpr()
3879  '(bvshl #x0000000a x)'
3880  """
3881  a, b = _coerce_exprs(self, other)
3882  return BitVecRef(Z3_mk_bvshl(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3883 
3884 
3886  """Bit-vector values."""
3887 
3888  def as_long(self):
3889  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3890 
3891  >>> v = BitVecVal(0xbadc0de, 32)
3892  >>> v
3893  195936478
3894  >>> print("0x%.8x" % v.as_long())
3895  0x0badc0de
3896  """
3897  return int(self.as_stringas_string())
3898 
3899  def as_signed_long(self):
3900  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3901  The most significant bit is assumed to be the sign.
3902 
3903  >>> BitVecVal(4, 3).as_signed_long()
3904  -4
3905  >>> BitVecVal(7, 3).as_signed_long()
3906  -1
3907  >>> BitVecVal(3, 3).as_signed_long()
3908  3
3909  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3910  -1
3911  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3912  -1
3913  """
3914  sz = self.sizesize()
3915  val = self.as_longas_long()
3916  if val >= 2**(sz - 1):
3917  val = val - 2**sz
3918  if val < -2**(sz - 1):
3919  val = val + 2**sz
3920  return int(val)
3921 
3922  def as_string(self):
3923  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3924 
3925  def as_binary_string(self):
3926  return Z3_get_numeral_binary_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3927 
3928 
3929 def is_bv(a):
3930  """Return `True` if `a` is a Z3 bit-vector expression.
3931 
3932  >>> b = BitVec('b', 32)
3933  >>> is_bv(b)
3934  True
3935  >>> is_bv(b + 10)
3936  True
3937  >>> is_bv(Int('x'))
3938  False
3939  """
3940  return isinstance(a, BitVecRef)
3941 
3942 
3944  """Return `True` if `a` is a Z3 bit-vector numeral value.
3945 
3946  >>> b = BitVec('b', 32)
3947  >>> is_bv_value(b)
3948  False
3949  >>> b = BitVecVal(10, 32)
3950  >>> b
3951  10
3952  >>> is_bv_value(b)
3953  True
3954  """
3955  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3956 
3957 
3958 def BV2Int(a, is_signed=False):
3959  """Return the Z3 expression BV2Int(a).
3960 
3961  >>> b = BitVec('b', 3)
3962  >>> BV2Int(b).sort()
3963  Int
3964  >>> x = Int('x')
3965  >>> x > BV2Int(b)
3966  x > BV2Int(b)
3967  >>> x > BV2Int(b, is_signed=False)
3968  x > BV2Int(b)
3969  >>> x > BV2Int(b, is_signed=True)
3970  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3971  >>> solve(x > BV2Int(b), b == 1, x < 3)
3972  [x = 2, b = 1]
3973  """
3974  if z3_debug():
3975  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3976  ctx = a.ctx
3977  # investigate problem with bv2int
3978  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3979 
3980 
3981 def Int2BV(a, num_bits):
3982  """Return the z3 expression Int2BV(a, num_bits).
3983  It is a bit-vector of width num_bits and represents the
3984  modulo of a by 2^num_bits
3985  """
3986  ctx = a.ctx
3987  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3988 
3989 
3990 def BitVecSort(sz, ctx=None):
3991  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3992 
3993  >>> Byte = BitVecSort(8)
3994  >>> Word = BitVecSort(16)
3995  >>> Byte
3996  BitVec(8)
3997  >>> x = Const('x', Byte)
3998  >>> eq(x, BitVec('x', 8))
3999  True
4000  """
4001  ctx = _get_ctx(ctx)
4002  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4003 
4004 
4005 def BitVecVal(val, bv, ctx=None):
4006  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4007 
4008  >>> v = BitVecVal(10, 32)
4009  >>> v
4010  10
4011  >>> print("0x%.8x" % v.as_long())
4012  0x0000000a
4013  """
4014  if is_bv_sort(bv):
4015  ctx = bv.ctx
4016  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4017  else:
4018  ctx = _get_ctx(ctx)
4019  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4020 
4021 
4022 def BitVec(name, bv, ctx=None):
4023  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4024  If `ctx=None`, then the global context is used.
4025 
4026  >>> x = BitVec('x', 16)
4027  >>> is_bv(x)
4028  True
4029  >>> x.size()
4030  16
4031  >>> x.sort()
4032  BitVec(16)
4033  >>> word = BitVecSort(16)
4034  >>> x2 = BitVec('x', word)
4035  >>> eq(x, x2)
4036  True
4037  """
4038  if isinstance(bv, BitVecSortRef):
4039  ctx = bv.ctx
4040  else:
4041  ctx = _get_ctx(ctx)
4042  bv = BitVecSort(bv, ctx)
4043  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4044 
4045 
4046 def BitVecs(names, bv, ctx=None):
4047  """Return a tuple of bit-vector constants of size bv.
4048 
4049  >>> x, y, z = BitVecs('x y z', 16)
4050  >>> x.size()
4051  16
4052  >>> x.sort()
4053  BitVec(16)
4054  >>> Sum(x, y, z)
4055  0 + x + y + z
4056  >>> Product(x, y, z)
4057  1*x*y*z
4058  >>> simplify(Product(x, y, z))
4059  x*y*z
4060  """
4061  ctx = _get_ctx(ctx)
4062  if isinstance(names, str):
4063  names = names.split(" ")
4064  return [BitVec(name, bv, ctx) for name in names]
4065 
4066 
4067 def Concat(*args):
4068  """Create a Z3 bit-vector concatenation expression.
4069 
4070  >>> v = BitVecVal(1, 4)
4071  >>> Concat(v, v+1, v)
4072  Concat(Concat(1, 1 + 1), 1)
4073  >>> simplify(Concat(v, v+1, v))
4074  289
4075  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4076  121
4077  """
4078  args = _get_args(args)
4079  sz = len(args)
4080  if z3_debug():
4081  _z3_assert(sz >= 2, "At least two arguments expected.")
4082 
4083  ctx = None
4084  for a in args:
4085  if is_expr(a):
4086  ctx = a.ctx
4087  break
4088  if is_seq(args[0]) or isinstance(args[0], str):
4089  args = [_coerce_seq(s, ctx) for s in args]
4090  if z3_debug():
4091  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4092  v = (Ast * sz)()
4093  for i in range(sz):
4094  v[i] = args[i].as_ast()
4095  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4096 
4097  if is_re(args[0]):
4098  if z3_debug():
4099  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4100  v = (Ast * sz)()
4101  for i in range(sz):
4102  v[i] = args[i].as_ast()
4103  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4104 
4105  if z3_debug():
4106  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4107  r = args[0]
4108  for i in range(sz - 1):
4109  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4110  return r
4111 
4112 
4113 def Extract(high, low, a):
4114  """Create a Z3 bit-vector extraction expression.
4115  Extract is overloaded to also work on sequence extraction.
4116  The functions SubString and SubSeq are redirected to Extract.
4117  For this case, the arguments are reinterpreted as:
4118  high - is a sequence (string)
4119  low - is an offset
4120  a - is the length to be extracted
4121 
4122  >>> x = BitVec('x', 8)
4123  >>> Extract(6, 2, x)
4124  Extract(6, 2, x)
4125  >>> Extract(6, 2, x).sort()
4126  BitVec(5)
4127  >>> simplify(Extract(StringVal("abcd"),2,1))
4128  "c"
4129  """
4130  if isinstance(high, str):
4131  high = StringVal(high)
4132  if is_seq(high):
4133  s = high
4134  offset, length = _coerce_exprs(low, a, s.ctx)
4135  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4136  if z3_debug():
4137  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4138  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4139  "First and second arguments must be non negative integers")
4140  _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4141  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4142 
4143 
4144 def _check_bv_args(a, b):
4145  if z3_debug():
4146  _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4147 
4148 
4149 def ULE(a, b):
4150  """Create the Z3 expression (unsigned) `other <= self`.
4151 
4152  Use the operator <= for signed less than or equal to.
4153 
4154  >>> x, y = BitVecs('x y', 32)
4155  >>> ULE(x, y)
4156  ULE(x, y)
4157  >>> (x <= y).sexpr()
4158  '(bvsle x y)'
4159  >>> ULE(x, y).sexpr()
4160  '(bvule x y)'
4161  """
4162  _check_bv_args(a, b)
4163  a, b = _coerce_exprs(a, b)
4164  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4165 
4166 
4167 def ULT(a, b):
4168  """Create the Z3 expression (unsigned) `other < self`.
4169 
4170  Use the operator < for signed less than.
4171 
4172  >>> x, y = BitVecs('x y', 32)
4173  >>> ULT(x, y)
4174  ULT(x, y)
4175  >>> (x < y).sexpr()
4176  '(bvslt x y)'
4177  >>> ULT(x, y).sexpr()
4178  '(bvult x y)'
4179  """
4180  _check_bv_args(a, b)
4181  a, b = _coerce_exprs(a, b)
4182  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4183 
4184 
4185 def UGE(a, b):
4186  """Create the Z3 expression (unsigned) `other >= self`.
4187 
4188  Use the operator >= for signed greater than or equal to.
4189 
4190  >>> x, y = BitVecs('x y', 32)
4191  >>> UGE(x, y)
4192  UGE(x, y)
4193  >>> (x >= y).sexpr()
4194  '(bvsge x y)'
4195  >>> UGE(x, y).sexpr()
4196  '(bvuge x y)'
4197  """
4198  _check_bv_args(a, b)
4199  a, b = _coerce_exprs(a, b)
4200  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4201 
4202 
4203 def UGT(a, b):
4204  """Create the Z3 expression (unsigned) `other > self`.
4205 
4206  Use the operator > for signed greater than.
4207 
4208  >>> x, y = BitVecs('x y', 32)
4209  >>> UGT(x, y)
4210  UGT(x, y)
4211  >>> (x > y).sexpr()
4212  '(bvsgt x y)'
4213  >>> UGT(x, y).sexpr()
4214  '(bvugt x y)'
4215  """
4216  _check_bv_args(a, b)
4217  a, b = _coerce_exprs(a, b)
4218  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4219 
4220 
4221 def UDiv(a, b):
4222  """Create the Z3 expression (unsigned) division `self / other`.
4223 
4224  Use the operator / for signed division.
4225 
4226  >>> x = BitVec('x', 32)
4227  >>> y = BitVec('y', 32)
4228  >>> UDiv(x, y)
4229  UDiv(x, y)
4230  >>> UDiv(x, y).sort()
4231  BitVec(32)
4232  >>> (x / y).sexpr()
4233  '(bvsdiv x y)'
4234  >>> UDiv(x, y).sexpr()
4235  '(bvudiv x y)'
4236  """
4237  _check_bv_args(a, b)
4238  a, b = _coerce_exprs(a, b)
4239  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4240 
4241 
4242 def URem(a, b):
4243  """Create the Z3 expression (unsigned) remainder `self % other`.
4244 
4245  Use the operator % for signed modulus, and SRem() for signed remainder.
4246 
4247  >>> x = BitVec('x', 32)
4248  >>> y = BitVec('y', 32)
4249  >>> URem(x, y)
4250  URem(x, y)
4251  >>> URem(x, y).sort()
4252  BitVec(32)
4253  >>> (x % y).sexpr()
4254  '(bvsmod x y)'
4255  >>> URem(x, y).sexpr()
4256  '(bvurem x y)'
4257  """
4258  _check_bv_args(a, b)
4259  a, b = _coerce_exprs(a, b)
4260  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4261 
4262 
4263 def SRem(a, b):
4264  """Create the Z3 expression signed remainder.
4265 
4266  Use the operator % for signed modulus, and URem() for unsigned remainder.
4267 
4268  >>> x = BitVec('x', 32)
4269  >>> y = BitVec('y', 32)
4270  >>> SRem(x, y)
4271  SRem(x, y)
4272  >>> SRem(x, y).sort()
4273  BitVec(32)
4274  >>> (x % y).sexpr()
4275  '(bvsmod x y)'
4276  >>> SRem(x, y).sexpr()
4277  '(bvsrem x y)'
4278  """
4279  _check_bv_args(a, b)
4280  a, b = _coerce_exprs(a, b)
4281  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4282 
4283 
4284 def LShR(a, b):
4285  """Create the Z3 expression logical right shift.
4286 
4287  Use the operator >> for the arithmetical right shift.
4288 
4289  >>> x, y = BitVecs('x y', 32)
4290  >>> LShR(x, y)
4291  LShR(x, y)
4292  >>> (x >> y).sexpr()
4293  '(bvashr x y)'
4294  >>> LShR(x, y).sexpr()
4295  '(bvlshr x y)'
4296  >>> BitVecVal(4, 3)
4297  4
4298  >>> BitVecVal(4, 3).as_signed_long()
4299  -4
4300  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4301  -2
4302  >>> simplify(BitVecVal(4, 3) >> 1)
4303  6
4304  >>> simplify(LShR(BitVecVal(4, 3), 1))
4305  2
4306  >>> simplify(BitVecVal(2, 3) >> 1)
4307  1
4308  >>> simplify(LShR(BitVecVal(2, 3), 1))
4309  1
4310  """
4311  _check_bv_args(a, b)
4312  a, b = _coerce_exprs(a, b)
4313  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4314 
4315 
4316 def RotateLeft(a, b):
4317  """Return an expression representing `a` rotated to the left `b` times.
4318 
4319  >>> a, b = BitVecs('a b', 16)
4320  >>> RotateLeft(a, b)
4321  RotateLeft(a, b)
4322  >>> simplify(RotateLeft(a, 0))
4323  a
4324  >>> simplify(RotateLeft(a, 16))
4325  a
4326  """
4327  _check_bv_args(a, b)
4328  a, b = _coerce_exprs(a, b)
4329  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4330 
4331 
4332 def RotateRight(a, b):
4333  """Return an expression representing `a` rotated to the right `b` times.
4334 
4335  >>> a, b = BitVecs('a b', 16)
4336  >>> RotateRight(a, b)
4337  RotateRight(a, b)
4338  >>> simplify(RotateRight(a, 0))
4339  a
4340  >>> simplify(RotateRight(a, 16))
4341  a
4342  """
4343  _check_bv_args(a, b)
4344  a, b = _coerce_exprs(a, b)
4345  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4346 
4347 
4348 def SignExt(n, a):
4349  """Return a bit-vector expression with `n` extra sign-bits.
4350 
4351  >>> x = BitVec('x', 16)
4352  >>> n = SignExt(8, x)
4353  >>> n.size()
4354  24
4355  >>> n
4356  SignExt(8, x)
4357  >>> n.sort()
4358  BitVec(24)
4359  >>> v0 = BitVecVal(2, 2)
4360  >>> v0
4361  2
4362  >>> v0.size()
4363  2
4364  >>> v = simplify(SignExt(6, v0))
4365  >>> v
4366  254
4367  >>> v.size()
4368  8
4369  >>> print("%.x" % v.as_long())
4370  fe
4371  """
4372  if z3_debug():
4373  _z3_assert(_is_int(n), "First argument must be an integer")
4374  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4375  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4376 
4377 
4378 def ZeroExt(n, a):
4379  """Return a bit-vector expression with `n` extra zero-bits.
4380 
4381  >>> x = BitVec('x', 16)
4382  >>> n = ZeroExt(8, x)
4383  >>> n.size()
4384  24
4385  >>> n
4386  ZeroExt(8, x)
4387  >>> n.sort()
4388  BitVec(24)
4389  >>> v0 = BitVecVal(2, 2)
4390  >>> v0
4391  2
4392  >>> v0.size()
4393  2
4394  >>> v = simplify(ZeroExt(6, v0))
4395  >>> v
4396  2
4397  >>> v.size()
4398  8
4399  """
4400  if z3_debug():
4401  _z3_assert(_is_int(n), "First argument must be an integer")
4402  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4403  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4404 
4405 
4406 def RepeatBitVec(n, a):
4407  """Return an expression representing `n` copies of `a`.
4408 
4409  >>> x = BitVec('x', 8)
4410  >>> n = RepeatBitVec(4, x)
4411  >>> n
4412  RepeatBitVec(4, x)
4413  >>> n.size()
4414  32
4415  >>> v0 = BitVecVal(10, 4)
4416  >>> print("%.x" % v0.as_long())
4417  a
4418  >>> v = simplify(RepeatBitVec(4, v0))
4419  >>> v.size()
4420  16
4421  >>> print("%.x" % v.as_long())
4422  aaaa
4423  """
4424  if z3_debug():
4425  _z3_assert(_is_int(n), "First argument must be an integer")
4426  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4427  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4428 
4429 
4430 def BVRedAnd(a):
4431  """Return the reduction-and expression of `a`."""
4432  if z3_debug():
4433  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4434  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4435 
4436 
4437 def BVRedOr(a):
4438  """Return the reduction-or expression of `a`."""
4439  if z3_debug():
4440  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4441  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4442 
4443 
4444 def BVAddNoOverflow(a, b, signed):
4445  """A predicate the determines that bit-vector addition does not overflow"""
4446  _check_bv_args(a, b)
4447  a, b = _coerce_exprs(a, b)
4448  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4449 
4450 
4452  """A predicate the determines that signed bit-vector addition does not underflow"""
4453  _check_bv_args(a, b)
4454  a, b = _coerce_exprs(a, b)
4455  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4456 
4457 
4459  """A predicate the determines that bit-vector subtraction does not overflow"""
4460  _check_bv_args(a, b)
4461  a, b = _coerce_exprs(a, b)
4462  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4463 
4464 
4465 def BVSubNoUnderflow(a, b, signed):
4466  """A predicate the determines that bit-vector subtraction does not underflow"""
4467  _check_bv_args(a, b)
4468  a, b = _coerce_exprs(a, b)
4469  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4470 
4471 
4473  """A predicate the determines that bit-vector signed division does not overflow"""
4474  _check_bv_args(a, b)
4475  a, b = _coerce_exprs(a, b)
4476  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4477 
4478 
4480  """A predicate the determines that bit-vector unary negation does not overflow"""
4481  if z3_debug():
4482  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4483  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4484 
4485 
4486 def BVMulNoOverflow(a, b, signed):
4487  """A predicate the determines that bit-vector multiplication does not overflow"""
4488  _check_bv_args(a, b)
4489  a, b = _coerce_exprs(a, b)
4490  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4491 
4492 
4494  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4495  _check_bv_args(a, b)
4496  a, b = _coerce_exprs(a, b)
4497  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4498 
4499 
4500 
4505 
4507  """Array sorts."""
4508 
4509  def domain(self):
4510  """Return the domain of the array sort `self`.
4511 
4512  >>> A = ArraySort(IntSort(), BoolSort())
4513  >>> A.domain()
4514  Int
4515  """
4516  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_refctx_ref(), self.astast), self.ctxctx)
4517 
4518  def domain_n(self, i):
4519  """Return the domain of the array sort `self`.
4520  """
4521  return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_refctx_ref(), self.astast, i), self.ctxctx)
4522 
4523  def range(self):
4524  """Return the range of the array sort `self`.
4525 
4526  >>> A = ArraySort(IntSort(), BoolSort())
4527  >>> A.range()
4528  Bool
4529  """
4530  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_refctx_ref(), self.astast), self.ctxctx)
4531 
4532 
4534  """Array expressions. """
4535 
4536  def sort(self):
4537  """Return the array sort of the array expression `self`.
4538 
4539  >>> a = Array('a', IntSort(), BoolSort())
4540  >>> a.sort()
4541  Array(Int, Bool)
4542  """
4543  return ArraySortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
4544 
4545  def domain(self):
4546  """Shorthand for `self.sort().domain()`.
4547 
4548  >>> a = Array('a', IntSort(), BoolSort())
4549  >>> a.domain()
4550  Int
4551  """
4552  return self.sortsortsort().domain()
4553 
4554  def domain_n(self, i):
4555  """Shorthand for self.sort().domain_n(i)`."""
4556  return self.sortsortsort().domain_n(i)
4557 
4558  def range(self):
4559  """Shorthand for `self.sort().range()`.
4560 
4561  >>> a = Array('a', IntSort(), BoolSort())
4562  >>> a.range()
4563  Bool
4564  """
4565  return self.sortsortsort().range()
4566 
4567  def __getitem__(self, arg):
4568  """Return the Z3 expression `self[arg]`.
4569 
4570  >>> a = Array('a', IntSort(), BoolSort())
4571  >>> i = Int('i')
4572  >>> a[i]
4573  a[i]
4574  >>> a[i].sexpr()
4575  '(select a i)'
4576  """
4577  return _array_select(self, arg)
4578 
4579  def default(self):
4580  return _to_expr_ref(Z3_mk_array_default(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
4581 
4582 
4583 def _array_select(ar, arg):
4584  if isinstance(arg, tuple):
4585  args = [ar.domain_n(i).cast(arg[i]) for i in range(len(arg))]
4586  _args, sz = _to_ast_array(args)
4587  return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4588  arg = ar.domain().cast(arg)
4589  return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4590 
4591 
4593  return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4594 
4595 
4596 def is_array(a):
4597  """Return `True` if `a` is a Z3 array expression.
4598 
4599  >>> a = Array('a', IntSort(), IntSort())
4600  >>> is_array(a)
4601  True
4602  >>> is_array(Store(a, 0, 1))
4603  True
4604  >>> is_array(a[0])
4605  False
4606  """
4607  return isinstance(a, ArrayRef)
4608 
4609 
4611  """Return `True` if `a` is a Z3 constant array.
4612 
4613  >>> a = K(IntSort(), 10)
4614  >>> is_const_array(a)
4615  True
4616  >>> a = Array('a', IntSort(), IntSort())
4617  >>> is_const_array(a)
4618  False
4619  """
4620  return is_app_of(a, Z3_OP_CONST_ARRAY)
4621 
4622 
4623 def is_K(a):
4624  """Return `True` if `a` is a Z3 constant array.
4625 
4626  >>> a = K(IntSort(), 10)
4627  >>> is_K(a)
4628  True
4629  >>> a = Array('a', IntSort(), IntSort())
4630  >>> is_K(a)
4631  False
4632  """
4633  return is_app_of(a, Z3_OP_CONST_ARRAY)
4634 
4635 
4636 def is_map(a):
4637  """Return `True` if `a` is a Z3 map array expression.
4638 
4639  >>> f = Function('f', IntSort(), IntSort())
4640  >>> b = Array('b', IntSort(), IntSort())
4641  >>> a = Map(f, b)
4642  >>> a
4643  Map(f, b)
4644  >>> is_map(a)
4645  True
4646  >>> is_map(b)
4647  False
4648  """
4649  return is_app_of(a, Z3_OP_ARRAY_MAP)
4650 
4651 
4652 def is_default(a):
4653  """Return `True` if `a` is a Z3 default array expression.
4654  >>> d = Default(K(IntSort(), 10))
4655  >>> is_default(d)
4656  True
4657  """
4658  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4659 
4660 
4662  """Return the function declaration associated with a Z3 map array expression.
4663 
4664  >>> f = Function('f', IntSort(), IntSort())
4665  >>> b = Array('b', IntSort(), IntSort())
4666  >>> a = Map(f, b)
4667  >>> eq(f, get_map_func(a))
4668  True
4669  >>> get_map_func(a)
4670  f
4671  >>> get_map_func(a)(0)
4672  f(0)
4673  """
4674  if z3_debug():
4675  _z3_assert(is_map(a), "Z3 array map expression expected.")
4676  return FuncDeclRef(
4678  a.ctx_ref(),
4679  Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4680  ),
4681  ctx=a.ctx,
4682  )
4683 
4684 
4685 def ArraySort(*sig):
4686  """Return the Z3 array sort with the given domain and range sorts.
4687 
4688  >>> A = ArraySort(IntSort(), BoolSort())
4689  >>> A
4690  Array(Int, Bool)
4691  >>> A.domain()
4692  Int
4693  >>> A.range()
4694  Bool
4695  >>> AA = ArraySort(IntSort(), A)
4696  >>> AA
4697  Array(Int, Array(Int, Bool))
4698  """
4699  sig = _get_args(sig)
4700  if z3_debug():
4701  _z3_assert(len(sig) > 1, "At least two arguments expected")
4702  arity = len(sig) - 1
4703  r = sig[arity]
4704  d = sig[0]
4705  if z3_debug():
4706  for s in sig:
4707  _z3_assert(is_sort(s), "Z3 sort expected")
4708  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4709  ctx = d.ctx
4710  if len(sig) == 2:
4711  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4712  dom = (Sort * arity)()
4713  for i in range(arity):
4714  dom[i] = sig[i].ast
4715  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4716 
4717 
4718 def Array(name, *sorts):
4719  """Return an array constant named `name` with the given domain and range sorts.
4720 
4721  >>> a = Array('a', IntSort(), IntSort())
4722  >>> a.sort()
4723  Array(Int, Int)
4724  >>> a[0]
4725  a[0]
4726  """
4727  s = ArraySort(sorts)
4728  ctx = s.ctx
4729  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4730 
4731 
4732 def Update(a, *args):
4733  """Return a Z3 store array expression.
4734 
4735  >>> a = Array('a', IntSort(), IntSort())
4736  >>> i, v = Ints('i v')
4737  >>> s = Update(a, i, v)
4738  >>> s.sort()
4739  Array(Int, Int)
4740  >>> prove(s[i] == v)
4741  proved
4742  >>> j = Int('j')
4743  >>> prove(Implies(i != j, s[j] == a[j]))
4744  proved
4745  """
4746  if z3_debug():
4747  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4748  args = _get_args(args)
4749  ctx = a.ctx
4750  if len(args) <= 1:
4751  raise Z3Exception("array update requires index and value arguments")
4752  if len(args) == 2:
4753  i = args[0]
4754  v = args[1]
4755  i = a.sort().domain().cast(i)
4756  v = a.sort().range().cast(v)
4757  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4758  v = a.sort().range().cast(args[-1])
4759  idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
4760  _args, sz = _to_ast_array(idxs)
4761  return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
4762 
4763 
4764 def Default(a):
4765  """ Return a default value for array expression.
4766  >>> b = K(IntSort(), 1)
4767  >>> prove(Default(b) == 1)
4768  proved
4769  """
4770  if z3_debug():
4771  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4772  return a.default()
4773 
4774 
4775 def Store(a, *args):
4776  """Return a Z3 store array expression.
4777 
4778  >>> a = Array('a', IntSort(), IntSort())
4779  >>> i, v = Ints('i v')
4780  >>> s = Store(a, i, v)
4781  >>> s.sort()
4782  Array(Int, Int)
4783  >>> prove(s[i] == v)
4784  proved
4785  >>> j = Int('j')
4786  >>> prove(Implies(i != j, s[j] == a[j]))
4787  proved
4788  """
4789  return Update(a, args)
4790 
4791 
4792 def Select(a, *args):
4793  """Return a Z3 select array expression.
4794 
4795  >>> a = Array('a', IntSort(), IntSort())
4796  >>> i = Int('i')
4797  >>> Select(a, i)
4798  a[i]
4799  >>> eq(Select(a, i), a[i])
4800  True
4801  """
4802  args = _get_args(args)
4803  if z3_debug():
4804  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4805  return a[args]
4806 
4807 
4808 def Map(f, *args):
4809  """Return a Z3 map array expression.
4810 
4811  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4812  >>> a1 = Array('a1', IntSort(), IntSort())
4813  >>> a2 = Array('a2', IntSort(), IntSort())
4814  >>> b = Map(f, a1, a2)
4815  >>> b
4816  Map(f, a1, a2)
4817  >>> prove(b[0] == f(a1[0], a2[0]))
4818  proved
4819  """
4820  args = _get_args(args)
4821  if z3_debug():
4822  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4823  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4824  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4825  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4826  _args, sz = _to_ast_array(args)
4827  ctx = f.ctx
4828  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4829 
4830 
4831 def K(dom, v):
4832  """Return a Z3 constant array expression.
4833 
4834  >>> a = K(IntSort(), 10)
4835  >>> a
4836  K(Int, 10)
4837  >>> a.sort()
4838  Array(Int, Int)
4839  >>> i = Int('i')
4840  >>> a[i]
4841  K(Int, 10)[i]
4842  >>> simplify(a[i])
4843  10
4844  """
4845  if z3_debug():
4846  _z3_assert(is_sort(dom), "Z3 sort expected")
4847  ctx = dom.ctx
4848  if not is_expr(v):
4849  v = _py2expr(v, ctx)
4850  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4851 
4852 
4853 def Ext(a, b):
4854  """Return extensionality index for one-dimensional arrays.
4855  >> a, b = Consts('a b', SetSort(IntSort()))
4856  >> Ext(a, b)
4857  Ext(a, b)
4858  """
4859  ctx = a.ctx
4860  if z3_debug():
4861  _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
4862  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4863 
4864 
4865 def SetHasSize(a, k):
4866  ctx = a.ctx
4867  k = _py2expr(k, ctx)
4868  return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4869 
4870 
4871 def is_select(a):
4872  """Return `True` if `a` is a Z3 array select application.
4873 
4874  >>> a = Array('a', IntSort(), IntSort())
4875  >>> is_select(a)
4876  False
4877  >>> i = Int('i')
4878  >>> is_select(a[i])
4879  True
4880  """
4881  return is_app_of(a, Z3_OP_SELECT)
4882 
4883 
4884 def is_store(a):
4885  """Return `True` if `a` is a Z3 array store application.
4886 
4887  >>> a = Array('a', IntSort(), IntSort())
4888  >>> is_store(a)
4889  False
4890  >>> is_store(Store(a, 0, 1))
4891  True
4892  """
4893  return is_app_of(a, Z3_OP_STORE)
4894 
4895 
4900 
4901 
4902 def SetSort(s):
4903  """ Create a set sort over element sort s"""
4904  return ArraySort(s, BoolSort())
4905 
4906 
4907 def EmptySet(s):
4908  """Create the empty set
4909  >>> EmptySet(IntSort())
4910  K(Int, False)
4911  """
4912  ctx = s.ctx
4913  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4914 
4915 
4916 def FullSet(s):
4917  """Create the full set
4918  >>> FullSet(IntSort())
4919  K(Int, True)
4920  """
4921  ctx = s.ctx
4922  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4923 
4924 
4925 def SetUnion(*args):
4926  """ Take the union of sets
4927  >>> a = Const('a', SetSort(IntSort()))
4928  >>> b = Const('b', SetSort(IntSort()))
4929  >>> SetUnion(a, b)
4930  union(a, b)
4931  """
4932  args = _get_args(args)
4933  ctx = _ctx_from_ast_arg_list(args)
4934  _args, sz = _to_ast_array(args)
4935  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4936 
4937 
4938 def SetIntersect(*args):
4939  """ Take the union of sets
4940  >>> a = Const('a', SetSort(IntSort()))
4941  >>> b = Const('b', SetSort(IntSort()))
4942  >>> SetIntersect(a, b)
4943  intersection(a, b)
4944  """
4945  args = _get_args(args)
4946  ctx = _ctx_from_ast_arg_list(args)
4947  _args, sz = _to_ast_array(args)
4948  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4949 
4950 
4951 def SetAdd(s, e):
4952  """ Add element e to set s
4953  >>> a = Const('a', SetSort(IntSort()))
4954  >>> SetAdd(a, 1)
4955  Store(a, 1, True)
4956  """
4957  ctx = _ctx_from_ast_arg_list([s, e])
4958  e = _py2expr(e, ctx)
4959  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4960 
4961 
4962 def SetDel(s, e):
4963  """ Remove element e to set s
4964  >>> a = Const('a', SetSort(IntSort()))
4965  >>> SetDel(a, 1)
4966  Store(a, 1, False)
4967  """
4968  ctx = _ctx_from_ast_arg_list([s, e])
4969  e = _py2expr(e, ctx)
4970  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4971 
4972 
4974  """ The complement of set s
4975  >>> a = Const('a', SetSort(IntSort()))
4976  >>> SetComplement(a)
4977  complement(a)
4978  """
4979  ctx = s.ctx
4980  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4981 
4982 
4983 def SetDifference(a, b):
4984  """ The set difference of a and b
4985  >>> a = Const('a', SetSort(IntSort()))
4986  >>> b = Const('b', SetSort(IntSort()))
4987  >>> SetDifference(a, b)
4988  setminus(a, b)
4989  """
4990  ctx = _ctx_from_ast_arg_list([a, b])
4991  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4992 
4993 
4994 def IsMember(e, s):
4995  """ Check if e is a member of set s
4996  >>> a = Const('a', SetSort(IntSort()))
4997  >>> IsMember(1, a)
4998  a[1]
4999  """
5000  ctx = _ctx_from_ast_arg_list([s, e])
5001  e = _py2expr(e, ctx)
5002  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5003 
5004 
5005 def IsSubset(a, b):
5006  """ Check if a is a subset of b
5007  >>> a = Const('a', SetSort(IntSort()))
5008  >>> b = Const('b', SetSort(IntSort()))
5009  >>> IsSubset(a, b)
5010  subset(a, b)
5011  """
5012  ctx = _ctx_from_ast_arg_list([a, b])
5013  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5014 
5015 
5016 
5021 
5022 def _valid_accessor(acc):
5023  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5024  if not isinstance(acc, tuple):
5025  return False
5026  if len(acc) != 2:
5027  return False
5028  return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5029 
5030 
5031 class Datatype:
5032  """Helper class for declaring Z3 datatypes.
5033 
5034  >>> List = Datatype('List')
5035  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5036  >>> List.declare('nil')
5037  >>> List = List.create()
5038  >>> # List is now a Z3 declaration
5039  >>> List.nil
5040  nil
5041  >>> List.cons(10, List.nil)
5042  cons(10, nil)
5043  >>> List.cons(10, List.nil).sort()
5044  List
5045  >>> cons = List.cons
5046  >>> nil = List.nil
5047  >>> car = List.car
5048  >>> cdr = List.cdr
5049  >>> n = cons(1, cons(0, nil))
5050  >>> n
5051  cons(1, cons(0, nil))
5052  >>> simplify(cdr(n))
5053  cons(0, nil)
5054  >>> simplify(car(n))
5055  1
5056  """
5057 
5058  def __init__(self, name, ctx=None):
5059  self.ctxctx = _get_ctx(ctx)
5060  self.namename = name
5061  self.constructorsconstructors = []
5062 
5063  def __deepcopy__(self, memo={}):
5064  r = Datatype(self.namename, self.ctxctx)
5065  r.constructors = copy.deepcopy(self.constructorsconstructors)
5066  return r
5067 
5068  def declare_core(self, name, rec_name, *args):
5069  if z3_debug():
5070  _z3_assert(isinstance(name, str), "String expected")
5071  _z3_assert(isinstance(rec_name, str), "String expected")
5072  _z3_assert(
5073  all([_valid_accessor(a) for a in args]),
5074  "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5075  )
5076  self.constructorsconstructors.append((name, rec_name, args))
5077 
5078  def declare(self, name, *args):
5079  """Declare constructor named `name` with the given accessors `args`.
5080  Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5081  or a reference to the datatypes being declared.
5082 
5083  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5084  declares the constructor named `cons` that builds a new List using an integer and a List.
5085  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5086  of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5087  we use the method create() to create the actual datatype in Z3.
5088 
5089  >>> List = Datatype('List')
5090  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5091  >>> List.declare('nil')
5092  >>> List = List.create()
5093  """
5094  if z3_debug():
5095  _z3_assert(isinstance(name, str), "String expected")
5096  _z3_assert(name != "", "Constructor name cannot be empty")
5097  return self.declare_coredeclare_core(name, "is-" + name, *args)
5098 
5099  def __repr__(self):
5100  return "Datatype(%s, %s)" % (self.namename, self.constructorsconstructors)
5101 
5102  def create(self):
5103  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5104 
5105  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5106 
5107  >>> List = Datatype('List')
5108  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5109  >>> List.declare('nil')
5110  >>> List = List.create()
5111  >>> List.nil
5112  nil
5113  >>> List.cons(10, List.nil)
5114  cons(10, nil)
5115  """
5116  return CreateDatatypes([self])[0]
5117 
5118 
5120  """Auxiliary object used to create Z3 datatypes."""
5121 
5122  def __init__(self, c, ctx):
5123  self.cc = c
5124  self.ctxctx = ctx
5125 
5126  def __del__(self):
5127  if self.ctxctx.ref() is not None:
5128  Z3_del_constructor(self.ctxctx.ref(), self.cc)
5129 
5130 
5132  """Auxiliary object used to create Z3 datatypes."""
5133 
5134  def __init__(self, c, ctx):
5135  self.cc = c
5136  self.ctxctx = ctx
5137 
5138  def __del__(self):
5139  if self.ctxctx.ref() is not None:
5140  Z3_del_constructor_list(self.ctxctx.ref(), self.cc)
5141 
5142 
5144  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5145 
5146  In the following example we define a Tree-List using two mutually recursive datatypes.
5147 
5148  >>> TreeList = Datatype('TreeList')
5149  >>> Tree = Datatype('Tree')
5150  >>> # Tree has two constructors: leaf and node
5151  >>> Tree.declare('leaf', ('val', IntSort()))
5152  >>> # a node contains a list of trees
5153  >>> Tree.declare('node', ('children', TreeList))
5154  >>> TreeList.declare('nil')
5155  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5156  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5157  >>> Tree.val(Tree.leaf(10))
5158  val(leaf(10))
5159  >>> simplify(Tree.val(Tree.leaf(10)))
5160  10
5161  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5162  >>> n1
5163  node(cons(leaf(10), cons(leaf(20), nil)))
5164  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5165  >>> simplify(n2 == n1)
5166  False
5167  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5168  True
5169  """
5170  ds = _get_args(ds)
5171  if z3_debug():
5172  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5173  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5174  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5175  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5176  ctx = ds[0].ctx
5177  num = len(ds)
5178  names = (Symbol * num)()
5179  out = (Sort * num)()
5180  clists = (ConstructorList * num)()
5181  to_delete = []
5182  for i in range(num):
5183  d = ds[i]
5184  names[i] = to_symbol(d.name, ctx)
5185  num_cs = len(d.constructors)
5186  cs = (Constructor * num_cs)()
5187  for j in range(num_cs):
5188  c = d.constructors[j]
5189  cname = to_symbol(c[0], ctx)
5190  rname = to_symbol(c[1], ctx)
5191  fs = c[2]
5192  num_fs = len(fs)
5193  fnames = (Symbol * num_fs)()
5194  sorts = (Sort * num_fs)()
5195  refs = (ctypes.c_uint * num_fs)()
5196  for k in range(num_fs):
5197  fname = fs[k][0]
5198  ftype = fs[k][1]
5199  fnames[k] = to_symbol(fname, ctx)
5200  if isinstance(ftype, Datatype):
5201  if z3_debug():
5202  _z3_assert(
5203  ds.count(ftype) == 1,
5204  "One and only one occurrence of each datatype is expected",
5205  )
5206  sorts[k] = None
5207  refs[k] = ds.index(ftype)
5208  else:
5209  if z3_debug():
5210  _z3_assert(is_sort(ftype), "Z3 sort expected")
5211  sorts[k] = ftype.ast
5212  refs[k] = 0
5213  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5214  to_delete.append(ScopedConstructor(cs[j], ctx))
5215  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5216  to_delete.append(ScopedConstructorList(clists[i], ctx))
5217  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5218  result = []
5219  # Create a field for every constructor, recognizer and accessor
5220  for i in range(num):
5221  dref = DatatypeSortRef(out[i], ctx)
5222  num_cs = dref.num_constructors()
5223  for j in range(num_cs):
5224  cref = dref.constructor(j)
5225  cref_name = cref.name()
5226  cref_arity = cref.arity()
5227  if cref.arity() == 0:
5228  cref = cref()
5229  setattr(dref, cref_name, cref)
5230  rref = dref.recognizer(j)
5231  setattr(dref, "is_" + cref_name, rref)
5232  for k in range(cref_arity):
5233  aref = dref.accessor(j, k)
5234  setattr(dref, aref.name(), aref)
5235  result.append(dref)
5236  return tuple(result)
5237 
5238 
5240  """Datatype sorts."""
5241 
5242  def num_constructors(self):
5243  """Return the number of constructors in the given Z3 datatype.
5244 
5245  >>> List = Datatype('List')
5246  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5247  >>> List.declare('nil')
5248  >>> List = List.create()
5249  >>> # List is now a Z3 declaration
5250  >>> List.num_constructors()
5251  2
5252  """
5253  return int(Z3_get_datatype_sort_num_constructors(self.ctx_refctx_ref(), self.astast))
5254 
5255  def constructor(self, idx):
5256  """Return a constructor of the datatype `self`.
5257 
5258  >>> List = Datatype('List')
5259  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5260  >>> List.declare('nil')
5261  >>> List = List.create()
5262  >>> # List is now a Z3 declaration
5263  >>> List.num_constructors()
5264  2
5265  >>> List.constructor(0)
5266  cons
5267  >>> List.constructor(1)
5268  nil
5269  """
5270  if z3_debug():
5271  _z3_assert(idx < self.num_constructorsnum_constructors(), "Invalid constructor index")
5272  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
5273 
5274  def recognizer(self, idx):
5275  """In Z3, each constructor has an associated recognizer predicate.
5276 
5277  If the constructor is named `name`, then the recognizer `is_name`.
5278 
5279  >>> List = Datatype('List')
5280  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5281  >>> List.declare('nil')
5282  >>> List = List.create()
5283  >>> # List is now a Z3 declaration
5284  >>> List.num_constructors()
5285  2
5286  >>> List.recognizer(0)
5287  is(cons)
5288  >>> List.recognizer(1)
5289  is(nil)
5290  >>> simplify(List.is_nil(List.cons(10, List.nil)))
5291  False
5292  >>> simplify(List.is_cons(List.cons(10, List.nil)))
5293  True
5294  >>> l = Const('l', List)
5295  >>> simplify(List.is_cons(l))
5296  is(cons, l)
5297  """
5298  if z3_debug():
5299  _z3_assert(idx < self.num_constructorsnum_constructors(), "Invalid recognizer index")
5300  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
5301 
5302  def accessor(self, i, j):
5303  """In Z3, each constructor has 0 or more accessor.
5304  The number of accessors is equal to the arity of the constructor.
5305 
5306  >>> List = Datatype('List')
5307  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5308  >>> List.declare('nil')
5309  >>> List = List.create()
5310  >>> List.num_constructors()
5311  2
5312  >>> List.constructor(0)
5313  cons
5314  >>> num_accs = List.constructor(0).arity()
5315  >>> num_accs
5316  2
5317  >>> List.accessor(0, 0)
5318  car
5319  >>> List.accessor(0, 1)
5320  cdr
5321  >>> List.constructor(1)
5322  nil
5323  >>> num_accs = List.constructor(1).arity()
5324  >>> num_accs
5325  0
5326  """
5327  if z3_debug():
5328  _z3_assert(i < self.num_constructorsnum_constructors(), "Invalid constructor index")
5329  _z3_assert(j < self.constructorconstructor(i).arity(), "Invalid accessor index")
5330  return FuncDeclRef(
5331  Z3_get_datatype_sort_constructor_accessor(self.ctx_refctx_ref(), self.astast, i, j),
5332  ctx=self.ctxctx,
5333  )
5334 
5335 
5337  """Datatype expressions."""
5338 
5339  def sort(self):
5340  """Return the datatype sort of the datatype expression `self`."""
5341  return DatatypeSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
5342 
5343 
5344 def TupleSort(name, sorts, ctx=None):
5345  """Create a named tuple sort base on a set of underlying sorts
5346  Example:
5347  >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5348  """
5349  tuple = Datatype(name, ctx)
5350  projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5351  tuple.declare(name, *projects)
5352  tuple = tuple.create()
5353  return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5354 
5355 
5356 def DisjointSum(name, sorts, ctx=None):
5357  """Create a named tagged union sort base on a set of underlying sorts
5358  Example:
5359  >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5360  """
5361  sum = Datatype(name, ctx)
5362  for i in range(len(sorts)):
5363  sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5364  sum = sum.create()
5365  return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5366 
5367 
5368 def EnumSort(name, values, ctx=None):
5369  """Return a new enumeration sort named `name` containing the given values.
5370 
5371  The result is a pair (sort, list of constants).
5372  Example:
5373  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5374  """
5375  if z3_debug():
5376  _z3_assert(isinstance(name, str), "Name must be a string")
5377  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5378  _z3_assert(len(values) > 0, "At least one value expected")
5379  ctx = _get_ctx(ctx)
5380  num = len(values)
5381  _val_names = (Symbol * num)()
5382  for i in range(num):
5383  _val_names[i] = to_symbol(values[i])
5384  _values = (FuncDecl * num)()
5385  _testers = (FuncDecl * num)()
5386  name = to_symbol(name)
5387  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5388  V = []
5389  for i in range(num):
5390  V.append(FuncDeclRef(_values[i], ctx))
5391  V = [a() for a in V]
5392  return S, V
5393 
5394 
5399 
5400 
5402  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5403 
5404  Consider using the function `args2params` to create instances of this object.
5405  """
5406 
5407  def __init__(self, ctx=None, params=None):
5408  self.ctxctx = _get_ctx(ctx)
5409  if params is None:
5410  self.paramsparams = Z3_mk_params(self.ctxctx.ref())
5411  else:
5412  self.paramsparams = params
5413  Z3_params_inc_ref(self.ctxctx.ref(), self.paramsparams)
5414 
5415  def __deepcopy__(self, memo={}):
5416  return ParamsRef(self.ctxctx, self.paramsparams)
5417 
5418  def __del__(self):
5419  if self.ctxctx.ref() is not None:
5420  Z3_params_dec_ref(self.ctxctx.ref(), self.paramsparams)
5421 
5422  def set(self, name, val):
5423  """Set parameter name with value val."""
5424  if z3_debug():
5425  _z3_assert(isinstance(name, str), "parameter name must be a string")
5426  name_sym = to_symbol(name, self.ctxctx)
5427  if isinstance(val, bool):
5428  Z3_params_set_bool(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5429  elif _is_int(val):
5430  Z3_params_set_uint(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5431  elif isinstance(val, float):
5432  Z3_params_set_double(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5433  elif isinstance(val, str):
5434  Z3_params_set_symbol(self.ctxctx.ref(), self.paramsparams, name_sym, to_symbol(val, self.ctxctx))
5435  else:
5436  if z3_debug():
5437  _z3_assert(False, "invalid parameter value")
5438 
5439  def __repr__(self):
5440  return Z3_params_to_string(self.ctxctx.ref(), self.paramsparams)
5441 
5442  def validate(self, ds):
5443  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5444  Z3_params_validate(self.ctxctx.ref(), self.paramsparams, ds.descr)
5445 
5446 
5447 def args2params(arguments, keywords, ctx=None):
5448  """Convert python arguments into a Z3_params object.
5449  A ':' is added to the keywords, and '_' is replaced with '-'
5450 
5451  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5452  (params model true relevancy 2 elim_and true)
5453  """
5454  if z3_debug():
5455  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5456  prev = None
5457  r = ParamsRef(ctx)
5458  for a in arguments:
5459  if prev is None:
5460  prev = a
5461  else:
5462  r.set(prev, a)
5463  prev = None
5464  for k in keywords:
5465  v = keywords[k]
5466  r.set(k, v)
5467  return r
5468 
5469 
5471  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5472  """
5473 
5474  def __init__(self, descr, ctx=None):
5475  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5476  self.ctxctx = _get_ctx(ctx)
5477  self.descrdescr = descr
5478  Z3_param_descrs_inc_ref(self.ctxctx.ref(), self.descrdescr)
5479 
5480  def __deepcopy__(self, memo={}):
5481  return ParamsDescrsRef(self.descrdescr, self.ctxctx)
5482 
5483  def __del__(self):
5484  if self.ctxctx.ref() is not None:
5485  Z3_param_descrs_dec_ref(self.ctxctx.ref(), self.descrdescr)
5486 
5487  def size(self):
5488  """Return the size of in the parameter description `self`.
5489  """
5490  return int(Z3_param_descrs_size(self.ctxctx.ref(), self.descrdescr))
5491 
5492  def __len__(self):
5493  """Return the size of in the parameter description `self`.
5494  """
5495  return self.sizesize()
5496 
5497  def get_name(self, i):
5498  """Return the i-th parameter name in the parameter description `self`.
5499  """
5500  return _symbol2py(self.ctxctx, Z3_param_descrs_get_name(self.ctxctx.ref(), self.descrdescr, i))
5501 
5502  def get_kind(self, n):
5503  """Return the kind of the parameter named `n`.
5504  """
5505  return Z3_param_descrs_get_kind(self.ctxctx.ref(), self.descrdescr, to_symbol(n, self.ctxctx))
5506 
5507  def get_documentation(self, n):
5508  """Return the documentation string of the parameter named `n`.
5509  """
5510  return Z3_param_descrs_get_documentation(self.ctxctx.ref(), self.descrdescr, to_symbol(n, self.ctxctx))
5511 
5512  def __getitem__(self, arg):
5513  if _is_int(arg):
5514  return self.get_nameget_name(arg)
5515  else:
5516  return self.get_kindget_kind(arg)
5517 
5518  def __repr__(self):
5519  return Z3_param_descrs_to_string(self.ctxctx.ref(), self.descrdescr)
5520 
5521 
5526 
5527 
5529  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5530 
5531  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5532  A goal has a solution if one of its subgoals has a solution.
5533  A goal is unsatisfiable if all subgoals are unsatisfiable.
5534  """
5535 
5536  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5537  if z3_debug():
5538  _z3_assert(goal is None or ctx is not None,
5539  "If goal is different from None, then ctx must be also different from None")
5540  self.ctxctx = _get_ctx(ctx)
5541  self.goalgoal = goal
5542  if self.goalgoal is None:
5543  self.goalgoal = Z3_mk_goal(self.ctxctx.ref(), models, unsat_cores, proofs)
5544  Z3_goal_inc_ref(self.ctxctx.ref(), self.goalgoal)
5545 
5546  def __del__(self):
5547  if self.goalgoal is not None and self.ctxctx.ref() is not None:
5548  Z3_goal_dec_ref(self.ctxctx.ref(), self.goalgoal)
5549 
5550  def depth(self):
5551  """Return the depth of the goal `self`.
5552  The depth corresponds to the number of tactics applied to `self`.
5553 
5554  >>> x, y = Ints('x y')
5555  >>> g = Goal()
5556  >>> g.add(x == 0, y >= x + 1)
5557  >>> g.depth()
5558  0
5559  >>> r = Then('simplify', 'solve-eqs')(g)
5560  >>> # r has 1 subgoal
5561  >>> len(r)
5562  1
5563  >>> r[0].depth()
5564  2
5565  """
5566  return int(Z3_goal_depth(self.ctxctx.ref(), self.goalgoal))
5567 
5568  def inconsistent(self):
5569  """Return `True` if `self` contains the `False` constraints.
5570 
5571  >>> x, y = Ints('x y')
5572  >>> g = Goal()
5573  >>> g.inconsistent()
5574  False
5575  >>> g.add(x == 0, x == 1)
5576  >>> g
5577  [x == 0, x == 1]
5578  >>> g.inconsistent()
5579  False
5580  >>> g2 = Tactic('propagate-values')(g)[0]
5581  >>> g2.inconsistent()
5582  True
5583  """
5584  return Z3_goal_inconsistent(self.ctxctx.ref(), self.goalgoal)
5585 
5586  def prec(self):
5587  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5588 
5589  >>> g = Goal()
5590  >>> g.prec() == Z3_GOAL_PRECISE
5591  True
5592  >>> x, y = Ints('x y')
5593  >>> g.add(x == y + 1)
5594  >>> g.prec() == Z3_GOAL_PRECISE
5595  True
5596  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5597  >>> g2 = t(g)[0]
5598  >>> g2
5599  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5600  >>> g2.prec() == Z3_GOAL_PRECISE
5601  False
5602  >>> g2.prec() == Z3_GOAL_UNDER
5603  True
5604  """
5605  return Z3_goal_precision(self.ctxctx.ref(), self.goalgoal)
5606 
5607  def precision(self):
5608  """Alias for `prec()`.
5609 
5610  >>> g = Goal()
5611  >>> g.precision() == Z3_GOAL_PRECISE
5612  True
5613  """
5614  return self.precprec()
5615 
5616  def size(self):
5617  """Return the number of constraints in the goal `self`.
5618 
5619  >>> g = Goal()
5620  >>> g.size()
5621  0
5622  >>> x, y = Ints('x y')
5623  >>> g.add(x == 0, y > x)
5624  >>> g.size()
5625  2
5626  """
5627  return int(Z3_goal_size(self.ctxctx.ref(), self.goalgoal))
5628 
5629  def __len__(self):
5630  """Return the number of constraints in the goal `self`.
5631 
5632  >>> g = Goal()
5633  >>> len(g)
5634  0
5635  >>> x, y = Ints('x y')
5636  >>> g.add(x == 0, y > x)
5637  >>> len(g)
5638  2
5639  """
5640  return self.sizesize()
5641 
5642  def get(self, i):
5643  """Return a constraint in the goal `self`.
5644 
5645  >>> g = Goal()
5646  >>> x, y = Ints('x y')
5647  >>> g.add(x == 0, y > x)
5648  >>> g.get(0)
5649  x == 0
5650  >>> g.get(1)
5651  y > x
5652  """
5653  return _to_expr_ref(Z3_goal_formula(self.ctxctx.ref(), self.goalgoal, i), self.ctxctx)
5654 
5655  def __getitem__(self, arg):
5656  """Return a constraint in the goal `self`.
5657 
5658  >>> g = Goal()
5659  >>> x, y = Ints('x y')
5660  >>> g.add(x == 0, y > x)
5661  >>> g[0]
5662  x == 0
5663  >>> g[1]
5664  y > x
5665  """
5666  if arg >= len(self):
5667  raise IndexError
5668  return self.getget(arg)
5669 
5670  def assert_exprs(self, *args):
5671  """Assert constraints into the goal.
5672 
5673  >>> x = Int('x')
5674  >>> g = Goal()
5675  >>> g.assert_exprs(x > 0, x < 2)
5676  >>> g
5677  [x > 0, x < 2]
5678  """
5679  args = _get_args(args)
5680  s = BoolSort(self.ctxctx)
5681  for arg in args:
5682  arg = s.cast(arg)
5683  Z3_goal_assert(self.ctxctx.ref(), self.goalgoal, arg.as_ast())
5684 
5685  def append(self, *args):
5686  """Add constraints.
5687 
5688  >>> x = Int('x')
5689  >>> g = Goal()
5690  >>> g.append(x > 0, x < 2)
5691  >>> g
5692  [x > 0, x < 2]
5693  """
5694  self.assert_exprsassert_exprs(*args)
5695 
5696  def insert(self, *args):
5697  """Add constraints.
5698 
5699  >>> x = Int('x')
5700  >>> g = Goal()
5701  >>> g.insert(x > 0, x < 2)
5702  >>> g
5703  [x > 0, x < 2]
5704  """
5705  self.assert_exprsassert_exprs(*args)
5706 
5707  def add(self, *args):
5708  """Add constraints.
5709 
5710  >>> x = Int('x')
5711  >>> g = Goal()
5712  >>> g.add(x > 0, x < 2)
5713  >>> g
5714  [x > 0, x < 2]
5715  """
5716  self.assert_exprsassert_exprs(*args)
5717 
5718  def convert_model(self, model):
5719  """Retrieve model from a satisfiable goal
5720  >>> a, b = Ints('a b')
5721  >>> g = Goal()
5722  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5723  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5724  >>> r = t(g)
5725  >>> r[0]
5726  [Or(b == 0, b == 1), Not(0 <= b)]
5727  >>> r[1]
5728  [Or(b == 0, b == 1), Not(1 <= b)]
5729  >>> # Remark: the subgoal r[0] is unsatisfiable
5730  >>> # Creating a solver for solving the second subgoal
5731  >>> s = Solver()
5732  >>> s.add(r[1])
5733  >>> s.check()
5734  sat
5735  >>> s.model()
5736  [b = 0]
5737  >>> # Model s.model() does not assign a value to `a`
5738  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5739  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5740  >>> r[1].convert_model(s.model())
5741  [b = 0, a = 1]
5742  """
5743  if z3_debug():
5744  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5745  return ModelRef(Z3_goal_convert_model(self.ctxctx.ref(), self.goalgoal, model.model), self.ctxctx)
5746 
5747  def __repr__(self):
5748  return obj_to_string(self)
5749 
5750  def sexpr(self):
5751  """Return a textual representation of the s-expression representing the goal."""
5752  return Z3_goal_to_string(self.ctxctx.ref(), self.goalgoal)
5753 
5754  def dimacs(self, include_names=True):
5755  """Return a textual representation of the goal in DIMACS format."""
5756  return Z3_goal_to_dimacs_string(self.ctxctx.ref(), self.goalgoal, include_names)
5757 
5758  def translate(self, target):
5759  """Copy goal `self` to context `target`.
5760 
5761  >>> x = Int('x')
5762  >>> g = Goal()
5763  >>> g.add(x > 10)
5764  >>> g
5765  [x > 10]
5766  >>> c2 = Context()
5767  >>> g2 = g.translate(c2)
5768  >>> g2
5769  [x > 10]
5770  >>> g.ctx == main_ctx()
5771  True
5772  >>> g2.ctx == c2
5773  True
5774  >>> g2.ctx == main_ctx()
5775  False
5776  """
5777  if z3_debug():
5778  _z3_assert(isinstance(target, Context), "target must be a context")
5779  return Goal(goal=Z3_goal_translate(self.ctxctx.ref(), self.goalgoal, target.ref()), ctx=target)
5780 
5781  def __copy__(self):
5782  return self.translatetranslate(self.ctxctx)
5783 
5784  def __deepcopy__(self, memo={}):
5785  return self.translatetranslate(self.ctxctx)
5786 
5787  def simplify(self, *arguments, **keywords):
5788  """Return a new simplified goal.
5789 
5790  This method is essentially invoking the simplify tactic.
5791 
5792  >>> g = Goal()
5793  >>> x = Int('x')
5794  >>> g.add(x + 1 >= 2)
5795  >>> g
5796  [x + 1 >= 2]
5797  >>> g2 = g.simplify()
5798  >>> g2
5799  [x >= 1]
5800  >>> # g was not modified
5801  >>> g
5802  [x + 1 >= 2]
5803  """
5804  t = Tactic("simplify")
5805  return t.apply(self, *arguments, **keywords)[0]
5806 
5807  def as_expr(self):
5808  """Return goal `self` as a single Z3 expression.
5809 
5810  >>> x = Int('x')
5811  >>> g = Goal()
5812  >>> g.as_expr()
5813  True
5814  >>> g.add(x > 1)
5815  >>> g.as_expr()
5816  x > 1
5817  >>> g.add(x < 10)
5818  >>> g.as_expr()
5819  And(x > 1, x < 10)
5820  """
5821  sz = len(self)
5822  if sz == 0:
5823  return BoolVal(True, self.ctxctx)
5824  elif sz == 1:
5825  return self.getget(0)
5826  else:
5827  return And([self.getget(i) for i in range(len(self))], self.ctxctx)
5828 
5829 
5834 
5835 
5837  """A collection (vector) of ASTs."""
5838 
5839  def __init__(self, v=None, ctx=None):
5840  self.vectorvector = None
5841  if v is None:
5842  self.ctxctx = _get_ctx(ctx)
5843  self.vectorvector = Z3_mk_ast_vector(self.ctxctx.ref())
5844  else:
5845  self.vectorvector = v
5846  assert ctx is not None
5847  self.ctxctx = ctx
5848  Z3_ast_vector_inc_ref(self.ctxctx.ref(), self.vectorvector)
5849 
5850  def __del__(self):
5851  if self.vectorvector is not None and self.ctxctx.ref() is not None:
5852  Z3_ast_vector_dec_ref(self.ctxctx.ref(), self.vectorvector)
5853 
5854  def __len__(self):
5855  """Return the size of the vector `self`.
5856 
5857  >>> A = AstVector()
5858  >>> len(A)
5859  0
5860  >>> A.push(Int('x'))
5861  >>> A.push(Int('x'))
5862  >>> len(A)
5863  2
5864  """
5865  return int(Z3_ast_vector_size(self.ctxctx.ref(), self.vectorvector))
5866 
5867  def __getitem__(self, i):
5868  """Return the AST at position `i`.
5869 
5870  >>> A = AstVector()
5871  >>> A.push(Int('x') + 1)
5872  >>> A.push(Int('y'))
5873  >>> A[0]
5874  x + 1
5875  >>> A[1]
5876  y
5877  """
5878 
5879  if isinstance(i, int):
5880  if i < 0:
5881  i += self.__len____len__()
5882 
5883  if i >= self.__len____len__():
5884  raise IndexError
5885  return _to_ast_ref(Z3_ast_vector_get(self.ctxctx.ref(), self.vectorvector, i), self.ctxctx)
5886 
5887  elif isinstance(i, slice):
5888  result = []
5889  for ii in range(*i.indices(self.__len____len__())):
5890  result.append(_to_ast_ref(
5891  Z3_ast_vector_get(self.ctxctx.ref(), self.vectorvector, ii),
5892  self.ctxctx,
5893  ))
5894  return result
5895 
5896  def __setitem__(self, i, v):
5897  """Update AST at position `i`.
5898 
5899  >>> A = AstVector()
5900  >>> A.push(Int('x') + 1)
5901  >>> A.push(Int('y'))
5902  >>> A[0]
5903  x + 1
5904  >>> A[0] = Int('x')
5905  >>> A[0]
5906  x
5907  """
5908  if i >= self.__len____len__():
5909  raise IndexError
5910  Z3_ast_vector_set(self.ctxctx.ref(), self.vectorvector, i, v.as_ast())
5911 
5912  def push(self, v):
5913  """Add `v` in the end of the vector.
5914 
5915  >>> A = AstVector()
5916  >>> len(A)
5917  0
5918  >>> A.push(Int('x'))
5919  >>> len(A)
5920  1
5921  """
5922  Z3_ast_vector_push(self.ctxctx.ref(), self.vectorvector, v.as_ast())
5923 
5924  def resize(self, sz):
5925  """Resize the vector to `sz` elements.
5926 
5927  >>> A = AstVector()
5928  >>> A.resize(10)
5929  >>> len(A)
5930  10
5931  >>> for i in range(10): A[i] = Int('x')
5932  >>> A[5]
5933  x
5934  """
5935  Z3_ast_vector_resize(self.ctxctx.ref(), self.vectorvector, sz)
5936 
5937  def __contains__(self, item):
5938  """Return `True` if the vector contains `item`.
5939 
5940  >>> x = Int('x')
5941  >>> A = AstVector()
5942  >>> x in A
5943  False
5944  >>> A.push(x)
5945  >>> x in A
5946  True
5947  >>> (x+1) in A
5948  False
5949  >>> A.push(x+1)
5950  >>> (x+1) in A
5951  True
5952  >>> A
5953  [x, x + 1]
5954  """
5955  for elem in self:
5956  if elem.eq(item):
5957  return True
5958  return False
5959 
5960  def translate(self, other_ctx):
5961  """Copy vector `self` to context `other_ctx`.
5962 
5963  >>> x = Int('x')
5964  >>> A = AstVector()
5965  >>> A.push(x)
5966  >>> c2 = Context()
5967  >>> B = A.translate(c2)
5968  >>> B
5969  [x]
5970  """
5971  return AstVector(
5972  Z3_ast_vector_translate(self.ctxctx.ref(), self.vectorvector, other_ctx.ref()),
5973  ctx=other_ctx,
5974  )
5975 
5976  def __copy__(self):
5977  return self.translatetranslate(self.ctxctx)
5978 
5979  def __deepcopy__(self, memo={}):
5980  return self.translatetranslate(self.ctxctx)
5981 
5982  def __repr__(self):
5983  return obj_to_string(self)
5984 
5985  def sexpr(self):
5986  """Return a textual representation of the s-expression representing the vector."""
5987  return Z3_ast_vector_to_string(self.ctxctx.ref(), self.vectorvector)
5988 
5989 
5994 
5995 
5996 class AstMap:
5997  """A mapping from ASTs to ASTs."""
5998 
5999  def __init__(self, m=None, ctx=None):
6000  self.mapmap = None
6001  if m is None:
6002  self.ctxctx = _get_ctx(ctx)
6003  self.mapmap = Z3_mk_ast_map(self.ctxctx.ref())
6004  else:
6005  self.mapmap = m
6006  assert ctx is not None
6007  self.ctxctx = ctx
6008  Z3_ast_map_inc_ref(self.ctxctx.ref(), self.mapmap)
6009 
6010  def __deepcopy__(self, memo={}):
6011  return AstMap(self.mapmap, self.ctxctx)
6012 
6013  def __del__(self):
6014  if self.mapmap is not None and self.ctxctx.ref() is not None:
6015  Z3_ast_map_dec_ref(self.ctxctx.ref(), self.mapmap)
6016 
6017  def __len__(self):
6018  """Return the size of the map.
6019 
6020  >>> M = AstMap()
6021  >>> len(M)
6022  0
6023  >>> x = Int('x')
6024  >>> M[x] = IntVal(1)
6025  >>> len(M)
6026  1
6027  """
6028  return int(Z3_ast_map_size(self.ctxctx.ref(), self.mapmap))
6029 
6030  def __contains__(self, key):
6031  """Return `True` if the map contains key `key`.
6032 
6033  >>> M = AstMap()
6034  >>> x = Int('x')
6035  >>> M[x] = x + 1
6036  >>> x in M
6037  True
6038  >>> x+1 in M
6039  False
6040  """
6041  return Z3_ast_map_contains(self.ctxctx.ref(), self.mapmap, key.as_ast())
6042 
6043  def __getitem__(self, key):
6044  """Retrieve the value associated with key `key`.
6045 
6046  >>> M = AstMap()
6047  >>> x = Int('x')
6048  >>> M[x] = x + 1
6049  >>> M[x]
6050  x + 1
6051  """
6052  return _to_ast_ref(Z3_ast_map_find(self.ctxctx.ref(), self.mapmap, key.as_ast()), self.ctxctx)
6053 
6054  def __setitem__(self, k, v):
6055  """Add/Update key `k` with value `v`.
6056 
6057  >>> M = AstMap()
6058  >>> x = Int('x')
6059  >>> M[x] = x + 1
6060  >>> len(M)
6061  1
6062  >>> M[x]
6063  x + 1
6064  >>> M[x] = IntVal(1)
6065  >>> M[x]
6066  1
6067  """
6068  Z3_ast_map_insert(self.ctxctx.ref(), self.mapmap, k.as_ast(), v.as_ast())
6069 
6070  def __repr__(self):
6071  return Z3_ast_map_to_string(self.ctxctx.ref(), self.mapmap)
6072 
6073  def erase(self, k):
6074  """Remove the entry associated with key `k`.
6075 
6076  >>> M = AstMap()
6077  >>> x = Int('x')
6078  >>> M[x] = x + 1
6079  >>> len(M)
6080  1
6081  >>> M.erase(x)
6082  >>> len(M)
6083  0
6084  """
6085  Z3_ast_map_erase(self.ctxctx.ref(), self.mapmap, k.as_ast())
6086 
6087  def reset(self):
6088  """Remove all entries from the map.
6089 
6090  >>> M = AstMap()
6091  >>> x = Int('x')
6092  >>> M[x] = x + 1
6093  >>> M[x+x] = IntVal(1)
6094  >>> len(M)
6095  2
6096  >>> M.reset()
6097  >>> len(M)
6098  0
6099  """
6100  Z3_ast_map_reset(self.ctxctx.ref(), self.mapmap)
6101 
6102  def keys(self):
6103  """Return an AstVector containing all keys in the map.
6104 
6105  >>> M = AstMap()
6106  >>> x = Int('x')
6107  >>> M[x] = x + 1
6108  >>> M[x+x] = IntVal(1)
6109  >>> M.keys()
6110  [x, x + x]
6111  """
6112  return AstVector(Z3_ast_map_keys(self.ctxctx.ref(), self.mapmap), self.ctxctx)
6113 
6114 
6119 
6120 
6122  """Store the value of the interpretation of a function in a particular point."""
6123 
6124  def __init__(self, entry, ctx):
6125  self.entryentry = entry
6126  self.ctxctx = ctx
6127  Z3_func_entry_inc_ref(self.ctxctx.ref(), self.entryentry)
6128 
6129  def __deepcopy__(self, memo={}):
6130  return FuncEntry(self.entryentry, self.ctxctx)
6131 
6132  def __del__(self):
6133  if self.ctxctx.ref() is not None:
6134  Z3_func_entry_dec_ref(self.ctxctx.ref(), self.entryentry)
6135 
6136  def num_args(self):
6137  """Return the number of arguments in the given entry.
6138 
6139  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6140  >>> s = Solver()
6141  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6142  >>> s.check()
6143  sat
6144  >>> m = s.model()
6145  >>> f_i = m[f]
6146  >>> f_i.num_entries()
6147  1
6148  >>> e = f_i.entry(0)
6149  >>> e.num_args()
6150  2
6151  """
6152  return int(Z3_func_entry_get_num_args(self.ctxctx.ref(), self.entryentry))
6153 
6154  def arg_value(self, idx):
6155  """Return the value of argument `idx`.
6156 
6157  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6158  >>> s = Solver()
6159  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6160  >>> s.check()
6161  sat
6162  >>> m = s.model()
6163  >>> f_i = m[f]
6164  >>> f_i.num_entries()
6165  1
6166  >>> e = f_i.entry(0)
6167  >>> e
6168  [1, 2, 20]
6169  >>> e.num_args()
6170  2
6171  >>> e.arg_value(0)
6172  1
6173  >>> e.arg_value(1)
6174  2
6175  >>> try:
6176  ... e.arg_value(2)
6177  ... except IndexError:
6178  ... print("index error")
6179  index error
6180  """
6181  if idx >= self.num_argsnum_args():
6182  raise IndexError
6183  return _to_expr_ref(Z3_func_entry_get_arg(self.ctxctx.ref(), self.entryentry, idx), self.ctxctx)
6184 
6185  def value(self):
6186  """Return the value of the function at point `self`.
6187 
6188  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6189  >>> s = Solver()
6190  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6191  >>> s.check()
6192  sat
6193  >>> m = s.model()
6194  >>> f_i = m[f]
6195  >>> f_i.num_entries()
6196  1
6197  >>> e = f_i.entry(0)
6198  >>> e
6199  [1, 2, 20]
6200  >>> e.num_args()
6201  2
6202  >>> e.value()
6203  20
6204  """
6205  return _to_expr_ref(Z3_func_entry_get_value(self.ctxctx.ref(), self.entryentry), self.ctxctx)
6206 
6207  def as_list(self):
6208  """Return entry `self` as a Python list.
6209  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6210  >>> s = Solver()
6211  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6212  >>> s.check()
6213  sat
6214  >>> m = s.model()
6215  >>> f_i = m[f]
6216  >>> f_i.num_entries()
6217  1
6218  >>> e = f_i.entry(0)
6219  >>> e.as_list()
6220  [1, 2, 20]
6221  """
6222  args = [self.arg_valuearg_value(i) for i in range(self.num_argsnum_args())]
6223  args.append(self.valuevalue())
6224  return args
6225 
6226  def __repr__(self):
6227  return repr(self.as_listas_list())
6228 
6229 
6231  """Stores the interpretation of a function in a Z3 model."""
6232 
6233  def __init__(self, f, ctx):
6234  self.ff = f
6235  self.ctxctx = ctx
6236  if self.ff is not None:
6237  Z3_func_interp_inc_ref(self.ctxctx.ref(), self.ff)
6238 
6239  def __del__(self):
6240  if self.ff is not None and self.ctxctx.ref() is not None:
6241  Z3_func_interp_dec_ref(self.ctxctx.ref(), self.ff)
6242 
6243  def else_value(self):
6244  """
6245  Return the `else` value for a function interpretation.
6246  Return None if Z3 did not specify the `else` value for
6247  this object.
6248 
6249  >>> f = Function('f', IntSort(), IntSort())
6250  >>> s = Solver()
6251  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6252  >>> s.check()
6253  sat
6254  >>> m = s.model()
6255  >>> m[f]
6256  [2 -> 0, else -> 1]
6257  >>> m[f].else_value()
6258  1
6259  """
6260  r = Z3_func_interp_get_else(self.ctxctx.ref(), self.ff)
6261  if r:
6262  return _to_expr_ref(r, self.ctxctx)
6263  else:
6264  return None
6265 
6266  def num_entries(self):
6267  """Return the number of entries/points in the function interpretation `self`.
6268 
6269  >>> f = Function('f', IntSort(), IntSort())
6270  >>> s = Solver()
6271  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6272  >>> s.check()
6273  sat
6274  >>> m = s.model()
6275  >>> m[f]
6276  [2 -> 0, else -> 1]
6277  >>> m[f].num_entries()
6278  1
6279  """
6280  return int(Z3_func_interp_get_num_entries(self.ctxctx.ref(), self.ff))
6281 
6282  def arity(self):
6283  """Return the number of arguments for each entry in the function interpretation `self`.
6284 
6285  >>> f = Function('f', IntSort(), IntSort())
6286  >>> s = Solver()
6287  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6288  >>> s.check()
6289  sat
6290  >>> m = s.model()
6291  >>> m[f].arity()
6292  1
6293  """
6294  return int(Z3_func_interp_get_arity(self.ctxctx.ref(), self.ff))
6295 
6296  def entry(self, idx):
6297  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6298 
6299  >>> f = Function('f', IntSort(), IntSort())
6300  >>> s = Solver()
6301  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6302  >>> s.check()
6303  sat
6304  >>> m = s.model()
6305  >>> m[f]
6306  [2 -> 0, else -> 1]
6307  >>> m[f].num_entries()
6308  1
6309  >>> m[f].entry(0)
6310  [2, 0]
6311  """
6312  if idx >= self.num_entriesnum_entries():
6313  raise IndexError
6314  return FuncEntry(Z3_func_interp_get_entry(self.ctxctx.ref(), self.ff, idx), self.ctxctx)
6315 
6316  def translate(self, other_ctx):
6317  """Copy model 'self' to context 'other_ctx'.
6318  """
6319  return ModelRef(Z3_model_translate(self.ctxctx.ref(), self.model, other_ctx.ref()), other_ctx)
6320 
6321  def __copy__(self):
6322  return self.translatetranslate(self.ctxctx)
6323 
6324  def __deepcopy__(self, memo={}):
6325  return self.translatetranslate(self.ctxctx)
6326 
6327  def as_list(self):
6328  """Return the function interpretation as a Python list.
6329  >>> f = Function('f', IntSort(), IntSort())
6330  >>> s = Solver()
6331  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6332  >>> s.check()
6333  sat
6334  >>> m = s.model()
6335  >>> m[f]
6336  [2 -> 0, else -> 1]
6337  >>> m[f].as_list()
6338  [[2, 0], 1]
6339  """
6340  r = [self.entryentry(i).as_list() for i in range(self.num_entriesnum_entries())]
6341  r.append(self.else_valueelse_value())
6342  return r
6343 
6344  def __repr__(self):
6345  return obj_to_string(self)
6346 
6347 
6349  """Model/Solution of a satisfiability problem (aka system of constraints)."""
6350 
6351  def __init__(self, m, ctx):
6352  assert ctx is not None
6353  self.modelmodel = m
6354  self.ctxctx = ctx
6355  Z3_model_inc_ref(self.ctxctx.ref(), self.modelmodel)
6356 
6357  def __del__(self):
6358  if self.ctxctx.ref() is not None:
6359  Z3_model_dec_ref(self.ctxctx.ref(), self.modelmodel)
6360 
6361  def __repr__(self):
6362  return obj_to_string(self)
6363 
6364  def sexpr(self):
6365  """Return a textual representation of the s-expression representing the model."""
6366  return Z3_model_to_string(self.ctxctx.ref(), self.modelmodel)
6367 
6368  def eval(self, t, model_completion=False):
6369  """Evaluate the expression `t` in the model `self`.
6370  If `model_completion` is enabled, then a default interpretation is automatically added
6371  for symbols that do not have an interpretation in the model `self`.
6372 
6373  >>> x = Int('x')
6374  >>> s = Solver()
6375  >>> s.add(x > 0, x < 2)
6376  >>> s.check()
6377  sat
6378  >>> m = s.model()
6379  >>> m.eval(x + 1)
6380  2
6381  >>> m.eval(x == 1)
6382  True
6383  >>> y = Int('y')
6384  >>> m.eval(y + x)
6385  1 + y
6386  >>> m.eval(y)
6387  y
6388  >>> m.eval(y, model_completion=True)
6389  0
6390  >>> # Now, m contains an interpretation for y
6391  >>> m.eval(y + x)
6392  1
6393  """
6394  r = (Ast * 1)()
6395  if Z3_model_eval(self.ctxctx.ref(), self.modelmodel, t.as_ast(), model_completion, r):
6396  return _to_expr_ref(r[0], self.ctxctx)
6397  raise Z3Exception("failed to evaluate expression in the model")
6398 
6399  def evaluate(self, t, model_completion=False):
6400  """Alias for `eval`.
6401 
6402  >>> x = Int('x')
6403  >>> s = Solver()
6404  >>> s.add(x > 0, x < 2)
6405  >>> s.check()
6406  sat
6407  >>> m = s.model()
6408  >>> m.evaluate(x + 1)
6409  2
6410  >>> m.evaluate(x == 1)
6411  True
6412  >>> y = Int('y')
6413  >>> m.evaluate(y + x)
6414  1 + y
6415  >>> m.evaluate(y)
6416  y
6417  >>> m.evaluate(y, model_completion=True)
6418  0
6419  >>> # Now, m contains an interpretation for y
6420  >>> m.evaluate(y + x)
6421  1
6422  """
6423  return self.evaleval(t, model_completion)
6424 
6425  def __len__(self):
6426  """Return the number of constant and function declarations in the model `self`.
6427 
6428  >>> f = Function('f', IntSort(), IntSort())
6429  >>> x = Int('x')
6430  >>> s = Solver()
6431  >>> s.add(x > 0, f(x) != x)
6432  >>> s.check()
6433  sat
6434  >>> m = s.model()
6435  >>> len(m)
6436  2
6437  """
6438  num_consts = int(Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel))
6439  num_funcs = int(Z3_model_get_num_funcs(self.ctxctx.ref(), self.modelmodel))
6440  return num_consts + num_funcs
6441 
6442  def get_interp(self, decl):
6443  """Return the interpretation for a given declaration or constant.
6444 
6445  >>> f = Function('f', IntSort(), IntSort())
6446  >>> x = Int('x')
6447  >>> s = Solver()
6448  >>> s.add(x > 0, x < 2, f(x) == 0)
6449  >>> s.check()
6450  sat
6451  >>> m = s.model()
6452  >>> m[x]
6453  1
6454  >>> m[f]
6455  [else -> 0]
6456  """
6457  if z3_debug():
6458  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6459  if is_const(decl):
6460  decl = decl.decl()
6461  try:
6462  if decl.arity() == 0:
6463  _r = Z3_model_get_const_interp(self.ctxctx.ref(), self.modelmodel, decl.ast)
6464  if _r.value is None:
6465  return None
6466  r = _to_expr_ref(_r, self.ctxctx)
6467  if is_as_array(r):
6468  return self.get_interpget_interp(get_as_array_func(r))
6469  else:
6470  return r
6471  else:
6472  return FuncInterp(Z3_model_get_func_interp(self.ctxctx.ref(), self.modelmodel, decl.ast), self.ctxctx)
6473  except Z3Exception:
6474  return None
6475 
6476  def num_sorts(self):
6477  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6478 
6479  >>> A = DeclareSort('A')
6480  >>> a, b = Consts('a b', A)
6481  >>> s = Solver()
6482  >>> s.add(a != b)
6483  >>> s.check()
6484  sat
6485  >>> m = s.model()
6486  >>> m.num_sorts()
6487  1
6488  """
6489  return int(Z3_model_get_num_sorts(self.ctxctx.ref(), self.modelmodel))
6490 
6491  def get_sort(self, idx):
6492  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6493 
6494  >>> A = DeclareSort('A')
6495  >>> B = DeclareSort('B')
6496  >>> a1, a2 = Consts('a1 a2', A)
6497  >>> b1, b2 = Consts('b1 b2', B)
6498  >>> s = Solver()
6499  >>> s.add(a1 != a2, b1 != b2)
6500  >>> s.check()
6501  sat
6502  >>> m = s.model()
6503  >>> m.num_sorts()
6504  2
6505  >>> m.get_sort(0)
6506  A
6507  >>> m.get_sort(1)
6508  B
6509  """
6510  if idx >= self.num_sortsnum_sorts():
6511  raise IndexError
6512  return _to_sort_ref(Z3_model_get_sort(self.ctxctx.ref(), self.modelmodel, idx), self.ctxctx)
6513 
6514  def sorts(self):
6515  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6516 
6517  >>> A = DeclareSort('A')
6518  >>> B = DeclareSort('B')
6519  >>> a1, a2 = Consts('a1 a2', A)
6520  >>> b1, b2 = Consts('b1 b2', B)
6521  >>> s = Solver()
6522  >>> s.add(a1 != a2, b1 != b2)
6523  >>> s.check()
6524  sat
6525  >>> m = s.model()
6526  >>> m.sorts()
6527  [A, B]
6528  """
6529  return [self.get_sortget_sort(i) for i in range(self.num_sortsnum_sorts())]
6530 
6531  def get_universe(self, s):
6532  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6533 
6534  >>> A = DeclareSort('A')
6535  >>> a, b = Consts('a b', A)
6536  >>> s = Solver()
6537  >>> s.add(a != b)
6538  >>> s.check()
6539  sat
6540  >>> m = s.model()
6541  >>> m.get_universe(A)
6542  [A!val!1, A!val!0]
6543  """
6544  if z3_debug():
6545  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6546  try:
6547  return AstVector(Z3_model_get_sort_universe(self.ctxctx.ref(), self.modelmodel, s.ast), self.ctxctx)
6548  except Z3Exception:
6549  return None
6550 
6551  def __getitem__(self, idx):
6552  """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6553  If `idx` is a declaration, then the actual interpretation is returned.
6554 
6555  The elements can be retrieved using position or the actual declaration.
6556 
6557  >>> f = Function('f', IntSort(), IntSort())
6558  >>> x = Int('x')
6559  >>> s = Solver()
6560  >>> s.add(x > 0, x < 2, f(x) == 0)
6561  >>> s.check()
6562  sat
6563  >>> m = s.model()
6564  >>> len(m)
6565  2
6566  >>> m[0]
6567  x
6568  >>> m[1]
6569  f
6570  >>> m[x]
6571  1
6572  >>> m[f]
6573  [else -> 0]
6574  >>> for d in m: print("%s -> %s" % (d, m[d]))
6575  x -> 1
6576  f -> [else -> 0]
6577  """
6578  if _is_int(idx):
6579  if idx >= len(self):
6580  raise IndexError
6581  num_consts = Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel)
6582  if (idx < num_consts):
6583  return FuncDeclRef(Z3_model_get_const_decl(self.ctxctx.ref(), self.modelmodel, idx), self.ctxctx)
6584  else:
6585  return FuncDeclRef(Z3_model_get_func_decl(self.ctxctx.ref(), self.modelmodel, idx - num_consts), self.ctxctx)
6586  if isinstance(idx, FuncDeclRef):
6587  return self.get_interpget_interp(idx)
6588  if is_const(idx):
6589  return self.get_interpget_interp(idx.decl())
6590  if isinstance(idx, SortRef):
6591  return self.get_universeget_universe(idx)
6592  if z3_debug():
6593  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6594  return None
6595 
6596  def decls(self):
6597  """Return a list with all symbols that have an interpretation in the model `self`.
6598  >>> f = Function('f', IntSort(), IntSort())
6599  >>> x = Int('x')
6600  >>> s = Solver()
6601  >>> s.add(x > 0, x < 2, f(x) == 0)
6602  >>> s.check()
6603  sat
6604  >>> m = s.model()
6605  >>> m.decls()
6606  [x, f]
6607  """
6608  r = []
6609  for i in range(Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel)):
6610  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctxctx.ref(), self.modelmodel, i), self.ctxctx))
6611  for i in range(Z3_model_get_num_funcs(self.ctxctx.ref(), self.modelmodel)):
6612  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctxctx.ref(), self.modelmodel, i), self.ctxctx))
6613  return r
6614 
6615  def update_value(self, x, value):
6616  """Update the interpretation of a constant"""
6617  if is_expr(x):
6618  x = x.decl()
6619  if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
6620  fi1 = value.f
6621  fi2 = Z3_add_func_interp(x.ctx_ref(), self.modelmodel, x.ast, value.else_value().ast);
6622  fi2 = FuncInterp(fi2, x.ctx)
6623  for i in range(value.num_entries()):
6624  e = value.entry(i)
6625  n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
6626  v = AstVector()
6627  for j in range(n):
6628  v.push(entry.arg_value(j))
6629  val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
6630  Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
6631  return
6632  if not is_func_decl(x) or x.arity() != 0:
6633  raise Z3Exception("Expecting 0-ary function or constant expression")
6634  value = _py2expr(value)
6635  Z3_add_const_interp(x.ctx_ref(), self.modelmodel, x.ast, value.ast)
6636 
6637  def translate(self, target):
6638  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6639  """
6640  if z3_debug():
6641  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6642  model = Z3_model_translate(self.ctxctx.ref(), self.modelmodel, target.ref())
6643  return ModelRef(model, target)
6644 
6645  def __copy__(self):
6646  return self.translatetranslate(self.ctxctx)
6647 
6648  def __deepcopy__(self, memo={}):
6649  return self.translatetranslate(self.ctxctx)
6650 
6651 
6652 def Model(ctx=None):
6653  ctx = _get_ctx(ctx)
6654  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6655 
6656 
6658  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6659  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6660 
6661 
6663  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6664  if z3_debug():
6665  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6666  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6667 
6668 
6673 
6674 
6676  """Statistics for `Solver.check()`."""
6677 
6678  def __init__(self, stats, ctx):
6679  self.statsstats = stats
6680  self.ctxctx = ctx
6681  Z3_stats_inc_ref(self.ctxctx.ref(), self.statsstats)
6682 
6683  def __deepcopy__(self, memo={}):
6684  return Statistics(self.statsstats, self.ctxctx)
6685 
6686  def __del__(self):
6687  if self.ctxctx.ref() is not None:
6688  Z3_stats_dec_ref(self.ctxctx.ref(), self.statsstats)
6689 
6690  def __repr__(self):
6691  if in_html_mode():
6692  out = io.StringIO()
6693  even = True
6694  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6695  for k, v in self:
6696  if even:
6697  out.write(u('<tr style="background-color:#CFCFCF">'))
6698  even = False
6699  else:
6700  out.write(u("<tr>"))
6701  even = True
6702  out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6703  out.write(u("</table>"))
6704  return out.getvalue()
6705  else:
6706  return Z3_stats_to_string(self.ctxctx.ref(), self.statsstats)
6707 
6708  def __len__(self):
6709  """Return the number of statistical counters.
6710 
6711  >>> x = Int('x')
6712  >>> s = Then('simplify', 'nlsat').solver()
6713  >>> s.add(x > 0)
6714  >>> s.check()
6715  sat
6716  >>> st = s.statistics()
6717  >>> len(st)
6718  6
6719  """
6720  return int(Z3_stats_size(self.ctxctx.ref(), self.statsstats))
6721 
6722  def __getitem__(self, idx):
6723  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6724 
6725  >>> x = Int('x')
6726  >>> s = Then('simplify', 'nlsat').solver()
6727  >>> s.add(x > 0)
6728  >>> s.check()
6729  sat
6730  >>> st = s.statistics()
6731  >>> len(st)
6732  6
6733  >>> st[0]
6734  ('nlsat propagations', 2)
6735  >>> st[1]
6736  ('nlsat stages', 2)
6737  """
6738  if idx >= len(self):
6739  raise IndexError
6740  if Z3_stats_is_uint(self.ctxctx.ref(), self.statsstats, idx):
6741  val = int(Z3_stats_get_uint_value(self.ctxctx.ref(), self.statsstats, idx))
6742  else:
6743  val = Z3_stats_get_double_value(self.ctxctx.ref(), self.statsstats, idx)
6744  return (Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx), val)
6745 
6746  def keys(self):
6747  """Return the list of statistical counters.
6748 
6749  >>> x = Int('x')
6750  >>> s = Then('simplify', 'nlsat').solver()
6751  >>> s.add(x > 0)
6752  >>> s.check()
6753  sat
6754  >>> st = s.statistics()
6755  """
6756  return [Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx) for idx in range(len(self))]
6757 
6758  def get_key_value(self, key):
6759  """Return the value of a particular statistical counter.
6760 
6761  >>> x = Int('x')
6762  >>> s = Then('simplify', 'nlsat').solver()
6763  >>> s.add(x > 0)
6764  >>> s.check()
6765  sat
6766  >>> st = s.statistics()
6767  >>> st.get_key_value('nlsat propagations')
6768  2
6769  """
6770  for idx in range(len(self)):
6771  if key == Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx):
6772  if Z3_stats_is_uint(self.ctxctx.ref(), self.statsstats, idx):
6773  return int(Z3_stats_get_uint_value(self.ctxctx.ref(), self.statsstats, idx))
6774  else:
6775  return Z3_stats_get_double_value(self.ctxctx.ref(), self.statsstats, idx)
6776  raise Z3Exception("unknown key")
6777 
6778  def __getattr__(self, name):
6779  """Access the value of statistical using attributes.
6780 
6781  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6782  we should use '_' (e.g., 'nlsat_propagations').
6783 
6784  >>> x = Int('x')
6785  >>> s = Then('simplify', 'nlsat').solver()
6786  >>> s.add(x > 0)
6787  >>> s.check()
6788  sat
6789  >>> st = s.statistics()
6790  >>> st.nlsat_propagations
6791  2
6792  >>> st.nlsat_stages
6793  2
6794  """
6795  key = name.replace("_", " ")
6796  try:
6797  return self.get_key_valueget_key_value(key)
6798  except Z3Exception:
6799  raise AttributeError
6800 
6801 
6806 
6807 
6809  """Represents the result of a satisfiability check: sat, unsat, unknown.
6810 
6811  >>> s = Solver()
6812  >>> s.check()
6813  sat
6814  >>> r = s.check()
6815  >>> isinstance(r, CheckSatResult)
6816  True
6817  """
6818 
6819  def __init__(self, r):
6820  self.rr = r
6821 
6822  def __deepcopy__(self, memo={}):
6823  return CheckSatResult(self.rr)
6824 
6825  def __eq__(self, other):
6826  return isinstance(other, CheckSatResult) and self.rr == other.r
6827 
6828  def __ne__(self, other):
6829  return not self.__eq____eq__(other)
6830 
6831  def __repr__(self):
6832  if in_html_mode():
6833  if self.rr == Z3_L_TRUE:
6834  return "<b>sat</b>"
6835  elif self.rr == Z3_L_FALSE:
6836  return "<b>unsat</b>"
6837  else:
6838  return "<b>unknown</b>"
6839  else:
6840  if self.rr == Z3_L_TRUE:
6841  return "sat"
6842  elif self.rr == Z3_L_FALSE:
6843  return "unsat"
6844  else:
6845  return "unknown"
6846 
6847  def _repr_html_(self):
6848  in_html = in_html_mode()
6849  set_html_mode(True)
6850  res = repr(self)
6851  set_html_mode(in_html)
6852  return res
6853 
6854 
6855 sat = CheckSatResult(Z3_L_TRUE)
6856 unsat = CheckSatResult(Z3_L_FALSE)
6857 unknown = CheckSatResult(Z3_L_UNDEF)
6858 
6859 
6861  """
6862  Solver API provides methods for implementing the main SMT 2.0 commands:
6863  push, pop, check, get-model, etc.
6864  """
6865 
6866  def __init__(self, solver=None, ctx=None, logFile=None):
6867  assert solver is None or ctx is not None
6868  self.ctxctx = _get_ctx(ctx)
6869  self.backtrack_levelbacktrack_level = 4000000000
6870  self.solversolver = None
6871  if solver is None:
6872  self.solversolver = Z3_mk_solver(self.ctxctx.ref())
6873  else:
6874  self.solversolver = solver
6875  Z3_solver_inc_ref(self.ctxctx.ref(), self.solversolver)
6876  if logFile is not None:
6877  self.setset("smtlib2_log", logFile)
6878 
6879  def __del__(self):
6880  if self.solversolver is not None and self.ctxctx.ref() is not None:
6881  Z3_solver_dec_ref(self.ctxctx.ref(), self.solversolver)
6882 
6883  def set(self, *args, **keys):
6884  """Set a configuration option.
6885  The method `help()` return a string containing all available options.
6886 
6887  >>> s = Solver()
6888  >>> # The option MBQI can be set using three different approaches.
6889  >>> s.set(mbqi=True)
6890  >>> s.set('MBQI', True)
6891  >>> s.set(':mbqi', True)
6892  """
6893  p = args2params(args, keys, self.ctxctx)
6894  Z3_solver_set_params(self.ctxctx.ref(), self.solversolver, p.params)
6895 
6896  def push(self):
6897  """Create a backtracking point.
6898 
6899  >>> x = Int('x')
6900  >>> s = Solver()
6901  >>> s.add(x > 0)
6902  >>> s
6903  [x > 0]
6904  >>> s.push()
6905  >>> s.add(x < 1)
6906  >>> s
6907  [x > 0, x < 1]
6908  >>> s.check()
6909  unsat
6910  >>> s.pop()
6911  >>> s.check()
6912  sat
6913  >>> s
6914  [x > 0]
6915  """
6916  Z3_solver_push(self.ctxctx.ref(), self.solversolver)
6917 
6918  def pop(self, num=1):
6919  """Backtrack \\c num backtracking points.
6920 
6921  >>> x = Int('x')
6922  >>> s = Solver()
6923  >>> s.add(x > 0)
6924  >>> s
6925  [x > 0]
6926  >>> s.push()
6927  >>> s.add(x < 1)
6928  >>> s
6929  [x > 0, x < 1]
6930  >>> s.check()
6931  unsat
6932  >>> s.pop()
6933  >>> s.check()
6934  sat
6935  >>> s
6936  [x > 0]
6937  """
6938  Z3_solver_pop(self.ctxctx.ref(), self.solversolver, num)
6939 
6940  def num_scopes(self):
6941  """Return the current number of backtracking points.
6942 
6943  >>> s = Solver()
6944  >>> s.num_scopes()
6945  0
6946  >>> s.push()
6947  >>> s.num_scopes()
6948  1
6949  >>> s.push()
6950  >>> s.num_scopes()
6951  2
6952  >>> s.pop()
6953  >>> s.num_scopes()
6954  1
6955  """
6956  return Z3_solver_get_num_scopes(self.ctxctx.ref(), self.solversolver)
6957 
6958  def reset(self):
6959  """Remove all asserted constraints and backtracking points created using `push()`.
6960 
6961  >>> x = Int('x')
6962  >>> s = Solver()
6963  >>> s.add(x > 0)
6964  >>> s
6965  [x > 0]
6966  >>> s.reset()
6967  >>> s
6968  []
6969  """
6970  Z3_solver_reset(self.ctxctx.ref(), self.solversolver)
6971 
6972  def assert_exprs(self, *args):
6973  """Assert constraints into the solver.
6974 
6975  >>> x = Int('x')
6976  >>> s = Solver()
6977  >>> s.assert_exprs(x > 0, x < 2)
6978  >>> s
6979  [x > 0, x < 2]
6980  """
6981  args = _get_args(args)
6982  s = BoolSort(self.ctxctx)
6983  for arg in args:
6984  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6985  for f in arg:
6986  Z3_solver_assert(self.ctxctx.ref(), self.solversolver, f.as_ast())
6987  else:
6988  arg = s.cast(arg)
6989  Z3_solver_assert(self.ctxctx.ref(), self.solversolver, arg.as_ast())
6990 
6991  def add(self, *args):
6992  """Assert constraints into the solver.
6993 
6994  >>> x = Int('x')
6995  >>> s = Solver()
6996  >>> s.add(x > 0, x < 2)
6997  >>> s
6998  [x > 0, x < 2]
6999  """
7000  self.assert_exprsassert_exprs(*args)
7001 
7002  def __iadd__(self, fml):
7003  self.addadd(fml)
7004  return self
7005 
7006  def append(self, *args):
7007  """Assert constraints into the solver.
7008 
7009  >>> x = Int('x')
7010  >>> s = Solver()
7011  >>> s.append(x > 0, x < 2)
7012  >>> s
7013  [x > 0, x < 2]
7014  """
7015  self.assert_exprsassert_exprs(*args)
7016 
7017  def insert(self, *args):
7018  """Assert constraints into the solver.
7019 
7020  >>> x = Int('x')
7021  >>> s = Solver()
7022  >>> s.insert(x > 0, x < 2)
7023  >>> s
7024  [x > 0, x < 2]
7025  """
7026  self.assert_exprsassert_exprs(*args)
7027 
7028  def assert_and_track(self, a, p):
7029  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7030 
7031  If `p` is a string, it will be automatically converted into a Boolean constant.
7032 
7033  >>> x = Int('x')
7034  >>> p3 = Bool('p3')
7035  >>> s = Solver()
7036  >>> s.set(unsat_core=True)
7037  >>> s.assert_and_track(x > 0, 'p1')
7038  >>> s.assert_and_track(x != 1, 'p2')
7039  >>> s.assert_and_track(x < 0, p3)
7040  >>> print(s.check())
7041  unsat
7042  >>> c = s.unsat_core()
7043  >>> len(c)
7044  2
7045  >>> Bool('p1') in c
7046  True
7047  >>> Bool('p2') in c
7048  False
7049  >>> p3 in c
7050  True
7051  """
7052  if isinstance(p, str):
7053  p = Bool(p, self.ctxctx)
7054  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7055  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7056  Z3_solver_assert_and_track(self.ctxctx.ref(), self.solversolver, a.as_ast(), p.as_ast())
7057 
7058  def check(self, *assumptions):
7059  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7060 
7061  >>> x = Int('x')
7062  >>> s = Solver()
7063  >>> s.check()
7064  sat
7065  >>> s.add(x > 0, x < 2)
7066  >>> s.check()
7067  sat
7068  >>> s.model().eval(x)
7069  1
7070  >>> s.add(x < 1)
7071  >>> s.check()
7072  unsat
7073  >>> s.reset()
7074  >>> s.add(2**x == 4)
7075  >>> s.check()
7076  unknown
7077  """
7078  s = BoolSort(self.ctxctx)
7079  assumptions = _get_args(assumptions)
7080  num = len(assumptions)
7081  _assumptions = (Ast * num)()
7082  for i in range(num):
7083  _assumptions[i] = s.cast(assumptions[i]).as_ast()
7084  r = Z3_solver_check_assumptions(self.ctxctx.ref(), self.solversolver, num, _assumptions)
7085  return CheckSatResult(r)
7086 
7087  def model(self):
7088  """Return a model for the last `check()`.
7089 
7090  This function raises an exception if
7091  a model is not available (e.g., last `check()` returned unsat).
7092 
7093  >>> s = Solver()
7094  >>> a = Int('a')
7095  >>> s.add(a + 2 == 0)
7096  >>> s.check()
7097  sat
7098  >>> s.model()
7099  [a = -2]
7100  """
7101  try:
7102  return ModelRef(Z3_solver_get_model(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7103  except Z3Exception:
7104  raise Z3Exception("model is not available")
7105 
7106  def import_model_converter(self, other):
7107  """Import model converter from other into the current solver"""
7108  Z3_solver_import_model_converter(self.ctxctx.ref(), other.solver, self.solversolver)
7109 
7110  def unsat_core(self):
7111  """Return a subset (as an AST vector) of the assumptions provided to the last check().
7112 
7113  These are the assumptions Z3 used in the unsatisfiability proof.
7114  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7115  They may be also used to "retract" assumptions. Note that, assumptions are not really
7116  "soft constraints", but they can be used to implement them.
7117 
7118  >>> p1, p2, p3 = Bools('p1 p2 p3')
7119  >>> x, y = Ints('x y')
7120  >>> s = Solver()
7121  >>> s.add(Implies(p1, x > 0))
7122  >>> s.add(Implies(p2, y > x))
7123  >>> s.add(Implies(p2, y < 1))
7124  >>> s.add(Implies(p3, y > -3))
7125  >>> s.check(p1, p2, p3)
7126  unsat
7127  >>> core = s.unsat_core()
7128  >>> len(core)
7129  2
7130  >>> p1 in core
7131  True
7132  >>> p2 in core
7133  True
7134  >>> p3 in core
7135  False
7136  >>> # "Retracting" p2
7137  >>> s.check(p1, p3)
7138  sat
7139  """
7140  return AstVector(Z3_solver_get_unsat_core(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7141 
7142  def consequences(self, assumptions, variables):
7143  """Determine fixed values for the variables based on the solver state and assumptions.
7144  >>> s = Solver()
7145  >>> a, b, c, d = Bools('a b c d')
7146  >>> s.add(Implies(a,b), Implies(b, c))
7147  >>> s.consequences([a],[b,c,d])
7148  (sat, [Implies(a, b), Implies(a, c)])
7149  >>> s.consequences([Not(c),d],[a,b,c,d])
7150  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7151  """
7152  if isinstance(assumptions, list):
7153  _asms = AstVector(None, self.ctxctx)
7154  for a in assumptions:
7155  _asms.push(a)
7156  assumptions = _asms
7157  if isinstance(variables, list):
7158  _vars = AstVector(None, self.ctxctx)
7159  for a in variables:
7160  _vars.push(a)
7161  variables = _vars
7162  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7163  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7164  consequences = AstVector(None, self.ctxctx)
7165  r = Z3_solver_get_consequences(self.ctxctx.ref(), self.solversolver, assumptions.vector,
7166  variables.vector, consequences.vector)
7167  sz = len(consequences)
7168  consequences = [consequences[i] for i in range(sz)]
7169  return CheckSatResult(r), consequences
7170 
7171  def from_file(self, filename):
7172  """Parse assertions from a file"""
7173  Z3_solver_from_file(self.ctxctx.ref(), self.solversolver, filename)
7174 
7175  def from_string(self, s):
7176  """Parse assertions from a string"""
7177  Z3_solver_from_string(self.ctxctx.ref(), self.solversolver, s)
7178 
7179  def cube(self, vars=None):
7180  """Get set of cubes
7181  The method takes an optional set of variables that restrict which
7182  variables may be used as a starting point for cubing.
7183  If vars is not None, then the first case split is based on a variable in
7184  this set.
7185  """
7186  self.cube_vscube_vs = AstVector(None, self.ctxctx)
7187  if vars is not None:
7188  for v in vars:
7189  self.cube_vscube_vs.push(v)
7190  while True:
7191  lvl = self.backtrack_levelbacktrack_level
7192  self.backtrack_levelbacktrack_level = 4000000000
7193  r = AstVector(Z3_solver_cube(self.ctxctx.ref(), self.solversolver, self.cube_vscube_vs.vector, lvl), self.ctxctx)
7194  if (len(r) == 1 and is_false(r[0])):
7195  return
7196  yield r
7197  if (len(r) == 0):
7198  return
7199 
7200  def cube_vars(self):
7201  """Access the set of variables that were touched by the most recently generated cube.
7202  This set of variables can be used as a starting point for additional cubes.
7203  The idea is that variables that appear in clauses that are reduced by the most recent
7204  cube are likely more useful to cube on."""
7205  return self.cube_vscube_vs
7206 
7207  def proof(self):
7208  """Return a proof for the last `check()`. Proof construction must be enabled."""
7209  return _to_expr_ref(Z3_solver_get_proof(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7210 
7211  def assertions(self):
7212  """Return an AST vector containing all added constraints.
7213 
7214  >>> s = Solver()
7215  >>> s.assertions()
7216  []
7217  >>> a = Int('a')
7218  >>> s.add(a > 0)
7219  >>> s.add(a < 10)
7220  >>> s.assertions()
7221  [a > 0, a < 10]
7222  """
7223  return AstVector(Z3_solver_get_assertions(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7224 
7225  def units(self):
7226  """Return an AST vector containing all currently inferred units.
7227  """
7228  return AstVector(Z3_solver_get_units(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7229 
7230  def non_units(self):
7231  """Return an AST vector containing all atomic formulas in solver state that are not units.
7232  """
7233  return AstVector(Z3_solver_get_non_units(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7234 
7235  def trail_levels(self):
7236  """Return trail and decision levels of the solver state after a check() call.
7237  """
7238  trail = self.trailtrail()
7239  levels = (ctypes.c_uint * len(trail))()
7240  Z3_solver_get_levels(self.ctxctx.ref(), self.solversolver, trail.vector, len(trail), levels)
7241  return trail, levels
7242 
7243  def trail(self):
7244  """Return trail of the solver state after a check() call.
7245  """
7246  return AstVector(Z3_solver_get_trail(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7247 
7248  def statistics(self):
7249  """Return statistics for the last `check()`.
7250 
7251  >>> s = SimpleSolver()
7252  >>> x = Int('x')
7253  >>> s.add(x > 0)
7254  >>> s.check()
7255  sat
7256  >>> st = s.statistics()
7257  >>> st.get_key_value('final checks')
7258  1
7259  >>> len(st) > 0
7260  True
7261  >>> st[0] != 0
7262  True
7263  """
7264  return Statistics(Z3_solver_get_statistics(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7265 
7266  def reason_unknown(self):
7267  """Return a string describing why the last `check()` returned `unknown`.
7268 
7269  >>> x = Int('x')
7270  >>> s = SimpleSolver()
7271  >>> s.add(2**x == 4)
7272  >>> s.check()
7273  unknown
7274  >>> s.reason_unknown()
7275  '(incomplete (theory arithmetic))'
7276  """
7277  return Z3_solver_get_reason_unknown(self.ctxctx.ref(), self.solversolver)
7278 
7279  def help(self):
7280  """Display a string describing all available options."""
7281  print(Z3_solver_get_help(self.ctxctx.ref(), self.solversolver))
7282 
7283  def param_descrs(self):
7284  """Return the parameter description set."""
7285  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7286 
7287  def __repr__(self):
7288  """Return a formatted string with all added constraints."""
7289  return obj_to_string(self)
7290 
7291  def translate(self, target):
7292  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7293 
7294  >>> c1 = Context()
7295  >>> c2 = Context()
7296  >>> s1 = Solver(ctx=c1)
7297  >>> s2 = s1.translate(c2)
7298  """
7299  if z3_debug():
7300  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7301  solver = Z3_solver_translate(self.ctxctx.ref(), self.solversolver, target.ref())
7302  return Solver(solver, target)
7303 
7304  def __copy__(self):
7305  return self.translatetranslate(self.ctxctx)
7306 
7307  def __deepcopy__(self, memo={}):
7308  return self.translatetranslate(self.ctxctx)
7309 
7310  def sexpr(self):
7311  """Return a formatted string (in Lisp-like format) with all added constraints.
7312  We say the string is in s-expression format.
7313 
7314  >>> x = Int('x')
7315  >>> s = Solver()
7316  >>> s.add(x > 0)
7317  >>> s.add(x < 2)
7318  >>> r = s.sexpr()
7319  """
7320  return Z3_solver_to_string(self.ctxctx.ref(), self.solversolver)
7321 
7322  def dimacs(self, include_names=True):
7323  """Return a textual representation of the solver in DIMACS format."""
7324  return Z3_solver_to_dimacs_string(self.ctxctx.ref(), self.solversolver, include_names)
7325 
7326  def to_smt2(self):
7327  """return SMTLIB2 formatted benchmark for solver's assertions"""
7328  es = self.assertionsassertions()
7329  sz = len(es)
7330  sz1 = sz
7331  if sz1 > 0:
7332  sz1 -= 1
7333  v = (Ast * sz1)()
7334  for i in range(sz1):
7335  v[i] = es[i].as_ast()
7336  if sz > 0:
7337  e = es[sz1].as_ast()
7338  else:
7339  e = BoolVal(True, self.ctxctx).as_ast()
7341  self.ctxctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7342  )
7343 
7344 
7345 def SolverFor(logic, ctx=None, logFile=None):
7346  """Create a solver customized for the given logic.
7347 
7348  The parameter `logic` is a string. It should be contains
7349  the name of a SMT-LIB logic.
7350  See http://www.smtlib.org/ for the name of all available logics.
7351 
7352  >>> s = SolverFor("QF_LIA")
7353  >>> x = Int('x')
7354  >>> s.add(x > 0)
7355  >>> s.add(x < 2)
7356  >>> s.check()
7357  sat
7358  >>> s.model()
7359  [x = 1]
7360  """
7361  ctx = _get_ctx(ctx)
7362  logic = to_symbol(logic)
7363  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7364 
7365 
7366 def SimpleSolver(ctx=None, logFile=None):
7367  """Return a simple general purpose solver with limited amount of preprocessing.
7368 
7369  >>> s = SimpleSolver()
7370  >>> x = Int('x')
7371  >>> s.add(x > 0)
7372  >>> s.check()
7373  sat
7374  """
7375  ctx = _get_ctx(ctx)
7376  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7377 
7378 
7383 
7384 
7386  """Fixedpoint API provides methods for solving with recursive predicates"""
7387 
7388  def __init__(self, fixedpoint=None, ctx=None):
7389  assert fixedpoint is None or ctx is not None
7390  self.ctxctx = _get_ctx(ctx)
7391  self.fixedpointfixedpoint = None
7392  if fixedpoint is None:
7393  self.fixedpointfixedpoint = Z3_mk_fixedpoint(self.ctxctx.ref())
7394  else:
7395  self.fixedpointfixedpoint = fixedpoint
7396  Z3_fixedpoint_inc_ref(self.ctxctx.ref(), self.fixedpointfixedpoint)
7397  self.varsvars = []
7398 
7399  def __deepcopy__(self, memo={}):
7400  return FixedPoint(self.fixedpointfixedpoint, self.ctxctx)
7401 
7402  def __del__(self):
7403  if self.fixedpointfixedpoint is not None and self.ctxctx.ref() is not None:
7404  Z3_fixedpoint_dec_ref(self.ctxctx.ref(), self.fixedpointfixedpoint)
7405 
7406  def set(self, *args, **keys):
7407  """Set a configuration option. The method `help()` return a string containing all available options.
7408  """
7409  p = args2params(args, keys, self.ctxctx)
7410  Z3_fixedpoint_set_params(self.ctxctx.ref(), self.fixedpointfixedpoint, p.params)
7411 
7412  def help(self):
7413  """Display a string describing all available options."""
7414  print(Z3_fixedpoint_get_help(self.ctxctx.ref(), self.fixedpointfixedpoint))
7415 
7416  def param_descrs(self):
7417  """Return the parameter description set."""
7418  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7419 
7420  def assert_exprs(self, *args):
7421  """Assert constraints as background axioms for the fixedpoint solver."""
7422  args = _get_args(args)
7423  s = BoolSort(self.ctxctx)
7424  for arg in args:
7425  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7426  for f in arg:
7427  f = self.abstractabstract(f)
7428  Z3_fixedpoint_assert(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast())
7429  else:
7430  arg = s.cast(arg)
7431  arg = self.abstractabstract(arg)
7432  Z3_fixedpoint_assert(self.ctxctx.ref(), self.fixedpointfixedpoint, arg.as_ast())
7433 
7434  def add(self, *args):
7435  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7436  self.assert_exprsassert_exprs(*args)
7437 
7438  def __iadd__(self, fml):
7439  self.addadd(fml)
7440  return self
7441 
7442  def append(self, *args):
7443  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7444  self.assert_exprsassert_exprs(*args)
7445 
7446  def insert(self, *args):
7447  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7448  self.assert_exprsassert_exprs(*args)
7449 
7450  def add_rule(self, head, body=None, name=None):
7451  """Assert rules defining recursive predicates to the fixedpoint solver.
7452  >>> a = Bool('a')
7453  >>> b = Bool('b')
7454  >>> s = Fixedpoint()
7455  >>> s.register_relation(a.decl())
7456  >>> s.register_relation(b.decl())
7457  >>> s.fact(a)
7458  >>> s.rule(b, a)
7459  >>> s.query(b)
7460  sat
7461  """
7462  if name is None:
7463  name = ""
7464  name = to_symbol(name, self.ctxctx)
7465  if body is None:
7466  head = self.abstractabstract(head)
7467  Z3_fixedpoint_add_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, head.as_ast(), name)
7468  else:
7469  body = _get_args(body)
7470  f = self.abstractabstract(Implies(And(body, self.ctxctx), head))
7471  Z3_fixedpoint_add_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast(), name)
7472 
7473  def rule(self, head, body=None, name=None):
7474  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7475  self.add_ruleadd_rule(head, body, name)
7476 
7477  def fact(self, head, name=None):
7478  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7479  self.add_ruleadd_rule(head, None, name)
7480 
7481  def query(self, *query):
7482  """Query the fixedpoint engine whether formula is derivable.
7483  You can also pass an tuple or list of recursive predicates.
7484  """
7485  query = _get_args(query)
7486  sz = len(query)
7487  if sz >= 1 and isinstance(query[0], FuncDeclRef):
7488  _decls = (FuncDecl * sz)()
7489  i = 0
7490  for q in query:
7491  _decls[i] = q.ast
7492  i = i + 1
7493  r = Z3_fixedpoint_query_relations(self.ctxctx.ref(), self.fixedpointfixedpoint, sz, _decls)
7494  else:
7495  if sz == 1:
7496  query = query[0]
7497  else:
7498  query = And(query, self.ctxctx)
7499  query = self.abstractabstract(query, False)
7500  r = Z3_fixedpoint_query(self.ctxctx.ref(), self.fixedpointfixedpoint, query.as_ast())
7501  return CheckSatResult(r)
7502 
7503  def query_from_lvl(self, lvl, *query):
7504  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7505  """
7506  query = _get_args(query)
7507  sz = len(query)
7508  if sz >= 1 and isinstance(query[0], FuncDecl):
7509  _z3_assert(False, "unsupported")
7510  else:
7511  if sz == 1:
7512  query = query[0]
7513  else:
7514  query = And(query)
7515  query = self.abstractabstract(query, False)
7516  r = Z3_fixedpoint_query_from_lvl(self.ctxctx.ref(), self.fixedpointfixedpoint, query.as_ast(), lvl)
7517  return CheckSatResult(r)
7518 
7519  def update_rule(self, head, body, name):
7520  """update rule"""
7521  if name is None:
7522  name = ""
7523  name = to_symbol(name, self.ctxctx)
7524  body = _get_args(body)
7525  f = self.abstractabstract(Implies(And(body, self.ctxctx), head))
7526  Z3_fixedpoint_update_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast(), name)
7527 
7528  def get_answer(self):
7529  """Retrieve answer from last query call."""
7530  r = Z3_fixedpoint_get_answer(self.ctxctx.ref(), self.fixedpointfixedpoint)
7531  return _to_expr_ref(r, self.ctxctx)
7532 
7534  """Retrieve a ground cex from last query call."""
7535  r = Z3_fixedpoint_get_ground_sat_answer(self.ctxctx.ref(), self.fixedpointfixedpoint)
7536  return _to_expr_ref(r, self.ctxctx)
7537 
7539  """retrieve rules along the counterexample trace"""
7540  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7541 
7543  """retrieve rule names along the counterexample trace"""
7544  # this is a hack as I don't know how to return a list of symbols from C++;
7545  # obtain names as a single string separated by semicolons
7546  names = _symbol2py(self.ctxctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctxctx.ref(), self.fixedpointfixedpoint))
7547  # split into individual names
7548  return names.split(";")
7549 
7550  def get_num_levels(self, predicate):
7551  """Retrieve number of levels used for predicate in PDR engine"""
7552  return Z3_fixedpoint_get_num_levels(self.ctxctx.ref(), self.fixedpointfixedpoint, predicate.ast)
7553 
7554  def get_cover_delta(self, level, predicate):
7555  """Retrieve properties known about predicate for the level'th unfolding.
7556  -1 is treated as the limit (infinity)
7557  """
7558  r = Z3_fixedpoint_get_cover_delta(self.ctxctx.ref(), self.fixedpointfixedpoint, level, predicate.ast)
7559  return _to_expr_ref(r, self.ctxctx)
7560 
7561  def add_cover(self, level, predicate, property):
7562  """Add property to predicate for the level'th unfolding.
7563  -1 is treated as infinity (infinity)
7564  """
7565  Z3_fixedpoint_add_cover(self.ctxctx.ref(), self.fixedpointfixedpoint, level, predicate.ast, property.ast)
7566 
7567  def register_relation(self, *relations):
7568  """Register relation as recursive"""
7569  relations = _get_args(relations)
7570  for f in relations:
7571  Z3_fixedpoint_register_relation(self.ctxctx.ref(), self.fixedpointfixedpoint, f.ast)
7572 
7573  def set_predicate_representation(self, f, *representations):
7574  """Control how relation is represented"""
7575  representations = _get_args(representations)
7576  representations = [to_symbol(s) for s in representations]
7577  sz = len(representations)
7578  args = (Symbol * sz)()
7579  for i in range(sz):
7580  args[i] = representations[i]
7581  Z3_fixedpoint_set_predicate_representation(self.ctxctx.ref(), self.fixedpointfixedpoint, f.ast, sz, args)
7582 
7583  def parse_string(self, s):
7584  """Parse rules and queries from a string"""
7585  return AstVector(Z3_fixedpoint_from_string(self.ctxctx.ref(), self.fixedpointfixedpoint, s), self.ctxctx)
7586 
7587  def parse_file(self, f):
7588  """Parse rules and queries from a file"""
7589  return AstVector(Z3_fixedpoint_from_file(self.ctxctx.ref(), self.fixedpointfixedpoint, f), self.ctxctx)
7590 
7591  def get_rules(self):
7592  """retrieve rules that have been added to fixedpoint context"""
7593  return AstVector(Z3_fixedpoint_get_rules(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7594 
7595  def get_assertions(self):
7596  """retrieve assertions that have been added to fixedpoint context"""
7597  return AstVector(Z3_fixedpoint_get_assertions(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7598 
7599  def __repr__(self):
7600  """Return a formatted string with all added rules and constraints."""
7601  return self.sexprsexpr()
7602 
7603  def sexpr(self):
7604  """Return a formatted string (in Lisp-like format) with all added constraints.
7605  We say the string is in s-expression format.
7606  """
7607  return Z3_fixedpoint_to_string(self.ctxctx.ref(), self.fixedpointfixedpoint, 0, (Ast * 0)())
7608 
7609  def to_string(self, queries):
7610  """Return a formatted string (in Lisp-like format) with all added constraints.
7611  We say the string is in s-expression format.
7612  Include also queries.
7613  """
7614  args, len = _to_ast_array(queries)
7615  return Z3_fixedpoint_to_string(self.ctxctx.ref(), self.fixedpointfixedpoint, len, args)
7616 
7617  def statistics(self):
7618  """Return statistics for the last `query()`.
7619  """
7620  return Statistics(Z3_fixedpoint_get_statistics(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7621 
7622  def reason_unknown(self):
7623  """Return a string describing why the last `query()` returned `unknown`.
7624  """
7625  return Z3_fixedpoint_get_reason_unknown(self.ctxctx.ref(), self.fixedpointfixedpoint)
7626 
7627  def declare_var(self, *vars):
7628  """Add variable or several variables.
7629  The added variable or variables will be bound in the rules
7630  and queries
7631  """
7632  vars = _get_args(vars)
7633  for v in vars:
7634  self.varsvars += [v]
7635 
7636  def abstract(self, fml, is_forall=True):
7637  if self.varsvars == []:
7638  return fml
7639  if is_forall:
7640  return ForAll(self.varsvars, fml)
7641  else:
7642  return Exists(self.varsvars, fml)
7643 
7644 
7645 
7650 
7652  """Finite domain sort."""
7653 
7654  def size(self):
7655  """Return the size of the finite domain sort"""
7656  r = (ctypes.c_ulonglong * 1)()
7657  if Z3_get_finite_domain_sort_size(self.ctx_refctx_ref(), self.astast, r):
7658  return r[0]
7659  else:
7660  raise Z3Exception("Failed to retrieve finite domain sort size")
7661 
7662 
7663 def FiniteDomainSort(name, sz, ctx=None):
7664  """Create a named finite domain sort of a given size sz"""
7665  if not isinstance(name, Symbol):
7666  name = to_symbol(name)
7667  ctx = _get_ctx(ctx)
7668  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7669 
7670 
7672  """Return True if `s` is a Z3 finite-domain sort.
7673 
7674  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7675  True
7676  >>> is_finite_domain_sort(IntSort())
7677  False
7678  """
7679  return isinstance(s, FiniteDomainSortRef)
7680 
7681 
7683  """Finite-domain expressions."""
7684 
7685  def sort(self):
7686  """Return the sort of the finite-domain expression `self`."""
7687  return FiniteDomainSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
7688 
7689  def as_string(self):
7690  """Return a Z3 floating point expression as a Python string."""
7691  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
7692 
7693 
7695  """Return `True` if `a` is a Z3 finite-domain expression.
7696 
7697  >>> s = FiniteDomainSort('S', 100)
7698  >>> b = Const('b', s)
7699  >>> is_finite_domain(b)
7700  True
7701  >>> is_finite_domain(Int('x'))
7702  False
7703  """
7704  return isinstance(a, FiniteDomainRef)
7705 
7706 
7708  """Integer values."""
7709 
7710  def as_long(self):
7711  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7712 
7713  >>> s = FiniteDomainSort('S', 100)
7714  >>> v = FiniteDomainVal(3, s)
7715  >>> v
7716  3
7717  >>> v.as_long() + 1
7718  4
7719  """
7720  return int(self.as_stringas_stringas_string())
7721 
7722  def as_string(self):
7723  """Return a Z3 finite-domain numeral as a Python string.
7724 
7725  >>> s = FiniteDomainSort('S', 100)
7726  >>> v = FiniteDomainVal(42, s)
7727  >>> v.as_string()
7728  '42'
7729  """
7730  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
7731 
7732 
7733 def FiniteDomainVal(val, sort, ctx=None):
7734  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7735 
7736  >>> s = FiniteDomainSort('S', 256)
7737  >>> FiniteDomainVal(255, s)
7738  255
7739  >>> FiniteDomainVal('100', s)
7740  100
7741  """
7742  if z3_debug():
7743  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7744  ctx = sort.ctx
7745  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7746 
7747 
7749  """Return `True` if `a` is a Z3 finite-domain value.
7750 
7751  >>> s = FiniteDomainSort('S', 100)
7752  >>> b = Const('b', s)
7753  >>> is_finite_domain_value(b)
7754  False
7755  >>> b = FiniteDomainVal(10, s)
7756  >>> b
7757  10
7758  >>> is_finite_domain_value(b)
7759  True
7760  """
7761  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7762 
7763 
7764 
7769 
7771  def __init__(self, opt, value, is_max):
7772  self._opt_opt = opt
7773  self._value_value = value
7774  self._is_max_is_max = is_max
7775 
7776  def lower(self):
7777  opt = self._opt_opt
7778  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7779 
7780  def upper(self):
7781  opt = self._opt_opt
7782  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7783 
7784  def lower_values(self):
7785  opt = self._opt_opt
7786  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7787 
7788  def upper_values(self):
7789  opt = self._opt_opt
7790  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7791 
7792  def value(self):
7793  if self._is_max_is_max:
7794  return self.upperupper()
7795  else:
7796  return self.lowerlower()
7797 
7798  def __str__(self):
7799  return "%s:%s" % (self._value_value, self._is_max_is_max)
7800 
7801 
7802 _on_models = {}
7803 
7804 
7805 def _global_on_model(ctx):
7806  (fn, mdl) = _on_models[ctx]
7807  fn(mdl)
7808 
7809 
7810 _on_model_eh = on_model_eh_type(_global_on_model)
7811 
7812 
7814  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7815 
7816  def __init__(self, ctx=None):
7817  self.ctxctx = _get_ctx(ctx)
7818  self.optimizeoptimize = Z3_mk_optimize(self.ctxctx.ref())
7819  self._on_models_id_on_models_id = None
7820  Z3_optimize_inc_ref(self.ctxctx.ref(), self.optimizeoptimize)
7821 
7822  def __deepcopy__(self, memo={}):
7823  return Optimize(self.optimizeoptimize, self.ctxctx)
7824 
7825  def __del__(self):
7826  if self.optimizeoptimize is not None and self.ctxctx.ref() is not None:
7827  Z3_optimize_dec_ref(self.ctxctx.ref(), self.optimizeoptimize)
7828  if self._on_models_id_on_models_id is not None:
7829  del _on_models[self._on_models_id_on_models_id]
7830 
7831  def set(self, *args, **keys):
7832  """Set a configuration option.
7833  The method `help()` return a string containing all available options.
7834  """
7835  p = args2params(args, keys, self.ctxctx)
7836  Z3_optimize_set_params(self.ctxctx.ref(), self.optimizeoptimize, p.params)
7837 
7838  def help(self):
7839  """Display a string describing all available options."""
7840  print(Z3_optimize_get_help(self.ctxctx.ref(), self.optimizeoptimize))
7841 
7842  def param_descrs(self):
7843  """Return the parameter description set."""
7844  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7845 
7846  def assert_exprs(self, *args):
7847  """Assert constraints as background axioms for the optimize solver."""
7848  args = _get_args(args)
7849  s = BoolSort(self.ctxctx)
7850  for arg in args:
7851  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7852  for f in arg:
7853  Z3_optimize_assert(self.ctxctx.ref(), self.optimizeoptimize, f.as_ast())
7854  else:
7855  arg = s.cast(arg)
7856  Z3_optimize_assert(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast())
7857 
7858  def add(self, *args):
7859  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7860  self.assert_exprsassert_exprs(*args)
7861 
7862  def __iadd__(self, fml):
7863  self.addadd(fml)
7864  return self
7865 
7866  def assert_and_track(self, a, p):
7867  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7868 
7869  If `p` is a string, it will be automatically converted into a Boolean constant.
7870 
7871  >>> x = Int('x')
7872  >>> p3 = Bool('p3')
7873  >>> s = Optimize()
7874  >>> s.assert_and_track(x > 0, 'p1')
7875  >>> s.assert_and_track(x != 1, 'p2')
7876  >>> s.assert_and_track(x < 0, p3)
7877  >>> print(s.check())
7878  unsat
7879  >>> c = s.unsat_core()
7880  >>> len(c)
7881  2
7882  >>> Bool('p1') in c
7883  True
7884  >>> Bool('p2') in c
7885  False
7886  >>> p3 in c
7887  True
7888  """
7889  if isinstance(p, str):
7890  p = Bool(p, self.ctxctx)
7891  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7892  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7893  Z3_optimize_assert_and_track(self.ctxctx.ref(), self.optimizeoptimize, a.as_ast(), p.as_ast())
7894 
7895  def add_soft(self, arg, weight="1", id=None):
7896  """Add soft constraint with optional weight and optional identifier.
7897  If no weight is supplied, then the penalty for violating the soft constraint
7898  is 1.
7899  Soft constraints are grouped by identifiers. Soft constraints that are
7900  added without identifiers are grouped by default.
7901  """
7902  if _is_int(weight):
7903  weight = "%d" % weight
7904  elif isinstance(weight, float):
7905  weight = "%f" % weight
7906  if not isinstance(weight, str):
7907  raise Z3Exception("weight should be a string or an integer")
7908  if id is None:
7909  id = ""
7910  id = to_symbol(id, self.ctxctx)
7911 
7912  def asoft(a):
7913  v = Z3_optimize_assert_soft(self.ctxctx.ref(), self.optimizeoptimize, a.as_ast(), weight, id)
7914  return OptimizeObjective(self, v, False)
7915  if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7916  return [asoft(a) for a in arg]
7917  return asoft(arg)
7918 
7919  def maximize(self, arg):
7920  """Add objective function to maximize."""
7921  return OptimizeObjective(
7922  self,
7923  Z3_optimize_maximize(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast()),
7924  is_max=True,
7925  )
7926 
7927  def minimize(self, arg):
7928  """Add objective function to minimize."""
7929  return OptimizeObjective(
7930  self,
7931  Z3_optimize_minimize(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast()),
7932  is_max=False,
7933  )
7934 
7935  def push(self):
7936  """create a backtracking point for added rules, facts and assertions"""
7937  Z3_optimize_push(self.ctxctx.ref(), self.optimizeoptimize)
7938 
7939  def pop(self):
7940  """restore to previously created backtracking point"""
7941  Z3_optimize_pop(self.ctxctx.ref(), self.optimizeoptimize)
7942 
7943  def check(self, *assumptions):
7944  """Check satisfiability while optimizing objective functions."""
7945  assumptions = _get_args(assumptions)
7946  num = len(assumptions)
7947  _assumptions = (Ast * num)()
7948  for i in range(num):
7949  _assumptions[i] = assumptions[i].as_ast()
7950  return CheckSatResult(Z3_optimize_check(self.ctxctx.ref(), self.optimizeoptimize, num, _assumptions))
7951 
7952  def reason_unknown(self):
7953  """Return a string that describes why the last `check()` returned `unknown`."""
7954  return Z3_optimize_get_reason_unknown(self.ctxctx.ref(), self.optimizeoptimize)
7955 
7956  def model(self):
7957  """Return a model for the last check()."""
7958  try:
7959  return ModelRef(Z3_optimize_get_model(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7960  except Z3Exception:
7961  raise Z3Exception("model is not available")
7962 
7963  def unsat_core(self):
7964  return AstVector(Z3_optimize_get_unsat_core(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7965 
7966  def lower(self, obj):
7967  if not isinstance(obj, OptimizeObjective):
7968  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7969  return obj.lower()
7970 
7971  def upper(self, obj):
7972  if not isinstance(obj, OptimizeObjective):
7973  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7974  return obj.upper()
7975 
7976  def lower_values(self, obj):
7977  if not isinstance(obj, OptimizeObjective):
7978  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7979  return obj.lower_values()
7980 
7981  def upper_values(self, obj):
7982  if not isinstance(obj, OptimizeObjective):
7983  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7984  return obj.upper_values()
7985 
7986  def from_file(self, filename):
7987  """Parse assertions and objectives from a file"""
7988  Z3_optimize_from_file(self.ctxctx.ref(), self.optimizeoptimize, filename)
7989 
7990  def from_string(self, s):
7991  """Parse assertions and objectives from a string"""
7992  Z3_optimize_from_string(self.ctxctx.ref(), self.optimizeoptimize, s)
7993 
7994  def assertions(self):
7995  """Return an AST vector containing all added constraints."""
7996  return AstVector(Z3_optimize_get_assertions(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7997 
7998  def objectives(self):
7999  """returns set of objective functions"""
8000  return AstVector(Z3_optimize_get_objectives(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
8001 
8002  def __repr__(self):
8003  """Return a formatted string with all added rules and constraints."""
8004  return self.sexprsexpr()
8005 
8006  def sexpr(self):
8007  """Return a formatted string (in Lisp-like format) with all added constraints.
8008  We say the string is in s-expression format.
8009  """
8010  return Z3_optimize_to_string(self.ctxctx.ref(), self.optimizeoptimize)
8011 
8012  def statistics(self):
8013  """Return statistics for the last check`.
8014  """
8015  return Statistics(Z3_optimize_get_statistics(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
8016 
8017  def set_on_model(self, on_model):
8018  """Register a callback that is invoked with every incremental improvement to
8019  objective values. The callback takes a model as argument.
8020  The life-time of the model is limited to the callback so the
8021  model has to be (deep) copied if it is to be used after the callback
8022  """
8023  id = len(_on_models) + 41
8024  mdl = Model(self.ctxctx)
8025  _on_models[id] = (on_model, mdl)
8026  self._on_models_id_on_models_id = id
8028  self.ctxctx.ref(), self.optimizeoptimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8029  )
8030 
8031 
8032 
8038  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8039  It also contains model and proof converters.
8040  """
8041 
8042  def __init__(self, result, ctx):
8043  self.resultresult = result
8044  self.ctxctx = ctx
8045  Z3_apply_result_inc_ref(self.ctxctx.ref(), self.resultresult)
8046 
8047  def __deepcopy__(self, memo={}):
8048  return ApplyResult(self.resultresult, self.ctxctx)
8049 
8050  def __del__(self):
8051  if self.ctxctx.ref() is not None:
8052  Z3_apply_result_dec_ref(self.ctxctx.ref(), self.resultresult)
8053 
8054  def __len__(self):
8055  """Return the number of subgoals in `self`.
8056 
8057  >>> a, b = Ints('a b')
8058  >>> g = Goal()
8059  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8060  >>> t = Tactic('split-clause')
8061  >>> r = t(g)
8062  >>> len(r)
8063  2
8064  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8065  >>> len(t(g))
8066  4
8067  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8068  >>> len(t(g))
8069  1
8070  """
8071  return int(Z3_apply_result_get_num_subgoals(self.ctxctx.ref(), self.resultresult))
8072 
8073  def __getitem__(self, idx):
8074  """Return one of the subgoals stored in ApplyResult object `self`.
8075 
8076  >>> a, b = Ints('a b')
8077  >>> g = Goal()
8078  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8079  >>> t = Tactic('split-clause')
8080  >>> r = t(g)
8081  >>> r[0]
8082  [a == 0, Or(b == 0, b == 1), a > b]
8083  >>> r[1]
8084  [a == 1, Or(b == 0, b == 1), a > b]
8085  """
8086  if idx >= len(self):
8087  raise IndexError
8088  return Goal(goal=Z3_apply_result_get_subgoal(self.ctxctx.ref(), self.resultresult, idx), ctx=self.ctxctx)
8089 
8090  def __repr__(self):
8091  return obj_to_string(self)
8092 
8093  def sexpr(self):
8094  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8095  return Z3_apply_result_to_string(self.ctxctx.ref(), self.resultresult)
8096 
8097  def as_expr(self):
8098  """Return a Z3 expression consisting of all subgoals.
8099 
8100  >>> x = Int('x')
8101  >>> g = Goal()
8102  >>> g.add(x > 1)
8103  >>> g.add(Or(x == 2, x == 3))
8104  >>> r = Tactic('simplify')(g)
8105  >>> r
8106  [[Not(x <= 1), Or(x == 2, x == 3)]]
8107  >>> r.as_expr()
8108  And(Not(x <= 1), Or(x == 2, x == 3))
8109  >>> r = Tactic('split-clause')(g)
8110  >>> r
8111  [[x > 1, x == 2], [x > 1, x == 3]]
8112  >>> r.as_expr()
8113  Or(And(x > 1, x == 2), And(x > 1, x == 3))
8114  """
8115  sz = len(self)
8116  if sz == 0:
8117  return BoolVal(False, self.ctxctx)
8118  elif sz == 1:
8119  return self[0].as_expr()
8120  else:
8121  return Or([self[i].as_expr() for i in range(len(self))])
8122 
8123 
8128 
8129 
8130 class Tactic:
8131  """Tactics transform, solver and/or simplify sets of constraints (Goal).
8132  A Tactic can be converted into a Solver using the method solver().
8133 
8134  Several combinators are available for creating new tactics using the built-in ones:
8135  Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8136  """
8137 
8138  def __init__(self, tactic, ctx=None):
8139  self.ctxctx = _get_ctx(ctx)
8140  self.tactictactic = None
8141  if isinstance(tactic, TacticObj):
8142  self.tactictactic = tactic
8143  else:
8144  if z3_debug():
8145  _z3_assert(isinstance(tactic, str), "tactic name expected")
8146  try:
8147  self.tactictactic = Z3_mk_tactic(self.ctxctx.ref(), str(tactic))
8148  except Z3Exception:
8149  raise Z3Exception("unknown tactic '%s'" % tactic)
8150  Z3_tactic_inc_ref(self.ctxctx.ref(), self.tactictactic)
8151 
8152  def __deepcopy__(self, memo={}):
8153  return Tactic(self.tactictactic, self.ctxctx)
8154 
8155  def __del__(self):
8156  if self.tactictactic is not None and self.ctxctx.ref() is not None:
8157  Z3_tactic_dec_ref(self.ctxctx.ref(), self.tactictactic)
8158 
8159  def solver(self, logFile=None):
8160  """Create a solver using the tactic `self`.
8161 
8162  The solver supports the methods `push()` and `pop()`, but it
8163  will always solve each `check()` from scratch.
8164 
8165  >>> t = Then('simplify', 'nlsat')
8166  >>> s = t.solver()
8167  >>> x = Real('x')
8168  >>> s.add(x**2 == 2, x > 0)
8169  >>> s.check()
8170  sat
8171  >>> s.model()
8172  [x = 1.4142135623?]
8173  """
8174  return Solver(Z3_mk_solver_from_tactic(self.ctxctx.ref(), self.tactictactic), self.ctxctx, logFile)
8175 
8176  def apply(self, goal, *arguments, **keywords):
8177  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8178 
8179  >>> x, y = Ints('x y')
8180  >>> t = Tactic('solve-eqs')
8181  >>> t.apply(And(x == 0, y >= x + 1))
8182  [[y >= 1]]
8183  """
8184  if z3_debug():
8185  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8186  goal = _to_goal(goal)
8187  if len(arguments) > 0 or len(keywords) > 0:
8188  p = args2params(arguments, keywords, self.ctxctx)
8189  return ApplyResult(Z3_tactic_apply_ex(self.ctxctx.ref(), self.tactictactic, goal.goal, p.params), self.ctxctx)
8190  else:
8191  return ApplyResult(Z3_tactic_apply(self.ctxctx.ref(), self.tactictactic, goal.goal), self.ctxctx)
8192 
8193  def __call__(self, goal, *arguments, **keywords):
8194  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8195 
8196  >>> x, y = Ints('x y')
8197  >>> t = Tactic('solve-eqs')
8198  >>> t(And(x == 0, y >= x + 1))
8199  [[y >= 1]]
8200  """
8201  return self.applyapply(goal, *arguments, **keywords)
8202 
8203  def help(self):
8204  """Display a string containing a description of the available options for the `self` tactic."""
8205  print(Z3_tactic_get_help(self.ctxctx.ref(), self.tactictactic))
8206 
8207  def param_descrs(self):
8208  """Return the parameter description set."""
8209  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctxctx.ref(), self.tactictactic), self.ctxctx)
8210 
8211 
8212 def _to_goal(a):
8213  if isinstance(a, BoolRef):
8214  goal = Goal(ctx=a.ctx)
8215  goal.add(a)
8216  return goal
8217  else:
8218  return a
8219 
8220 
8221 def _to_tactic(t, ctx=None):
8222  if isinstance(t, Tactic):
8223  return t
8224  else:
8225  return Tactic(t, ctx)
8226 
8227 
8228 def _and_then(t1, t2, ctx=None):
8229  t1 = _to_tactic(t1, ctx)
8230  t2 = _to_tactic(t2, ctx)
8231  if z3_debug():
8232  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8233  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8234 
8235 
8236 def _or_else(t1, t2, ctx=None):
8237  t1 = _to_tactic(t1, ctx)
8238  t2 = _to_tactic(t2, ctx)
8239  if z3_debug():
8240  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8241  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8242 
8243 
8244 def AndThen(*ts, **ks):
8245  """Return a tactic that applies the tactics in `*ts` in sequence.
8246 
8247  >>> x, y = Ints('x y')
8248  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8249  >>> t(And(x == 0, y > x + 1))
8250  [[Not(y <= 1)]]
8251  >>> t(And(x == 0, y > x + 1)).as_expr()
8252  Not(y <= 1)
8253  """
8254  if z3_debug():
8255  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8256  ctx = ks.get("ctx", None)
8257  num = len(ts)
8258  r = ts[0]
8259  for i in range(num - 1):
8260  r = _and_then(r, ts[i + 1], ctx)
8261  return r
8262 
8263 
8264 def Then(*ts, **ks):
8265  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8266 
8267  >>> x, y = Ints('x y')
8268  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8269  >>> t(And(x == 0, y > x + 1))
8270  [[Not(y <= 1)]]
8271  >>> t(And(x == 0, y > x + 1)).as_expr()
8272  Not(y <= 1)
8273  """
8274  return AndThen(*ts, **ks)
8275 
8276 
8277 def OrElse(*ts, **ks):
8278  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8279 
8280  >>> x = Int('x')
8281  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8282  >>> # Tactic split-clause fails if there is no clause in the given goal.
8283  >>> t(x == 0)
8284  [[x == 0]]
8285  >>> t(Or(x == 0, x == 1))
8286  [[x == 0], [x == 1]]
8287  """
8288  if z3_debug():
8289  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8290  ctx = ks.get("ctx", None)
8291  num = len(ts)
8292  r = ts[0]
8293  for i in range(num - 1):
8294  r = _or_else(r, ts[i + 1], ctx)
8295  return r
8296 
8297 
8298 def ParOr(*ts, **ks):
8299  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8300 
8301  >>> x = Int('x')
8302  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8303  >>> t(x + 1 == 2)
8304  [[x == 1]]
8305  """
8306  if z3_debug():
8307  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8308  ctx = _get_ctx(ks.get("ctx", None))
8309  ts = [_to_tactic(t, ctx) for t in ts]
8310  sz = len(ts)
8311  _args = (TacticObj * sz)()
8312  for i in range(sz):
8313  _args[i] = ts[i].tactic
8314  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8315 
8316 
8317 def ParThen(t1, t2, ctx=None):
8318  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8319  The subgoals are processed in parallel.
8320 
8321  >>> x, y = Ints('x y')
8322  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8323  >>> t(And(Or(x == 1, x == 2), y == x + 1))
8324  [[x == 1, y == 2], [x == 2, y == 3]]
8325  """
8326  t1 = _to_tactic(t1, ctx)
8327  t2 = _to_tactic(t2, ctx)
8328  if z3_debug():
8329  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8330  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8331 
8332 
8333 def ParAndThen(t1, t2, ctx=None):
8334  """Alias for ParThen(t1, t2, ctx)."""
8335  return ParThen(t1, t2, ctx)
8336 
8337 
8338 def With(t, *args, **keys):
8339  """Return a tactic that applies tactic `t` using the given configuration options.
8340 
8341  >>> x, y = Ints('x y')
8342  >>> t = With(Tactic('simplify'), som=True)
8343  >>> t((x + 1)*(y + 2) == 0)
8344  [[2*x + y + x*y == -2]]
8345  """
8346  ctx = keys.pop("ctx", None)
8347  t = _to_tactic(t, ctx)
8348  p = args2params(args, keys, t.ctx)
8349  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8350 
8351 
8352 def WithParams(t, p):
8353  """Return a tactic that applies tactic `t` using the given configuration options.
8354 
8355  >>> x, y = Ints('x y')
8356  >>> p = ParamsRef()
8357  >>> p.set("som", True)
8358  >>> t = WithParams(Tactic('simplify'), p)
8359  >>> t((x + 1)*(y + 2) == 0)
8360  [[2*x + y + x*y == -2]]
8361  """
8362  t = _to_tactic(t, None)
8363  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8364 
8365 
8366 def Repeat(t, max=4294967295, ctx=None):
8367  """Return a tactic that keeps applying `t` until the goal is not modified anymore
8368  or the maximum number of iterations `max` is reached.
8369 
8370  >>> x, y = Ints('x y')
8371  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8372  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8373  >>> r = t(c)
8374  >>> for subgoal in r: print(subgoal)
8375  [x == 0, y == 0, x > y]
8376  [x == 0, y == 1, x > y]
8377  [x == 1, y == 0, x > y]
8378  [x == 1, y == 1, x > y]
8379  >>> t = Then(t, Tactic('propagate-values'))
8380  >>> t(c)
8381  [[x == 1, y == 0]]
8382  """
8383  t = _to_tactic(t, ctx)
8384  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8385 
8386 
8387 def TryFor(t, ms, ctx=None):
8388  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8389 
8390  If `t` does not terminate in `ms` milliseconds, then it fails.
8391  """
8392  t = _to_tactic(t, ctx)
8393  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8394 
8395 
8396 def tactics(ctx=None):
8397  """Return a list of all available tactics in Z3.
8398 
8399  >>> l = tactics()
8400  >>> l.count('simplify') == 1
8401  True
8402  """
8403  ctx = _get_ctx(ctx)
8404  return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8405 
8406 
8407 def tactic_description(name, ctx=None):
8408  """Return a short description for the tactic named `name`.
8409 
8410  >>> d = tactic_description('simplify')
8411  """
8412  ctx = _get_ctx(ctx)
8413  return Z3_tactic_get_descr(ctx.ref(), name)
8414 
8415 
8417  """Display a (tabular) description of all available tactics in Z3."""
8418  if in_html_mode():
8419  even = True
8420  print('<table border="1" cellpadding="2" cellspacing="0">')
8421  for t in tactics():
8422  if even:
8423  print('<tr style="background-color:#CFCFCF">')
8424  even = False
8425  else:
8426  print("<tr>")
8427  even = True
8428  print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8429  print("</table>")
8430  else:
8431  for t in tactics():
8432  print("%s : %s" % (t, tactic_description(t)))
8433 
8434 
8435 class Probe:
8436  """Probes are used to inspect a goal (aka problem) and collect information that may be used
8437  to decide which solver and/or preprocessing step will be used.
8438  """
8439 
8440  def __init__(self, probe, ctx=None):
8441  self.ctxctx = _get_ctx(ctx)
8442  self.probeprobe = None
8443  if isinstance(probe, ProbeObj):
8444  self.probeprobe = probe
8445  elif isinstance(probe, float):
8446  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), probe)
8447  elif _is_int(probe):
8448  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), float(probe))
8449  elif isinstance(probe, bool):
8450  if probe:
8451  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), 1.0)
8452  else:
8453  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), 0.0)
8454  else:
8455  if z3_debug():
8456  _z3_assert(isinstance(probe, str), "probe name expected")
8457  try:
8458  self.probeprobe = Z3_mk_probe(self.ctxctx.ref(), probe)
8459  except Z3Exception:
8460  raise Z3Exception("unknown probe '%s'" % probe)
8461  Z3_probe_inc_ref(self.ctxctx.ref(), self.probeprobe)
8462 
8463  def __deepcopy__(self, memo={}):
8464  return Probe(self.probeprobe, self.ctxctx)
8465 
8466  def __del__(self):
8467  if self.probeprobe is not None and self.ctxctx.ref() is not None:
8468  Z3_probe_dec_ref(self.ctxctx.ref(), self.probeprobe)
8469 
8470  def __lt__(self, other):
8471  """Return a probe that evaluates to "true" when the value returned by `self`
8472  is less than the value returned by `other`.
8473 
8474  >>> p = Probe('size') < 10
8475  >>> x = Int('x')
8476  >>> g = Goal()
8477  >>> g.add(x > 0)
8478  >>> g.add(x < 10)
8479  >>> p(g)
8480  1.0
8481  """
8482  return Probe(Z3_probe_lt(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8483 
8484  def __gt__(self, other):
8485  """Return a probe that evaluates to "true" when the value returned by `self`
8486  is greater than the value returned by `other`.
8487 
8488  >>> p = Probe('size') > 10
8489  >>> x = Int('x')
8490  >>> g = Goal()
8491  >>> g.add(x > 0)
8492  >>> g.add(x < 10)
8493  >>> p(g)
8494  0.0
8495  """
8496  return Probe(Z3_probe_gt(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8497 
8498  def __le__(self, other):
8499  """Return a probe that evaluates to "true" when the value returned by `self`
8500  is less than or equal to the value returned by `other`.
8501 
8502  >>> p = Probe('size') <= 2
8503  >>> x = Int('x')
8504  >>> g = Goal()
8505  >>> g.add(x > 0)
8506  >>> g.add(x < 10)
8507  >>> p(g)
8508  1.0
8509  """
8510  return Probe(Z3_probe_le(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8511 
8512  def __ge__(self, other):
8513  """Return a probe that evaluates to "true" when the value returned by `self`
8514  is greater than or equal to the value returned by `other`.
8515 
8516  >>> p = Probe('size') >= 2
8517  >>> x = Int('x')
8518  >>> g = Goal()
8519  >>> g.add(x > 0)
8520  >>> g.add(x < 10)
8521  >>> p(g)
8522  1.0
8523  """
8524  return Probe(Z3_probe_ge(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8525 
8526  def __eq__(self, other):
8527  """Return a probe that evaluates to "true" when the value returned by `self`
8528  is equal to the value returned by `other`.
8529 
8530  >>> p = Probe('size') == 2
8531  >>> x = Int('x')
8532  >>> g = Goal()
8533  >>> g.add(x > 0)
8534  >>> g.add(x < 10)
8535  >>> p(g)
8536  1.0
8537  """
8538  return Probe(Z3_probe_eq(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8539 
8540  def __ne__(self, other):
8541  """Return a probe that evaluates to "true" when the value returned by `self`
8542  is not equal to the value returned by `other`.
8543 
8544  >>> p = Probe('size') != 2
8545  >>> x = Int('x')
8546  >>> g = Goal()
8547  >>> g.add(x > 0)
8548  >>> g.add(x < 10)
8549  >>> p(g)
8550  0.0
8551  """
8552  p = self.__eq____eq__(other)
8553  return Probe(Z3_probe_not(self.ctxctx.ref(), p.probe), self.ctxctx)
8554 
8555  def __call__(self, goal):
8556  """Evaluate the probe `self` in the given goal.
8557 
8558  >>> p = Probe('size')
8559  >>> x = Int('x')
8560  >>> g = Goal()
8561  >>> g.add(x > 0)
8562  >>> g.add(x < 10)
8563  >>> p(g)
8564  2.0
8565  >>> g.add(x < 20)
8566  >>> p(g)
8567  3.0
8568  >>> p = Probe('num-consts')
8569  >>> p(g)
8570  1.0
8571  >>> p = Probe('is-propositional')
8572  >>> p(g)
8573  0.0
8574  >>> p = Probe('is-qflia')
8575  >>> p(g)
8576  1.0
8577  """
8578  if z3_debug():
8579  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8580  goal = _to_goal(goal)
8581  return Z3_probe_apply(self.ctxctx.ref(), self.probeprobe, goal.goal)
8582 
8583 
8584 def is_probe(p):
8585  """Return `True` if `p` is a Z3 probe.
8586 
8587  >>> is_probe(Int('x'))
8588  False
8589  >>> is_probe(Probe('memory'))
8590  True
8591  """
8592  return isinstance(p, Probe)
8593 
8594 
8595 def _to_probe(p, ctx=None):
8596  if is_probe(p):
8597  return p
8598  else:
8599  return Probe(p, ctx)
8600 
8601 
8602 def probes(ctx=None):
8603  """Return a list of all available probes in Z3.
8604 
8605  >>> l = probes()
8606  >>> l.count('memory') == 1
8607  True
8608  """
8609  ctx = _get_ctx(ctx)
8610  return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8611 
8612 
8613 def probe_description(name, ctx=None):
8614  """Return a short description for the probe named `name`.
8615 
8616  >>> d = probe_description('memory')
8617  """
8618  ctx = _get_ctx(ctx)
8619  return Z3_probe_get_descr(ctx.ref(), name)
8620 
8621 
8623  """Display a (tabular) description of all available probes in Z3."""
8624  if in_html_mode():
8625  even = True
8626  print('<table border="1" cellpadding="2" cellspacing="0">')
8627  for p in probes():
8628  if even:
8629  print('<tr style="background-color:#CFCFCF">')
8630  even = False
8631  else:
8632  print("<tr>")
8633  even = True
8634  print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8635  print("</table>")
8636  else:
8637  for p in probes():
8638  print("%s : %s" % (p, probe_description(p)))
8639 
8640 
8641 def _probe_nary(f, args, ctx):
8642  if z3_debug():
8643  _z3_assert(len(args) > 0, "At least one argument expected")
8644  num = len(args)
8645  r = _to_probe(args[0], ctx)
8646  for i in range(num - 1):
8647  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8648  return r
8649 
8650 
8651 def _probe_and(args, ctx):
8652  return _probe_nary(Z3_probe_and, args, ctx)
8653 
8654 
8655 def _probe_or(args, ctx):
8656  return _probe_nary(Z3_probe_or, args, ctx)
8657 
8658 
8659 def FailIf(p, ctx=None):
8660  """Return a tactic that fails if the probe `p` evaluates to true.
8661  Otherwise, it returns the input goal unmodified.
8662 
8663  In the following example, the tactic applies 'simplify' if and only if there are
8664  more than 2 constraints in the goal.
8665 
8666  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8667  >>> x, y = Ints('x y')
8668  >>> g = Goal()
8669  >>> g.add(x > 0)
8670  >>> g.add(y > 0)
8671  >>> t(g)
8672  [[x > 0, y > 0]]
8673  >>> g.add(x == y + 1)
8674  >>> t(g)
8675  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8676  """
8677  p = _to_probe(p, ctx)
8678  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8679 
8680 
8681 def When(p, t, ctx=None):
8682  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8683  Otherwise, it returns the input goal unmodified.
8684 
8685  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8686  >>> x, y = Ints('x y')
8687  >>> g = Goal()
8688  >>> g.add(x > 0)
8689  >>> g.add(y > 0)
8690  >>> t(g)
8691  [[x > 0, y > 0]]
8692  >>> g.add(x == y + 1)
8693  >>> t(g)
8694  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8695  """
8696  p = _to_probe(p, ctx)
8697  t = _to_tactic(t, ctx)
8698  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8699 
8700 
8701 def Cond(p, t1, t2, ctx=None):
8702  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8703 
8704  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8705  """
8706  p = _to_probe(p, ctx)
8707  t1 = _to_tactic(t1, ctx)
8708  t2 = _to_tactic(t2, ctx)
8709  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8710 
8711 
8716 
8717 
8718 def simplify(a, *arguments, **keywords):
8719  """Simplify the expression `a` using the given options.
8720 
8721  This function has many options. Use `help_simplify` to obtain the complete list.
8722 
8723  >>> x = Int('x')
8724  >>> y = Int('y')
8725  >>> simplify(x + 1 + y + x + 1)
8726  2 + 2*x + y
8727  >>> simplify((x + 1)*(y + 1), som=True)
8728  1 + x + y + x*y
8729  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8730  And(Not(x == y), Not(x == 1), Not(y == 1))
8731  >>> simplify(And(x == 0, y == 1), elim_and=True)
8732  Not(Or(Not(x == 0), Not(y == 1)))
8733  """
8734  if z3_debug():
8735  _z3_assert(is_expr(a), "Z3 expression expected")
8736  if len(arguments) > 0 or len(keywords) > 0:
8737  p = args2params(arguments, keywords, a.ctx)
8738  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8739  else:
8740  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8741 
8742 
8744  """Return a string describing all options available for Z3 `simplify` procedure."""
8745  print(Z3_simplify_get_help(main_ctx().ref()))
8746 
8747 
8749  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8751 
8752 
8753 def substitute(t, *m):
8754  """Apply substitution m on t, m is a list of pairs of the form (from, to).
8755  Every occurrence in t of from is replaced with to.
8756 
8757  >>> x = Int('x')
8758  >>> y = Int('y')
8759  >>> substitute(x + 1, (x, y + 1))
8760  y + 1 + 1
8761  >>> f = Function('f', IntSort(), IntSort())
8762  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8763  1 + 1
8764  """
8765  if isinstance(m, tuple):
8766  m1 = _get_args(m)
8767  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8768  m = m1
8769  if z3_debug():
8770  _z3_assert(is_expr(t), "Z3 expression expected")
8771  _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(
8772  p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
8773  num = len(m)
8774  _from = (Ast * num)()
8775  _to = (Ast * num)()
8776  for i in range(num):
8777  _from[i] = m[i][0].as_ast()
8778  _to[i] = m[i][1].as_ast()
8779  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8780 
8781 
8782 def substitute_vars(t, *m):
8783  """Substitute the free variables in t with the expression in m.
8784 
8785  >>> v0 = Var(0, IntSort())
8786  >>> v1 = Var(1, IntSort())
8787  >>> x = Int('x')
8788  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8789  >>> # replace v0 with x+1 and v1 with x
8790  >>> substitute_vars(f(v0, v1), x + 1, x)
8791  f(x + 1, x)
8792  """
8793  if z3_debug():
8794  _z3_assert(is_expr(t), "Z3 expression expected")
8795  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8796  num = len(m)
8797  _to = (Ast * num)()
8798  for i in range(num):
8799  _to[i] = m[i].as_ast()
8800  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8801 
8802 
8803 def Sum(*args):
8804  """Create the sum of the Z3 expressions.
8805 
8806  >>> a, b, c = Ints('a b c')
8807  >>> Sum(a, b, c)
8808  a + b + c
8809  >>> Sum([a, b, c])
8810  a + b + c
8811  >>> A = IntVector('a', 5)
8812  >>> Sum(A)
8813  a__0 + a__1 + a__2 + a__3 + a__4
8814  """
8815  args = _get_args(args)
8816  if len(args) == 0:
8817  return 0
8818  ctx = _ctx_from_ast_arg_list(args)
8819  if ctx is None:
8820  return _reduce(lambda a, b: a + b, args, 0)
8821  args = _coerce_expr_list(args, ctx)
8822  if is_bv(args[0]):
8823  return _reduce(lambda a, b: a + b, args, 0)
8824  else:
8825  _args, sz = _to_ast_array(args)
8826  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8827 
8828 
8829 def Product(*args):
8830  """Create the product of the Z3 expressions.
8831 
8832  >>> a, b, c = Ints('a b c')
8833  >>> Product(a, b, c)
8834  a*b*c
8835  >>> Product([a, b, c])
8836  a*b*c
8837  >>> A = IntVector('a', 5)
8838  >>> Product(A)
8839  a__0*a__1*a__2*a__3*a__4
8840  """
8841  args = _get_args(args)
8842  if len(args) == 0:
8843  return 1
8844  ctx = _ctx_from_ast_arg_list(args)
8845  if ctx is None:
8846  return _reduce(lambda a, b: a * b, args, 1)
8847  args = _coerce_expr_list(args, ctx)
8848  if is_bv(args[0]):
8849  return _reduce(lambda a, b: a * b, args, 1)
8850  else:
8851  _args, sz = _to_ast_array(args)
8852  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8853 
8854 def Abs(arg):
8855  """Create the absolute value of an arithmetic expression"""
8856  return If(arg > 0, arg, -arg)
8857 
8858 
8859 def AtMost(*args):
8860  """Create an at-most Pseudo-Boolean k constraint.
8861 
8862  >>> a, b, c = Bools('a b c')
8863  >>> f = AtMost(a, b, c, 2)
8864  """
8865  args = _get_args(args)
8866  if z3_debug():
8867  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8868  ctx = _ctx_from_ast_arg_list(args)
8869  if z3_debug():
8870  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8871  args1 = _coerce_expr_list(args[:-1], ctx)
8872  k = args[-1]
8873  _args, sz = _to_ast_array(args1)
8874  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8875 
8876 
8877 def AtLeast(*args):
8878  """Create an at-most Pseudo-Boolean k constraint.
8879 
8880  >>> a, b, c = Bools('a b c')
8881  >>> f = AtLeast(a, b, c, 2)
8882  """
8883  args = _get_args(args)
8884  if z3_debug():
8885  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8886  ctx = _ctx_from_ast_arg_list(args)
8887  if z3_debug():
8888  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8889  args1 = _coerce_expr_list(args[:-1], ctx)
8890  k = args[-1]
8891  _args, sz = _to_ast_array(args1)
8892  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8893 
8894 
8895 def _reorder_pb_arg(arg):
8896  a, b = arg
8897  if not _is_int(b) and _is_int(a):
8898  return b, a
8899  return arg
8900 
8901 
8902 def _pb_args_coeffs(args, default_ctx=None):
8903  args = _get_args_ast_list(args)
8904  if len(args) == 0:
8905  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8906  args = [_reorder_pb_arg(arg) for arg in args]
8907  args, coeffs = zip(*args)
8908  if z3_debug():
8909  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8910  ctx = _ctx_from_ast_arg_list(args)
8911  if z3_debug():
8912  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8913  args = _coerce_expr_list(args, ctx)
8914  _args, sz = _to_ast_array(args)
8915  _coeffs = (ctypes.c_int * len(coeffs))()
8916  for i in range(len(coeffs)):
8917  _z3_check_cint_overflow(coeffs[i], "coefficient")
8918  _coeffs[i] = coeffs[i]
8919  return ctx, sz, _args, _coeffs, args
8920 
8921 
8922 def PbLe(args, k):
8923  """Create a Pseudo-Boolean inequality k constraint.
8924 
8925  >>> a, b, c = Bools('a b c')
8926  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8927  """
8928  _z3_check_cint_overflow(k, "k")
8929  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8930  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8931 
8932 
8933 def PbGe(args, k):
8934  """Create a Pseudo-Boolean inequality k constraint.
8935 
8936  >>> a, b, c = Bools('a b c')
8937  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8938  """
8939  _z3_check_cint_overflow(k, "k")
8940  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8941  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8942 
8943 
8944 def PbEq(args, k, ctx=None):
8945  """Create a Pseudo-Boolean inequality k constraint.
8946 
8947  >>> a, b, c = Bools('a b c')
8948  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8949  """
8950  _z3_check_cint_overflow(k, "k")
8951  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8952  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8953 
8954 
8955 def solve(*args, **keywords):
8956  """Solve the constraints `*args`.
8957 
8958  This is a simple function for creating demonstrations. It creates a solver,
8959  configure it using the options in `keywords`, adds the constraints
8960  in `args`, and invokes check.
8961 
8962  >>> a = Int('a')
8963  >>> solve(a > 0, a < 2)
8964  [a = 1]
8965  """
8966  show = keywords.pop("show", False)
8967  s = Solver()
8968  s.set(**keywords)
8969  s.add(*args)
8970  if show:
8971  print(s)
8972  r = s.check()
8973  if r == unsat:
8974  print("no solution")
8975  elif r == unknown:
8976  print("failed to solve")
8977  try:
8978  print(s.model())
8979  except Z3Exception:
8980  return
8981  else:
8982  print(s.model())
8983 
8984 
8985 def solve_using(s, *args, **keywords):
8986  """Solve the constraints `*args` using solver `s`.
8987 
8988  This is a simple function for creating demonstrations. It is similar to `solve`,
8989  but it uses the given solver `s`.
8990  It configures solver `s` using the options in `keywords`, adds the constraints
8991  in `args`, and invokes check.
8992  """
8993  show = keywords.pop("show", False)
8994  if z3_debug():
8995  _z3_assert(isinstance(s, Solver), "Solver object expected")
8996  s.set(**keywords)
8997  s.add(*args)
8998  if show:
8999  print("Problem:")
9000  print(s)
9001  r = s.check()
9002  if r == unsat:
9003  print("no solution")
9004  elif r == unknown:
9005  print("failed to solve")
9006  try:
9007  print(s.model())
9008  except Z3Exception:
9009  return
9010  else:
9011  if show:
9012  print("Solution:")
9013  print(s.model())
9014 
9015 
9016 def prove(claim, show=False, **keywords):
9017  """Try to prove the given claim.
9018 
9019  This is a simple function for creating demonstrations. It tries to prove
9020  `claim` by showing the negation is unsatisfiable.
9021 
9022  >>> p, q = Bools('p q')
9023  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9024  proved
9025  """
9026  if z3_debug():
9027  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9028  s = Solver()
9029  s.set(**keywords)
9030  s.add(Not(claim))
9031  if show:
9032  print(s)
9033  r = s.check()
9034  if r == unsat:
9035  print("proved")
9036  elif r == unknown:
9037  print("failed to prove")
9038  print(s.model())
9039  else:
9040  print("counterexample")
9041  print(s.model())
9042 
9043 
9044 def _solve_html(*args, **keywords):
9045  """Version of function `solve` that renders HTML output."""
9046  show = keywords.pop("show", False)
9047  s = Solver()
9048  s.set(**keywords)
9049  s.add(*args)
9050  if show:
9051  print("<b>Problem:</b>")
9052  print(s)
9053  r = s.check()
9054  if r == unsat:
9055  print("<b>no solution</b>")
9056  elif r == unknown:
9057  print("<b>failed to solve</b>")
9058  try:
9059  print(s.model())
9060  except Z3Exception:
9061  return
9062  else:
9063  if show:
9064  print("<b>Solution:</b>")
9065  print(s.model())
9066 
9067 
9068 def _solve_using_html(s, *args, **keywords):
9069  """Version of function `solve_using` that renders HTML."""
9070  show = keywords.pop("show", False)
9071  if z3_debug():
9072  _z3_assert(isinstance(s, Solver), "Solver object expected")
9073  s.set(**keywords)
9074  s.add(*args)
9075  if show:
9076  print("<b>Problem:</b>")
9077  print(s)
9078  r = s.check()
9079  if r == unsat:
9080  print("<b>no solution</b>")
9081  elif r == unknown:
9082  print("<b>failed to solve</b>")
9083  try:
9084  print(s.model())
9085  except Z3Exception:
9086  return
9087  else:
9088  if show:
9089  print("<b>Solution:</b>")
9090  print(s.model())
9091 
9092 
9093 def _prove_html(claim, show=False, **keywords):
9094  """Version of function `prove` that renders HTML."""
9095  if z3_debug():
9096  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9097  s = Solver()
9098  s.set(**keywords)
9099  s.add(Not(claim))
9100  if show:
9101  print(s)
9102  r = s.check()
9103  if r == unsat:
9104  print("<b>proved</b>")
9105  elif r == unknown:
9106  print("<b>failed to prove</b>")
9107  print(s.model())
9108  else:
9109  print("<b>counterexample</b>")
9110  print(s.model())
9111 
9112 
9113 def _dict2sarray(sorts, ctx):
9114  sz = len(sorts)
9115  _names = (Symbol * sz)()
9116  _sorts = (Sort * sz)()
9117  i = 0
9118  for k in sorts:
9119  v = sorts[k]
9120  if z3_debug():
9121  _z3_assert(isinstance(k, str), "String expected")
9122  _z3_assert(is_sort(v), "Z3 sort expected")
9123  _names[i] = to_symbol(k, ctx)
9124  _sorts[i] = v.ast
9125  i = i + 1
9126  return sz, _names, _sorts
9127 
9128 
9129 def _dict2darray(decls, ctx):
9130  sz = len(decls)
9131  _names = (Symbol * sz)()
9132  _decls = (FuncDecl * sz)()
9133  i = 0
9134  for k in decls:
9135  v = decls[k]
9136  if z3_debug():
9137  _z3_assert(isinstance(k, str), "String expected")
9138  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9139  _names[i] = to_symbol(k, ctx)
9140  if is_const(v):
9141  _decls[i] = v.decl().ast
9142  else:
9143  _decls[i] = v.ast
9144  i = i + 1
9145  return sz, _names, _decls
9146 
9147 
9148 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9149  """Parse a string in SMT 2.0 format using the given sorts and decls.
9150 
9151  The arguments sorts and decls are Python dictionaries used to initialize
9152  the symbol table used for the SMT 2.0 parser.
9153 
9154  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9155  [x > 0, x < 10]
9156  >>> x, y = Ints('x y')
9157  >>> f = Function('f', IntSort(), IntSort())
9158  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9159  [x + f(y) > 0]
9160  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9161  [a > 0]
9162  """
9163  ctx = _get_ctx(ctx)
9164  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9165  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9166  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9167 
9168 
9169 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9170  """Parse a file in SMT 2.0 format using the given sorts and decls.
9171 
9172  This function is similar to parse_smt2_string().
9173  """
9174  ctx = _get_ctx(ctx)
9175  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9176  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9177  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9178 
9179 
9180 
9185 
9186 
9187 # Global default rounding mode
9188 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
9189 _dflt_fpsort_ebits = 11
9190 _dflt_fpsort_sbits = 53
9191 
9192 
9194  """Retrieves the global default rounding mode."""
9195  global _dflt_rounding_mode
9196  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9197  return RTZ(ctx)
9198  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9199  return RTN(ctx)
9200  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9201  return RTP(ctx)
9202  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9203  return RNE(ctx)
9204  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9205  return RNA(ctx)
9206 
9207 
9208 _ROUNDING_MODES = frozenset({
9209  Z3_OP_FPA_RM_TOWARD_ZERO,
9210  Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9211  Z3_OP_FPA_RM_TOWARD_POSITIVE,
9212  Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9213  Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9214 })
9215 
9216 
9217 def set_default_rounding_mode(rm, ctx=None):
9218  global _dflt_rounding_mode
9219  if is_fprm_value(rm):
9220  _dflt_rounding_mode = rm.decl().kind()
9221  else:
9222  _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9223  _dflt_rounding_mode = rm
9224 
9225 
9226 def get_default_fp_sort(ctx=None):
9227  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9228 
9229 
9230 def set_default_fp_sort(ebits, sbits, ctx=None):
9231  global _dflt_fpsort_ebits
9232  global _dflt_fpsort_sbits
9233  _dflt_fpsort_ebits = ebits
9234  _dflt_fpsort_sbits = sbits
9235 
9236 
9237 def _dflt_rm(ctx=None):
9238  return get_default_rounding_mode(ctx)
9239 
9240 
9241 def _dflt_fps(ctx=None):
9242  return get_default_fp_sort(ctx)
9243 
9244 
9245 def _coerce_fp_expr_list(alist, ctx):
9246  first_fp_sort = None
9247  for a in alist:
9248  if is_fp(a):
9249  if first_fp_sort is None:
9250  first_fp_sort = a.sort()
9251  elif first_fp_sort == a.sort():
9252  pass # OK, same as before
9253  else:
9254  # we saw at least 2 different float sorts; something will
9255  # throw a sort mismatch later, for now assume None.
9256  first_fp_sort = None
9257  break
9258 
9259  r = []
9260  for i in range(len(alist)):
9261  a = alist[i]
9262  is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9263  if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9264  r.append(FPVal(a, None, first_fp_sort, ctx))
9265  else:
9266  r.append(a)
9267  return _coerce_expr_list(r, ctx)
9268 
9269 
9270 # FP Sorts
9271 
9273  """Floating-point sort."""
9274 
9275  def ebits(self):
9276  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9277  >>> b = FPSort(8, 24)
9278  >>> b.ebits()
9279  8
9280  """
9281  return int(Z3_fpa_get_ebits(self.ctx_refctx_ref(), self.astast))
9282 
9283  def sbits(self):
9284  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9285  >>> b = FPSort(8, 24)
9286  >>> b.sbits()
9287  24
9288  """
9289  return int(Z3_fpa_get_sbits(self.ctx_refctx_ref(), self.astast))
9290 
9291  def cast(self, val):
9292  """Try to cast `val` as a floating-point expression.
9293  >>> b = FPSort(8, 24)
9294  >>> b.cast(1.0)
9295  1
9296  >>> b.cast(1.0).sexpr()
9297  '(fp #b0 #x7f #b00000000000000000000000)'
9298  """
9299  if is_expr(val):
9300  if z3_debug():
9301  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
9302  return val
9303  else:
9304  return FPVal(val, None, self, self.ctxctxctx)
9305 
9306 
9307 def Float16(ctx=None):
9308  """Floating-point 16-bit (half) sort."""
9309  ctx = _get_ctx(ctx)
9310  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9311 
9312 
9313 def FloatHalf(ctx=None):
9314  """Floating-point 16-bit (half) sort."""
9315  ctx = _get_ctx(ctx)
9316  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9317 
9318 
9319 def Float32(ctx=None):
9320  """Floating-point 32-bit (single) sort."""
9321  ctx = _get_ctx(ctx)
9322  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9323 
9324 
9325 def FloatSingle(ctx=None):
9326  """Floating-point 32-bit (single) sort."""
9327  ctx = _get_ctx(ctx)
9328  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9329 
9330 
9331 def Float64(ctx=None):
9332  """Floating-point 64-bit (double) sort."""
9333  ctx = _get_ctx(ctx)
9334  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9335 
9336 
9337 def FloatDouble(ctx=None):
9338  """Floating-point 64-bit (double) sort."""
9339  ctx = _get_ctx(ctx)
9340  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9341 
9342 
9343 def Float128(ctx=None):
9344  """Floating-point 128-bit (quadruple) sort."""
9345  ctx = _get_ctx(ctx)
9346  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9347 
9348 
9349 def FloatQuadruple(ctx=None):
9350  """Floating-point 128-bit (quadruple) sort."""
9351  ctx = _get_ctx(ctx)
9352  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9353 
9354 
9356  """"Floating-point rounding mode sort."""
9357 
9358 
9359 def is_fp_sort(s):
9360  """Return True if `s` is a Z3 floating-point sort.
9361 
9362  >>> is_fp_sort(FPSort(8, 24))
9363  True
9364  >>> is_fp_sort(IntSort())
9365  False
9366  """
9367  return isinstance(s, FPSortRef)
9368 
9369 
9371  """Return True if `s` is a Z3 floating-point rounding mode sort.
9372 
9373  >>> is_fprm_sort(FPSort(8, 24))
9374  False
9375  >>> is_fprm_sort(RNE().sort())
9376  True
9377  """
9378  return isinstance(s, FPRMSortRef)
9379 
9380 # FP Expressions
9381 
9382 
9384  """Floating-point expressions."""
9385 
9386  def sort(self):
9387  """Return the sort of the floating-point expression `self`.
9388 
9389  >>> x = FP('1.0', FPSort(8, 24))
9390  >>> x.sort()
9391  FPSort(8, 24)
9392  >>> x.sort() == FPSort(8, 24)
9393  True
9394  """
9395  return FPSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
9396 
9397  def ebits(self):
9398  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9399  >>> b = FPSort(8, 24)
9400  >>> b.ebits()
9401  8
9402  """
9403  return self.sortsortsort().ebits()
9404 
9405  def sbits(self):
9406  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9407  >>> b = FPSort(8, 24)
9408  >>> b.sbits()
9409  24
9410  """
9411  return self.sortsortsort().sbits()
9412 
9413  def as_string(self):
9414  """Return a Z3 floating point expression as a Python string."""
9415  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
9416 
9417  def __le__(self, other):
9418  return fpLEQ(self, other, self.ctxctx)
9419 
9420  def __lt__(self, other):
9421  return fpLT(self, other, self.ctxctx)
9422 
9423  def __ge__(self, other):
9424  return fpGEQ(self, other, self.ctxctx)
9425 
9426  def __gt__(self, other):
9427  return fpGT(self, other, self.ctxctx)
9428 
9429  def __add__(self, other):
9430  """Create the Z3 expression `self + other`.
9431 
9432  >>> x = FP('x', FPSort(8, 24))
9433  >>> y = FP('y', FPSort(8, 24))
9434  >>> x + y
9435  x + y
9436  >>> (x + y).sort()
9437  FPSort(8, 24)
9438  """
9439  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9440  return fpAdd(_dflt_rm(), a, b, self.ctxctx)
9441 
9442  def __radd__(self, other):
9443  """Create the Z3 expression `other + self`.
9444 
9445  >>> x = FP('x', FPSort(8, 24))
9446  >>> 10 + x
9447  1.25*(2**3) + x
9448  """
9449  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9450  return fpAdd(_dflt_rm(), a, b, self.ctxctx)
9451 
9452  def __sub__(self, other):
9453  """Create the Z3 expression `self - other`.
9454 
9455  >>> x = FP('x', FPSort(8, 24))
9456  >>> y = FP('y', FPSort(8, 24))
9457  >>> x - y
9458  x - y
9459  >>> (x - y).sort()
9460  FPSort(8, 24)
9461  """
9462  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9463  return fpSub(_dflt_rm(), a, b, self.ctxctx)
9464 
9465  def __rsub__(self, other):
9466  """Create the Z3 expression `other - self`.
9467 
9468  >>> x = FP('x', FPSort(8, 24))
9469  >>> 10 - x
9470  1.25*(2**3) - x
9471  """
9472  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9473  return fpSub(_dflt_rm(), a, b, self.ctxctx)
9474 
9475  def __mul__(self, other):
9476  """Create the Z3 expression `self * other`.
9477 
9478  >>> x = FP('x', FPSort(8, 24))
9479  >>> y = FP('y', FPSort(8, 24))
9480  >>> x * y
9481  x * y
9482  >>> (x * y).sort()
9483  FPSort(8, 24)
9484  >>> 10 * y
9485  1.25*(2**3) * y
9486  """
9487  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9488  return fpMul(_dflt_rm(), a, b, self.ctxctx)
9489 
9490  def __rmul__(self, other):
9491  """Create the Z3 expression `other * self`.
9492 
9493  >>> x = FP('x', FPSort(8, 24))
9494  >>> y = FP('y', FPSort(8, 24))
9495  >>> x * y
9496  x * y
9497  >>> x * 10
9498  x * 1.25*(2**3)
9499  """
9500  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9501  return fpMul(_dflt_rm(), a, b, self.ctxctx)
9502 
9503  def __pos__(self):
9504  """Create the Z3 expression `+self`."""
9505  return self
9506 
9507  def __neg__(self):
9508  """Create the Z3 expression `-self`.
9509 
9510  >>> x = FP('x', Float32())
9511  >>> -x
9512  -x
9513  """
9514  return fpNeg(self)
9515 
9516  def __div__(self, other):
9517  """Create the Z3 expression `self / other`.
9518 
9519  >>> x = FP('x', FPSort(8, 24))
9520  >>> y = FP('y', FPSort(8, 24))
9521  >>> x / y
9522  x / y
9523  >>> (x / y).sort()
9524  FPSort(8, 24)
9525  >>> 10 / y
9526  1.25*(2**3) / y
9527  """
9528  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9529  return fpDiv(_dflt_rm(), a, b, self.ctxctx)
9530 
9531  def __rdiv__(self, other):
9532  """Create the Z3 expression `other / self`.
9533 
9534  >>> x = FP('x', FPSort(8, 24))
9535  >>> y = FP('y', FPSort(8, 24))
9536  >>> x / y
9537  x / y
9538  >>> x / 10
9539  x / 1.25*(2**3)
9540  """
9541  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9542  return fpDiv(_dflt_rm(), a, b, self.ctxctx)
9543 
9544  def __truediv__(self, other):
9545  """Create the Z3 expression division `self / other`."""
9546  return self.__div____div__(other)
9547 
9548  def __rtruediv__(self, other):
9549  """Create the Z3 expression division `other / self`."""
9550  return self.__rdiv____rdiv__(other)
9551 
9552  def __mod__(self, other):
9553  """Create the Z3 expression mod `self % other`."""
9554  return fpRem(self, other)
9555 
9556  def __rmod__(self, other):
9557  """Create the Z3 expression mod `other % self`."""
9558  return fpRem(other, self)
9559 
9560 
9562  """Floating-point rounding mode expressions"""
9563 
9564  def as_string(self):
9565  """Return a Z3 floating point expression as a Python string."""
9566  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
9567 
9568 
9570  ctx = _get_ctx(ctx)
9571  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9572 
9573 
9574 def RNE(ctx=None):
9575  ctx = _get_ctx(ctx)
9576  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9577 
9578 
9580  ctx = _get_ctx(ctx)
9581  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9582 
9583 
9584 def RNA(ctx=None):
9585  ctx = _get_ctx(ctx)
9586  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9587 
9588 
9589 def RoundTowardPositive(ctx=None):
9590  ctx = _get_ctx(ctx)
9591  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9592 
9593 
9594 def RTP(ctx=None):
9595  ctx = _get_ctx(ctx)
9596  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9597 
9598 
9599 def RoundTowardNegative(ctx=None):
9600  ctx = _get_ctx(ctx)
9601  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9602 
9603 
9604 def RTN(ctx=None):
9605  ctx = _get_ctx(ctx)
9606  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9607 
9608 
9609 def RoundTowardZero(ctx=None):
9610  ctx = _get_ctx(ctx)
9611  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9612 
9613 
9614 def RTZ(ctx=None):
9615  ctx = _get_ctx(ctx)
9616  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9617 
9618 
9619 def is_fprm(a):
9620  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9621 
9622  >>> rm = RNE()
9623  >>> is_fprm(rm)
9624  True
9625  >>> rm = 1.0
9626  >>> is_fprm(rm)
9627  False
9628  """
9629  return isinstance(a, FPRMRef)
9630 
9631 
9633  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9634  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9635 
9636 # FP Numerals
9637 
9638 
9640  """The sign of the numeral.
9641 
9642  >>> x = FPVal(+1.0, FPSort(8, 24))
9643  >>> x.sign()
9644  False
9645  >>> x = FPVal(-1.0, FPSort(8, 24))
9646  >>> x.sign()
9647  True
9648  """
9649 
9650  def sign(self):
9651  num = (ctypes.c_int)()
9652  nsign = Z3_fpa_get_numeral_sign(self.ctxctx.ref(), self.as_astas_astas_ast(), byref(num))
9653  if nsign is False:
9654  raise Z3Exception("error retrieving the sign of a numeral.")
9655  return num.value != 0
9656 
9657  """The sign of a floating-point numeral as a bit-vector expression.
9658 
9659  Remark: NaN's are invalid arguments.
9660  """
9661 
9662  def sign_as_bv(self):
9663  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctxctx.ref(), self.as_astas_astas_ast()), self.ctxctx)
9664 
9665  """The significand of the numeral.
9666 
9667  >>> x = FPVal(2.5, FPSort(8, 24))
9668  >>> x.significand()
9669  1.25
9670  """
9671 
9672  def significand(self):
9673  return Z3_fpa_get_numeral_significand_string(self.ctxctx.ref(), self.as_astas_astas_ast())
9674 
9675  """The significand of the numeral as a long.
9676 
9677  >>> x = FPVal(2.5, FPSort(8, 24))
9678  >>> x.significand_as_long()
9679  1.25
9680  """
9681 
9683  ptr = (ctypes.c_ulonglong * 1)()
9684  if not Z3_fpa_get_numeral_significand_uint64(self.ctxctx.ref(), self.as_astas_astas_ast(), ptr):
9685  raise Z3Exception("error retrieving the significand of a numeral.")
9686  return ptr[0]
9687 
9688  """The significand of the numeral as a bit-vector expression.
9689 
9690  Remark: NaN are invalid arguments.
9691  """
9692 
9694  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctxctx.ref(), self.as_astas_astas_ast()), self.ctxctx)
9695 
9696  """The exponent of the numeral.
9697 
9698  >>> x = FPVal(2.5, FPSort(8, 24))
9699  >>> x.exponent()
9700  1
9701  """
9702 
9703  def exponent(self, biased=True):
9704  return Z3_fpa_get_numeral_exponent_string(self.ctxctx.ref(), self.as_astas_astas_ast(), biased)
9705 
9706  """The exponent of the numeral as a long.
9707 
9708  >>> x = FPVal(2.5, FPSort(8, 24))
9709  >>> x.exponent_as_long()
9710  1
9711  """
9712 
9713  def exponent_as_long(self, biased=True):
9714  ptr = (ctypes.c_longlong * 1)()
9715  if not Z3_fpa_get_numeral_exponent_int64(self.ctxctx.ref(), self.as_astas_astas_ast(), ptr, biased):
9716  raise Z3Exception("error retrieving the exponent of a numeral.")
9717  return ptr[0]
9718 
9719  """The exponent of the numeral as a bit-vector expression.
9720 
9721  Remark: NaNs are invalid arguments.
9722  """
9723 
9724  def exponent_as_bv(self, biased=True):
9725  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctxctx.ref(), self.as_astas_astas_ast(), biased), self.ctxctx)
9726 
9727  """Indicates whether the numeral is a NaN."""
9728 
9729  def isNaN(self):
9730  return Z3_fpa_is_numeral_nan(self.ctxctx.ref(), self.as_astas_astas_ast())
9731 
9732  """Indicates whether the numeral is +oo or -oo."""
9733 
9734  def isInf(self):
9735  return Z3_fpa_is_numeral_inf(self.ctxctx.ref(), self.as_astas_astas_ast())
9736 
9737  """Indicates whether the numeral is +zero or -zero."""
9738 
9739  def isZero(self):
9740  return Z3_fpa_is_numeral_zero(self.ctxctx.ref(), self.as_astas_astas_ast())
9741 
9742  """Indicates whether the numeral is normal."""
9743 
9744  def isNormal(self):
9745  return Z3_fpa_is_numeral_normal(self.ctxctx.ref(), self.as_astas_astas_ast())
9746 
9747  """Indicates whether the numeral is subnormal."""
9748 
9749  def isSubnormal(self):
9750  return Z3_fpa_is_numeral_subnormal(self.ctxctx.ref(), self.as_astas_astas_ast())
9751 
9752  """Indicates whether the numeral is positive."""
9753 
9754  def isPositive(self):
9755  return Z3_fpa_is_numeral_positive(self.ctxctx.ref(), self.as_astas_astas_ast())
9756 
9757  """Indicates whether the numeral is negative."""
9758 
9759  def isNegative(self):
9760  return Z3_fpa_is_numeral_negative(self.ctxctx.ref(), self.as_astas_astas_ast())
9761 
9762  """
9763  The string representation of the numeral.
9764 
9765  >>> x = FPVal(20, FPSort(8, 24))
9766  >>> x.as_string()
9767  1.25*(2**4)
9768  """
9769 
9770  def as_string(self):
9771  s = Z3_get_numeral_string(self.ctxctx.ref(), self.as_astas_astas_ast())
9772  return ("FPVal(%s, %s)" % (s, self.sortsortsort()))
9773 
9774 
9775 def is_fp(a):
9776  """Return `True` if `a` is a Z3 floating-point expression.
9777 
9778  >>> b = FP('b', FPSort(8, 24))
9779  >>> is_fp(b)
9780  True
9781  >>> is_fp(b + 1.0)
9782  True
9783  >>> is_fp(Int('x'))
9784  False
9785  """
9786  return isinstance(a, FPRef)
9787 
9788 
9790  """Return `True` if `a` is a Z3 floating-point numeral value.
9791 
9792  >>> b = FP('b', FPSort(8, 24))
9793  >>> is_fp_value(b)
9794  False
9795  >>> b = FPVal(1.0, FPSort(8, 24))
9796  >>> b
9797  1
9798  >>> is_fp_value(b)
9799  True
9800  """
9801  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9802 
9803 
9804 def FPSort(ebits, sbits, ctx=None):
9805  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9806 
9807  >>> Single = FPSort(8, 24)
9808  >>> Double = FPSort(11, 53)
9809  >>> Single
9810  FPSort(8, 24)
9811  >>> x = Const('x', Single)
9812  >>> eq(x, FP('x', FPSort(8, 24)))
9813  True
9814  """
9815  ctx = _get_ctx(ctx)
9816  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9817 
9818 
9819 def _to_float_str(val, exp=0):
9820  if isinstance(val, float):
9821  if math.isnan(val):
9822  res = "NaN"
9823  elif val == 0.0:
9824  sone = math.copysign(1.0, val)
9825  if sone < 0.0:
9826  return "-0.0"
9827  else:
9828  return "+0.0"
9829  elif val == float("+inf"):
9830  res = "+oo"
9831  elif val == float("-inf"):
9832  res = "-oo"
9833  else:
9834  v = val.as_integer_ratio()
9835  num = v[0]
9836  den = v[1]
9837  rvs = str(num) + "/" + str(den)
9838  res = rvs + "p" + _to_int_str(exp)
9839  elif isinstance(val, bool):
9840  if val:
9841  res = "1.0"
9842  else:
9843  res = "0.0"
9844  elif _is_int(val):
9845  res = str(val)
9846  elif isinstance(val, str):
9847  inx = val.find("*(2**")
9848  if inx == -1:
9849  res = val
9850  elif val[-1] == ")":
9851  res = val[0:inx]
9852  exp = str(int(val[inx + 5:-1]) + int(exp))
9853  else:
9854  _z3_assert(False, "String does not have floating-point numeral form.")
9855  elif z3_debug():
9856  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9857  if exp == 0:
9858  return res
9859  else:
9860  return res + "p" + exp
9861 
9862 
9863 def fpNaN(s):
9864  """Create a Z3 floating-point NaN term.
9865 
9866  >>> s = FPSort(8, 24)
9867  >>> set_fpa_pretty(True)
9868  >>> fpNaN(s)
9869  NaN
9870  >>> pb = get_fpa_pretty()
9871  >>> set_fpa_pretty(False)
9872  >>> fpNaN(s)
9873  fpNaN(FPSort(8, 24))
9874  >>> set_fpa_pretty(pb)
9875  """
9876  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9877  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9878 
9879 
9881  """Create a Z3 floating-point +oo term.
9882 
9883  >>> s = FPSort(8, 24)
9884  >>> pb = get_fpa_pretty()
9885  >>> set_fpa_pretty(True)
9886  >>> fpPlusInfinity(s)
9887  +oo
9888  >>> set_fpa_pretty(False)
9889  >>> fpPlusInfinity(s)
9890  fpPlusInfinity(FPSort(8, 24))
9891  >>> set_fpa_pretty(pb)
9892  """
9893  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9894  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9895 
9896 
9898  """Create a Z3 floating-point -oo term."""
9899  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9900  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9901 
9902 
9903 def fpInfinity(s, negative):
9904  """Create a Z3 floating-point +oo or -oo term."""
9905  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9906  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9907  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9908 
9909 
9910 def fpPlusZero(s):
9911  """Create a Z3 floating-point +0.0 term."""
9912  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9913  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9914 
9915 
9917  """Create a Z3 floating-point -0.0 term."""
9918  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9919  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9920 
9921 
9922 def fpZero(s, negative):
9923  """Create a Z3 floating-point +0.0 or -0.0 term."""
9924  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9925  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9926  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9927 
9928 
9929 def FPVal(sig, exp=None, fps=None, ctx=None):
9930  """Return a floating-point value of value `val` and sort `fps`.
9931  If `ctx=None`, then the global context is used.
9932 
9933  >>> v = FPVal(20.0, FPSort(8, 24))
9934  >>> v
9935  1.25*(2**4)
9936  >>> print("0x%.8x" % v.exponent_as_long(False))
9937  0x00000004
9938  >>> v = FPVal(2.25, FPSort(8, 24))
9939  >>> v
9940  1.125*(2**1)
9941  >>> v = FPVal(-2.25, FPSort(8, 24))
9942  >>> v
9943  -1.125*(2**1)
9944  >>> FPVal(-0.0, FPSort(8, 24))
9945  -0.0
9946  >>> FPVal(0.0, FPSort(8, 24))
9947  +0.0
9948  >>> FPVal(+0.0, FPSort(8, 24))
9949  +0.0
9950  """
9951  ctx = _get_ctx(ctx)
9952  if is_fp_sort(exp):
9953  fps = exp
9954  exp = None
9955  elif fps is None:
9956  fps = _dflt_fps(ctx)
9957  _z3_assert(is_fp_sort(fps), "sort mismatch")
9958  if exp is None:
9959  exp = 0
9960  val = _to_float_str(sig)
9961  if val == "NaN" or val == "nan":
9962  return fpNaN(fps)
9963  elif val == "-0.0":
9964  return fpMinusZero(fps)
9965  elif val == "0.0" or val == "+0.0":
9966  return fpPlusZero(fps)
9967  elif val == "+oo" or val == "+inf" or val == "+Inf":
9968  return fpPlusInfinity(fps)
9969  elif val == "-oo" or val == "-inf" or val == "-Inf":
9970  return fpMinusInfinity(fps)
9971  else:
9972  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9973 
9974 
9975 def FP(name, fpsort, ctx=None):
9976  """Return a floating-point constant named `name`.
9977  `fpsort` is the floating-point sort.
9978  If `ctx=None`, then the global context is used.
9979 
9980  >>> x = FP('x', FPSort(8, 24))
9981  >>> is_fp(x)
9982  True
9983  >>> x.ebits()
9984  8
9985  >>> x.sort()
9986  FPSort(8, 24)
9987  >>> word = FPSort(8, 24)
9988  >>> x2 = FP('x', word)
9989  >>> eq(x, x2)
9990  True
9991  """
9992  if isinstance(fpsort, FPSortRef) and ctx is None:
9993  ctx = fpsort.ctx
9994  else:
9995  ctx = _get_ctx(ctx)
9996  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9997 
9998 
9999 def FPs(names, fpsort, ctx=None):
10000  """Return an array of floating-point constants.
10001 
10002  >>> x, y, z = FPs('x y z', FPSort(8, 24))
10003  >>> x.sort()
10004  FPSort(8, 24)
10005  >>> x.sbits()
10006  24
10007  >>> x.ebits()
10008  8
10009  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10010  fpMul(RNE(), fpAdd(RNE(), x, y), z)
10011  """
10012  ctx = _get_ctx(ctx)
10013  if isinstance(names, str):
10014  names = names.split(" ")
10015  return [FP(name, fpsort, ctx) for name in names]
10016 
10017 
10018 def fpAbs(a, ctx=None):
10019  """Create a Z3 floating-point absolute value expression.
10020 
10021  >>> s = FPSort(8, 24)
10022  >>> rm = RNE()
10023  >>> x = FPVal(1.0, s)
10024  >>> fpAbs(x)
10025  fpAbs(1)
10026  >>> y = FPVal(-20.0, s)
10027  >>> y
10028  -1.25*(2**4)
10029  >>> fpAbs(y)
10030  fpAbs(-1.25*(2**4))
10031  >>> fpAbs(-1.25*(2**4))
10032  fpAbs(-1.25*(2**4))
10033  >>> fpAbs(x).sort()
10034  FPSort(8, 24)
10035  """
10036  ctx = _get_ctx(ctx)
10037  [a] = _coerce_fp_expr_list([a], ctx)
10038  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10039 
10040 
10041 def fpNeg(a, ctx=None):
10042  """Create a Z3 floating-point addition expression.
10043 
10044  >>> s = FPSort(8, 24)
10045  >>> rm = RNE()
10046  >>> x = FP('x', s)
10047  >>> fpNeg(x)
10048  -x
10049  >>> fpNeg(x).sort()
10050  FPSort(8, 24)
10051  """
10052  ctx = _get_ctx(ctx)
10053  [a] = _coerce_fp_expr_list([a], ctx)
10054  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10055 
10056 
10057 def _mk_fp_unary(f, rm, a, ctx):
10058  ctx = _get_ctx(ctx)
10059  [a] = _coerce_fp_expr_list([a], ctx)
10060  if z3_debug():
10061  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10062  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10063  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10064 
10065 
10066 def _mk_fp_unary_pred(f, a, ctx):
10067  ctx = _get_ctx(ctx)
10068  [a] = _coerce_fp_expr_list([a], ctx)
10069  if z3_debug():
10070  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10071  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10072 
10073 
10074 def _mk_fp_bin(f, rm, a, b, ctx):
10075  ctx = _get_ctx(ctx)
10076  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10077  if z3_debug():
10078  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10079  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10080  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10081 
10082 
10083 def _mk_fp_bin_norm(f, a, b, ctx):
10084  ctx = _get_ctx(ctx)
10085  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10086  if z3_debug():
10087  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10088  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10089 
10090 
10091 def _mk_fp_bin_pred(f, a, b, ctx):
10092  ctx = _get_ctx(ctx)
10093  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10094  if z3_debug():
10095  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10096  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10097 
10098 
10099 def _mk_fp_tern(f, rm, a, b, c, ctx):
10100  ctx = _get_ctx(ctx)
10101  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
10102  if z3_debug():
10103  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10104  _z3_assert(is_fp(a) or is_fp(b) or is_fp(
10105  c), "Second, third or fourth argument must be a Z3 floating-point expression")
10106  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10107 
10108 
10109 def fpAdd(rm, a, b, ctx=None):
10110  """Create a Z3 floating-point addition expression.
10111 
10112  >>> s = FPSort(8, 24)
10113  >>> rm = RNE()
10114  >>> x = FP('x', s)
10115  >>> y = FP('y', s)
10116  >>> fpAdd(rm, x, y)
10117  fpAdd(RNE(), x, y)
10118  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10119  x + y
10120  >>> fpAdd(rm, x, y).sort()
10121  FPSort(8, 24)
10122  """
10123  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10124 
10125 
10126 def fpSub(rm, a, b, ctx=None):
10127  """Create a Z3 floating-point subtraction expression.
10128 
10129  >>> s = FPSort(8, 24)
10130  >>> rm = RNE()
10131  >>> x = FP('x', s)
10132  >>> y = FP('y', s)
10133  >>> fpSub(rm, x, y)
10134  fpSub(RNE(), x, y)
10135  >>> fpSub(rm, x, y).sort()
10136  FPSort(8, 24)
10137  """
10138  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10139 
10140 
10141 def fpMul(rm, a, b, ctx=None):
10142  """Create a Z3 floating-point multiplication expression.
10143 
10144  >>> s = FPSort(8, 24)
10145  >>> rm = RNE()
10146  >>> x = FP('x', s)
10147  >>> y = FP('y', s)
10148  >>> fpMul(rm, x, y)
10149  fpMul(RNE(), x, y)
10150  >>> fpMul(rm, x, y).sort()
10151  FPSort(8, 24)
10152  """
10153  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10154 
10155 
10156 def fpDiv(rm, a, b, ctx=None):
10157  """Create a Z3 floating-point division expression.
10158 
10159  >>> s = FPSort(8, 24)
10160  >>> rm = RNE()
10161  >>> x = FP('x', s)
10162  >>> y = FP('y', s)
10163  >>> fpDiv(rm, x, y)
10164  fpDiv(RNE(), x, y)
10165  >>> fpDiv(rm, x, y).sort()
10166  FPSort(8, 24)
10167  """
10168  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10169 
10170 
10171 def fpRem(a, b, ctx=None):
10172  """Create a Z3 floating-point remainder expression.
10173 
10174  >>> s = FPSort(8, 24)
10175  >>> x = FP('x', s)
10176  >>> y = FP('y', s)
10177  >>> fpRem(x, y)
10178  fpRem(x, y)
10179  >>> fpRem(x, y).sort()
10180  FPSort(8, 24)
10181  """
10182  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10183 
10184 
10185 def fpMin(a, b, ctx=None):
10186  """Create a Z3 floating-point minimum expression.
10187 
10188  >>> s = FPSort(8, 24)
10189  >>> rm = RNE()
10190  >>> x = FP('x', s)
10191  >>> y = FP('y', s)
10192  >>> fpMin(x, y)
10193  fpMin(x, y)
10194  >>> fpMin(x, y).sort()
10195  FPSort(8, 24)
10196  """
10197  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10198 
10199 
10200 def fpMax(a, b, ctx=None):
10201  """Create a Z3 floating-point maximum expression.
10202 
10203  >>> s = FPSort(8, 24)
10204  >>> rm = RNE()
10205  >>> x = FP('x', s)
10206  >>> y = FP('y', s)
10207  >>> fpMax(x, y)
10208  fpMax(x, y)
10209  >>> fpMax(x, y).sort()
10210  FPSort(8, 24)
10211  """
10212  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10213 
10214 
10215 def fpFMA(rm, a, b, c, ctx=None):
10216  """Create a Z3 floating-point fused multiply-add expression.
10217  """
10218  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10219 
10220 
10221 def fpSqrt(rm, a, ctx=None):
10222  """Create a Z3 floating-point square root expression.
10223  """
10224  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10225 
10226 
10227 def fpRoundToIntegral(rm, a, ctx=None):
10228  """Create a Z3 floating-point roundToIntegral expression.
10229  """
10230  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10231 
10232 
10233 def fpIsNaN(a, ctx=None):
10234  """Create a Z3 floating-point isNaN expression.
10235 
10236  >>> s = FPSort(8, 24)
10237  >>> x = FP('x', s)
10238  >>> y = FP('y', s)
10239  >>> fpIsNaN(x)
10240  fpIsNaN(x)
10241  """
10242  return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10243 
10244 
10245 def fpIsInf(a, ctx=None):
10246  """Create a Z3 floating-point isInfinite expression.
10247 
10248  >>> s = FPSort(8, 24)
10249  >>> x = FP('x', s)
10250  >>> fpIsInf(x)
10251  fpIsInf(x)
10252  """
10253  return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10254 
10255 
10256 def fpIsZero(a, ctx=None):
10257  """Create a Z3 floating-point isZero expression.
10258  """
10259  return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10260 
10261 
10262 def fpIsNormal(a, ctx=None):
10263  """Create a Z3 floating-point isNormal expression.
10264  """
10265  return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10266 
10267 
10268 def fpIsSubnormal(a, ctx=None):
10269  """Create a Z3 floating-point isSubnormal expression.
10270  """
10271  return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10272 
10273 
10274 def fpIsNegative(a, ctx=None):
10275  """Create a Z3 floating-point isNegative expression.
10276  """
10277  return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10278 
10279 
10280 def fpIsPositive(a, ctx=None):
10281  """Create a Z3 floating-point isPositive expression.
10282  """
10283  return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10284 
10285 
10286 def _check_fp_args(a, b):
10287  if z3_debug():
10288  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10289 
10290 
10291 def fpLT(a, b, ctx=None):
10292  """Create the Z3 floating-point expression `other < self`.
10293 
10294  >>> x, y = FPs('x y', FPSort(8, 24))
10295  >>> fpLT(x, y)
10296  x < y
10297  >>> (x < y).sexpr()
10298  '(fp.lt x y)'
10299  """
10300  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10301 
10302 
10303 def fpLEQ(a, b, ctx=None):
10304  """Create the Z3 floating-point expression `other <= self`.
10305 
10306  >>> x, y = FPs('x y', FPSort(8, 24))
10307  >>> fpLEQ(x, y)
10308  x <= y
10309  >>> (x <= y).sexpr()
10310  '(fp.leq x y)'
10311  """
10312  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10313 
10314 
10315 def fpGT(a, b, ctx=None):
10316  """Create the Z3 floating-point expression `other > self`.
10317 
10318  >>> x, y = FPs('x y', FPSort(8, 24))
10319  >>> fpGT(x, y)
10320  x > y
10321  >>> (x > y).sexpr()
10322  '(fp.gt x y)'
10323  """
10324  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10325 
10326 
10327 def fpGEQ(a, b, ctx=None):
10328  """Create the Z3 floating-point expression `other >= self`.
10329 
10330  >>> x, y = FPs('x y', FPSort(8, 24))
10331  >>> fpGEQ(x, y)
10332  x >= y
10333  >>> (x >= y).sexpr()
10334  '(fp.geq x y)'
10335  """
10336  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10337 
10338 
10339 def fpEQ(a, b, ctx=None):
10340  """Create the Z3 floating-point expression `fpEQ(other, self)`.
10341 
10342  >>> x, y = FPs('x y', FPSort(8, 24))
10343  >>> fpEQ(x, y)
10344  fpEQ(x, y)
10345  >>> fpEQ(x, y).sexpr()
10346  '(fp.eq x y)'
10347  """
10348  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10349 
10350 
10351 def fpNEQ(a, b, ctx=None):
10352  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10353 
10354  >>> x, y = FPs('x y', FPSort(8, 24))
10355  >>> fpNEQ(x, y)
10356  Not(fpEQ(x, y))
10357  >>> (x != y).sexpr()
10358  '(distinct x y)'
10359  """
10360  return Not(fpEQ(a, b, ctx))
10361 
10362 
10363 def fpFP(sgn, exp, sig, ctx=None):
10364  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10365 
10366  >>> s = FPSort(8, 24)
10367  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10368  >>> print(x)
10369  fpFP(1, 127, 4194304)
10370  >>> xv = FPVal(-1.5, s)
10371  >>> print(xv)
10372  -1.5
10373  >>> slvr = Solver()
10374  >>> slvr.add(fpEQ(x, xv))
10375  >>> slvr.check()
10376  sat
10377  >>> xv = FPVal(+1.5, s)
10378  >>> print(xv)
10379  1.5
10380  >>> slvr = Solver()
10381  >>> slvr.add(fpEQ(x, xv))
10382  >>> slvr.check()
10383  unsat
10384  """
10385  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10386  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10387  ctx = _get_ctx(ctx)
10388  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10389  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10390 
10391 
10392 def fpToFP(a1, a2=None, a3=None, ctx=None):
10393  """Create a Z3 floating-point conversion expression from other term sorts
10394  to floating-point.
10395 
10396  From a bit-vector term in IEEE 754-2008 format:
10397  >>> x = FPVal(1.0, Float32())
10398  >>> x_bv = fpToIEEEBV(x)
10399  >>> simplify(fpToFP(x_bv, Float32()))
10400  1
10401 
10402  From a floating-point term with different precision:
10403  >>> x = FPVal(1.0, Float32())
10404  >>> x_db = fpToFP(RNE(), x, Float64())
10405  >>> x_db.sort()
10406  FPSort(11, 53)
10407 
10408  From a real term:
10409  >>> x_r = RealVal(1.5)
10410  >>> simplify(fpToFP(RNE(), x_r, Float32()))
10411  1.5
10412 
10413  From a signed bit-vector term:
10414  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10415  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10416  -1.25*(2**2)
10417  """
10418  ctx = _get_ctx(ctx)
10419  if is_bv(a1) and is_fp_sort(a2):
10420  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10421  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10422  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10423  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10424  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10425  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10426  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10427  else:
10428  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10429 
10430 
10431 def fpBVToFP(v, sort, ctx=None):
10432  """Create a Z3 floating-point conversion expression that represents the
10433  conversion from a bit-vector term to a floating-point term.
10434 
10435  >>> x_bv = BitVecVal(0x3F800000, 32)
10436  >>> x_fp = fpBVToFP(x_bv, Float32())
10437  >>> x_fp
10438  fpToFP(1065353216)
10439  >>> simplify(x_fp)
10440  1
10441  """
10442  _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10443  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10444  ctx = _get_ctx(ctx)
10445  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10446 
10447 
10448 def fpFPToFP(rm, v, sort, ctx=None):
10449  """Create a Z3 floating-point conversion expression that represents the
10450  conversion from a floating-point term to a floating-point term of different precision.
10451 
10452  >>> x_sgl = FPVal(1.0, Float32())
10453  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10454  >>> x_dbl
10455  fpToFP(RNE(), 1)
10456  >>> simplify(x_dbl)
10457  1
10458  >>> x_dbl.sort()
10459  FPSort(11, 53)
10460  """
10461  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10462  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10463  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10464  ctx = _get_ctx(ctx)
10465  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10466 
10467 
10468 def fpRealToFP(rm, v, sort, ctx=None):
10469  """Create a Z3 floating-point conversion expression that represents the
10470  conversion from a real term to a floating-point term.
10471 
10472  >>> x_r = RealVal(1.5)
10473  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10474  >>> x_fp
10475  fpToFP(RNE(), 3/2)
10476  >>> simplify(x_fp)
10477  1.5
10478  """
10479  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10480  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10481  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10482  ctx = _get_ctx(ctx)
10483  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10484 
10485 
10486 def fpSignedToFP(rm, v, sort, ctx=None):
10487  """Create a Z3 floating-point conversion expression that represents the
10488  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10489 
10490  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10491  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10492  >>> x_fp
10493  fpToFP(RNE(), 4294967291)
10494  >>> simplify(x_fp)
10495  -1.25*(2**2)
10496  """
10497  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10498  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10499  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10500  ctx = _get_ctx(ctx)
10501  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10502 
10503 
10504 def fpUnsignedToFP(rm, v, sort, ctx=None):
10505  """Create a Z3 floating-point conversion expression that represents the
10506  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10507 
10508  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10509  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10510  >>> x_fp
10511  fpToFPUnsigned(RNE(), 4294967291)
10512  >>> simplify(x_fp)
10513  1*(2**32)
10514  """
10515  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10516  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10517  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10518  ctx = _get_ctx(ctx)
10519  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10520 
10521 
10522 def fpToFPUnsigned(rm, x, s, ctx=None):
10523  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10524  if z3_debug():
10525  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10526  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10527  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10528  ctx = _get_ctx(ctx)
10529  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10530 
10531 
10532 def fpToSBV(rm, x, s, ctx=None):
10533  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10534 
10535  >>> x = FP('x', FPSort(8, 24))
10536  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10537  >>> print(is_fp(x))
10538  True
10539  >>> print(is_bv(y))
10540  True
10541  >>> print(is_fp(y))
10542  False
10543  >>> print(is_bv(x))
10544  False
10545  """
10546  if z3_debug():
10547  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10548  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10549  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10550  ctx = _get_ctx(ctx)
10551  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10552 
10553 
10554 def fpToUBV(rm, x, s, ctx=None):
10555  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10556 
10557  >>> x = FP('x', FPSort(8, 24))
10558  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10559  >>> print(is_fp(x))
10560  True
10561  >>> print(is_bv(y))
10562  True
10563  >>> print(is_fp(y))
10564  False
10565  >>> print(is_bv(x))
10566  False
10567  """
10568  if z3_debug():
10569  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10570  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10571  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10572  ctx = _get_ctx(ctx)
10573  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10574 
10575 
10576 def fpToReal(x, ctx=None):
10577  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10578 
10579  >>> x = FP('x', FPSort(8, 24))
10580  >>> y = fpToReal(x)
10581  >>> print(is_fp(x))
10582  True
10583  >>> print(is_real(y))
10584  True
10585  >>> print(is_fp(y))
10586  False
10587  >>> print(is_real(x))
10588  False
10589  """
10590  if z3_debug():
10591  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10592  ctx = _get_ctx(ctx)
10593  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10594 
10595 
10596 def fpToIEEEBV(x, ctx=None):
10597  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10598 
10599  The size of the resulting bit-vector is automatically determined.
10600 
10601  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10602  knows only one NaN and it will always produce the same bit-vector representation of
10603  that NaN.
10604 
10605  >>> x = FP('x', FPSort(8, 24))
10606  >>> y = fpToIEEEBV(x)
10607  >>> print(is_fp(x))
10608  True
10609  >>> print(is_bv(y))
10610  True
10611  >>> print(is_fp(y))
10612  False
10613  >>> print(is_bv(x))
10614  False
10615  """
10616  if z3_debug():
10617  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10618  ctx = _get_ctx(ctx)
10619  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10620 
10621 
10622 
10627 
10629  """Sequence sort."""
10630 
10631  def is_string(self):
10632  """Determine if sort is a string
10633  >>> s = StringSort()
10634  >>> s.is_string()
10635  True
10636  >>> s = SeqSort(IntSort())
10637  >>> s.is_string()
10638  False
10639  """
10640  return Z3_is_string_sort(self.ctx_refctx_ref(), self.astast)
10641 
10642  def basis(self):
10643  return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_refctx_ref(), self.astast), self.ctxctx)
10644 
10646  """Character sort."""
10647 
10648 
10649 def StringSort(ctx=None):
10650  """Create a string sort
10651  >>> s = StringSort()
10652  >>> print(s)
10653  String
10654  """
10655  ctx = _get_ctx(ctx)
10656  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10657 
10658 def CharSort(ctx=None):
10659  """Create a character sort
10660  >>> ch = CharSort()
10661  >>> print(ch)
10662  Char
10663  """
10664  ctx = _get_ctx(ctx)
10665  return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
10666 
10667 
10668 def SeqSort(s):
10669  """Create a sequence sort over elements provided in the argument
10670  >>> s = SeqSort(IntSort())
10671  >>> s == Unit(IntVal(1)).sort()
10672  True
10673  """
10674  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10675 
10676 
10678  """Sequence expression."""
10679 
10680  def sort(self):
10681  return SeqSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10682 
10683  def __add__(self, other):
10684  return Concat(self, other)
10685 
10686  def __radd__(self, other):
10687  return Concat(other, self)
10688 
10689  def __getitem__(self, i):
10690  if _is_int(i):
10691  i = IntVal(i, self.ctxctx)
10692  return _to_expr_ref(Z3_mk_seq_nth(self.ctx_refctx_ref(), self.as_astas_astas_ast(), i.as_ast()), self.ctxctx)
10693 
10694  def at(self, i):
10695  if _is_int(i):
10696  i = IntVal(i, self.ctxctx)
10697  return SeqRef(Z3_mk_seq_at(self.ctx_refctx_ref(), self.as_astas_astas_ast(), i.as_ast()), self.ctxctx)
10698 
10699  def is_string(self):
10700  return Z3_is_string_sort(self.ctx_refctx_ref(), Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()))
10701 
10702  def is_string_value(self):
10703  return Z3_is_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
10704 
10705  def as_string(self):
10706  """Return a string representation of sequence expression."""
10707  if self.is_string_valueis_string_value():
10708  string_length = ctypes.c_uint()
10709  chars = Z3_get_lstring(self.ctx_refctx_ref(), self.as_astas_astas_ast(), byref(string_length))
10710  return string_at(chars, size=string_length.value).decode("latin-1")
10711  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
10712 
10713  def __le__(self, other):
10714  return _to_expr_ref(Z3_mk_str_le(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10715 
10716  def __lt__(self, other):
10717  return _to_expr_ref(Z3_mk_str_lt(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10718 
10719  def __ge__(self, other):
10720  return _to_expr_ref(Z3_mk_str_le(self.ctx_refctx_ref(), other.as_ast(), self.as_astas_astas_ast()), self.ctxctx)
10721 
10722  def __gt__(self, other):
10723  return _to_expr_ref(Z3_mk_str_lt(self.ctx_refctx_ref(), other.as_ast(), self.as_astas_astas_ast()), self.ctxctx)
10724 
10725 
10726 def _coerce_char(ch, ctx=None):
10727  if isinstance(ch, str):
10728  ctx = _get_ctx(ctx)
10729  ch = CharVal(ch, ctx)
10730  if not is_expr(ch):
10731  raise Z3Exception("Character expression expected")
10732  return ch
10733 
10735  """Character expression."""
10736 
10737  def __le__(self, other):
10738  other = _coerce_char(other, self.ctxctx)
10739  return _to_expr_ref(Z3_mk_char_le(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10740 
10741  def to_int(self):
10742  return _to_expr_ref(Z3_mk_char_to_int(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10743 
10744  def to_bv(self):
10745  return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10746 
10747  def is_digit(self):
10748  return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10749 
10750 
10751 def CharVal(ch, ctx=None):
10752  ctx = _get_ctx(ctx)
10753  if isinstance(ch, str):
10754  ch = ord(ch)
10755  if not isinstance(ch, int):
10756  raise Z3Exception("character value should be an ordinal")
10757  return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
10758 
10759 def CharFromBv(ch, ctx=None):
10760  if not is_expr(ch):
10761  raise Z3Expression("Bit-vector expression needed")
10762  return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
10763 
10764 def CharToBv(ch, ctx=None):
10765  ch = _coerce_char(ch, ctx)
10766  return ch.to_bv()
10767 
10768 def CharToInt(ch, ctx=None):
10769  ch = _coerce_char(ch, ctx)
10770  return ch.to_int()
10771 
10772 def CharIsDigit(ch, ctx=None):
10773  ch = _coerce_char(ch, ctx)
10774  return ch.is_digit()
10775 
10776 def _coerce_seq(s, ctx=None):
10777  if isinstance(s, str):
10778  ctx = _get_ctx(ctx)
10779  s = StringVal(s, ctx)
10780  if not is_expr(s):
10781  raise Z3Exception("Non-expression passed as a sequence")
10782  if not is_seq(s):
10783  raise Z3Exception("Non-sequence passed as a sequence")
10784  return s
10785 
10786 
10787 def _get_ctx2(a, b, ctx=None):
10788  if is_expr(a):
10789  return a.ctx
10790  if is_expr(b):
10791  return b.ctx
10792  if ctx is None:
10793  ctx = main_ctx()
10794  return ctx
10795 
10796 
10797 def is_seq(a):
10798  """Return `True` if `a` is a Z3 sequence expression.
10799  >>> print (is_seq(Unit(IntVal(0))))
10800  True
10801  >>> print (is_seq(StringVal("abc")))
10802  True
10803  """
10804  return isinstance(a, SeqRef)
10805 
10806 
10807 def is_string(a):
10808  """Return `True` if `a` is a Z3 string expression.
10809  >>> print (is_string(StringVal("ab")))
10810  True
10811  """
10812  return isinstance(a, SeqRef) and a.is_string()
10813 
10814 
10816  """return 'True' if 'a' is a Z3 string constant expression.
10817  >>> print (is_string_value(StringVal("a")))
10818  True
10819  >>> print (is_string_value(StringVal("a") + StringVal("b")))
10820  False
10821  """
10822  return isinstance(a, SeqRef) and a.is_string_value()
10823 
10824 def StringVal(s, ctx=None):
10825  """create a string expression"""
10826  s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
10827  ctx = _get_ctx(ctx)
10828  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
10829 
10830 
10831 def String(name, ctx=None):
10832  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10833 
10834  >>> x = String('x')
10835  """
10836  ctx = _get_ctx(ctx)
10837  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10838 
10839 
10840 def Strings(names, ctx=None):
10841  """Return a tuple of String constants. """
10842  ctx = _get_ctx(ctx)
10843  if isinstance(names, str):
10844  names = names.split(" ")
10845  return [String(name, ctx) for name in names]
10846 
10847 
10848 def SubString(s, offset, length):
10849  """Extract substring or subsequence starting at offset"""
10850  return Extract(s, offset, length)
10851 
10852 
10853 def SubSeq(s, offset, length):
10854  """Extract substring or subsequence starting at offset"""
10855  return Extract(s, offset, length)
10856 
10857 
10858 def Empty(s):
10859  """Create the empty sequence of the given sort
10860  >>> e = Empty(StringSort())
10861  >>> e2 = StringVal("")
10862  >>> print(e.eq(e2))
10863  True
10864  >>> e3 = Empty(SeqSort(IntSort()))
10865  >>> print(e3)
10866  Empty(Seq(Int))
10867  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10868  >>> print(e4)
10869  Empty(ReSort(Seq(Int)))
10870  """
10871  if isinstance(s, SeqSortRef):
10872  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10873  if isinstance(s, ReSortRef):
10874  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10875  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10876 
10877 
10878 def Full(s):
10879  """Create the regular expression that accepts the universal language
10880  >>> e = Full(ReSort(SeqSort(IntSort())))
10881  >>> print(e)
10882  Full(ReSort(Seq(Int)))
10883  >>> e1 = Full(ReSort(StringSort()))
10884  >>> print(e1)
10885  Full(ReSort(String))
10886  """
10887  if isinstance(s, ReSortRef):
10888  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10889  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10890 
10891 
10892 
10893 def Unit(a):
10894  """Create a singleton sequence"""
10895  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10896 
10897 
10898 def PrefixOf(a, b):
10899  """Check if 'a' is a prefix of 'b'
10900  >>> s1 = PrefixOf("ab", "abc")
10901  >>> simplify(s1)
10902  True
10903  >>> s2 = PrefixOf("bc", "abc")
10904  >>> simplify(s2)
10905  False
10906  """
10907  ctx = _get_ctx2(a, b)
10908  a = _coerce_seq(a, ctx)
10909  b = _coerce_seq(b, ctx)
10910  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10911 
10912 
10913 def SuffixOf(a, b):
10914  """Check if 'a' is a suffix of 'b'
10915  >>> s1 = SuffixOf("ab", "abc")
10916  >>> simplify(s1)
10917  False
10918  >>> s2 = SuffixOf("bc", "abc")
10919  >>> simplify(s2)
10920  True
10921  """
10922  ctx = _get_ctx2(a, b)
10923  a = _coerce_seq(a, ctx)
10924  b = _coerce_seq(b, ctx)
10925  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10926 
10927 
10928 def Contains(a, b):
10929  """Check if 'a' contains 'b'
10930  >>> s1 = Contains("abc", "ab")
10931  >>> simplify(s1)
10932  True
10933  >>> s2 = Contains("abc", "bc")
10934  >>> simplify(s2)
10935  True
10936  >>> x, y, z = Strings('x y z')
10937  >>> s3 = Contains(Concat(x,y,z), y)
10938  >>> simplify(s3)
10939  True
10940  """
10941  ctx = _get_ctx2(a, b)
10942  a = _coerce_seq(a, ctx)
10943  b = _coerce_seq(b, ctx)
10944  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10945 
10946 
10947 def Replace(s, src, dst):
10948  """Replace the first occurrence of 'src' by 'dst' in 's'
10949  >>> r = Replace("aaa", "a", "b")
10950  >>> simplify(r)
10951  "baa"
10952  """
10953  ctx = _get_ctx2(dst, s)
10954  if ctx is None and is_expr(src):
10955  ctx = src.ctx
10956  src = _coerce_seq(src, ctx)
10957  dst = _coerce_seq(dst, ctx)
10958  s = _coerce_seq(s, ctx)
10959  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10960 
10961 
10962 def IndexOf(s, substr, offset=None):
10963  """Retrieve the index of substring within a string starting at a specified offset.
10964  >>> simplify(IndexOf("abcabc", "bc", 0))
10965  1
10966  >>> simplify(IndexOf("abcabc", "bc", 2))
10967  4
10968  """
10969  if offset is None:
10970  offset = IntVal(0)
10971  ctx = None
10972  if is_expr(offset):
10973  ctx = offset.ctx
10974  ctx = _get_ctx2(s, substr, ctx)
10975  s = _coerce_seq(s, ctx)
10976  substr = _coerce_seq(substr, ctx)
10977  if _is_int(offset):
10978  offset = IntVal(offset, ctx)
10979  return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10980 
10981 
10982 def LastIndexOf(s, substr):
10983  """Retrieve the last index of substring within a string"""
10984  ctx = None
10985  ctx = _get_ctx2(s, substr, ctx)
10986  s = _coerce_seq(s, ctx)
10987  substr = _coerce_seq(substr, ctx)
10988  return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10989 
10990 
10991 def Length(s):
10992  """Obtain the length of a sequence 's'
10993  >>> l = Length(StringVal("abc"))
10994  >>> simplify(l)
10995  3
10996  """
10997  s = _coerce_seq(s)
10998  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10999 
11000 
11001 def StrToInt(s):
11002  """Convert string expression to integer
11003  >>> a = StrToInt("1")
11004  >>> simplify(1 == a)
11005  True
11006  >>> b = StrToInt("2")
11007  >>> simplify(1 == b)
11008  False
11009  >>> c = StrToInt(IntToStr(2))
11010  >>> simplify(1 == c)
11011  False
11012  """
11013  s = _coerce_seq(s)
11014  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11015 
11016 
11017 def IntToStr(s):
11018  """Convert integer expression to string"""
11019  if not is_expr(s):
11020  s = _py2expr(s)
11021  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11022 
11023 
11024 def StrToCode(s):
11025  """Convert a unit length string to integer code"""
11026  if not is_expr(s):
11027  s = _py2expr(s)
11028  return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
11029 
11031  """Convert code to a string"""
11032  if not is_expr(c):
11033  c = _py2expr(c)
11034  return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
11035 
11036 def Re(s, ctx=None):
11037  """The regular expression that accepts sequence 's'
11038  >>> s1 = Re("ab")
11039  >>> s2 = Re(StringVal("ab"))
11040  >>> s3 = Re(Unit(BoolVal(True)))
11041  """
11042  s = _coerce_seq(s, ctx)
11043  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
11044 
11045 
11046 # Regular expressions
11047 
11049  """Regular expression sort."""
11050 
11051  def basis(self):
11052  return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_refctx_ref(), self.astast), self.ctxctx)
11053 
11054 
11055 def ReSort(s):
11056  if is_ast(s):
11057  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
11058  if s is None or isinstance(s, Context):
11059  ctx = _get_ctx(s)
11060  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
11061  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
11062 
11063 
11065  """Regular expressions."""
11066 
11067  def __add__(self, other):
11068  return Union(self, other)
11069 
11070 
11071 def is_re(s):
11072  return isinstance(s, ReRef)
11073 
11074 
11075 def InRe(s, re):
11076  """Create regular expression membership test
11077  >>> re = Union(Re("a"),Re("b"))
11078  >>> print (simplify(InRe("a", re)))
11079  True
11080  >>> print (simplify(InRe("b", re)))
11081  True
11082  >>> print (simplify(InRe("c", re)))
11083  False
11084  """
11085  s = _coerce_seq(s, re.ctx)
11086  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
11087 
11088 
11089 def Union(*args):
11090  """Create union of regular expressions.
11091  >>> re = Union(Re("a"), Re("b"), Re("c"))
11092  >>> print (simplify(InRe("d", re)))
11093  False
11094  """
11095  args = _get_args(args)
11096  sz = len(args)
11097  if z3_debug():
11098  _z3_assert(sz > 0, "At least one argument expected.")
11099  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11100  if sz == 1:
11101  return args[0]
11102  ctx = args[0].ctx
11103  v = (Ast * sz)()
11104  for i in range(sz):
11105  v[i] = args[i].as_ast()
11106  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
11107 
11108 
11109 def Intersect(*args):
11110  """Create intersection of regular expressions.
11111  >>> re = Intersect(Re("a"), Re("b"), Re("c"))
11112  """
11113  args = _get_args(args)
11114  sz = len(args)
11115  if z3_debug():
11116  _z3_assert(sz > 0, "At least one argument expected.")
11117  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11118  if sz == 1:
11119  return args[0]
11120  ctx = args[0].ctx
11121  v = (Ast * sz)()
11122  for i in range(sz):
11123  v[i] = args[i].as_ast()
11124  return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
11125 
11126 
11127 def Plus(re):
11128  """Create the regular expression accepting one or more repetitions of argument.
11129  >>> re = Plus(Re("a"))
11130  >>> print(simplify(InRe("aa", re)))
11131  True
11132  >>> print(simplify(InRe("ab", re)))
11133  False
11134  >>> print(simplify(InRe("", re)))
11135  False
11136  """
11137  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
11138 
11139 
11140 def Option(re):
11141  """Create the regular expression that optionally accepts the argument.
11142  >>> re = Option(Re("a"))
11143  >>> print(simplify(InRe("a", re)))
11144  True
11145  >>> print(simplify(InRe("", re)))
11146  True
11147  >>> print(simplify(InRe("aa", re)))
11148  False
11149  """
11150  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11151 
11152 
11153 def Complement(re):
11154  """Create the complement regular expression."""
11155  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11156 
11157 
11158 def Star(re):
11159  """Create the regular expression accepting zero or more repetitions of argument.
11160  >>> re = Star(Re("a"))
11161  >>> print(simplify(InRe("aa", re)))
11162  True
11163  >>> print(simplify(InRe("ab", re)))
11164  False
11165  >>> print(simplify(InRe("", re)))
11166  True
11167  """
11168  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11169 
11170 
11171 def Loop(re, lo, hi=0):
11172  """Create the regular expression accepting between a lower and upper bound repetitions
11173  >>> re = Loop(Re("a"), 1, 3)
11174  >>> print(simplify(InRe("aa", re)))
11175  True
11176  >>> print(simplify(InRe("aaaa", re)))
11177  False
11178  >>> print(simplify(InRe("", re)))
11179  False
11180  """
11181  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11182 
11183 
11184 def Range(lo, hi, ctx=None):
11185  """Create the range regular expression over two sequences of length 1
11186  >>> range = Range("a","z")
11187  >>> print(simplify(InRe("b", range)))
11188  True
11189  >>> print(simplify(InRe("bb", range)))
11190  False
11191  """
11192  lo = _coerce_seq(lo, ctx)
11193  hi = _coerce_seq(hi, ctx)
11194  return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11195 
11196 def Diff(a, b, ctx=None):
11197  """Create the difference regular epression
11198  """
11199  return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
11200 
11201 def AllChar(regex_sort, ctx=None):
11202  """Create a regular expression that accepts all single character strings
11203  """
11204  return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
11205 
11206 # Special Relations
11207 
11208 
11209 def PartialOrder(a, index):
11210  return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11211 
11212 
11213 def LinearOrder(a, index):
11214  return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11215 
11216 
11217 def TreeOrder(a, index):
11218  return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11219 
11220 
11221 def PiecewiseLinearOrder(a, index):
11222  return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11223 
11224 
11226  """Given a binary relation R, such that the two arguments have the same sort
11227  create the transitive closure relation R+.
11228  The transitive closure R+ is a new relation.
11229  """
11230  return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11231 
11232 
11234  def __init__(self):
11235  self.basesbases = {}
11236  self.locklock = None
11237 
11238  def set_threaded(self):
11239  if self.locklock is None:
11240  import threading
11241  self.locklock = threading.Lock()
11242 
11243  def get(self, ctx):
11244  if self.locklock:
11245  with self.locklock:
11246  r = self.basesbases[ctx]
11247  else:
11248  r = self.basesbases[ctx]
11249  return r
11250 
11251  def set(self, ctx, r):
11252  if self.locklock:
11253  with self.locklock:
11254  self.basesbases[ctx] = r
11255  else:
11256  self.basesbases[ctx] = r
11257 
11258  def insert(self, r):
11259  if self.locklock:
11260  with self.locklock:
11261  id = len(self.basesbases) + 3
11262  self.basesbases[id] = r
11263  else:
11264  id = len(self.basesbases) + 3
11265  self.basesbases[id] = r
11266  return id
11267 
11268 
11269 _prop_closures = None
11270 
11271 
11273  global _prop_closures
11274  if _prop_closures is None:
11275  _prop_closures = PropClosures()
11276 
11277 
11278 def user_prop_push(ctx, cb):
11279  prop = _prop_closures.get(ctx)
11280  prop.cb = cb
11281  prop.push()
11282 
11283 
11284 def user_prop_pop(ctx, cb, num_scopes):
11285  prop = _prop_closures.get(ctx)
11286  prop.cb = cb
11287  prop.pop(num_scopes)
11288 
11289 
11290 def user_prop_fresh(id, ctx):
11291  _prop_closures.set_threaded()
11292  prop = _prop_closures.get(id)
11293  new_prop = prop.fresh()
11294  _prop_closures.set(new_prop.id, new_prop)
11295  return ctypes.c_void_p(new_prop.id)
11296 
11297 def to_Ast(ptr,):
11298  ast = Ast(ptr)
11299  super(ctypes.c_void_p, ast).__init__(ptr)
11300  return ast
11301 
11302 def user_prop_fixed(ctx, cb, id, value):
11303  prop = _prop_closures.get(ctx)
11304  prop.cb = cb
11305  id = _to_expr_ref(to_Ast(id), prop.ctx())
11306  value = _to_expr_ref(to_Ast(value), prop.ctx())
11307  prop.fixed(id, value)
11308  prop.cb = None
11309 
11310 def user_prop_final(ctx, cb):
11311  prop = _prop_closures.get(ctx)
11312  prop.cb = cb
11313  prop.final()
11314  prop.cb = None
11315 
11316 def user_prop_eq(ctx, cb, x, y):
11317  prop = _prop_closures.get(ctx)
11318  prop.cb = cb
11319  x = _to_expr_ref(to_Ast(x), prop.ctx())
11320  y = _to_expr_ref(to_Ast(y), prop.ctx())
11321  prop.eq(x, y)
11322  prop.cb = None
11323 
11324 def user_prop_diseq(ctx, cb, x, y):
11325  prop = _prop_closures.get(ctx)
11326  prop.cb = cb
11327  x = _to_expr_ref(to_Ast(x), prop.ctx())
11328  y = _to_expr_ref(to_Ast(y), prop.ctx())
11329  prop.diseq(x, y)
11330  prop.cb = None
11331 
11332 
11333 _user_prop_push = push_eh_type(user_prop_push)
11334 _user_prop_pop = pop_eh_type(user_prop_pop)
11335 _user_prop_fresh = fresh_eh_type(user_prop_fresh)
11336 _user_prop_fixed = fixed_eh_type(user_prop_fixed)
11337 _user_prop_final = final_eh_type(user_prop_final)
11338 _user_prop_eq = eq_eh_type(user_prop_eq)
11339 _user_prop_diseq = eq_eh_type(user_prop_diseq)
11340 
11341 
11343 
11344  #
11345  # Either solver is set or ctx is set.
11346  # Propagators that are created throuh callbacks
11347  # to "fresh" inherit the context of that is supplied
11348  # as argument to the callback.
11349  # This context should not be deleted. It is owned by the solver.
11350  #
11351  def __init__(self, s, ctx=None):
11352  assert s is None or ctx is None
11354  self.solversolver = s
11355  self._ctx_ctx = None
11356  self.cbcb = None
11357  self.idid = _prop_closures.insert(self)
11358  self.fixedfixed = None
11359  self.finalfinal = None
11360  self.eqeq = None
11361  self.diseqdiseq = None
11362  if ctx:
11363  # TBD fresh is broken: ctx is not of the right type when we reach here.
11364  self._ctx_ctx = Context()
11365  #Z3_del_context(self._ctx.ctx)
11366  #self._ctx.ctx = ctx
11367  #self._ctx.eh = Z3_set_error_handler(ctx, z3_error_handler)
11368  #Z3_set_ast_print_mode(ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
11369  if s:
11370  Z3_solver_propagate_init(self.ctx_refctx_ref(),
11371  s.solver,
11372  ctypes.c_void_p(self.idid),
11373  _user_prop_push,
11374  _user_prop_pop,
11375  _user_prop_fresh)
11376 
11377  def __del__(self):
11378  if self._ctx_ctx:
11379  self._ctx_ctx.ctx = None
11380 
11381  def ctx(self):
11382  if self._ctx_ctx:
11383  return self._ctx_ctx
11384  else:
11385  return self.solversolver.ctx
11386 
11387  def ctx_ref(self):
11388  return self.ctxctx().ref()
11389 
11390  def add_fixed(self, fixed):
11391  assert not self.fixedfixed
11392  assert not self._ctx_ctx
11393  Z3_solver_propagate_fixed(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_fixed)
11394  self.fixedfixed = fixed
11395 
11396  def add_final(self, final):
11397  assert not self.finalfinal
11398  assert not self._ctx_ctx
11399  Z3_solver_propagate_final(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_final)
11400  self.finalfinal = final
11401 
11402  def add_eq(self, eq):
11403  assert not self.eqeq
11404  assert not self._ctx_ctx
11405  Z3_solver_propagate_eq(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_eq)
11406  self.eqeq = eq
11407 
11408  def add_diseq(self, diseq):
11409  assert not self.diseqdiseq
11410  assert not self._ctx_ctx
11411  Z3_solver_propagate_diseq(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_diseq)
11412  self.diseqdiseq = diseq
11413 
11414  def push(self):
11415  raise Z3Exception("push needs to be overwritten")
11416 
11417  def pop(self, num_scopes):
11418  raise Z3Exception("pop needs to be overwritten")
11419 
11420  def fresh(self):
11421  raise Z3Exception("fresh needs to be overwritten")
11422 
11423  def add(self, e):
11424  assert self.solversolver
11425  assert not self._ctx_ctx
11426  Z3_solver_propagate_register(self.ctx_refctx_ref(), self.solversolver.solver, e.ast)
11427 
11428  #
11429  # Propagation can only be invoked as during a fixed or final callback.
11430  #
11431  def propagate(self, e, ids, eqs=[]):
11432  _ids, num_fixed = _to_ast_array(ids)
11433  num_eqs = len(eqs)
11434  _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
11435  _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
11436  Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11437  self.cbcb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11438 
11439  def conflict(self, deps):
11440  self.propagatepropagate(BoolVal(False, self.ctxctx()), deps, eqs=[])
def poly(self)
Definition: z3py.py:3101
def as_decimal(self, prec)
Definition: z3py.py:3089
def index(self)
Definition: z3py.py:3104
def approx(self, precision=10)
Definition: z3py.py:3077
def __del__(self)
Definition: z3py.py:8050
def __getitem__(self, idx)
Definition: z3py.py:8073
def __init__(self, result, ctx)
Definition: z3py.py:8042
def __len__(self)
Definition: z3py.py:8054
def as_expr(self)
Definition: z3py.py:8097
def __repr__(self)
Definition: z3py.py:8090
def sexpr(self)
Definition: z3py.py:8093
def __deepcopy__(self, memo={})
Definition: z3py.py:8047
def is_real(self)
Definition: z3py.py:2392
def __pos__(self)
Definition: z3py.py:2588
def sort(self)
Definition: z3py.py:2368
def __radd__(self, other)
Definition: z3py.py:2416
def __pow__(self, other)
Definition: z3py.py:2474
def __add__(self, other)
Definition: z3py.py:2403
def __lt__(self, other)
Definition: z3py.py:2610
def __neg__(self)
Definition: z3py.py:2577
def __rmul__(self, other)
Definition: z3py.py:2441
def __le__(self, other)
Definition: z3py.py:2597
def __mul__(self, other)
Definition: z3py.py:2426
def __mod__(self, other)
Definition: z3py.py:2550
def __rsub__(self, other)
Definition: z3py.py:2464
def __rtruediv__(self, other)
Definition: z3py.py:2546
def __rdiv__(self, other)
Definition: z3py.py:2529
def __ge__(self, other)
Definition: z3py.py:2636
def is_int(self)
Definition: z3py.py:2378
def __truediv__(self, other)
Definition: z3py.py:2525
def __gt__(self, other)
Definition: z3py.py:2623
def __sub__(self, other)
Definition: z3py.py:2451
def __rpow__(self, other)
Definition: z3py.py:2488
def __rmod__(self, other)
Definition: z3py.py:2565
def __div__(self, other)
Definition: z3py.py:2502
Arithmetic.
Definition: z3py.py:2273
def is_real(self)
Definition: z3py.py:2276
def subsort(self, other)
Definition: z3py.py:2307
def cast(self, val)
Definition: z3py.py:2311
def is_int(self)
Definition: z3py.py:2290
def is_bool(self)
Definition: z3py.py:2304
def sort(self)
Definition: z3py.py:4536
def domain_n(self, i)
Definition: z3py.py:4554
def default(self)
Definition: z3py.py:4579
def __getitem__(self, arg)
Definition: z3py.py:4567
def domain(self)
Definition: z3py.py:4545
def range(self)
Definition: z3py.py:4558
def domain_n(self, i)
Definition: z3py.py:4518
def domain(self)
Definition: z3py.py:4509
def range(self)
Definition: z3py.py:4523
def erase(self, k)
Definition: z3py.py:6073
def __del__(self)
Definition: z3py.py:6013
def reset(self)
Definition: z3py.py:6087
def __init__(self, m=None, ctx=None)
Definition: z3py.py:5999
def __len__(self)
Definition: z3py.py:6017
def keys(self)
Definition: z3py.py:6102
def __repr__(self)
Definition: z3py.py:6070
def __getitem__(self, key)
Definition: z3py.py:6043
def __deepcopy__(self, memo={})
Definition: z3py.py:6010
def __setitem__(self, k, v)
Definition: z3py.py:6054
def __contains__(self, key)
Definition: z3py.py:6030
def ctx_ref(self)
Definition: z3py.py:394
def __str__(self)
Definition: z3py.py:352
def __hash__(self)
Definition: z3py.py:361
def __nonzero__(self)
Definition: z3py.py:364
def __bool__(self)
Definition: z3py.py:367
def __del__(self)
Definition: z3py.py:344
def hash(self)
Definition: z3py.py:434
def get_id(self)
Definition: z3py.py:390
def as_ast(self)
Definition: z3py.py:386
def __repr__(self)
Definition: z3py.py:355
def __init__(self, ast, ctx=None)
Definition: z3py.py:339
def sexpr(self)
Definition: z3py.py:377
def translate(self, target)
Definition: z3py.py:415
def __deepcopy__(self, memo={})
Definition: z3py.py:349
def __copy__(self)
Definition: z3py.py:431
def __eq__(self, other)
Definition: z3py.py:358
def eq(self, other)
Definition: z3py.py:398
def __contains__(self, item)
Definition: z3py.py:5937
def resize(self, sz)
Definition: z3py.py:5924
def __del__(self)
Definition: z3py.py:5850
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5839
def __setitem__(self, i, v)
Definition: z3py.py:5896
def push(self, v)
Definition: z3py.py:5912
def __len__(self)
Definition: z3py.py:5854
def translate(self, other_ctx)
Definition: z3py.py:5960
def __repr__(self)
Definition: z3py.py:5982
def sexpr(self)
Definition: z3py.py:5985
def __deepcopy__(self, memo={})
Definition: z3py.py:5979
def __copy__(self)
Definition: z3py.py:5976
def __getitem__(self, i)
Definition: z3py.py:5867
def as_signed_long(self)
Definition: z3py.py:3899
def as_long(self)
Definition: z3py.py:3888
def as_binary_string(self)
Definition: z3py.py:3925
def as_string(self)
Definition: z3py.py:3922
def __rlshift__(self, other)
Definition: z3py.py:3870
def __pos__(self)
Definition: z3py.py:3635
def sort(self)
Definition: z3py.py:3475
def __radd__(self, other)
Definition: z3py.py:3510
def __rxor__(self, other)
Definition: z3py.py:3625
def __xor__(self, other)
Definition: z3py.py:3612
def __ror__(self, other)
Definition: z3py.py:3579
def __add__(self, other)
Definition: z3py.py:3497
def __rshift__(self, other)
Definition: z3py.py:3812
def __lt__(self, other)
Definition: z3py.py:3764
def __or__(self, other)
Definition: z3py.py:3566
def size(self)
Definition: z3py.py:3486
def __neg__(self)
Definition: z3py.py:3644
def __rand__(self, other)
Definition: z3py.py:3602
def __rmul__(self, other)
Definition: z3py.py:3533
def __le__(self, other)
Definition: z3py.py:3748
def __mul__(self, other)
Definition: z3py.py:3520
def __mod__(self, other)
Definition: z3py.py:3709
def __rsub__(self, other)
Definition: z3py.py:3556
def __invert__(self)
Definition: z3py.py:3655
def __rtruediv__(self, other)
Definition: z3py.py:3705
def __rdiv__(self, other)
Definition: z3py.py:3689
def __lshift__(self, other)
Definition: z3py.py:3842
def __ge__(self, other)
Definition: z3py.py:3796
def __and__(self, other)
Definition: z3py.py:3589
def __rrshift__(self, other)
Definition: z3py.py:3856
def __truediv__(self, other)
Definition: z3py.py:3685
def __gt__(self, other)
Definition: z3py.py:3780
def __sub__(self, other)
Definition: z3py.py:3543
def __rmod__(self, other)
Definition: z3py.py:3730
def __div__(self, other)
Definition: z3py.py:3666
Bit-Vectors.
Definition: z3py.py:3428
def subsort(self, other)
Definition: z3py.py:3440
def size(self)
Definition: z3py.py:3431
def cast(self, val)
Definition: z3py.py:3443
def sort(self)
Definition: z3py.py:1540
def __rmul__(self, other)
Definition: z3py.py:1543
def __mul__(self, other)
Definition: z3py.py:1546
Booleans.
Definition: z3py.py:1501
def subsort(self, other)
Definition: z3py.py:1527
def cast(self, val)
Definition: z3py.py:1504
def is_int(self)
Definition: z3py.py:1530
def is_bool(self)
Definition: z3py.py:1533
def to_int(self)
Definition: z3py.py:10741
def is_digit(self)
Definition: z3py.py:10747
def __le__(self, other)
Definition: z3py.py:10737
def to_bv(self)
Definition: z3py.py:10744
def __repr__(self)
Definition: z3py.py:6831
def __ne__(self, other)
Definition: z3py.py:6828
def __init__(self, r)
Definition: z3py.py:6819
def __deepcopy__(self, memo={})
Definition: z3py.py:6822
def __eq__(self, other)
Definition: z3py.py:6825
def interrupt(self)
Definition: z3py.py:220
def __init__(self, *args, **kws)
Definition: z3py.py:192
def __del__(self)
Definition: z3py.py:211
def ref(self)
Definition: z3py.py:216
def create(self)
Definition: z3py.py:5102
def __init__(self, name, ctx=None)
Definition: z3py.py:5058
def declare(self, name, *args)
Definition: z3py.py:5078
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:5068
def __repr__(self)
Definition: z3py.py:5099
def __deepcopy__(self, memo={})
Definition: z3py.py:5063
def sort(self)
Definition: z3py.py:5339
def recognizer(self, idx)
Definition: z3py.py:5274
def num_constructors(self)
Definition: z3py.py:5242
def constructor(self, idx)
Definition: z3py.py:5255
def accessor(self, i, j)
Definition: z3py.py:5302
Expressions.
Definition: z3py.py:955
def params(self)
Definition: z3py.py:1034
def sort(self)
Definition: z3py.py:972
def __hash__(self)
Definition: z3py.py:1012
def from_string(self, s)
Definition: z3py.py:1104
def get_id(self)
Definition: z3py.py:969
def children(self)
Definition: z3py.py:1089
def as_ast(self)
Definition: z3py.py:966
def decl(self)
Definition: z3py.py:1037
def __ne__(self, other)
Definition: z3py.py:1016
def serialize(self)
Definition: z3py.py:1107
def num_args(self)
Definition: z3py.py:1052
def arg(self, idx)
Definition: z3py.py:1068
def sort_kind(self)
Definition: z3py.py:984
def __eq__(self, other)
Definition: z3py.py:995
def isNormal(self)
Definition: z3py.py:9744
def exponent(self, biased=True)
Definition: z3py.py:9703
def significand(self)
Definition: z3py.py:9672
def sign_as_bv(self)
Definition: z3py.py:9662
def isNegative(self)
Definition: z3py.py:9759
def significand_as_bv(self)
Definition: z3py.py:9693
def exponent_as_long(self, biased=True)
Definition: z3py.py:9713
def isInf(self)
Definition: z3py.py:9734
def isNaN(self)
Definition: z3py.py:9729
def sign(self)
Definition: z3py.py:9650
def isZero(self)
Definition: z3py.py:9739
def significand_as_long(self)
Definition: z3py.py:9682
def isSubnormal(self)
Definition: z3py.py:9749
def isPositive(self)
Definition: z3py.py:9754
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9724
def as_string(self)
Definition: z3py.py:9770
def as_string(self)
Definition: z3py.py:9564
def __pos__(self)
Definition: z3py.py:9503
def sort(self)
Definition: z3py.py:9386
def __radd__(self, other)
Definition: z3py.py:9442
def __add__(self, other)
Definition: z3py.py:9429
def sbits(self)
Definition: z3py.py:9405
def __lt__(self, other)
Definition: z3py.py:9420
def __neg__(self)
Definition: z3py.py:9507
def ebits(self)
Definition: z3py.py:9397
def __rmul__(self, other)
Definition: z3py.py:9490
def __le__(self, other)
Definition: z3py.py:9417
def __mul__(self, other)
Definition: z3py.py:9475
def __mod__(self, other)
Definition: z3py.py:9552
def __rsub__(self, other)
Definition: z3py.py:9465
def __rtruediv__(self, other)
Definition: z3py.py:9548
def __rdiv__(self, other)
Definition: z3py.py:9531
def __ge__(self, other)
Definition: z3py.py:9423
def __truediv__(self, other)
Definition: z3py.py:9544
def __gt__(self, other)
Definition: z3py.py:9426
def __sub__(self, other)
Definition: z3py.py:9452
def as_string(self)
Definition: z3py.py:9413
def __rmod__(self, other)
Definition: z3py.py:9556
def __div__(self, other)
Definition: z3py.py:9516
def sbits(self)
Definition: z3py.py:9283
def ebits(self)
Definition: z3py.py:9275
def cast(self, val)
Definition: z3py.py:9291
def as_long(self)
Definition: z3py.py:7710
def as_string(self)
Definition: z3py.py:7722
def sort(self)
Definition: z3py.py:7685
def as_string(self)
Definition: z3py.py:7689
Fixedpoint.
Definition: z3py.py:7385
def insert(self, *args)
Definition: z3py.py:7446
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7636
def fact(self, head, name=None)
Definition: z3py.py:7477
def reason_unknown(self)
Definition: z3py.py:7622
def rule(self, head, body=None, name=None)
Definition: z3py.py:7473
def to_string(self, queries)
Definition: z3py.py:7609
def add_cover(self, level, predicate, property)
Definition: z3py.py:7561
def add(self, *args)
Definition: z3py.py:7434
def __del__(self)
Definition: z3py.py:7402
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7450
def param_descrs(self)
Definition: z3py.py:7416
def assert_exprs(self, *args)
Definition: z3py.py:7420
def get_answer(self)
Definition: z3py.py:7528
def statistics(self)
Definition: z3py.py:7617
def update_rule(self, head, body, name)
Definition: z3py.py:7519
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7503
def append(self, *args)
Definition: z3py.py:7442
def query(self, *query)
Definition: z3py.py:7481
def parse_string(self, s)
Definition: z3py.py:7583
def help(self)
Definition: z3py.py:7412
def get_rules_along_trace(self)
Definition: z3py.py:7538
def get_ground_sat_answer(self)
Definition: z3py.py:7533
def __repr__(self)
Definition: z3py.py:7599
def get_rules(self)
Definition: z3py.py:7591
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7573
def sexpr(self)
Definition: z3py.py:7603
def get_assertions(self)
Definition: z3py.py:7595
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7554
def __deepcopy__(self, memo={})
Definition: z3py.py:7399
def get_num_levels(self, predicate)
Definition: z3py.py:7550
def declare_var(self, *vars)
Definition: z3py.py:7627
def parse_file(self, f)
Definition: z3py.py:7587
def set(self, *args, **keys)
Definition: z3py.py:7406
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:7388
def register_relation(self, *relations)
Definition: z3py.py:7567
def get_rule_names_along_trace(self)
Definition: z3py.py:7542
def __iadd__(self, fml)
Definition: z3py.py:7438
Function Declarations.
Definition: z3py.py:712
def params(self)
Definition: z3py.py:787
def get_id(self)
Definition: z3py.py:723
def name(self)
Definition: z3py.py:729
def __call__(self, *args)
Definition: z3py.py:811
def arity(self)
Definition: z3py.py:740
def kind(self)
Definition: z3py.py:774
def as_ast(self)
Definition: z3py.py:720
def as_func_decl(self)
Definition: z3py.py:726
def domain(self, i)
Definition: z3py.py:750
def range(self)
Definition: z3py.py:764
Definition: z3py.py:6121
def __del__(self)
Definition: z3py.py:6132
ctx
Definition: z3py.py:6126
def value(self)
Definition: z3py.py:6185
def __init__(self, entry, ctx)
Definition: z3py.py:6124
def arg_value(self, idx)
Definition: z3py.py:6154
entry
Definition: z3py.py:6125
def __repr__(self)
Definition: z3py.py:6226
def num_args(self)
Definition: z3py.py:6136
def __deepcopy__(self, memo={})
Definition: z3py.py:6129
def as_list(self)
Definition: z3py.py:6207
def __del__(self)
Definition: z3py.py:6239
def arity(self)
Definition: z3py.py:6282
def __init__(self, f, ctx)
Definition: z3py.py:6233
def translate(self, other_ctx)
Definition: z3py.py:6316
def __repr__(self)
Definition: z3py.py:6344
def num_entries(self)
Definition: z3py.py:6266
def __deepcopy__(self, memo={})
Definition: z3py.py:6324
def else_value(self)
Definition: z3py.py:6243
def __copy__(self)
Definition: z3py.py:6321
def as_list(self)
Definition: z3py.py:6327
def entry(self, idx)
Definition: z3py.py:6296
def insert(self, *args)
Definition: z3py.py:5696
def dimacs(self, include_names=True)
Definition: z3py.py:5754
def get(self, i)
Definition: z3py.py:5642
def depth(self)
Definition: z3py.py:5550
def convert_model(self, model)
Definition: z3py.py:5718
def add(self, *args)
Definition: z3py.py:5707
def __del__(self)
Definition: z3py.py:5546
def assert_exprs(self, *args)
Definition: z3py.py:5670
def __getitem__(self, arg)
Definition: z3py.py:5655
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5536
def size(self)
Definition: z3py.py:5616
def append(self, *args)
Definition: z3py.py:5685
def __len__(self)
Definition: z3py.py:5629
def as_expr(self)
Definition: z3py.py:5807
def __repr__(self)
Definition: z3py.py:5747
def sexpr(self)
Definition: z3py.py:5750
def precision(self)
Definition: z3py.py:5607
def translate(self, target)
Definition: z3py.py:5758
def __deepcopy__(self, memo={})
Definition: z3py.py:5784
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5787
def __copy__(self)
Definition: z3py.py:5781
def inconsistent(self)
Definition: z3py.py:5568
def prec(self)
Definition: z3py.py:5586
def as_long(self)
Definition: z3py.py:2947
def as_binary_string(self)
Definition: z3py.py:2968
def as_string(self)
Definition: z3py.py:2960
def decls(self)
Definition: z3py.py:6596
def get_universe(self, s)
Definition: z3py.py:6531
def __del__(self)
Definition: z3py.py:6357
def eval(self, t, model_completion=False)
Definition: z3py.py:6368
def __init__(self, m, ctx)
Definition: z3py.py:6351
def sorts(self)
Definition: z3py.py:6514
def __getitem__(self, idx)
Definition: z3py.py:6551
def __len__(self)
Definition: z3py.py:6425
def update_value(self, x, value)
Definition: z3py.py:6615
def num_sorts(self)
Definition: z3py.py:6476
def __repr__(self)
Definition: z3py.py:6361
def sexpr(self)
Definition: z3py.py:6364
def translate(self, target)
Definition: z3py.py:6637
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6399
def __deepcopy__(self, memo={})
Definition: z3py.py:6648
def __copy__(self)
Definition: z3py.py:6645
def get_interp(self, decl)
Definition: z3py.py:6442
def get_sort(self, idx)
Definition: z3py.py:6491
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7895
def reason_unknown(self)
Definition: z3py.py:7952
def objectives(self)
Definition: z3py.py:7998
def pop(self)
Definition: z3py.py:7939
def maximize(self, arg)
Definition: z3py.py:7919
def unsat_core(self)
Definition: z3py.py:7963
def from_string(self, s)
Definition: z3py.py:7990
def add(self, *args)
Definition: z3py.py:7858
def __del__(self)
Definition: z3py.py:7825
def param_descrs(self)
Definition: z3py.py:7842
def assert_exprs(self, *args)
Definition: z3py.py:7846
def model(self)
Definition: z3py.py:7956
def statistics(self)
Definition: z3py.py:8012
def help(self)
Definition: z3py.py:7838
def upper_values(self, obj)
Definition: z3py.py:7981
def __repr__(self)
Definition: z3py.py:8002
def from_file(self, filename)
Definition: z3py.py:7986
def set_on_model(self, on_model)
Definition: z3py.py:8017
def sexpr(self)
Definition: z3py.py:8006
def check(self, *assumptions)
Definition: z3py.py:7943
def push(self)
Definition: z3py.py:7935
def __deepcopy__(self, memo={})
Definition: z3py.py:7822
def minimize(self, arg)
Definition: z3py.py:7927
def lower(self, obj)
Definition: z3py.py:7966
def assert_and_track(self, a, p)
Definition: z3py.py:7866
def set(self, *args, **keys)
Definition: z3py.py:7831
def upper(self, obj)
Definition: z3py.py:7971
def lower_values(self, obj)
Definition: z3py.py:7976
def __init__(self, ctx=None)
Definition: z3py.py:7816
def assertions(self)
Definition: z3py.py:7994
def __iadd__(self, fml)
Definition: z3py.py:7862
def __str__(self)
Definition: z3py.py:7798
def upper(self)
Definition: z3py.py:7780
def value(self)
Definition: z3py.py:7792
def lower_values(self)
Definition: z3py.py:7784
def __init__(self, opt, value, is_max)
Definition: z3py.py:7771
def lower(self)
Definition: z3py.py:7776
def upper_values(self)
Definition: z3py.py:7788
def get_name(self, i)
Definition: z3py.py:5497
def get_kind(self, n)
Definition: z3py.py:5502
def __del__(self)
Definition: z3py.py:5483
def __getitem__(self, arg)
Definition: z3py.py:5512
def size(self)
Definition: z3py.py:5487
def __init__(self, descr, ctx=None)
Definition: z3py.py:5474
def __len__(self)
Definition: z3py.py:5492
def __repr__(self)
Definition: z3py.py:5518
def get_documentation(self, n)
Definition: z3py.py:5507
def __deepcopy__(self, memo={})
Definition: z3py.py:5480
Parameter Sets.
Definition: z3py.py:5401
def validate(self, ds)
Definition: z3py.py:5442
def __del__(self)
Definition: z3py.py:5418
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5407
def __repr__(self)
Definition: z3py.py:5439
def __deepcopy__(self, memo={})
Definition: z3py.py:5415
def set(self, name, val)
Definition: z3py.py:5422
Patterns.
Definition: z3py.py:1906
def get_id(self)
Definition: z3py.py:1914
def as_ast(self)
Definition: z3py.py:1911
def __del__(self)
Definition: z3py.py:8466
def __call__(self, goal)
Definition: z3py.py:8555
def __lt__(self, other)
Definition: z3py.py:8470
def __le__(self, other)
Definition: z3py.py:8498
def __init__(self, probe, ctx=None)
Definition: z3py.py:8440
def __ne__(self, other)
Definition: z3py.py:8540
def __ge__(self, other)
Definition: z3py.py:8512
def __deepcopy__(self, memo={})
Definition: z3py.py:8463
def __eq__(self, other)
Definition: z3py.py:8526
def __gt__(self, other)
Definition: z3py.py:8484
def set(self, ctx, r)
Definition: z3py.py:11251
def insert(self, r)
Definition: z3py.py:11258
def set_threaded(self)
Definition: z3py.py:11238
def get(self, ctx)
Definition: z3py.py:11243
def __init__(self)
Definition: z3py.py:11234
Quantifiers.
Definition: z3py.py:1973
def pattern(self, idx)
Definition: z3py.py:2063
def sort(self)
Definition: z3py.py:1982
def var_name(self, idx)
Definition: z3py.py:2114
def no_pattern(self, idx)
Definition: z3py.py:2085
def is_forall(self)
Definition: z3py.py:1988
def num_no_patterns(self)
Definition: z3py.py:2081
def body(self)
Definition: z3py.py:2091
def num_vars(self)
Definition: z3py.py:2102
def get_id(self)
Definition: z3py.py:1979
def __getitem__(self, arg)
Definition: z3py.py:2030
def children(self)
Definition: z3py.py:2146
def weight(self)
Definition: z3py.py:2037
def is_lambda(self)
Definition: z3py.py:2016
def as_ast(self)
Definition: z3py.py:1976
def var_sort(self, idx)
Definition: z3py.py:2130
def num_patterns(self)
Definition: z3py.py:2051
def is_exists(self)
Definition: z3py.py:2002
def is_real(self)
Definition: z3py.py:3033
def as_decimal(self, prec)
Definition: z3py.py:3043
def as_fraction(self)
Definition: z3py.py:3064
def is_int_value(self)
Definition: z3py.py:3036
def numerator_as_long(self)
Definition: z3py.py:3006
def as_long(self)
Definition: z3py.py:3039
def denominator(self)
Definition: z3py.py:2995
def denominator_as_long(self)
Definition: z3py.py:3019
def is_int(self)
Definition: z3py.py:3030
def numerator(self)
Definition: z3py.py:2980
def as_string(self)
Definition: z3py.py:3055
def __add__(self, other)
Definition: z3py.py:11067
def basis(self)
Definition: z3py.py:11051
def __del__(self)
Definition: z3py.py:5126
def __init__(self, c, ctx)
Definition: z3py.py:5122
def __init__(self, c, ctx)
Definition: z3py.py:5134
def sort(self)
Definition: z3py.py:10680
def __radd__(self, other)
Definition: z3py.py:10686
def at(self, i)
Definition: z3py.py:10694
def __add__(self, other)
Definition: z3py.py:10683
def __lt__(self, other)
Definition: z3py.py:10716
def is_string_value(self)
Definition: z3py.py:10702
def __le__(self, other)
Definition: z3py.py:10713
def __ge__(self, other)
Definition: z3py.py:10719
def __gt__(self, other)
Definition: z3py.py:10722
def is_string(self)
Definition: z3py.py:10699
def as_string(self)
Definition: z3py.py:10705
def __getitem__(self, i)
Definition: z3py.py:10689
Strings, Sequences and Regular expressions.
Definition: z3py.py:10628
def basis(self)
Definition: z3py.py:10642
def is_string(self)
Definition: z3py.py:10631
def insert(self, *args)
Definition: z3py.py:7017
def dimacs(self, include_names=True)
Definition: z3py.py:7322
def non_units(self)
Definition: z3py.py:7230
def reason_unknown(self)
Definition: z3py.py:7266
backtrack_level
Definition: z3py.py:6869
def num_scopes(self)
Definition: z3py.py:6940
def unsat_core(self)
Definition: z3py.py:7110
def trail_levels(self)
Definition: z3py.py:7235
def trail(self)
Definition: z3py.py:7243
def from_string(self, s)
Definition: z3py.py:7175
def add(self, *args)
Definition: z3py.py:6991
def __del__(self)
Definition: z3py.py:6879
def import_model_converter(self, other)
Definition: z3py.py:7106
def param_descrs(self)
Definition: z3py.py:7283
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6866
def reset(self)
Definition: z3py.py:6958
def assert_exprs(self, *args)
Definition: z3py.py:6972
def pop(self, num=1)
Definition: z3py.py:6918
def units(self)
Definition: z3py.py:7225
def cube(self, vars=None)
Definition: z3py.py:7179
def cube_vars(self)
Definition: z3py.py:7200
def model(self)
Definition: z3py.py:7087
def statistics(self)
Definition: z3py.py:7248
def append(self, *args)
Definition: z3py.py:7006
def to_smt2(self)
Definition: z3py.py:7326
def help(self)
Definition: z3py.py:7279
def __repr__(self)
Definition: z3py.py:7287
def from_file(self, filename)
Definition: z3py.py:7171
def proof(self)
Definition: z3py.py:7207
def sexpr(self)
Definition: z3py.py:7310
def check(self, *assumptions)
Definition: z3py.py:7058
def translate(self, target)
Definition: z3py.py:7291
def push(self)
Definition: z3py.py:6896
def __deepcopy__(self, memo={})
Definition: z3py.py:7307
def consequences(self, assumptions, variables)
Definition: z3py.py:7142
def assert_and_track(self, a, p)
Definition: z3py.py:7028
def set(self, *args, **keys)
Definition: z3py.py:6883
def __copy__(self)
Definition: z3py.py:7304
def assertions(self)
Definition: z3py.py:7211
def __iadd__(self, fml)
Definition: z3py.py:7002
def __hash__(self)
Definition: z3py.py:636
def subsort(self, other)
Definition: z3py.py:579
def get_id(self)
Definition: z3py.py:559
def name(self)
Definition: z3py.py:602
def kind(self)
Definition: z3py.py:562
def as_ast(self)
Definition: z3py.py:556
def __ne__(self, other)
Definition: z3py.py:625
def cast(self, val)
Definition: z3py.py:587
def __eq__(self, other)
Definition: z3py.py:612
Statistics.
Definition: z3py.py:6675
def __getattr__(self, name)
Definition: z3py.py:6778
def __del__(self)
Definition: z3py.py:6686
def __getitem__(self, idx)
Definition: z3py.py:6722
def __len__(self)
Definition: z3py.py:6708
def keys(self)
Definition: z3py.py:6746
def __init__(self, stats, ctx)
Definition: z3py.py:6678
def __repr__(self)
Definition: z3py.py:6690
def get_key_value(self, key)
Definition: z3py.py:6758
def __deepcopy__(self, memo={})
Definition: z3py.py:6683
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:8193
def __del__(self)
Definition: z3py.py:8155
def param_descrs(self)
Definition: z3py.py:8207
def solver(self, logFile=None)
Definition: z3py.py:8159
def __init__(self, tactic, ctx=None)
Definition: z3py.py:8138
def help(self)
Definition: z3py.py:8203
def __deepcopy__(self, memo={})
Definition: z3py.py:8152
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:8176
def ctx_ref(self)
Definition: z3py.py:11387
def add_fixed(self, fixed)
Definition: z3py.py:11390
def conflict(self, deps)
Definition: z3py.py:11439
def __del__(self)
Definition: z3py.py:11377
def add_diseq(self, diseq)
Definition: z3py.py:11408
def pop(self, num_scopes)
Definition: z3py.py:11417
def add_eq(self, eq)
Definition: z3py.py:11402
def add(self, e)
Definition: z3py.py:11423
def __init__(self, s, ctx=None)
Definition: z3py.py:11351
def propagate(self, e, ids, eqs=[])
Definition: z3py.py:11431
def add_final(self, final)
Definition: z3py.py:11396
ASTs base class.
Definition: z3py.py:322
def use_pp(self)
Definition: z3py.py:325
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
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_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
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.
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
Z3_ast Z3_API Z3_mk_char_to_bv(Z3_context c, Z3_ast ch)
Create a bit-vector (code point) from character.
void Z3_API Z3_solver_propagate_diseq(Z3_context c, Z3_solver s, Z3_eq_eh eq_eh)
register a callback on expression dis-equalities.
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
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.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
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:
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 ...
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
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.
Z3_sort Z3_API Z3_mk_char_sort(Z3_context c)
Create a sort for unicode characters.
Z3_ast Z3_API Z3_mk_re_option(Z3_context c, Z3_ast re)
Create the regular language [re].
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
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....
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].
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_mk_fpa_to_fp_bv(Z3_context c, Z3_ast bv, Z3_sort s)
Conversion of a single IEEE 754-2008 bit-vector into a floating-point number.
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_ast Z3_API Z3_mk_seq_replace(Z3_context c, Z3_ast s, Z3_ast src, Z3_ast dst)
Replace the first occurrence of src with dst in s.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_ast Z3_API Z3_mk_str_le(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is equal or lexicographically strictly less than s2.
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_ast Z3_API Z3_mk_fpa_to_ieee_bv(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
Z3_lbool Z3_API Z3_solver_get_consequences(Z3_context c, Z3_solver s, Z3_ast_vector assumptions, Z3_ast_vector variables, Z3_ast_vector consequences)
retrieve consequences from solver that determine values of the supplied function symbols.
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....
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
Z3_ast Z3_API Z3_mk_char_le(Z3_context c, Z3_ast ch1, Z3_ast ch2)
Create less than or equal to between two characters.
Z3_ast Z3_API Z3_mk_fpa_to_fp_signed(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort.
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
Z3_param_descrs Z3_API Z3_solver_get_param_descrs(Z3_context c, Z3_solver s)
Return the parameter description set for the given solver object.
Z3_ast Z3_API Z3_mk_fpa_to_sbv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into a signed bit-vector.
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
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'th optimization objective.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
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.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
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.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_string_from_code(Z3_context c, Z3_ast a)
Code to string conversion.
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives....
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
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....
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.
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
Z3_ast Z3_API Z3_mk_seq_length(Z3_context c, Z3_ast s)
Return the length of the sequence s.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
Z3_sort Z3_API Z3_get_seq_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for sequence sort.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
bool Z3_API Z3_fpa_get_numeral_sign(Z3_context c, Z3_ast t, int *sgn)
Retrieves the sign of a floating-point literal.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
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...
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
Z3_ast Z3_API Z3_mk_str_to_int(Z3_context c, Z3_ast s)
Convert string to integer.
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_ast Z3_API Z3_mk_re_allchar(Z3_context c, Z3_sort regex_sort)
Create a regular expression that accepts all singleton sequences of the regular expression sort.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
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....
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_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
Z3_ast Z3_API Z3_mk_fpa_to_ubv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into an unsigned bit-vector.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_ast Z3_API Z3_mk_seq_at(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the unit sequence positioned at position index. The sequence is empty if the index is...
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_ast Z3_API Z3_mk_re_complement(Z3_context c, Z3_ast re)
Create the complement of the regular language re.
Z3_sort Z3_API Z3_mk_fpa_sort_half(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
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....
unsigned Z3_API Z3_fpa_get_ebits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the exponent in a FloatingPoint sort.
Z3_ast_vector Z3_API Z3_solver_get_assertions(Z3_context c, Z3_solver s)
Return the set of asserted formulas on the solver.
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
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.
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
bool Z3_API Z3_fpa_is_numeral_positive(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is positive.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_char_ptr Z3_API Z3_get_lstring(Z3_context c, Z3_ast s, unsigned *length)
Retrieve the string constant stored in s. The string can contain escape sequences....
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
bool Z3_API Z3_fpa_get_numeral_exponent_int64(Z3_context c, Z3_ast t, int64_t *n, bool biased)
Return the exponent value of a floating-point numeral as a signed 64-bit integer.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
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.
bool Z3_API Z3_fpa_is_numeral_nan(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a NaN.
unsigned Z3_API Z3_fpa_get_sbits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the significand in a FloatingPoint sort.
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective. The returned vector ...
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort_opt const sorts[], unsigned sort_refs[])
Create a constructor.
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.
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_fpa_round_toward_negative(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardNegative rounding mode.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
void Z3_API Z3_optimize_assert_and_track(Z3_context c, Z3_optimize o, Z3_ast a, Z3_ast t)
Assert tracked hard constraint to the optimization context.
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.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_ast Z3_API Z3_mk_fpa_to_fp_real(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a term of real sort into a term of FloatingPoint sort.
Z3_ast_vector Z3_API Z3_solver_get_trail(Z3_context c, Z3_solver s)
Return the trail modulo model conversion, in order of decision level The decision level can be retrie...
bool Z3_API Z3_fpa_get_numeral_significand_uint64(Z3_context c, Z3_ast t, uint64_t *n)
Return the significand value of a floating-point numeral as a uint64.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
Z3_func_decl Z3_API Z3_mk_tree_order(Z3_context c, Z3_sort a, unsigned id)
create a tree ordering relation over signature a identified using index id.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a)
The (_ as-array f) AST node is a construct for assigning interpretations for arrays in Z3....
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.
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...
Z3_ast Z3_API Z3_mk_is_int(Z3_context c, Z3_ast t1)
Check if a real number is an integer.
void Z3_API Z3_params_set_bool(Z3_context c, Z3_params p, Z3_symbol k, bool v)
Add a Boolean parameter k with value v to the parameter set p.
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.
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_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i)
Array read. The argument a is the array and i is the index of the array that gets read.
Z3_ast Z3_API Z3_mk_sign_ext(Z3_context c, unsigned i, Z3_ast t1)
Sign-extend of the given bit-vector to the (signed) equivalent bit-vector of size m+i,...
Z3_ast Z3_API Z3_mk_seq_unit(Z3_context c, Z3_ast a)
Create a unit sequence of a.
Z3_ast Z3_API Z3_mk_re_intersect(Z3_context c, unsigned n, Z3_ast const args[])
Create the intersection of the regular languages.
Z3_ast_vector Z3_API Z3_solver_cube(Z3_context c, Z3_solver s, Z3_ast_vector vars, unsigned backtrack_level)
extract a next cube for a solver. The last cube is the constant true or false. The number of (non-con...
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
bool Z3_API Z3_is_string_sort(Z3_context c, Z3_sort s)
Check if s is a string sort.
Z3_string Z3_API Z3_fpa_get_numeral_exponent_string(Z3_context c, Z3_ast t, bool biased)
Return the exponent value of a floating-point numeral as a string.
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
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.
Z3_sort Z3_API Z3_mk_re_sort(Z3_context c, Z3_sort seq)
Create a regular expression sort out of a sequence sort.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_ast Z3_API Z3_mk_fpa_inf(Z3_context c, Z3_sort s, bool negative)
Create a floating-point infinity of sort s.
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
Z3_func_decl Z3_API Z3_mk_piecewise_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a piecewise linear ordering relation over signature a and index id.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
Z3_ast Z3_API Z3_mk_fpa_nan(Z3_context c, Z3_sort s)
Create a floating-point NaN of sort s.
bool Z3_API Z3_fpa_is_numeral_subnormal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is subnormal.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
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'th optimization objective.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_sort Z3_API Z3_get_array_sort_domain_n(Z3_context c, Z3_sort t, unsigned idx)
Return the i'th domain sort of an n-dimensional array.
void Z3_API Z3_solver_import_model_converter(Z3_context ctx, Z3_solver src, Z3_solver dst)
Ad-hoc method for importing model conversion from solver.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_re_union(Z3_context c, unsigned n, Z3_ast const args[])
Create the union of the regular languages.
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_ast Z3_API Z3_mk_fpa_round_toward_positive(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardPositive rounding mode.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
Z3_ast Z3_API Z3_mk_seq_empty(Z3_context c, Z3_sort seq)
Create an empty sequence of the sequence sort seq.
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 ...
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
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_seq_suffix(Z3_context c, Z3_ast suffix, Z3_ast s)
Check if suffix is a suffix of s.
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
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_sort Z3_API Z3_get_re_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for regex sort.
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
Z3_solver Z3_API Z3_solver_translate(Z3_context source, Z3_solver s, Z3_context target)
Copy a solver s from the context source to the context target.
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_string Z3_API Z3_solver_get_help(Z3_context c, Z3_solver s)
Return a string describing all solver available parameters.
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
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.
Z3_sort Z3_API Z3_mk_fpa_sort_16(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
void Z3_API Z3_add_const_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast a)
Add a constant interpretation.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a)
Return which root of the polynomial the algebraic number represents.
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
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.
Z3_ast Z3_API Z3_mk_str_lt(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is lexicographically strictly less than s2.
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
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.
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
void Z3_API Z3_solver_propagate_final(Z3_context c, Z3_solver s, Z3_final_eh final_eh)
register a callback on final check. This provides freedom to the propagator to delay actions or imple...
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
Z3_ast_vector Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Parse the given string using the SMT-LIB2 parser.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast_vector Z3_API Z3_solver_get_non_units(Z3_context c, Z3_solver s)
Return the set of non units in the solver state.
Z3_ast Z3_API Z3_mk_seq_to_re(Z3_context c, Z3_ast seq)
Create a regular expression that accepts the sequence seq.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
Z3_ast Z3_API Z3_mk_seq_index(Z3_context c, Z3_ast s, Z3_ast substr, Z3_ast offset)
Return index of the first occurrence of substr in s starting from offset offset. If s does not contai...
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
Z3_ast Z3_API Z3_mk_re_range(Z3_context c, Z3_ast lo, Z3_ast hi)
Create the range regular expression over two sequences of length 1.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
Z3_ast Z3_API Z3_fpa_get_numeral_significand_bv(Z3_context c, Z3_ast t)
Retrieves the significand of a floating-point literal as a bit-vector expression.
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.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
Z3_sort Z3_API Z3_mk_fpa_sort_quadruple(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_ast Z3_API Z3_mk_seq_prefix(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if prefix is a prefix of s.
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_away(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
void Z3_API Z3_solver_propagate_init(Z3_context c, Z3_solver s, void *user_context, Z3_push_eh push_eh, Z3_pop_eh pop_eh, Z3_fresh_eh fresh_eh)
register a user-properator with the solver.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
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...
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
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_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.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
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.
Z3_ast Z3_API Z3_mk_re_star(Z3_context c, Z3_ast re)
Create the regular language re*.
Z3_ast Z3_API Z3_mk_char(Z3_context c, unsigned ch)
Create a character literal.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_ast Z3_API Z3_mk_re_full(Z3_context c, Z3_sort re)
Create an universal regular expression of sort re.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_ast Z3_API Z3_mk_re_diff(Z3_context c, Z3_ast re1, Z3_ast re2)
Create the difference of regular expressions.
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate.
Z3_ast Z3_API Z3_mk_fpa_to_real(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a real-numbered term.
Z3_ast Z3_API Z3_mk_re_empty(Z3_context c, Z3_sort re)
Create an empty regular expression of sort re.
void Z3_API Z3_solver_from_string(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a string.
Z3_sort Z3_API Z3_mk_fpa_sort_128(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
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].
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast_vector Z3_API Z3_parse_smtlib2_file(Z3_context c, Z3_string file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Similar to Z3_parse_smtlib2_string, but reads the benchmark from a file.
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
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...
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
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.
void Z3_API Z3_solver_get_levels(Z3_context c, Z3_solver s, Z3_ast_vector literals, unsigned sz, unsigned levels[])
retrieve the decision depth of Boolean literals (variables or their negations). Assumes a check-sat c...
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
Z3_ast Z3_API Z3_mk_fpa_to_fp_unsigned(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement unsigned bit-vector term into a term of FloatingPoint sort.
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.
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
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_ast Z3_API Z3_mk_fpa_abs(Z3_context c, Z3_ast t)
Floating-point absolute value.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
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_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
void Z3_API Z3_solver_propagate_consequence(Z3_context c, Z3_solver_callback, unsigned num_fixed, Z3_ast const *fixed, unsigned num_eqs, Z3_ast const *eq_lhs, Z3_ast const *eq_rhs, Z3_ast conseq)
propagate a consequence based on fixed values. This is a callback a client may invoke during the fixe...
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
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_...
Z3_ast_vector Z3_API Z3_solver_get_unsat_core(Z3_context c, Z3_solver s)
Retrieve the unsat core for the last Z3_solver_check_assumptions The unsat core is a subset of the as...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
Z3_ast Z3_API Z3_mk_fpa_fp(Z3_context c, Z3_ast sgn, Z3_ast exp, Z3_ast sig)
Create an expression of FloatingPoint sort from three bit-vector expressions.
Z3_func_decl Z3_API Z3_mk_partial_order(Z3_context c, Z3_sort a, unsigned id)
create a partial ordering relation over signature a and index id.
Z3_ast Z3_API Z3_fpa_get_numeral_exponent_bv(Z3_context c, Z3_ast t, bool biased)
Retrieves the exponent of a floating-point literal as a bit-vector expression.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_sort Z3_API Z3_mk_fpa_sort_single(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_set_has_size(Z3_context c, Z3_ast set, Z3_ast k)
Create predicate that holds if Boolean array set has k elements set to true.
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
bool Z3_API Z3_is_string(Z3_context c, Z3_ast s)
Determine if s is a string constant.
Z3_ast Z3_API Z3_mk_re_loop(Z3_context c, Z3_ast r, unsigned lo, unsigned hi)
Create a regular expression loop. The supplied regular expression r is repeated between lo and hi tim...
Z3_ast Z3_API Z3_mk_char_to_int(Z3_context c, Z3_ast ch)
Create an integer (code point) from character.
Z3_ast Z3_API Z3_mk_fpa_neg(Z3_context c, Z3_ast t)
Floating-point negation.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
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.
Z3_ast Z3_API Z3_mk_re_plus(Z3_context c, Z3_ast re)
Create the regular language re+.
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
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 but two different AST objects can m...
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_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
Z3_sort Z3_API Z3_mk_fpa_sort_32(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
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...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
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.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
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...
Z3_sort Z3_API Z3_mk_fpa_sort_64(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_solver_get_proof(Z3_context c, Z3_solver s)
Retrieve the proof for the last Z3_solver_check or Z3_solver_check_assumptions.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
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.
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
void Z3_API Z3_solver_from_file(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a file.
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
void Z3_API Z3_solver_propagate_eq(Z3_context c, Z3_solver s, Z3_eq_eh eq_eh)
register a callback on expression equalities.
Z3_ast Z3_API Z3_mk_string(Z3_context c, Z3_string s)
Create a string constant out of the string that is passed in The string may contain escape encoding f...
Z3_func_decl Z3_API Z3_mk_transitive_closure(Z3_context c, Z3_func_decl f)
create transitive closure of binary relation.
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_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_sort Z3_API Z3_mk_seq_sort(Z3_context c, Z3_sort s)
Create a sequence sort out of the sort for the elements.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
Z3_ast_vector Z3_API Z3_solver_get_units(Z3_context c, Z3_solver s)
Return the set of units modulo model conversion.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
Z3_ast Z3_API Z3_mk_seq_last_index(Z3_context c, Z3_ast, Z3_ast substr)
Return index of the last occurrence of substr in s. If s does not contain substr, then the value is -...
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.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
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.
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...
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
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.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
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....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
Z3_ast Z3_API Z3_mk_fpa_to_fp_float(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_even(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
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.
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).
Z3_stats Z3_API Z3_solver_get_statistics(Z3_context c, Z3_solver s)
Return statistics for the given solver.
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_store_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs, Z3_ast v)
n-ary Array update.
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_func_decl Z3_API Z3_mk_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a linear ordering relation over signature a. The relation is identified by the index id.
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
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.
Z3_ast Z3_API Z3_mk_seq_in_re(Z3_context c, Z3_ast seq, Z3_ast re)
Check if seq is in the language generated by the regular expression re.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
Z3_string Z3_API Z3_solver_to_dimacs_string(Z3_context c, Z3_solver s, bool include_names)
Convert a solver into a DIMACS formatted string.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
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.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
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....
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
void Z3_API Z3_solver_propagate_register(Z3_context c, Z3_solver s, Z3_ast e)
register an expression to propagate on with the solver. Only expressions of type Bool and type Bit-Ve...
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,...
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
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...
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
Z3_sort Z3_API Z3_mk_fpa_sort(Z3_context c, unsigned ebits, unsigned sbits)
Create a FloatingPoint sort.
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives....
Z3_string Z3_API Z3_fpa_get_numeral_significand_string(Z3_context c, Z3_ast t)
Return the significand value of a floating-point numeral as a string.
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_ast Z3_API Z3_mk_int_to_str(Z3_context c, Z3_ast s)
Integer to string conversion.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
void Z3_API Z3_solver_propagate_fixed(Z3_context c, Z3_solver s, Z3_fixed_eh fixed_eh)
register a callback for when an expression is bound to a fixed value. The supported expression types ...
Z3_ast Z3_API Z3_fpa_get_numeral_sign_bv(Z3_context c, Z3_ast t)
Retrieves the sign of a floating-point literal as a bit-vector expression.
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...
Z3_ast Z3_API Z3_mk_char_is_digit(Z3_context c, Z3_ast ch)
Create a check if the character is a digit.
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_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value)
add a function entry to a function interpretation.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
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.
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_solver_to_string(Z3_context c, Z3_solver s)
Convert a solver into a string.
void Z3_API Z3_optimize_register_model_eh(Z3_context c, Z3_optimize o, Z3_model m, void *ctx, Z3_model_eh model_eh)
register a model event handler for new models.
bool Z3_API Z3_fpa_is_numeral_normal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is normal.
Z3_string Z3_API Z3_solver_get_reason_unknown(Z3_context c, Z3_solver s)
Return a brief justification for an "unknown" result (i.e., Z3_L_UNDEF) for the commands Z3_solver_ch...
Z3_string Z3_API Z3_get_numeral_binary_string(Z3_context c, Z3_ast a)
Return numeral value, as a binary string of a numeric constant term.
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
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.
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...
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
Z3_ast Z3_API Z3_mk_fpa_round_toward_zero(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardZero rounding mode.
Z3_ast Z3_API Z3_mk_char_from_bv(Z3_context c, Z3_ast bv)
Create a character from a bit-vector (code point).
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
Z3_ast Z3_API Z3_mk_fpa_zero(Z3_context c, Z3_sort s, bool negative)
Create a floating-point zero of sort s.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_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_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
Z3_sort Z3_API Z3_mk_fpa_sort_double(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_string_to_code(Z3_context c, Z3_ast a)
String to code conversion.
Z3_sort Z3_API Z3_mk_string_sort(Z3_context c)
Create a sort for unicode strings.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_seq_nth(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the element positioned at position index. The function is under-specified if the inde...
bool Z3_API Z3_fpa_is_numeral_inf(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a +oo or -oo.
Z3_ast Z3_API Z3_mk_seq_contains(Z3_context c, Z3_ast container, Z3_ast containee)
Check if container contains containee.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
bool Z3_API Z3_fpa_is_numeral_zero(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is +zero or -zero.
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3824
def fpIsNegative(a, ctx=None)
Definition: z3py.py:10274
def fpAbs(a, ctx=None)
Definition: z3py.py:10018
def is_pattern(a)
Definition: z3py.py:1918
def StrToInt(s)
Definition: z3py.py:11001
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:10363
def RNE(ctx=None)
Definition: z3py.py:9574
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:10392
def AtLeast(*args)
Definition: z3py.py:8877
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:11221
def BVRedOr(a)
Definition: z3py.py:4437
def is_lt(a)
Definition: z3py.py:2866
def Empty(s)
Definition: z3py.py:10858
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10468
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10504
def SRem(a, b)
Definition: z3py.py:4263
def OrElse(*ts, **ks)
Definition: z3py.py:8277
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:10109
def RealVarVector(n, ctx=None)
Definition: z3py.py:1483
def z3_debug()
Definition: z3py.py:62
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:9569
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:10227
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4486
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9148
def PbGe(args, k)
Definition: z3py.py:8933
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4472
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:9193
def is_mod(a)
Definition: z3py.py:2842
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10448
def IntSort(ctx=None)
Definition: z3py.py:3123
def Float16(ctx=None)
Definition: z3py.py:9307
def reset_params()
Definition: z3py.py:289
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8718
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:8317
def substitute_vars(t, *m)
Definition: z3py.py:8782
def is_var(a)
Definition: z3py.py:1299
def SetAdd(s, e)
Definition: z3py.py:4951
def is_gt(a)
Definition: z3py.py:2890
def is_fp_sort(s)
Definition: z3py.py:9359
def user_prop_push(ctx, cb)
Definition: z3py.py:11278
def fpToReal(x, ctx=None)
Definition: z3py.py:10576
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1741
def IsSubset(a, b)
Definition: z3py.py:5005
def BitVec(name, bv, ctx=None)
Definition: z3py.py:4022
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:8366
def EmptySet(s)
Definition: z3py.py:4907
def is_rational_value(a)
Definition: z3py.py:2741
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:4046
def Abs(arg)
Definition: z3py.py:8854
def DeclareSort(name, ctx=None)
Definition: z3py.py:687
def Float64(ctx=None)
Definition: z3py.py:9331
def With(t, *args, **keys)
Definition: z3py.py:8338
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5447
def PbEq(args, k, ctx=None)
Definition: z3py.py:8944
def StrToCode(s)
Definition: z3py.py:11024
def ToReal(a)
Definition: z3py.py:3343
def PrefixOf(a, b)
Definition: z3py.py:10898
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:10221
def Reals(names, ctx=None)
Definition: z3py.py:3299
def is_and(a)
Definition: z3py.py:1606
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:10327
def Xor(a, b, ctx=None)
Definition: z3py.py:1784
def Unit(a)
Definition: z3py.py:10893
def is_fprm_sort(s)
Definition: z3py.py:9370
def ULE(a, b)
Definition: z3py.py:4149
def Star(re)
Definition: z3py.py:11158
def Lambda(vs, body)
Definition: z3py.py:2246
def Diff(a, b, ctx=None)
Definition: z3py.py:11196
def is_bv(a)
Definition: z3py.py:3929
def SetDifference(a, b)
Definition: z3py.py:4983
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7733
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:9217
def is_array(a)
Definition: z3py.py:4596
def z3_error_handler(c, e)
Definition: z3py.py:174
def TryFor(t, ms, ctx=None)
Definition: z3py.py:8387
def simplify_param_descrs()
Definition: z3py.py:8748
def Length(s)
Definition: z3py.py:10991
def ensure_prop_closures()
Definition: z3py.py:11272
def help_simplify()
Definition: z3py.py:8743
def fpIsPositive(a, ctx=None)
Definition: z3py.py:10280
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2207
def Re(s, ctx=None)
Definition: z3py.py:11036
def Sqrt(a, ctx=None)
Definition: z3py.py:3396
def Select(a, *args)
Definition: z3py.py:4792
def set_option(*args, **kws)
Definition: z3py.py:295
def is_as_array(n)
Definition: z3py.py:6657
def fpEQ(a, b, ctx=None)
Definition: z3py.py:10339
def UGE(a, b)
Definition: z3py.py:4185
def CharVal(ch, ctx=None)
Definition: z3py.py:10751
def Extract(high, low, a)
Definition: z3py.py:4113
def fpNaN(s)
Definition: z3py.py:9863
def Q(a, b, ctx=None)
Definition: z3py.py:3220
def is_bv_sort(s)
Definition: z3py.py:3461
def append_log(s)
Definition: z3py.py:119
def is_string_value(a)
Definition: z3py.py:10815
def SetIntersect(*args)
Definition: z3py.py:4938
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4451
def SeqSort(s)
Definition: z3py.py:10668
def is_const_array(a)
Definition: z3py.py:4610
def get_default_fp_sort(ctx=None)
Definition: z3py.py:9226
def is_array_sort(a)
Definition: z3py.py:4592
def Product(*args)
Definition: z3py.py:8829
def Consts(names, sort)
Definition: z3py.py:1438
def fpIsZero(a, ctx=None)
Definition: z3py.py:10256
def Ext(a, b)
Definition: z3py.py:4853
def Range(lo, hi, ctx=None)
Definition: z3py.py:11184
def get_var_index(a)
Definition: z3py.py:1324
def set_param(*args, **kws)
Definition: z3py.py:265
def Bools(names, ctx=None)
Definition: z3py.py:1725
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:10522
def fpZero(s, negative)
Definition: z3py.py:9922
def CharToInt(ch, ctx=None)
Definition: z3py.py:10768
def FloatQuadruple(ctx=None)
Definition: z3py.py:9349
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:10554
def RTZ(ctx=None)
Definition: z3py.py:9614
def BVRedAnd(a)
Definition: z3py.py:4430
def Const(name, sort)
Definition: z3py.py:1426
def RealSort(ctx=None)
Definition: z3py.py:3140
def ZeroExt(n, a)
Definition: z3py.py:4378
def fpMax(a, b, ctx=None)
Definition: z3py.py:10200
def AllChar(regex_sort, ctx=None)
Definition: z3py.py:11201
def SetSort(s)
Sets.
Definition: z3py.py:4902
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9929
def get_ctx(ctx)
Definition: z3py.py:261
def fpMinusInfinity(s)
Definition: z3py.py:9897
def is_int_value(a)
Definition: z3py.py:2717
def mk_not(a)
Definition: z3py.py:1819
def is_distinct(a)
Definition: z3py.py:1664
def solve_using(s, *args, **keywords)
Definition: z3py.py:8985
def FloatDouble(ctx=None)
Definition: z3py.py:9337
def LinearOrder(a, index)
Definition: z3py.py:11213
def RTN(ctx=None)
Definition: z3py.py:9604
def probe_description(name, ctx=None)
Definition: z3py.py:8613
def get_param(name)
Definition: z3py.py:301
def IndexOf(s, substr, offset=None)
Definition: z3py.py:10962
def is_fprm(a)
Definition: z3py.py:9619
def is_store(a)
Definition: z3py.py:4884
def StrFromCode(c)
Definition: z3py.py:11030
def RotateLeft(a, b)
Definition: z3py.py:4316
def Function(name, *sig)
Definition: z3py.py:857
def user_prop_fixed(ctx, cb, id, value)
Definition: z3py.py:11302
def Update(a, *args)
Definition: z3py.py:4732
def UDiv(a, b)
Definition: z3py.py:4221
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:7366
def is_K(a)
Definition: z3py.py:4623
def FreshInt(prefix="x", ctx=None)
Definition: z3py.py:3272
def K(dom, v)
Definition: z3py.py:4831
def Replace(s, src, dst)
Definition: z3py.py:10947
def ArraySort(*sig)
Definition: z3py.py:4685
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:7345
def LShR(a, b)
Definition: z3py.py:4284
def FreshBool(prefix="b", ctx=None)
Definition: z3py.py:1756
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4444
def SignExt(n, a)
Definition: z3py.py:4348
def SubString(s, offset, length)
Definition: z3py.py:10848
def FullSet(s)
Definition: z3py.py:4916
def Not(a, ctx=None)
Definition: z3py.py:1800
def RecAddDefinition(f, args, body)
Definition: z3py.py:921
def fpRem(a, b, ctx=None)
Definition: z3py.py:10171
def is_expr(a)
Definition: z3py.py:1231
def FreshFunction(*sig)
Definition: z3py.py:880
def Var(idx, s)
Definition: z3py.py:1459
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:4005
def Intersect(*args)
Definition: z3py.py:11109
def Loop(re, lo, hi=0)
Definition: z3py.py:11171
def If(a, b, c, ctx=None)
Definition: z3py.py:1370
def WithParams(t, p)
Definition: z3py.py:8352
def is_ge(a)
Definition: z3py.py:2878
def Concat(*args)
Definition: z3py.py:4067
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10486
def BV2Int(a, is_signed=False)
Definition: z3py.py:3958
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8701
def is_idiv(a)
Definition: z3py.py:2830
def FailIf(p, ctx=None)
Definition: z3py.py:8659
def is_fp(a)
Definition: z3py.py:9775
def When(p, t, ctx=None)
Definition: z3py.py:8681
def Default(a)
Definition: z3py.py:4764
def PartialOrder(a, index)
Definition: z3py.py:11209
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:9579
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3259
def get_full_version()
Definition: z3py.py:101
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9999
def BVSubNoOverflow(a, b)
Definition: z3py.py:4458
def is_add(a)
Definition: z3py.py:2777
def user_prop_pop(ctx, cb, num_scopes)
Definition: z3py.py:11284
def is_to_int(a)
Definition: z3py.py:2929
def TransitiveClosure(f)
Definition: z3py.py:11225
def solve(*args, **keywords)
Definition: z3py.py:8955
def CharFromBv(ch, ctx=None)
Definition: z3py.py:10759
def FloatSingle(ctx=None)
Definition: z3py.py:9325
def RTP(ctx=None)
Definition: z3py.py:9594
def is_is_int(a)
Definition: z3py.py:2902
def get_version_string()
Definition: z3py.py:83
def AndThen(*ts, **ks)
Definition: z3py.py:8244
def open_log(fname)
Definition: z3py.py:114
def fpIsNaN(a, ctx=None)
Definition: z3py.py:10233
def PbLe(args, k)
Definition: z3py.py:8922
def Float32(ctx=None)
Definition: z3py.py:9319
def is_to_real(a)
Definition: z3py.py:2914
def user_prop_fresh(id, ctx)
Definition: z3py.py:11290
def AtMost(*args)
Definition: z3py.py:8859
def is_func_decl(a)
Definition: z3py.py:844
def RealVar(idx, ctx=None)
Definition: z3py.py:1472
def is_false(a)
Definition: z3py.py:1592
def describe_probes()
Definition: z3py.py:8622
def SubSeq(s, offset, length)
Definition: z3py.py:10853
def StringSort(ctx=None)
Definition: z3py.py:10649
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:10351
def Store(a, *args)
Definition: z3py.py:4775
def Ints(names, ctx=None)
Definition: z3py.py:3246
def SetHasSize(a, k)
Definition: z3py.py:4865
def fpIsNormal(a, ctx=None)
Definition: z3py.py:10262
def BoolSort(ctx=None)
Definition: z3py.py:1676
def SetComplement(s)
Definition: z3py.py:4973
def is_sub(a)
Definition: z3py.py:2801
def RatVal(a, b, ctx=None)
Definition: z3py.py:3204
def Then(*ts, **ks)
Definition: z3py.py:8264
def fpMin(a, b, ctx=None)
Definition: z3py.py:10185
def is_mul(a)
Definition: z3py.py:2789
def SuffixOf(a, b)
Definition: z3py.py:10913
def probes(ctx=None)
Definition: z3py.py:8602
def fpPlusZero(s)
Definition: z3py.py:9910
def fpLT(a, b, ctx=None)
Definition: z3py.py:10291
def is_fprm_value(a)
Definition: z3py.py:9632
def EnumSort(name, values, ctx=None)
Definition: z3py.py:5368
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2225
def RotateRight(a, b)
Definition: z3py.py:4332
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:10126
def CharIsDigit(ch, ctx=None)
Definition: z3py.py:10772
def Cbrt(a, ctx=None)
Definition: z3py.py:3409
def IsInt(a)
Definition: z3py.py:3379
def Union(*args)
Definition: z3py.py:11089
def is_finite_domain_sort(s)
Definition: z3py.py:7671
def LastIndexOf(s, substr)
Definition: z3py.py:10982
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9169
def IntToStr(s)
Definition: z3py.py:11017
def ReSort(s)
Definition: z3py.py:11055
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3314
def FloatHalf(ctx=None)
Definition: z3py.py:9313
def Array(name, *sorts)
Definition: z3py.py:4718
def is_finite_domain_value(a)
Definition: z3py.py:7748
def is_bool(a)
Definition: z3py.py:1556
def Distinct(*args)
Definition: z3py.py:1393
def is_int(a)
Definition: z3py.py:2671
def UGT(a, b)
Definition: z3py.py:4203
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:10596
def is_map(a)
Definition: z3py.py:4636
def fpMinusZero(s)
Definition: z3py.py:9916
def Map(f, *args)
Definition: z3py.py:4808
def is_bv_value(a)
Definition: z3py.py:3943
def is_const(a)
Definition: z3py.py:1280
def is_app_of(a, k)
Definition: z3py.py:1357
def is_sort(s)
Definition: z3py.py:641
def fpPlusInfinity(s)
Definition: z3py.py:9880
def ULT(a, b)
Definition: z3py.py:4167
def TreeOrder(a, index)
Definition: z3py.py:11217
def FreshConst(sort, prefix="c")
Definition: z3py.py:1453
def Implies(a, b, ctx=None)
Definition: z3py.py:1770
def BVSNegNoOverflow(a)
Definition: z3py.py:4479
def get_as_array_func(n)
Definition: z3py.py:6662
def is_quantifier(a)
Definition: z3py.py:2158
def deserialize(st)
Definition: z3py.py:1113
def RNA(ctx=None)
Definition: z3py.py:9584
def RoundTowardZero(ctx=None)
Definition: z3py.py:9609
def is_seq(a)
Definition: z3py.py:10797
def Float128(ctx=None)
Definition: z3py.py:9343
def RealVal(val, ctx=None)
Definition: z3py.py:3185
def Int(name, ctx=None)
Definition: z3py.py:3233
def Or(*args)
Definition: z3py.py:1867
def is_probe(p)
Definition: z3py.py:8584
def is_algebraic_value(a)
Definition: z3py.py:2763
def RepeatBitVec(n, a)
Definition: z3py.py:4406
def Option(re)
Definition: z3py.py:11140
def String(name, ctx=None)
Definition: z3py.py:10831
def tactics(ctx=None)
Definition: z3py.py:8396
def Int2BV(a, num_bits)
Definition: z3py.py:3981
def user_prop_final(ctx, cb)
Definition: z3py.py:11310
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:10303
def is_finite_domain(a)
Definition: z3py.py:7694
def is_string(a)
Definition: z3py.py:10807
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7663
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:10156
def user_prop_eq(ctx, cb, x, y)
Definition: z3py.py:11316
def CharSort(ctx=None)
Definition: z3py.py:10658
def ToInt(a)
Definition: z3py.py:3361
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9975
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4465
def RecFunction(name, *sig)
Definition: z3py.py:903
def user_prop_diseq(ctx, cb, x, y)
Definition: z3py.py:11324
def Bool(name, ctx=None)
Definition: z3py.py:1713
def Plus(re)
Definition: z3py.py:11127
def is_eq(a)
Definition: z3py.py:1654
def ParOr(*ts, **ks)
Definition: z3py.py:8298
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:10431
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9599
def is_ast(a)
Definition: z3py.py:445
def fpGT(a, b, ctx=None)
Definition: z3py.py:10315
def CharToBv(ch, ctx=None)
Definition: z3py.py:10764
def MultiPattern(*args)
Definition: z3py.py:1936
def is_not(a)
Definition: z3py.py:1642
def to_Ast(ptr)
Definition: z3py.py:11297
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9804
def eq(a, b)
Definition: z3py.py:466
def Complement(re)
Definition: z3py.py:11153
def disable_trace(msg)
Definition: z3py.py:79
def is_le(a)
Definition: z3py.py:2854
def is_real(a)
Definition: z3py.py:2690
def tactic_description(name, ctx=None)
Definition: z3py.py:8407
def is_app(a)
Definition: z3py.py:1254
def Strings(names, ctx=None)
Definition: z3py.py:10840
def Contains(a, b)
Definition: z3py.py:10928
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4493
def IsMember(e, s)
Definition: z3py.py:4994
def get_version()
Definition: z3py.py:92
def CreateDatatypes(*ds)
Definition: z3py.py:5143
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:5344
def get_map_func(a)
Definition: z3py.py:4661
def SetDel(s, e)
Definition: z3py.py:4962
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:10141
def is_default(a)
Definition: z3py.py:4652
def StringVal(s, ctx=None)
Definition: z3py.py:10824
def Full(s)
Definition: z3py.py:10878
def Sum(*args)
Definition: z3py.py:8803
def InRe(s, re)
Definition: z3py.py:11075
def enable_trace(msg)
Definition: z3py.py:75
def to_symbol(s, ctx=None)
Definition: z3py.py:124
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:8333
def is_arith_sort(s)
Definition: z3py.py:2349
def RoundTowardPositive(ctx=None)
Definition: z3py.py:9589
def is_true(a)
Definition: z3py.py:1574
def substitute(t, *m)
Definition: z3py.py:8753
def BoolVal(val, ctx=None)
Definition: z3py.py:1694
def FreshReal(prefix="b", ctx=None)
Definition: z3py.py:3329
def URem(a, b)
Definition: z3py.py:4242
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:10215
def main_ctx()
Definition: z3py.py:233
def describe_tactics()
Definition: z3py.py:8416
def is_implies(a)
Definition: z3py.py:1630
def is_fp_value(a)
Definition: z3py.py:9789
def Real(name, ctx=None)
Definition: z3py.py:3286
def is_div(a)
Definition: z3py.py:2813
def is_select(a)
Definition: z3py.py:4871
def fpIsInf(a, ctx=None)
Definition: z3py.py:10245
def And(*args)
Definition: z3py.py:1834
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:9230
def is_arith(a)
Definition: z3py.py:2650
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:10268
def is_or(a)
Definition: z3py.py:1618
def fpNeg(a, ctx=None)
Definition: z3py.py:10041
def SetUnion(*args)
Definition: z3py.py:4925
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:5356
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:10532
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3990
def Model(ctx=None)
Definition: z3py.py:6652
def fpInfinity(s, negative)
Definition: z3py.py:9903
def is_re(s)
Definition: z3py.py:11071
def IntVal(val, ctx=None)
Definition: z3py.py:3173
def prove(claim, show=False, **keywords)
Definition: z3py.py:9016