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 
1105 def _to_expr_ref(a, ctx):
1106  if isinstance(a, Pattern):
1107  return PatternRef(a, ctx)
1108  ctx_ref = ctx.ref()
1109  k = Z3_get_ast_kind(ctx_ref, a)
1110  if k == Z3_QUANTIFIER_AST:
1111  return QuantifierRef(a, ctx)
1112  sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1113  if sk == Z3_BOOL_SORT:
1114  return BoolRef(a, ctx)
1115  if sk == Z3_INT_SORT:
1116  if k == Z3_NUMERAL_AST:
1117  return IntNumRef(a, ctx)
1118  return ArithRef(a, ctx)
1119  if sk == Z3_REAL_SORT:
1120  if k == Z3_NUMERAL_AST:
1121  return RatNumRef(a, ctx)
1122  if _is_algebraic(ctx, a):
1123  return AlgebraicNumRef(a, ctx)
1124  return ArithRef(a, ctx)
1125  if sk == Z3_BV_SORT:
1126  if k == Z3_NUMERAL_AST:
1127  return BitVecNumRef(a, ctx)
1128  else:
1129  return BitVecRef(a, ctx)
1130  if sk == Z3_ARRAY_SORT:
1131  return ArrayRef(a, ctx)
1132  if sk == Z3_DATATYPE_SORT:
1133  return DatatypeRef(a, ctx)
1134  if sk == Z3_FLOATING_POINT_SORT:
1135  if k == Z3_APP_AST and _is_numeral(ctx, a):
1136  return FPNumRef(a, ctx)
1137  else:
1138  return FPRef(a, ctx)
1139  if sk == Z3_FINITE_DOMAIN_SORT:
1140  if k == Z3_NUMERAL_AST:
1141  return FiniteDomainNumRef(a, ctx)
1142  else:
1143  return FiniteDomainRef(a, ctx)
1144  if sk == Z3_ROUNDING_MODE_SORT:
1145  return FPRMRef(a, ctx)
1146  if sk == Z3_SEQ_SORT:
1147  return SeqRef(a, ctx)
1148  if sk == Z3_CHAR_SORT:
1149  return CharRef(a, ctx)
1150  if sk == Z3_RE_SORT:
1151  return ReRef(a, ctx)
1152  return ExprRef(a, ctx)
1153 
1154 
1155 def _coerce_expr_merge(s, a):
1156  if is_expr(a):
1157  s1 = a.sort()
1158  if s is None:
1159  return s1
1160  if s1.eq(s):
1161  return s
1162  elif s.subsort(s1):
1163  return s1
1164  elif s1.subsort(s):
1165  return s
1166  else:
1167  if z3_debug():
1168  _z3_assert(s1.ctx == s.ctx, "context mismatch")
1169  _z3_assert(False, "sort mismatch")
1170  else:
1171  return s
1172 
1173 
1174 def _coerce_exprs(a, b, ctx=None):
1175  if not is_expr(a) and not is_expr(b):
1176  a = _py2expr(a, ctx)
1177  b = _py2expr(b, ctx)
1178  if isinstance(a, str) and isinstance(b, SeqRef):
1179  a = StringVal(a, b.ctx)
1180  if isinstance(b, str) and isinstance(a, SeqRef):
1181  b = StringVal(b, a.ctx)
1182  s = None
1183  s = _coerce_expr_merge(s, a)
1184  s = _coerce_expr_merge(s, b)
1185  a = s.cast(a)
1186  b = s.cast(b)
1187  return (a, b)
1188 
1189 
1190 def _reduce(func, sequence, initial):
1191  result = initial
1192  for element in sequence:
1193  result = func(result, element)
1194  return result
1195 
1196 
1197 def _coerce_expr_list(alist, ctx=None):
1198  has_expr = False
1199  for a in alist:
1200  if is_expr(a):
1201  has_expr = True
1202  break
1203  if not has_expr:
1204  alist = [_py2expr(a, ctx) for a in alist]
1205  s = _reduce(_coerce_expr_merge, alist, None)
1206  return [s.cast(a) for a in alist]
1207 
1208 
1209 def is_expr(a):
1210  """Return `True` if `a` is a Z3 expression.
1211 
1212  >>> a = Int('a')
1213  >>> is_expr(a)
1214  True
1215  >>> is_expr(a + 1)
1216  True
1217  >>> is_expr(IntSort())
1218  False
1219  >>> is_expr(1)
1220  False
1221  >>> is_expr(IntVal(1))
1222  True
1223  >>> x = Int('x')
1224  >>> is_expr(ForAll(x, x >= 0))
1225  True
1226  >>> is_expr(FPVal(1.0))
1227  True
1228  """
1229  return isinstance(a, ExprRef)
1230 
1231 
1232 def is_app(a):
1233  """Return `True` if `a` is a Z3 function application.
1234 
1235  Note that, constants are function applications with 0 arguments.
1236 
1237  >>> a = Int('a')
1238  >>> is_app(a)
1239  True
1240  >>> is_app(a + 1)
1241  True
1242  >>> is_app(IntSort())
1243  False
1244  >>> is_app(1)
1245  False
1246  >>> is_app(IntVal(1))
1247  True
1248  >>> x = Int('x')
1249  >>> is_app(ForAll(x, x >= 0))
1250  False
1251  """
1252  if not isinstance(a, ExprRef):
1253  return False
1254  k = _ast_kind(a.ctx, a)
1255  return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1256 
1257 
1258 def is_const(a):
1259  """Return `True` if `a` is Z3 constant/variable expression.
1260 
1261  >>> a = Int('a')
1262  >>> is_const(a)
1263  True
1264  >>> is_const(a + 1)
1265  False
1266  >>> is_const(1)
1267  False
1268  >>> is_const(IntVal(1))
1269  True
1270  >>> x = Int('x')
1271  >>> is_const(ForAll(x, x >= 0))
1272  False
1273  """
1274  return is_app(a) and a.num_args() == 0
1275 
1276 
1277 def is_var(a):
1278  """Return `True` if `a` is variable.
1279 
1280  Z3 uses de-Bruijn indices for representing bound variables in
1281  quantifiers.
1282 
1283  >>> x = Int('x')
1284  >>> is_var(x)
1285  False
1286  >>> is_const(x)
1287  True
1288  >>> f = Function('f', IntSort(), IntSort())
1289  >>> # Z3 replaces x with bound variables when ForAll is executed.
1290  >>> q = ForAll(x, f(x) == x)
1291  >>> b = q.body()
1292  >>> b
1293  f(Var(0)) == Var(0)
1294  >>> b.arg(1)
1295  Var(0)
1296  >>> is_var(b.arg(1))
1297  True
1298  """
1299  return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1300 
1301 
1303  """Return the de-Bruijn index of the Z3 bounded variable `a`.
1304 
1305  >>> x = Int('x')
1306  >>> y = Int('y')
1307  >>> is_var(x)
1308  False
1309  >>> is_const(x)
1310  True
1311  >>> f = Function('f', IntSort(), IntSort(), IntSort())
1312  >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1313  >>> q = ForAll([x, y], f(x, y) == x + y)
1314  >>> q.body()
1315  f(Var(1), Var(0)) == Var(1) + Var(0)
1316  >>> b = q.body()
1317  >>> b.arg(0)
1318  f(Var(1), Var(0))
1319  >>> v1 = b.arg(0).arg(0)
1320  >>> v2 = b.arg(0).arg(1)
1321  >>> v1
1322  Var(1)
1323  >>> v2
1324  Var(0)
1325  >>> get_var_index(v1)
1326  1
1327  >>> get_var_index(v2)
1328  0
1329  """
1330  if z3_debug():
1331  _z3_assert(is_var(a), "Z3 bound variable expected")
1332  return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1333 
1334 
1335 def is_app_of(a, k):
1336  """Return `True` if `a` is an application of the given kind `k`.
1337 
1338  >>> x = Int('x')
1339  >>> n = x + 1
1340  >>> is_app_of(n, Z3_OP_ADD)
1341  True
1342  >>> is_app_of(n, Z3_OP_MUL)
1343  False
1344  """
1345  return is_app(a) and a.decl().kind() == k
1346 
1347 
1348 def If(a, b, c, ctx=None):
1349  """Create a Z3 if-then-else expression.
1350 
1351  >>> x = Int('x')
1352  >>> y = Int('y')
1353  >>> max = If(x > y, x, y)
1354  >>> max
1355  If(x > y, x, y)
1356  >>> simplify(max)
1357  If(x <= y, y, x)
1358  """
1359  if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1360  return Cond(a, b, c, ctx)
1361  else:
1362  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1363  s = BoolSort(ctx)
1364  a = s.cast(a)
1365  b, c = _coerce_exprs(b, c, ctx)
1366  if z3_debug():
1367  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1368  return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1369 
1370 
1371 def Distinct(*args):
1372  """Create a Z3 distinct expression.
1373 
1374  >>> x = Int('x')
1375  >>> y = Int('y')
1376  >>> Distinct(x, y)
1377  x != y
1378  >>> z = Int('z')
1379  >>> Distinct(x, y, z)
1380  Distinct(x, y, z)
1381  >>> simplify(Distinct(x, y, z))
1382  Distinct(x, y, z)
1383  >>> simplify(Distinct(x, y, z), blast_distinct=True)
1384  And(Not(x == y), Not(x == z), Not(y == z))
1385  """
1386  args = _get_args(args)
1387  ctx = _ctx_from_ast_arg_list(args)
1388  if z3_debug():
1389  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1390  args = _coerce_expr_list(args, ctx)
1391  _args, sz = _to_ast_array(args)
1392  return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1393 
1394 
1395 def _mk_bin(f, a, b):
1396  args = (Ast * 2)()
1397  if z3_debug():
1398  _z3_assert(a.ctx == b.ctx, "Context mismatch")
1399  args[0] = a.as_ast()
1400  args[1] = b.as_ast()
1401  return f(a.ctx.ref(), 2, args)
1402 
1403 
1404 def Const(name, sort):
1405  """Create a constant of the given sort.
1406 
1407  >>> Const('x', IntSort())
1408  x
1409  """
1410  if z3_debug():
1411  _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1412  ctx = sort.ctx
1413  return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1414 
1415 
1416 def Consts(names, sort):
1417  """Create several constants of the given sort.
1418 
1419  `names` is a string containing the names of all constants to be created.
1420  Blank spaces separate the names of different constants.
1421 
1422  >>> x, y, z = Consts('x y z', IntSort())
1423  >>> x + y + z
1424  x + y + z
1425  """
1426  if isinstance(names, str):
1427  names = names.split(" ")
1428  return [Const(name, sort) for name in names]
1429 
1430 
1431 def FreshConst(sort, prefix="c"):
1432  """Create a fresh constant of a specified sort"""
1433  ctx = _get_ctx(sort.ctx)
1434  return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1435 
1436 
1437 def Var(idx, s):
1438  """Create a Z3 free variable. Free variables are used to create quantified formulas.
1439 
1440  >>> Var(0, IntSort())
1441  Var(0)
1442  >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1443  False
1444  """
1445  if z3_debug():
1446  _z3_assert(is_sort(s), "Z3 sort expected")
1447  return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1448 
1449 
1450 def RealVar(idx, ctx=None):
1451  """
1452  Create a real free variable. Free variables are used to create quantified formulas.
1453  They are also used to create polynomials.
1454 
1455  >>> RealVar(0)
1456  Var(0)
1457  """
1458  return Var(idx, RealSort(ctx))
1459 
1460 
1461 def RealVarVector(n, ctx=None):
1462  """
1463  Create a list of Real free variables.
1464  The variables have ids: 0, 1, ..., n-1
1465 
1466  >>> x0, x1, x2, x3 = RealVarVector(4)
1467  >>> x2
1468  Var(2)
1469  """
1470  return [RealVar(i, ctx) for i in range(n)]
1471 
1472 
1477 
1478 
1480  """Boolean sort."""
1481 
1482  def cast(self, val):
1483  """Try to cast `val` as a Boolean.
1484 
1485  >>> x = BoolSort().cast(True)
1486  >>> x
1487  True
1488  >>> is_expr(x)
1489  True
1490  >>> is_expr(True)
1491  False
1492  >>> x.sort()
1493  Bool
1494  """
1495  if isinstance(val, bool):
1496  return BoolVal(val, self.ctxctx)
1497  if z3_debug():
1498  if not is_expr(val):
1499  msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1500  _z3_assert(is_expr(val), msg % (val, type(val)))
1501  if not self.eqeq(val.sort()):
1502  _z3_assert(self.eqeq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1503  return val
1504 
1505  def subsort(self, other):
1506  return isinstance(other, ArithSortRef)
1507 
1508  def is_int(self):
1509  return True
1510 
1511  def is_bool(self):
1512  return True
1513 
1514 
1516  """All Boolean expressions are instances of this class."""
1517 
1518  def sort(self):
1519  return BoolSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
1520 
1521  def __rmul__(self, other):
1522  return self * other
1523 
1524  def __mul__(self, other):
1525  """Create the Z3 expression `self * other`.
1526  """
1527  if other == 1:
1528  return self
1529  if other == 0:
1530  return 0
1531  return If(self, other, 0)
1532 
1533 
1534 def is_bool(a):
1535  """Return `True` if `a` is a Z3 Boolean expression.
1536 
1537  >>> p = Bool('p')
1538  >>> is_bool(p)
1539  True
1540  >>> q = Bool('q')
1541  >>> is_bool(And(p, q))
1542  True
1543  >>> x = Real('x')
1544  >>> is_bool(x)
1545  False
1546  >>> is_bool(x == 0)
1547  True
1548  """
1549  return isinstance(a, BoolRef)
1550 
1551 
1552 def is_true(a):
1553  """Return `True` if `a` is the Z3 true expression.
1554 
1555  >>> p = Bool('p')
1556  >>> is_true(p)
1557  False
1558  >>> is_true(simplify(p == p))
1559  True
1560  >>> x = Real('x')
1561  >>> is_true(x == 0)
1562  False
1563  >>> # True is a Python Boolean expression
1564  >>> is_true(True)
1565  False
1566  """
1567  return is_app_of(a, Z3_OP_TRUE)
1568 
1569 
1570 def is_false(a):
1571  """Return `True` if `a` is the Z3 false expression.
1572 
1573  >>> p = Bool('p')
1574  >>> is_false(p)
1575  False
1576  >>> is_false(False)
1577  False
1578  >>> is_false(BoolVal(False))
1579  True
1580  """
1581  return is_app_of(a, Z3_OP_FALSE)
1582 
1583 
1584 def is_and(a):
1585  """Return `True` if `a` is a Z3 and expression.
1586 
1587  >>> p, q = Bools('p q')
1588  >>> is_and(And(p, q))
1589  True
1590  >>> is_and(Or(p, q))
1591  False
1592  """
1593  return is_app_of(a, Z3_OP_AND)
1594 
1595 
1596 def is_or(a):
1597  """Return `True` if `a` is a Z3 or expression.
1598 
1599  >>> p, q = Bools('p q')
1600  >>> is_or(Or(p, q))
1601  True
1602  >>> is_or(And(p, q))
1603  False
1604  """
1605  return is_app_of(a, Z3_OP_OR)
1606 
1607 
1608 def is_implies(a):
1609  """Return `True` if `a` is a Z3 implication expression.
1610 
1611  >>> p, q = Bools('p q')
1612  >>> is_implies(Implies(p, q))
1613  True
1614  >>> is_implies(And(p, q))
1615  False
1616  """
1617  return is_app_of(a, Z3_OP_IMPLIES)
1618 
1619 
1620 def is_not(a):
1621  """Return `True` if `a` is a Z3 not expression.
1622 
1623  >>> p = Bool('p')
1624  >>> is_not(p)
1625  False
1626  >>> is_not(Not(p))
1627  True
1628  """
1629  return is_app_of(a, Z3_OP_NOT)
1630 
1631 
1632 def is_eq(a):
1633  """Return `True` if `a` is a Z3 equality expression.
1634 
1635  >>> x, y = Ints('x y')
1636  >>> is_eq(x == y)
1637  True
1638  """
1639  return is_app_of(a, Z3_OP_EQ)
1640 
1641 
1643  """Return `True` if `a` is a Z3 distinct expression.
1644 
1645  >>> x, y, z = Ints('x y z')
1646  >>> is_distinct(x == y)
1647  False
1648  >>> is_distinct(Distinct(x, y, z))
1649  True
1650  """
1651  return is_app_of(a, Z3_OP_DISTINCT)
1652 
1653 
1654 def BoolSort(ctx=None):
1655  """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1656 
1657  >>> BoolSort()
1658  Bool
1659  >>> p = Const('p', BoolSort())
1660  >>> is_bool(p)
1661  True
1662  >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1663  >>> r(0, 1)
1664  r(0, 1)
1665  >>> is_bool(r(0, 1))
1666  True
1667  """
1668  ctx = _get_ctx(ctx)
1669  return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1670 
1671 
1672 def BoolVal(val, ctx=None):
1673  """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1674 
1675  >>> BoolVal(True)
1676  True
1677  >>> is_true(BoolVal(True))
1678  True
1679  >>> is_true(True)
1680  False
1681  >>> is_false(BoolVal(False))
1682  True
1683  """
1684  ctx = _get_ctx(ctx)
1685  if val:
1686  return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1687  else:
1688  return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1689 
1690 
1691 def Bool(name, ctx=None):
1692  """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1693 
1694  >>> p = Bool('p')
1695  >>> q = Bool('q')
1696  >>> And(p, q)
1697  And(p, q)
1698  """
1699  ctx = _get_ctx(ctx)
1700  return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1701 
1702 
1703 def Bools(names, ctx=None):
1704  """Return a tuple of Boolean constants.
1705 
1706  `names` is a single string containing all names separated by blank spaces.
1707  If `ctx=None`, then the global context is used.
1708 
1709  >>> p, q, r = Bools('p q r')
1710  >>> And(p, Or(q, r))
1711  And(p, Or(q, r))
1712  """
1713  ctx = _get_ctx(ctx)
1714  if isinstance(names, str):
1715  names = names.split(" ")
1716  return [Bool(name, ctx) for name in names]
1717 
1718 
1719 def BoolVector(prefix, sz, ctx=None):
1720  """Return a list of Boolean constants of size `sz`.
1721 
1722  The constants are named using the given prefix.
1723  If `ctx=None`, then the global context is used.
1724 
1725  >>> P = BoolVector('p', 3)
1726  >>> P
1727  [p__0, p__1, p__2]
1728  >>> And(P)
1729  And(p__0, p__1, p__2)
1730  """
1731  return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1732 
1733 
1734 def FreshBool(prefix="b", ctx=None):
1735  """Return a fresh Boolean constant in the given context using the given prefix.
1736 
1737  If `ctx=None`, then the global context is used.
1738 
1739  >>> b1 = FreshBool()
1740  >>> b2 = FreshBool()
1741  >>> eq(b1, b2)
1742  False
1743  """
1744  ctx = _get_ctx(ctx)
1745  return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1746 
1747 
1748 def Implies(a, b, ctx=None):
1749  """Create a Z3 implies expression.
1750 
1751  >>> p, q = Bools('p q')
1752  >>> Implies(p, q)
1753  Implies(p, q)
1754  """
1755  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1756  s = BoolSort(ctx)
1757  a = s.cast(a)
1758  b = s.cast(b)
1759  return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1760 
1761 
1762 def Xor(a, b, ctx=None):
1763  """Create a Z3 Xor expression.
1764 
1765  >>> p, q = Bools('p q')
1766  >>> Xor(p, q)
1767  Xor(p, q)
1768  >>> simplify(Xor(p, q))
1769  Not(p == q)
1770  """
1771  ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1772  s = BoolSort(ctx)
1773  a = s.cast(a)
1774  b = s.cast(b)
1775  return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1776 
1777 
1778 def Not(a, ctx=None):
1779  """Create a Z3 not expression or probe.
1780 
1781  >>> p = Bool('p')
1782  >>> Not(Not(p))
1783  Not(Not(p))
1784  >>> simplify(Not(Not(p)))
1785  p
1786  """
1787  ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1788  if is_probe(a):
1789  # Not is also used to build probes
1790  return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1791  else:
1792  s = BoolSort(ctx)
1793  a = s.cast(a)
1794  return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1795 
1796 
1797 def mk_not(a):
1798  if is_not(a):
1799  return a.arg(0)
1800  else:
1801  return Not(a)
1802 
1803 
1804 def _has_probe(args):
1805  """Return `True` if one of the elements of the given collection is a Z3 probe."""
1806  for arg in args:
1807  if is_probe(arg):
1808  return True
1809  return False
1810 
1811 
1812 def And(*args):
1813  """Create a Z3 and-expression or and-probe.
1814 
1815  >>> p, q, r = Bools('p q r')
1816  >>> And(p, q, r)
1817  And(p, q, r)
1818  >>> P = BoolVector('p', 5)
1819  >>> And(P)
1820  And(p__0, p__1, p__2, p__3, p__4)
1821  """
1822  last_arg = None
1823  if len(args) > 0:
1824  last_arg = args[len(args) - 1]
1825  if isinstance(last_arg, Context):
1826  ctx = args[len(args) - 1]
1827  args = args[:len(args) - 1]
1828  elif len(args) == 1 and isinstance(args[0], AstVector):
1829  ctx = args[0].ctx
1830  args = [a for a in args[0]]
1831  else:
1832  ctx = None
1833  args = _get_args(args)
1834  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1835  if z3_debug():
1836  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1837  if _has_probe(args):
1838  return _probe_and(args, ctx)
1839  else:
1840  args = _coerce_expr_list(args, ctx)
1841  _args, sz = _to_ast_array(args)
1842  return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1843 
1844 
1845 def Or(*args):
1846  """Create a Z3 or-expression or or-probe.
1847 
1848  >>> p, q, r = Bools('p q r')
1849  >>> Or(p, q, r)
1850  Or(p, q, r)
1851  >>> P = BoolVector('p', 5)
1852  >>> Or(P)
1853  Or(p__0, p__1, p__2, p__3, p__4)
1854  """
1855  last_arg = None
1856  if len(args) > 0:
1857  last_arg = args[len(args) - 1]
1858  if isinstance(last_arg, Context):
1859  ctx = args[len(args) - 1]
1860  args = args[:len(args) - 1]
1861  elif len(args) == 1 and isinstance(args[0], AstVector):
1862  ctx = args[0].ctx
1863  args = [a for a in args[0]]
1864  else:
1865  ctx = None
1866  args = _get_args(args)
1867  ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1868  if z3_debug():
1869  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1870  if _has_probe(args):
1871  return _probe_or(args, ctx)
1872  else:
1873  args = _coerce_expr_list(args, ctx)
1874  _args, sz = _to_ast_array(args)
1875  return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1876 
1877 
1882 
1883 
1885  """Patterns are hints for quantifier instantiation.
1886 
1887  """
1888 
1889  def as_ast(self):
1890  return Z3_pattern_to_ast(self.ctx_refctx_ref(), self.astast)
1891 
1892  def get_id(self):
1893  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_astas_ast())
1894 
1895 
1896 def is_pattern(a):
1897  """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1898 
1899  >>> f = Function('f', IntSort(), IntSort())
1900  >>> x = Int('x')
1901  >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1902  >>> q
1903  ForAll(x, f(x) == 0)
1904  >>> q.num_patterns()
1905  1
1906  >>> is_pattern(q.pattern(0))
1907  True
1908  >>> q.pattern(0)
1909  f(Var(0))
1910  """
1911  return isinstance(a, PatternRef)
1912 
1913 
1914 def MultiPattern(*args):
1915  """Create a Z3 multi-pattern using the given expressions `*args`
1916 
1917  >>> f = Function('f', IntSort(), IntSort())
1918  >>> g = Function('g', IntSort(), IntSort())
1919  >>> x = Int('x')
1920  >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1921  >>> q
1922  ForAll(x, f(x) != g(x))
1923  >>> q.num_patterns()
1924  1
1925  >>> is_pattern(q.pattern(0))
1926  True
1927  >>> q.pattern(0)
1928  MultiPattern(f(Var(0)), g(Var(0)))
1929  """
1930  if z3_debug():
1931  _z3_assert(len(args) > 0, "At least one argument expected")
1932  _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1933  ctx = args[0].ctx
1934  args, sz = _to_ast_array(args)
1935  return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1936 
1937 
1938 def _to_pattern(arg):
1939  if is_pattern(arg):
1940  return arg
1941  else:
1942  return MultiPattern(arg)
1943 
1944 
1949 
1950 
1952  """Universally and Existentially quantified formulas."""
1953 
1954  def as_ast(self):
1955  return self.astast
1956 
1957  def get_id(self):
1958  return Z3_get_ast_id(self.ctx_refctx_ref(), self.as_astas_astas_astas_ast())
1959 
1960  def sort(self):
1961  """Return the Boolean sort or sort of Lambda."""
1962  if self.is_lambdais_lambda():
1963  return _sort(self.ctxctx, self.as_astas_astas_astas_ast())
1964  return BoolSort(self.ctxctx)
1965 
1966  def is_forall(self):
1967  """Return `True` if `self` is a universal quantifier.
1968 
1969  >>> f = Function('f', IntSort(), IntSort())
1970  >>> x = Int('x')
1971  >>> q = ForAll(x, f(x) == 0)
1972  >>> q.is_forall()
1973  True
1974  >>> q = Exists(x, f(x) != 0)
1975  >>> q.is_forall()
1976  False
1977  """
1978  return Z3_is_quantifier_forall(self.ctx_refctx_ref(), self.astast)
1979 
1980  def is_exists(self):
1981  """Return `True` if `self` is an existential quantifier.
1982 
1983  >>> f = Function('f', IntSort(), IntSort())
1984  >>> x = Int('x')
1985  >>> q = ForAll(x, f(x) == 0)
1986  >>> q.is_exists()
1987  False
1988  >>> q = Exists(x, f(x) != 0)
1989  >>> q.is_exists()
1990  True
1991  """
1992  return Z3_is_quantifier_exists(self.ctx_refctx_ref(), self.astast)
1993 
1994  def is_lambda(self):
1995  """Return `True` if `self` is a lambda expression.
1996 
1997  >>> f = Function('f', IntSort(), IntSort())
1998  >>> x = Int('x')
1999  >>> q = Lambda(x, f(x))
2000  >>> q.is_lambda()
2001  True
2002  >>> q = Exists(x, f(x) != 0)
2003  >>> q.is_lambda()
2004  False
2005  """
2006  return Z3_is_lambda(self.ctx_refctx_ref(), self.astast)
2007 
2008  def __getitem__(self, arg):
2009  """Return the Z3 expression `self[arg]`.
2010  """
2011  if z3_debug():
2012  _z3_assert(self.is_lambdais_lambda(), "quantifier should be a lambda expression")
2013  return _array_select(self, arg)
2014 
2015  def weight(self):
2016  """Return the weight annotation of `self`.
2017 
2018  >>> f = Function('f', IntSort(), IntSort())
2019  >>> x = Int('x')
2020  >>> q = ForAll(x, f(x) == 0)
2021  >>> q.weight()
2022  1
2023  >>> q = ForAll(x, f(x) == 0, weight=10)
2024  >>> q.weight()
2025  10
2026  """
2027  return int(Z3_get_quantifier_weight(self.ctx_refctx_ref(), self.astast))
2028 
2029  def num_patterns(self):
2030  """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2031 
2032  >>> f = Function('f', IntSort(), IntSort())
2033  >>> g = Function('g', IntSort(), IntSort())
2034  >>> x = Int('x')
2035  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2036  >>> q.num_patterns()
2037  2
2038  """
2039  return int(Z3_get_quantifier_num_patterns(self.ctx_refctx_ref(), self.astast))
2040 
2041  def pattern(self, idx):
2042  """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2043 
2044  >>> f = Function('f', IntSort(), IntSort())
2045  >>> g = Function('g', IntSort(), IntSort())
2046  >>> x = Int('x')
2047  >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2048  >>> q.num_patterns()
2049  2
2050  >>> q.pattern(0)
2051  f(Var(0))
2052  >>> q.pattern(1)
2053  g(Var(0))
2054  """
2055  if z3_debug():
2056  _z3_assert(idx < self.num_patternsnum_patterns(), "Invalid pattern idx")
2057  return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2058 
2059  def num_no_patterns(self):
2060  """Return the number of no-patterns."""
2061  return Z3_get_quantifier_num_no_patterns(self.ctx_refctx_ref(), self.astast)
2062 
2063  def no_pattern(self, idx):
2064  """Return a no-pattern."""
2065  if z3_debug():
2066  _z3_assert(idx < self.num_no_patternsnum_no_patterns(), "Invalid no-pattern idx")
2067  return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2068 
2069  def body(self):
2070  """Return the expression being quantified.
2071 
2072  >>> f = Function('f', IntSort(), IntSort())
2073  >>> x = Int('x')
2074  >>> q = ForAll(x, f(x) == 0)
2075  >>> q.body()
2076  f(Var(0)) == 0
2077  """
2078  return _to_expr_ref(Z3_get_quantifier_body(self.ctx_refctx_ref(), self.astast), self.ctxctx)
2079 
2080  def num_vars(self):
2081  """Return the number of variables bounded by this quantifier.
2082 
2083  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2084  >>> x = Int('x')
2085  >>> y = Int('y')
2086  >>> q = ForAll([x, y], f(x, y) >= x)
2087  >>> q.num_vars()
2088  2
2089  """
2090  return int(Z3_get_quantifier_num_bound(self.ctx_refctx_ref(), self.astast))
2091 
2092  def var_name(self, idx):
2093  """Return a string representing a name used when displaying the quantifier.
2094 
2095  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2096  >>> x = Int('x')
2097  >>> y = Int('y')
2098  >>> q = ForAll([x, y], f(x, y) >= x)
2099  >>> q.var_name(0)
2100  'x'
2101  >>> q.var_name(1)
2102  'y'
2103  """
2104  if z3_debug():
2105  _z3_assert(idx < self.num_varsnum_vars(), "Invalid variable idx")
2106  return _symbol2py(self.ctxctx, Z3_get_quantifier_bound_name(self.ctx_refctx_ref(), self.astast, idx))
2107 
2108  def var_sort(self, idx):
2109  """Return the sort of a bound variable.
2110 
2111  >>> f = Function('f', IntSort(), RealSort(), IntSort())
2112  >>> x = Int('x')
2113  >>> y = Real('y')
2114  >>> q = ForAll([x, y], f(x, y) >= x)
2115  >>> q.var_sort(0)
2116  Int
2117  >>> q.var_sort(1)
2118  Real
2119  """
2120  if z3_debug():
2121  _z3_assert(idx < self.num_varsnum_vars(), "Invalid variable idx")
2122  return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
2123 
2124  def children(self):
2125  """Return a list containing a single element self.body()
2126 
2127  >>> f = Function('f', IntSort(), IntSort())
2128  >>> x = Int('x')
2129  >>> q = ForAll(x, f(x) == 0)
2130  >>> q.children()
2131  [f(Var(0)) == 0]
2132  """
2133  return [self.bodybody()]
2134 
2135 
2137  """Return `True` if `a` is a Z3 quantifier.
2138 
2139  >>> f = Function('f', IntSort(), IntSort())
2140  >>> x = Int('x')
2141  >>> q = ForAll(x, f(x) == 0)
2142  >>> is_quantifier(q)
2143  True
2144  >>> is_quantifier(f(x))
2145  False
2146  """
2147  return isinstance(a, QuantifierRef)
2148 
2149 
2150 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2151  if z3_debug():
2152  _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2153  _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2154  _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2155  _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2156  if is_app(vs):
2157  ctx = vs.ctx
2158  vs = [vs]
2159  else:
2160  ctx = vs[0].ctx
2161  if not is_expr(body):
2162  body = BoolVal(body, ctx)
2163  num_vars = len(vs)
2164  if num_vars == 0:
2165  return body
2166  _vs = (Ast * num_vars)()
2167  for i in range(num_vars):
2168  # TODO: Check if is constant
2169  _vs[i] = vs[i].as_ast()
2170  patterns = [_to_pattern(p) for p in patterns]
2171  num_pats = len(patterns)
2172  _pats = (Pattern * num_pats)()
2173  for i in range(num_pats):
2174  _pats[i] = patterns[i].ast
2175  _no_pats, num_no_pats = _to_ast_array(no_patterns)
2176  qid = to_symbol(qid, ctx)
2177  skid = to_symbol(skid, ctx)
2178  return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2179  num_vars, _vs,
2180  num_pats, _pats,
2181  num_no_pats, _no_pats,
2182  body.as_ast()), ctx)
2183 
2184 
2185 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2186  """Create a Z3 forall formula.
2187 
2188  The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2189 
2190  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2191  >>> x = Int('x')
2192  >>> y = Int('y')
2193  >>> ForAll([x, y], f(x, y) >= x)
2194  ForAll([x, y], f(x, y) >= x)
2195  >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2196  ForAll([x, y], f(x, y) >= x)
2197  >>> ForAll([x, y], f(x, y) >= x, weight=10)
2198  ForAll([x, y], f(x, y) >= x)
2199  """
2200  return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2201 
2202 
2203 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2204  """Create a Z3 exists formula.
2205 
2206  The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2207 
2208 
2209  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2210  >>> x = Int('x')
2211  >>> y = Int('y')
2212  >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2213  >>> q
2214  Exists([x, y], f(x, y) >= x)
2215  >>> is_quantifier(q)
2216  True
2217  >>> r = Tactic('nnf')(q).as_expr()
2218  >>> is_quantifier(r)
2219  False
2220  """
2221  return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2222 
2223 
2224 def Lambda(vs, body):
2225  """Create a Z3 lambda expression.
2226 
2227  >>> f = Function('f', IntSort(), IntSort(), IntSort())
2228  >>> mem0 = Array('mem0', IntSort(), IntSort())
2229  >>> lo, hi, e, i = Ints('lo hi e i')
2230  >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2231  >>> mem1
2232  Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2233  """
2234  ctx = body.ctx
2235  if is_app(vs):
2236  vs = [vs]
2237  num_vars = len(vs)
2238  _vs = (Ast * num_vars)()
2239  for i in range(num_vars):
2240  # TODO: Check if is constant
2241  _vs[i] = vs[i].as_ast()
2242  return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2243 
2244 
2249 
2250 
2252  """Real and Integer sorts."""
2253 
2254  def is_real(self):
2255  """Return `True` if `self` is of the sort Real.
2256 
2257  >>> x = Real('x')
2258  >>> x.is_real()
2259  True
2260  >>> (x + 1).is_real()
2261  True
2262  >>> x = Int('x')
2263  >>> x.is_real()
2264  False
2265  """
2266  return self.kindkind() == Z3_REAL_SORT
2267 
2268  def is_int(self):
2269  """Return `True` if `self` is of the sort Integer.
2270 
2271  >>> x = Int('x')
2272  >>> x.is_int()
2273  True
2274  >>> (x + 1).is_int()
2275  True
2276  >>> x = Real('x')
2277  >>> x.is_int()
2278  False
2279  """
2280  return self.kindkind() == Z3_INT_SORT
2281 
2282  def subsort(self, other):
2283  """Return `True` if `self` is a subsort of `other`."""
2284  return self.is_intis_int() and is_arith_sort(other) and other.is_real()
2285 
2286  def cast(self, val):
2287  """Try to cast `val` as an Integer or Real.
2288 
2289  >>> IntSort().cast(10)
2290  10
2291  >>> is_int(IntSort().cast(10))
2292  True
2293  >>> is_int(10)
2294  False
2295  >>> RealSort().cast(10)
2296  10
2297  >>> is_real(RealSort().cast(10))
2298  True
2299  """
2300  if is_expr(val):
2301  if z3_debug():
2302  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
2303  val_s = val.sort()
2304  if self.eqeq(val_s):
2305  return val
2306  if val_s.is_int() and self.is_realis_real():
2307  return ToReal(val)
2308  if val_s.is_bool() and self.is_intis_int():
2309  return If(val, 1, 0)
2310  if val_s.is_bool() and self.is_realis_real():
2311  return ToReal(If(val, 1, 0))
2312  if z3_debug():
2313  _z3_assert(False, "Z3 Integer/Real expression expected")
2314  else:
2315  if self.is_intis_int():
2316  return IntVal(val, self.ctxctxctx)
2317  if self.is_realis_real():
2318  return RealVal(val, self.ctxctxctx)
2319  if z3_debug():
2320  msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2321  _z3_assert(False, msg % self)
2322 
2323 
2325  """Return `True` if s is an arithmetical sort (type).
2326 
2327  >>> is_arith_sort(IntSort())
2328  True
2329  >>> is_arith_sort(RealSort())
2330  True
2331  >>> is_arith_sort(BoolSort())
2332  False
2333  >>> n = Int('x') + 1
2334  >>> is_arith_sort(n.sort())
2335  True
2336  """
2337  return isinstance(s, ArithSortRef)
2338 
2339 
2341  """Integer and Real expressions."""
2342 
2343  def sort(self):
2344  """Return the sort (type) of the arithmetical expression `self`.
2345 
2346  >>> Int('x').sort()
2347  Int
2348  >>> (Real('x') + 1).sort()
2349  Real
2350  """
2351  return ArithSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2352 
2353  def is_int(self):
2354  """Return `True` if `self` is an integer expression.
2355 
2356  >>> x = Int('x')
2357  >>> x.is_int()
2358  True
2359  >>> (x + 1).is_int()
2360  True
2361  >>> y = Real('y')
2362  >>> (x + y).is_int()
2363  False
2364  """
2365  return self.sortsortsort().is_int()
2366 
2367  def is_real(self):
2368  """Return `True` if `self` is an real expression.
2369 
2370  >>> x = Real('x')
2371  >>> x.is_real()
2372  True
2373  >>> (x + 1).is_real()
2374  True
2375  """
2376  return self.sortsortsort().is_real()
2377 
2378  def __add__(self, other):
2379  """Create the Z3 expression `self + other`.
2380 
2381  >>> x = Int('x')
2382  >>> y = Int('y')
2383  >>> x + y
2384  x + y
2385  >>> (x + y).sort()
2386  Int
2387  """
2388  a, b = _coerce_exprs(self, other)
2389  return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctxctx)
2390 
2391  def __radd__(self, other):
2392  """Create the Z3 expression `other + self`.
2393 
2394  >>> x = Int('x')
2395  >>> 10 + x
2396  10 + x
2397  """
2398  a, b = _coerce_exprs(self, other)
2399  return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctxctx)
2400 
2401  def __mul__(self, other):
2402  """Create the Z3 expression `self * other`.
2403 
2404  >>> x = Real('x')
2405  >>> y = Real('y')
2406  >>> x * y
2407  x*y
2408  >>> (x * y).sort()
2409  Real
2410  """
2411  if isinstance(other, BoolRef):
2412  return If(other, self, 0)
2413  a, b = _coerce_exprs(self, other)
2414  return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctxctx)
2415 
2416  def __rmul__(self, other):
2417  """Create the Z3 expression `other * self`.
2418 
2419  >>> x = Real('x')
2420  >>> 10 * x
2421  10*x
2422  """
2423  a, b = _coerce_exprs(self, other)
2424  return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctxctx)
2425 
2426  def __sub__(self, other):
2427  """Create the Z3 expression `self - other`.
2428 
2429  >>> x = Int('x')
2430  >>> y = Int('y')
2431  >>> x - y
2432  x - y
2433  >>> (x - y).sort()
2434  Int
2435  """
2436  a, b = _coerce_exprs(self, other)
2437  return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctxctx)
2438 
2439  def __rsub__(self, other):
2440  """Create the Z3 expression `other - self`.
2441 
2442  >>> x = Int('x')
2443  >>> 10 - x
2444  10 - x
2445  """
2446  a, b = _coerce_exprs(self, other)
2447  return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctxctx)
2448 
2449  def __pow__(self, other):
2450  """Create the Z3 expression `self**other` (** is the power operator).
2451 
2452  >>> x = Real('x')
2453  >>> x**3
2454  x**3
2455  >>> (x**3).sort()
2456  Real
2457  >>> simplify(IntVal(2)**8)
2458  256
2459  """
2460  a, b = _coerce_exprs(self, other)
2461  return ArithRef(Z3_mk_power(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2462 
2463  def __rpow__(self, other):
2464  """Create the Z3 expression `other**self` (** is the power operator).
2465 
2466  >>> x = Real('x')
2467  >>> 2**x
2468  2**x
2469  >>> (2**x).sort()
2470  Real
2471  >>> simplify(2**IntVal(8))
2472  256
2473  """
2474  a, b = _coerce_exprs(self, other)
2475  return ArithRef(Z3_mk_power(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2476 
2477  def __div__(self, other):
2478  """Create the Z3 expression `other/self`.
2479 
2480  >>> x = Int('x')
2481  >>> y = Int('y')
2482  >>> x/y
2483  x/y
2484  >>> (x/y).sort()
2485  Int
2486  >>> (x/y).sexpr()
2487  '(div x y)'
2488  >>> x = Real('x')
2489  >>> y = Real('y')
2490  >>> x/y
2491  x/y
2492  >>> (x/y).sort()
2493  Real
2494  >>> (x/y).sexpr()
2495  '(/ x y)'
2496  """
2497  a, b = _coerce_exprs(self, other)
2498  return ArithRef(Z3_mk_div(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2499 
2500  def __truediv__(self, other):
2501  """Create the Z3 expression `other/self`."""
2502  return self.__div____div__(other)
2503 
2504  def __rdiv__(self, other):
2505  """Create the Z3 expression `other/self`.
2506 
2507  >>> x = Int('x')
2508  >>> 10/x
2509  10/x
2510  >>> (10/x).sexpr()
2511  '(div 10 x)'
2512  >>> x = Real('x')
2513  >>> 10/x
2514  10/x
2515  >>> (10/x).sexpr()
2516  '(/ 10.0 x)'
2517  """
2518  a, b = _coerce_exprs(self, other)
2519  return ArithRef(Z3_mk_div(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2520 
2521  def __rtruediv__(self, other):
2522  """Create the Z3 expression `other/self`."""
2523  return self.__rdiv____rdiv__(other)
2524 
2525  def __mod__(self, other):
2526  """Create the Z3 expression `other%self`.
2527 
2528  >>> x = Int('x')
2529  >>> y = Int('y')
2530  >>> x % y
2531  x%y
2532  >>> simplify(IntVal(10) % IntVal(3))
2533  1
2534  """
2535  a, b = _coerce_exprs(self, other)
2536  if z3_debug():
2537  _z3_assert(a.is_int(), "Z3 integer expression expected")
2538  return ArithRef(Z3_mk_mod(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2539 
2540  def __rmod__(self, other):
2541  """Create the Z3 expression `other%self`.
2542 
2543  >>> x = Int('x')
2544  >>> 10 % x
2545  10%x
2546  """
2547  a, b = _coerce_exprs(self, other)
2548  if z3_debug():
2549  _z3_assert(a.is_int(), "Z3 integer expression expected")
2550  return ArithRef(Z3_mk_mod(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
2551 
2552  def __neg__(self):
2553  """Return an expression representing `-self`.
2554 
2555  >>> x = Int('x')
2556  >>> -x
2557  -x
2558  >>> simplify(-(-x))
2559  x
2560  """
2561  return ArithRef(Z3_mk_unary_minus(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2562 
2563  def __pos__(self):
2564  """Return `self`.
2565 
2566  >>> x = Int('x')
2567  >>> +x
2568  x
2569  """
2570  return self
2571 
2572  def __le__(self, other):
2573  """Create the Z3 expression `other <= self`.
2574 
2575  >>> x, y = Ints('x y')
2576  >>> x <= y
2577  x <= y
2578  >>> y = Real('y')
2579  >>> x <= y
2580  ToReal(x) <= y
2581  """
2582  a, b = _coerce_exprs(self, other)
2583  return BoolRef(Z3_mk_le(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2584 
2585  def __lt__(self, other):
2586  """Create the Z3 expression `other < self`.
2587 
2588  >>> x, y = Ints('x y')
2589  >>> x < y
2590  x < y
2591  >>> y = Real('y')
2592  >>> x < y
2593  ToReal(x) < y
2594  """
2595  a, b = _coerce_exprs(self, other)
2596  return BoolRef(Z3_mk_lt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2597 
2598  def __gt__(self, other):
2599  """Create the Z3 expression `other > self`.
2600 
2601  >>> x, y = Ints('x y')
2602  >>> x > y
2603  x > y
2604  >>> y = Real('y')
2605  >>> x > y
2606  ToReal(x) > y
2607  """
2608  a, b = _coerce_exprs(self, other)
2609  return BoolRef(Z3_mk_gt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2610 
2611  def __ge__(self, other):
2612  """Create the Z3 expression `other >= self`.
2613 
2614  >>> x, y = Ints('x y')
2615  >>> x >= y
2616  x >= y
2617  >>> y = Real('y')
2618  >>> x >= y
2619  ToReal(x) >= y
2620  """
2621  a, b = _coerce_exprs(self, other)
2622  return BoolRef(Z3_mk_ge(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
2623 
2624 
2625 def is_arith(a):
2626  """Return `True` if `a` is an arithmetical expression.
2627 
2628  >>> x = Int('x')
2629  >>> is_arith(x)
2630  True
2631  >>> is_arith(x + 1)
2632  True
2633  >>> is_arith(1)
2634  False
2635  >>> is_arith(IntVal(1))
2636  True
2637  >>> y = Real('y')
2638  >>> is_arith(y)
2639  True
2640  >>> is_arith(y + 1)
2641  True
2642  """
2643  return isinstance(a, ArithRef)
2644 
2645 
2646 def is_int(a):
2647  """Return `True` if `a` is an integer expression.
2648 
2649  >>> x = Int('x')
2650  >>> is_int(x + 1)
2651  True
2652  >>> is_int(1)
2653  False
2654  >>> is_int(IntVal(1))
2655  True
2656  >>> y = Real('y')
2657  >>> is_int(y)
2658  False
2659  >>> is_int(y + 1)
2660  False
2661  """
2662  return is_arith(a) and a.is_int()
2663 
2664 
2665 def is_real(a):
2666  """Return `True` if `a` is a real expression.
2667 
2668  >>> x = Int('x')
2669  >>> is_real(x + 1)
2670  False
2671  >>> y = Real('y')
2672  >>> is_real(y)
2673  True
2674  >>> is_real(y + 1)
2675  True
2676  >>> is_real(1)
2677  False
2678  >>> is_real(RealVal(1))
2679  True
2680  """
2681  return is_arith(a) and a.is_real()
2682 
2683 
2684 def _is_numeral(ctx, a):
2685  return Z3_is_numeral_ast(ctx.ref(), a)
2686 
2687 
2688 def _is_algebraic(ctx, a):
2689  return Z3_is_algebraic_number(ctx.ref(), a)
2690 
2691 
2693  """Return `True` if `a` is an integer value of sort Int.
2694 
2695  >>> is_int_value(IntVal(1))
2696  True
2697  >>> is_int_value(1)
2698  False
2699  >>> is_int_value(Int('x'))
2700  False
2701  >>> n = Int('x') + 1
2702  >>> n
2703  x + 1
2704  >>> n.arg(1)
2705  1
2706  >>> is_int_value(n.arg(1))
2707  True
2708  >>> is_int_value(RealVal("1/3"))
2709  False
2710  >>> is_int_value(RealVal(1))
2711  False
2712  """
2713  return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2714 
2715 
2717  """Return `True` if `a` is rational value of sort Real.
2718 
2719  >>> is_rational_value(RealVal(1))
2720  True
2721  >>> is_rational_value(RealVal("3/5"))
2722  True
2723  >>> is_rational_value(IntVal(1))
2724  False
2725  >>> is_rational_value(1)
2726  False
2727  >>> n = Real('x') + 1
2728  >>> n.arg(1)
2729  1
2730  >>> is_rational_value(n.arg(1))
2731  True
2732  >>> is_rational_value(Real('x'))
2733  False
2734  """
2735  return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2736 
2737 
2739  """Return `True` if `a` is an algebraic value of sort Real.
2740 
2741  >>> is_algebraic_value(RealVal("3/5"))
2742  False
2743  >>> n = simplify(Sqrt(2))
2744  >>> n
2745  1.4142135623?
2746  >>> is_algebraic_value(n)
2747  True
2748  """
2749  return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2750 
2751 
2752 def is_add(a):
2753  """Return `True` if `a` is an expression of the form b + c.
2754 
2755  >>> x, y = Ints('x y')
2756  >>> is_add(x + y)
2757  True
2758  >>> is_add(x - y)
2759  False
2760  """
2761  return is_app_of(a, Z3_OP_ADD)
2762 
2763 
2764 def is_mul(a):
2765  """Return `True` if `a` is an expression of the form b * c.
2766 
2767  >>> x, y = Ints('x y')
2768  >>> is_mul(x * y)
2769  True
2770  >>> is_mul(x - y)
2771  False
2772  """
2773  return is_app_of(a, Z3_OP_MUL)
2774 
2775 
2776 def is_sub(a):
2777  """Return `True` if `a` is an expression of the form b - c.
2778 
2779  >>> x, y = Ints('x y')
2780  >>> is_sub(x - y)
2781  True
2782  >>> is_sub(x + y)
2783  False
2784  """
2785  return is_app_of(a, Z3_OP_SUB)
2786 
2787 
2788 def is_div(a):
2789  """Return `True` if `a` is an expression of the form b / c.
2790 
2791  >>> x, y = Reals('x y')
2792  >>> is_div(x / y)
2793  True
2794  >>> is_div(x + y)
2795  False
2796  >>> x, y = Ints('x y')
2797  >>> is_div(x / y)
2798  False
2799  >>> is_idiv(x / y)
2800  True
2801  """
2802  return is_app_of(a, Z3_OP_DIV)
2803 
2804 
2805 def is_idiv(a):
2806  """Return `True` if `a` is an expression of the form b div c.
2807 
2808  >>> x, y = Ints('x y')
2809  >>> is_idiv(x / y)
2810  True
2811  >>> is_idiv(x + y)
2812  False
2813  """
2814  return is_app_of(a, Z3_OP_IDIV)
2815 
2816 
2817 def is_mod(a):
2818  """Return `True` if `a` is an expression of the form b % c.
2819 
2820  >>> x, y = Ints('x y')
2821  >>> is_mod(x % y)
2822  True
2823  >>> is_mod(x + y)
2824  False
2825  """
2826  return is_app_of(a, Z3_OP_MOD)
2827 
2828 
2829 def is_le(a):
2830  """Return `True` if `a` is an expression of the form b <= c.
2831 
2832  >>> x, y = Ints('x y')
2833  >>> is_le(x <= y)
2834  True
2835  >>> is_le(x < y)
2836  False
2837  """
2838  return is_app_of(a, Z3_OP_LE)
2839 
2840 
2841 def is_lt(a):
2842  """Return `True` if `a` is an expression of the form b < c.
2843 
2844  >>> x, y = Ints('x y')
2845  >>> is_lt(x < y)
2846  True
2847  >>> is_lt(x == y)
2848  False
2849  """
2850  return is_app_of(a, Z3_OP_LT)
2851 
2852 
2853 def is_ge(a):
2854  """Return `True` if `a` is an expression of the form b >= c.
2855 
2856  >>> x, y = Ints('x y')
2857  >>> is_ge(x >= y)
2858  True
2859  >>> is_ge(x == y)
2860  False
2861  """
2862  return is_app_of(a, Z3_OP_GE)
2863 
2864 
2865 def is_gt(a):
2866  """Return `True` if `a` is an expression of the form b > c.
2867 
2868  >>> x, y = Ints('x y')
2869  >>> is_gt(x > y)
2870  True
2871  >>> is_gt(x == y)
2872  False
2873  """
2874  return is_app_of(a, Z3_OP_GT)
2875 
2876 
2877 def is_is_int(a):
2878  """Return `True` if `a` is an expression of the form IsInt(b).
2879 
2880  >>> x = Real('x')
2881  >>> is_is_int(IsInt(x))
2882  True
2883  >>> is_is_int(x)
2884  False
2885  """
2886  return is_app_of(a, Z3_OP_IS_INT)
2887 
2888 
2889 def is_to_real(a):
2890  """Return `True` if `a` is an expression of the form ToReal(b).
2891 
2892  >>> x = Int('x')
2893  >>> n = ToReal(x)
2894  >>> n
2895  ToReal(x)
2896  >>> is_to_real(n)
2897  True
2898  >>> is_to_real(x)
2899  False
2900  """
2901  return is_app_of(a, Z3_OP_TO_REAL)
2902 
2903 
2904 def is_to_int(a):
2905  """Return `True` if `a` is an expression of the form ToInt(b).
2906 
2907  >>> x = Real('x')
2908  >>> n = ToInt(x)
2909  >>> n
2910  ToInt(x)
2911  >>> is_to_int(n)
2912  True
2913  >>> is_to_int(x)
2914  False
2915  """
2916  return is_app_of(a, Z3_OP_TO_INT)
2917 
2918 
2920  """Integer values."""
2921 
2922  def as_long(self):
2923  """Return a Z3 integer numeral as a Python long (bignum) numeral.
2924 
2925  >>> v = IntVal(1)
2926  >>> v + 1
2927  1 + 1
2928  >>> v.as_long() + 1
2929  2
2930  """
2931  if z3_debug():
2932  _z3_assert(self.is_intis_int(), "Integer value expected")
2933  return int(self.as_stringas_string())
2934 
2935  def as_string(self):
2936  """Return a Z3 integer numeral as a Python string.
2937  >>> v = IntVal(100)
2938  >>> v.as_string()
2939  '100'
2940  """
2941  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
2942 
2943  def as_binary_string(self):
2944  """Return a Z3 integer numeral as a Python binary string.
2945  >>> v = IntVal(10)
2946  >>> v.as_binary_string()
2947  '1010'
2948  """
2949  return Z3_get_numeral_binary_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
2950 
2951 
2953  """Rational values."""
2954 
2955  def numerator(self):
2956  """ Return the numerator of a Z3 rational numeral.
2957 
2958  >>> is_rational_value(RealVal("3/5"))
2959  True
2960  >>> n = RealVal("3/5")
2961  >>> n.numerator()
2962  3
2963  >>> is_rational_value(Q(3,5))
2964  True
2965  >>> Q(3,5).numerator()
2966  3
2967  """
2968  return IntNumRef(Z3_get_numerator(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2969 
2970  def denominator(self):
2971  """ Return the denominator of a Z3 rational numeral.
2972 
2973  >>> is_rational_value(Q(3,5))
2974  True
2975  >>> n = Q(3,5)
2976  >>> n.denominator()
2977  5
2978  """
2979  return IntNumRef(Z3_get_denominator(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
2980 
2982  """ Return the numerator as a Python long.
2983 
2984  >>> v = RealVal(10000000000)
2985  >>> v
2986  10000000000
2987  >>> v + 1
2988  10000000000 + 1
2989  >>> v.numerator_as_long() + 1 == 10000000001
2990  True
2991  """
2992  return self.numeratornumerator().as_long()
2993 
2995  """ Return the denominator as a Python long.
2996 
2997  >>> v = RealVal("1/3")
2998  >>> v
2999  1/3
3000  >>> v.denominator_as_long()
3001  3
3002  """
3003  return self.denominatordenominator().as_long()
3004 
3005  def is_int(self):
3006  return False
3007 
3008  def is_real(self):
3009  return True
3010 
3011  def is_int_value(self):
3012  return self.denominatordenominator().is_int() and self.denominator_as_longdenominator_as_long() == 1
3013 
3014  def as_long(self):
3015  _z3_assert(self.is_int_valueis_int_value(), "Expected integer fraction")
3016  return self.numerator_as_longnumerator_as_long()
3017 
3018  def as_decimal(self, prec):
3019  """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3020 
3021  >>> v = RealVal("1/5")
3022  >>> v.as_decimal(3)
3023  '0.2'
3024  >>> v = RealVal("1/3")
3025  >>> v.as_decimal(3)
3026  '0.333?'
3027  """
3028  return Z3_get_numeral_decimal_string(self.ctx_refctx_ref(), self.as_astas_astas_ast(), prec)
3029 
3030  def as_string(self):
3031  """Return a Z3 rational numeral as a Python string.
3032 
3033  >>> v = Q(3,6)
3034  >>> v.as_string()
3035  '1/2'
3036  """
3037  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3038 
3039  def as_fraction(self):
3040  """Return a Z3 rational as a Python Fraction object.
3041 
3042  >>> v = RealVal("1/5")
3043  >>> v.as_fraction()
3044  Fraction(1, 5)
3045  """
3046  return Fraction(self.numerator_as_longnumerator_as_long(), self.denominator_as_longdenominator_as_long())
3047 
3048 
3050  """Algebraic irrational values."""
3051 
3052  def approx(self, precision=10):
3053  """Return a Z3 rational number that approximates the algebraic number `self`.
3054  The result `r` is such that |r - self| <= 1/10^precision
3055 
3056  >>> x = simplify(Sqrt(2))
3057  >>> x.approx(20)
3058  6838717160008073720548335/4835703278458516698824704
3059  >>> x.approx(5)
3060  2965821/2097152
3061  """
3062  return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_refctx_ref(), self.as_astas_astas_ast(), precision), self.ctxctx)
3063 
3064  def as_decimal(self, prec):
3065  """Return a string representation of the algebraic number `self` in decimal notation
3066  using `prec` decimal places.
3067 
3068  >>> x = simplify(Sqrt(2))
3069  >>> x.as_decimal(10)
3070  '1.4142135623?'
3071  >>> x.as_decimal(20)
3072  '1.41421356237309504880?'
3073  """
3074  return Z3_get_numeral_decimal_string(self.ctx_refctx_ref(), self.as_astas_astas_ast(), prec)
3075 
3076  def poly(self):
3077  return AstVector(Z3_algebraic_get_poly(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3078 
3079  def index(self):
3080  return Z3_algebraic_get_i(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3081 
3082 
3083 def _py2expr(a, ctx=None):
3084  if isinstance(a, bool):
3085  return BoolVal(a, ctx)
3086  if _is_int(a):
3087  return IntVal(a, ctx)
3088  if isinstance(a, float):
3089  return RealVal(a, ctx)
3090  if isinstance(a, str):
3091  return StringVal(a, ctx)
3092  if is_expr(a):
3093  return a
3094  if z3_debug():
3095  _z3_assert(False, "Python bool, int, long or float expected")
3096 
3097 
3098 def IntSort(ctx=None):
3099  """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3100 
3101  >>> IntSort()
3102  Int
3103  >>> x = Const('x', IntSort())
3104  >>> is_int(x)
3105  True
3106  >>> x.sort() == IntSort()
3107  True
3108  >>> x.sort() == BoolSort()
3109  False
3110  """
3111  ctx = _get_ctx(ctx)
3112  return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3113 
3114 
3115 def RealSort(ctx=None):
3116  """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3117 
3118  >>> RealSort()
3119  Real
3120  >>> x = Const('x', RealSort())
3121  >>> is_real(x)
3122  True
3123  >>> is_int(x)
3124  False
3125  >>> x.sort() == RealSort()
3126  True
3127  """
3128  ctx = _get_ctx(ctx)
3129  return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3130 
3131 
3132 def _to_int_str(val):
3133  if isinstance(val, float):
3134  return str(int(val))
3135  elif isinstance(val, bool):
3136  if val:
3137  return "1"
3138  else:
3139  return "0"
3140  elif _is_int(val):
3141  return str(val)
3142  elif isinstance(val, str):
3143  return val
3144  if z3_debug():
3145  _z3_assert(False, "Python value cannot be used as a Z3 integer")
3146 
3147 
3148 def IntVal(val, ctx=None):
3149  """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3150 
3151  >>> IntVal(1)
3152  1
3153  >>> IntVal("100")
3154  100
3155  """
3156  ctx = _get_ctx(ctx)
3157  return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3158 
3159 
3160 def RealVal(val, ctx=None):
3161  """Return a Z3 real value.
3162 
3163  `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3164  If `ctx=None`, then the global context is used.
3165 
3166  >>> RealVal(1)
3167  1
3168  >>> RealVal(1).sort()
3169  Real
3170  >>> RealVal("3/5")
3171  3/5
3172  >>> RealVal("1.5")
3173  3/2
3174  """
3175  ctx = _get_ctx(ctx)
3176  return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3177 
3178 
3179 def RatVal(a, b, ctx=None):
3180  """Return a Z3 rational a/b.
3181 
3182  If `ctx=None`, then the global context is used.
3183 
3184  >>> RatVal(3,5)
3185  3/5
3186  >>> RatVal(3,5).sort()
3187  Real
3188  """
3189  if z3_debug():
3190  _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3191  _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3192  return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3193 
3194 
3195 def Q(a, b, ctx=None):
3196  """Return a Z3 rational a/b.
3197 
3198  If `ctx=None`, then the global context is used.
3199 
3200  >>> Q(3,5)
3201  3/5
3202  >>> Q(3,5).sort()
3203  Real
3204  """
3205  return simplify(RatVal(a, b, ctx=ctx))
3206 
3207 
3208 def Int(name, ctx=None):
3209  """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3210 
3211  >>> x = Int('x')
3212  >>> is_int(x)
3213  True
3214  >>> is_int(x + 1)
3215  True
3216  """
3217  ctx = _get_ctx(ctx)
3218  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3219 
3220 
3221 def Ints(names, ctx=None):
3222  """Return a tuple of Integer constants.
3223 
3224  >>> x, y, z = Ints('x y z')
3225  >>> Sum(x, y, z)
3226  x + y + z
3227  """
3228  ctx = _get_ctx(ctx)
3229  if isinstance(names, str):
3230  names = names.split(" ")
3231  return [Int(name, ctx) for name in names]
3232 
3233 
3234 def IntVector(prefix, sz, ctx=None):
3235  """Return a list of integer constants of size `sz`.
3236 
3237  >>> X = IntVector('x', 3)
3238  >>> X
3239  [x__0, x__1, x__2]
3240  >>> Sum(X)
3241  x__0 + x__1 + x__2
3242  """
3243  ctx = _get_ctx(ctx)
3244  return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3245 
3246 
3247 def FreshInt(prefix="x", ctx=None):
3248  """Return a fresh integer constant in the given context using the given prefix.
3249 
3250  >>> x = FreshInt()
3251  >>> y = FreshInt()
3252  >>> eq(x, y)
3253  False
3254  >>> x.sort()
3255  Int
3256  """
3257  ctx = _get_ctx(ctx)
3258  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3259 
3260 
3261 def Real(name, ctx=None):
3262  """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3263 
3264  >>> x = Real('x')
3265  >>> is_real(x)
3266  True
3267  >>> is_real(x + 1)
3268  True
3269  """
3270  ctx = _get_ctx(ctx)
3271  return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3272 
3273 
3274 def Reals(names, ctx=None):
3275  """Return a tuple of real constants.
3276 
3277  >>> x, y, z = Reals('x y z')
3278  >>> Sum(x, y, z)
3279  x + y + z
3280  >>> Sum(x, y, z).sort()
3281  Real
3282  """
3283  ctx = _get_ctx(ctx)
3284  if isinstance(names, str):
3285  names = names.split(" ")
3286  return [Real(name, ctx) for name in names]
3287 
3288 
3289 def RealVector(prefix, sz, ctx=None):
3290  """Return a list of real constants of size `sz`.
3291 
3292  >>> X = RealVector('x', 3)
3293  >>> X
3294  [x__0, x__1, x__2]
3295  >>> Sum(X)
3296  x__0 + x__1 + x__2
3297  >>> Sum(X).sort()
3298  Real
3299  """
3300  ctx = _get_ctx(ctx)
3301  return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3302 
3303 
3304 def FreshReal(prefix="b", ctx=None):
3305  """Return a fresh real constant in the given context using the given prefix.
3306 
3307  >>> x = FreshReal()
3308  >>> y = FreshReal()
3309  >>> eq(x, y)
3310  False
3311  >>> x.sort()
3312  Real
3313  """
3314  ctx = _get_ctx(ctx)
3315  return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3316 
3317 
3318 def ToReal(a):
3319  """ Return the Z3 expression ToReal(a).
3320 
3321  >>> x = Int('x')
3322  >>> x.sort()
3323  Int
3324  >>> n = ToReal(x)
3325  >>> n
3326  ToReal(x)
3327  >>> n.sort()
3328  Real
3329  """
3330  if z3_debug():
3331  _z3_assert(a.is_int(), "Z3 integer expression expected.")
3332  ctx = a.ctx
3333  return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3334 
3335 
3336 def ToInt(a):
3337  """ Return the Z3 expression ToInt(a).
3338 
3339  >>> x = Real('x')
3340  >>> x.sort()
3341  Real
3342  >>> n = ToInt(x)
3343  >>> n
3344  ToInt(x)
3345  >>> n.sort()
3346  Int
3347  """
3348  if z3_debug():
3349  _z3_assert(a.is_real(), "Z3 real expression expected.")
3350  ctx = a.ctx
3351  return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3352 
3353 
3354 def IsInt(a):
3355  """ Return the Z3 predicate IsInt(a).
3356 
3357  >>> x = Real('x')
3358  >>> IsInt(x + "1/2")
3359  IsInt(x + 1/2)
3360  >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3361  [x = 1/2]
3362  >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3363  no solution
3364  """
3365  if z3_debug():
3366  _z3_assert(a.is_real(), "Z3 real expression expected.")
3367  ctx = a.ctx
3368  return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3369 
3370 
3371 def Sqrt(a, ctx=None):
3372  """ Return a Z3 expression which represents the square root of a.
3373 
3374  >>> x = Real('x')
3375  >>> Sqrt(x)
3376  x**(1/2)
3377  """
3378  if not is_expr(a):
3379  ctx = _get_ctx(ctx)
3380  a = RealVal(a, ctx)
3381  return a ** "1/2"
3382 
3383 
3384 def Cbrt(a, ctx=None):
3385  """ Return a Z3 expression which represents the cubic root of a.
3386 
3387  >>> x = Real('x')
3388  >>> Cbrt(x)
3389  x**(1/3)
3390  """
3391  if not is_expr(a):
3392  ctx = _get_ctx(ctx)
3393  a = RealVal(a, ctx)
3394  return a ** "1/3"
3395 
3396 
3401 
3402 
3404  """Bit-vector sort."""
3405 
3406  def size(self):
3407  """Return the size (number of bits) of the bit-vector sort `self`.
3408 
3409  >>> b = BitVecSort(32)
3410  >>> b.size()
3411  32
3412  """
3413  return int(Z3_get_bv_sort_size(self.ctx_refctx_ref(), self.astast))
3414 
3415  def subsort(self, other):
3416  return is_bv_sort(other) and self.sizesize() < other.size()
3417 
3418  def cast(self, val):
3419  """Try to cast `val` as a Bit-Vector.
3420 
3421  >>> b = BitVecSort(32)
3422  >>> b.cast(10)
3423  10
3424  >>> b.cast(10).sexpr()
3425  '#x0000000a'
3426  """
3427  if is_expr(val):
3428  if z3_debug():
3429  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
3430  # Idea: use sign_extend if sort of val is a bitvector of smaller size
3431  return val
3432  else:
3433  return BitVecVal(val, self)
3434 
3435 
3436 def is_bv_sort(s):
3437  """Return True if `s` is a Z3 bit-vector sort.
3438 
3439  >>> is_bv_sort(BitVecSort(32))
3440  True
3441  >>> is_bv_sort(IntSort())
3442  False
3443  """
3444  return isinstance(s, BitVecSortRef)
3445 
3446 
3448  """Bit-vector expressions."""
3449 
3450  def sort(self):
3451  """Return the sort of the bit-vector expression `self`.
3452 
3453  >>> x = BitVec('x', 32)
3454  >>> x.sort()
3455  BitVec(32)
3456  >>> x.sort() == BitVecSort(32)
3457  True
3458  """
3459  return BitVecSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3460 
3461  def size(self):
3462  """Return the number of bits of the bit-vector expression `self`.
3463 
3464  >>> x = BitVec('x', 32)
3465  >>> (x + 1).size()
3466  32
3467  >>> Concat(x, x).size()
3468  64
3469  """
3470  return self.sortsortsort().size()
3471 
3472  def __add__(self, other):
3473  """Create the Z3 expression `self + other`.
3474 
3475  >>> x = BitVec('x', 32)
3476  >>> y = BitVec('y', 32)
3477  >>> x + y
3478  x + y
3479  >>> (x + y).sort()
3480  BitVec(32)
3481  """
3482  a, b = _coerce_exprs(self, other)
3483  return BitVecRef(Z3_mk_bvadd(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3484 
3485  def __radd__(self, other):
3486  """Create the Z3 expression `other + self`.
3487 
3488  >>> x = BitVec('x', 32)
3489  >>> 10 + x
3490  10 + x
3491  """
3492  a, b = _coerce_exprs(self, other)
3493  return BitVecRef(Z3_mk_bvadd(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3494 
3495  def __mul__(self, other):
3496  """Create the Z3 expression `self * other`.
3497 
3498  >>> x = BitVec('x', 32)
3499  >>> y = BitVec('y', 32)
3500  >>> x * y
3501  x*y
3502  >>> (x * y).sort()
3503  BitVec(32)
3504  """
3505  a, b = _coerce_exprs(self, other)
3506  return BitVecRef(Z3_mk_bvmul(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3507 
3508  def __rmul__(self, other):
3509  """Create the Z3 expression `other * self`.
3510 
3511  >>> x = BitVec('x', 32)
3512  >>> 10 * x
3513  10*x
3514  """
3515  a, b = _coerce_exprs(self, other)
3516  return BitVecRef(Z3_mk_bvmul(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3517 
3518  def __sub__(self, other):
3519  """Create the Z3 expression `self - other`.
3520 
3521  >>> x = BitVec('x', 32)
3522  >>> y = BitVec('y', 32)
3523  >>> x - y
3524  x - y
3525  >>> (x - y).sort()
3526  BitVec(32)
3527  """
3528  a, b = _coerce_exprs(self, other)
3529  return BitVecRef(Z3_mk_bvsub(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3530 
3531  def __rsub__(self, other):
3532  """Create the Z3 expression `other - self`.
3533 
3534  >>> x = BitVec('x', 32)
3535  >>> 10 - x
3536  10 - x
3537  """
3538  a, b = _coerce_exprs(self, other)
3539  return BitVecRef(Z3_mk_bvsub(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3540 
3541  def __or__(self, other):
3542  """Create the Z3 expression bitwise-or `self | other`.
3543 
3544  >>> x = BitVec('x', 32)
3545  >>> y = BitVec('y', 32)
3546  >>> x | y
3547  x | y
3548  >>> (x | y).sort()
3549  BitVec(32)
3550  """
3551  a, b = _coerce_exprs(self, other)
3552  return BitVecRef(Z3_mk_bvor(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3553 
3554  def __ror__(self, other):
3555  """Create the Z3 expression bitwise-or `other | self`.
3556 
3557  >>> x = BitVec('x', 32)
3558  >>> 10 | x
3559  10 | x
3560  """
3561  a, b = _coerce_exprs(self, other)
3562  return BitVecRef(Z3_mk_bvor(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3563 
3564  def __and__(self, other):
3565  """Create the Z3 expression bitwise-and `self & other`.
3566 
3567  >>> x = BitVec('x', 32)
3568  >>> y = BitVec('y', 32)
3569  >>> x & y
3570  x & y
3571  >>> (x & y).sort()
3572  BitVec(32)
3573  """
3574  a, b = _coerce_exprs(self, other)
3575  return BitVecRef(Z3_mk_bvand(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3576 
3577  def __rand__(self, other):
3578  """Create the Z3 expression bitwise-or `other & self`.
3579 
3580  >>> x = BitVec('x', 32)
3581  >>> 10 & x
3582  10 & x
3583  """
3584  a, b = _coerce_exprs(self, other)
3585  return BitVecRef(Z3_mk_bvand(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3586 
3587  def __xor__(self, other):
3588  """Create the Z3 expression bitwise-xor `self ^ other`.
3589 
3590  >>> x = BitVec('x', 32)
3591  >>> y = BitVec('y', 32)
3592  >>> x ^ y
3593  x ^ y
3594  >>> (x ^ y).sort()
3595  BitVec(32)
3596  """
3597  a, b = _coerce_exprs(self, other)
3598  return BitVecRef(Z3_mk_bvxor(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3599 
3600  def __rxor__(self, other):
3601  """Create the Z3 expression bitwise-xor `other ^ self`.
3602 
3603  >>> x = BitVec('x', 32)
3604  >>> 10 ^ x
3605  10 ^ x
3606  """
3607  a, b = _coerce_exprs(self, other)
3608  return BitVecRef(Z3_mk_bvxor(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3609 
3610  def __pos__(self):
3611  """Return `self`.
3612 
3613  >>> x = BitVec('x', 32)
3614  >>> +x
3615  x
3616  """
3617  return self
3618 
3619  def __neg__(self):
3620  """Return an expression representing `-self`.
3621 
3622  >>> x = BitVec('x', 32)
3623  >>> -x
3624  -x
3625  >>> simplify(-(-x))
3626  x
3627  """
3628  return BitVecRef(Z3_mk_bvneg(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3629 
3630  def __invert__(self):
3631  """Create the Z3 expression bitwise-not `~self`.
3632 
3633  >>> x = BitVec('x', 32)
3634  >>> ~x
3635  ~x
3636  >>> simplify(~(~x))
3637  x
3638  """
3639  return BitVecRef(Z3_mk_bvnot(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
3640 
3641  def __div__(self, other):
3642  """Create the Z3 expression (signed) division `self / other`.
3643 
3644  Use the function UDiv() for unsigned division.
3645 
3646  >>> x = BitVec('x', 32)
3647  >>> y = BitVec('y', 32)
3648  >>> x / y
3649  x/y
3650  >>> (x / y).sort()
3651  BitVec(32)
3652  >>> (x / y).sexpr()
3653  '(bvsdiv x y)'
3654  >>> UDiv(x, y).sexpr()
3655  '(bvudiv x y)'
3656  """
3657  a, b = _coerce_exprs(self, other)
3658  return BitVecRef(Z3_mk_bvsdiv(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3659 
3660  def __truediv__(self, other):
3661  """Create the Z3 expression (signed) division `self / other`."""
3662  return self.__div____div__(other)
3663 
3664  def __rdiv__(self, other):
3665  """Create the Z3 expression (signed) division `other / self`.
3666 
3667  Use the function UDiv() for unsigned division.
3668 
3669  >>> x = BitVec('x', 32)
3670  >>> 10 / x
3671  10/x
3672  >>> (10 / x).sexpr()
3673  '(bvsdiv #x0000000a x)'
3674  >>> UDiv(10, x).sexpr()
3675  '(bvudiv #x0000000a x)'
3676  """
3677  a, b = _coerce_exprs(self, other)
3678  return BitVecRef(Z3_mk_bvsdiv(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3679 
3680  def __rtruediv__(self, other):
3681  """Create the Z3 expression (signed) division `other / self`."""
3682  return self.__rdiv____rdiv__(other)
3683 
3684  def __mod__(self, other):
3685  """Create the Z3 expression (signed) mod `self % other`.
3686 
3687  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3688 
3689  >>> x = BitVec('x', 32)
3690  >>> y = BitVec('y', 32)
3691  >>> x % y
3692  x%y
3693  >>> (x % y).sort()
3694  BitVec(32)
3695  >>> (x % y).sexpr()
3696  '(bvsmod x y)'
3697  >>> URem(x, y).sexpr()
3698  '(bvurem x y)'
3699  >>> SRem(x, y).sexpr()
3700  '(bvsrem x y)'
3701  """
3702  a, b = _coerce_exprs(self, other)
3703  return BitVecRef(Z3_mk_bvsmod(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3704 
3705  def __rmod__(self, other):
3706  """Create the Z3 expression (signed) mod `other % self`.
3707 
3708  Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3709 
3710  >>> x = BitVec('x', 32)
3711  >>> 10 % x
3712  10%x
3713  >>> (10 % x).sexpr()
3714  '(bvsmod #x0000000a x)'
3715  >>> URem(10, x).sexpr()
3716  '(bvurem #x0000000a x)'
3717  >>> SRem(10, x).sexpr()
3718  '(bvsrem #x0000000a x)'
3719  """
3720  a, b = _coerce_exprs(self, other)
3721  return BitVecRef(Z3_mk_bvsmod(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3722 
3723  def __le__(self, other):
3724  """Create the Z3 expression (signed) `other <= self`.
3725 
3726  Use the function ULE() for unsigned less than or equal to.
3727 
3728  >>> x, y = BitVecs('x y', 32)
3729  >>> x <= y
3730  x <= y
3731  >>> (x <= y).sexpr()
3732  '(bvsle x y)'
3733  >>> ULE(x, y).sexpr()
3734  '(bvule x y)'
3735  """
3736  a, b = _coerce_exprs(self, other)
3737  return BoolRef(Z3_mk_bvsle(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3738 
3739  def __lt__(self, other):
3740  """Create the Z3 expression (signed) `other < self`.
3741 
3742  Use the function ULT() for unsigned less than.
3743 
3744  >>> x, y = BitVecs('x y', 32)
3745  >>> x < y
3746  x < y
3747  >>> (x < y).sexpr()
3748  '(bvslt x y)'
3749  >>> ULT(x, y).sexpr()
3750  '(bvult x y)'
3751  """
3752  a, b = _coerce_exprs(self, other)
3753  return BoolRef(Z3_mk_bvslt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3754 
3755  def __gt__(self, other):
3756  """Create the Z3 expression (signed) `other > self`.
3757 
3758  Use the function UGT() for unsigned greater than.
3759 
3760  >>> x, y = BitVecs('x y', 32)
3761  >>> x > y
3762  x > y
3763  >>> (x > y).sexpr()
3764  '(bvsgt x y)'
3765  >>> UGT(x, y).sexpr()
3766  '(bvugt x y)'
3767  """
3768  a, b = _coerce_exprs(self, other)
3769  return BoolRef(Z3_mk_bvsgt(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3770 
3771  def __ge__(self, other):
3772  """Create the Z3 expression (signed) `other >= self`.
3773 
3774  Use the function UGE() for unsigned greater than or equal to.
3775 
3776  >>> x, y = BitVecs('x y', 32)
3777  >>> x >= y
3778  x >= y
3779  >>> (x >= y).sexpr()
3780  '(bvsge x y)'
3781  >>> UGE(x, y).sexpr()
3782  '(bvuge x y)'
3783  """
3784  a, b = _coerce_exprs(self, other)
3785  return BoolRef(Z3_mk_bvsge(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3786 
3787  def __rshift__(self, other):
3788  """Create the Z3 expression (arithmetical) right shift `self >> other`
3789 
3790  Use the function LShR() for the right logical shift
3791 
3792  >>> x, y = BitVecs('x y', 32)
3793  >>> x >> y
3794  x >> y
3795  >>> (x >> y).sexpr()
3796  '(bvashr x y)'
3797  >>> LShR(x, y).sexpr()
3798  '(bvlshr x y)'
3799  >>> BitVecVal(4, 3)
3800  4
3801  >>> BitVecVal(4, 3).as_signed_long()
3802  -4
3803  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3804  -2
3805  >>> simplify(BitVecVal(4, 3) >> 1)
3806  6
3807  >>> simplify(LShR(BitVecVal(4, 3), 1))
3808  2
3809  >>> simplify(BitVecVal(2, 3) >> 1)
3810  1
3811  >>> simplify(LShR(BitVecVal(2, 3), 1))
3812  1
3813  """
3814  a, b = _coerce_exprs(self, other)
3815  return BitVecRef(Z3_mk_bvashr(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3816 
3817  def __lshift__(self, other):
3818  """Create the Z3 expression left shift `self << other`
3819 
3820  >>> x, y = BitVecs('x y', 32)
3821  >>> x << y
3822  x << y
3823  >>> (x << y).sexpr()
3824  '(bvshl x y)'
3825  >>> simplify(BitVecVal(2, 3) << 1)
3826  4
3827  """
3828  a, b = _coerce_exprs(self, other)
3829  return BitVecRef(Z3_mk_bvshl(self.ctx_refctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
3830 
3831  def __rrshift__(self, other):
3832  """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3833 
3834  Use the function LShR() for the right logical shift
3835 
3836  >>> x = BitVec('x', 32)
3837  >>> 10 >> x
3838  10 >> x
3839  >>> (10 >> x).sexpr()
3840  '(bvashr #x0000000a x)'
3841  """
3842  a, b = _coerce_exprs(self, other)
3843  return BitVecRef(Z3_mk_bvashr(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3844 
3845  def __rlshift__(self, other):
3846  """Create the Z3 expression left shift `other << self`.
3847 
3848  Use the function LShR() for the right logical shift
3849 
3850  >>> x = BitVec('x', 32)
3851  >>> 10 << x
3852  10 << x
3853  >>> (10 << x).sexpr()
3854  '(bvshl #x0000000a x)'
3855  """
3856  a, b = _coerce_exprs(self, other)
3857  return BitVecRef(Z3_mk_bvshl(self.ctx_refctx_ref(), b.as_ast(), a.as_ast()), self.ctxctx)
3858 
3859 
3861  """Bit-vector values."""
3862 
3863  def as_long(self):
3864  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3865 
3866  >>> v = BitVecVal(0xbadc0de, 32)
3867  >>> v
3868  195936478
3869  >>> print("0x%.8x" % v.as_long())
3870  0x0badc0de
3871  """
3872  return int(self.as_stringas_string())
3873 
3874  def as_signed_long(self):
3875  """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3876  The most significant bit is assumed to be the sign.
3877 
3878  >>> BitVecVal(4, 3).as_signed_long()
3879  -4
3880  >>> BitVecVal(7, 3).as_signed_long()
3881  -1
3882  >>> BitVecVal(3, 3).as_signed_long()
3883  3
3884  >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3885  -1
3886  >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3887  -1
3888  """
3889  sz = self.sizesize()
3890  val = self.as_longas_long()
3891  if val >= 2**(sz - 1):
3892  val = val - 2**sz
3893  if val < -2**(sz - 1):
3894  val = val + 2**sz
3895  return int(val)
3896 
3897  def as_string(self):
3898  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3899 
3900  def as_binary_string(self):
3901  return Z3_get_numeral_binary_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
3902 
3903 
3904 def is_bv(a):
3905  """Return `True` if `a` is a Z3 bit-vector expression.
3906 
3907  >>> b = BitVec('b', 32)
3908  >>> is_bv(b)
3909  True
3910  >>> is_bv(b + 10)
3911  True
3912  >>> is_bv(Int('x'))
3913  False
3914  """
3915  return isinstance(a, BitVecRef)
3916 
3917 
3919  """Return `True` if `a` is a Z3 bit-vector numeral value.
3920 
3921  >>> b = BitVec('b', 32)
3922  >>> is_bv_value(b)
3923  False
3924  >>> b = BitVecVal(10, 32)
3925  >>> b
3926  10
3927  >>> is_bv_value(b)
3928  True
3929  """
3930  return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3931 
3932 
3933 def BV2Int(a, is_signed=False):
3934  """Return the Z3 expression BV2Int(a).
3935 
3936  >>> b = BitVec('b', 3)
3937  >>> BV2Int(b).sort()
3938  Int
3939  >>> x = Int('x')
3940  >>> x > BV2Int(b)
3941  x > BV2Int(b)
3942  >>> x > BV2Int(b, is_signed=False)
3943  x > BV2Int(b)
3944  >>> x > BV2Int(b, is_signed=True)
3945  x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3946  >>> solve(x > BV2Int(b), b == 1, x < 3)
3947  [x = 2, b = 1]
3948  """
3949  if z3_debug():
3950  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3951  ctx = a.ctx
3952  # investigate problem with bv2int
3953  return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3954 
3955 
3956 def Int2BV(a, num_bits):
3957  """Return the z3 expression Int2BV(a, num_bits).
3958  It is a bit-vector of width num_bits and represents the
3959  modulo of a by 2^num_bits
3960  """
3961  ctx = a.ctx
3962  return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3963 
3964 
3965 def BitVecSort(sz, ctx=None):
3966  """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3967 
3968  >>> Byte = BitVecSort(8)
3969  >>> Word = BitVecSort(16)
3970  >>> Byte
3971  BitVec(8)
3972  >>> x = Const('x', Byte)
3973  >>> eq(x, BitVec('x', 8))
3974  True
3975  """
3976  ctx = _get_ctx(ctx)
3977  return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3978 
3979 
3980 def BitVecVal(val, bv, ctx=None):
3981  """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3982 
3983  >>> v = BitVecVal(10, 32)
3984  >>> v
3985  10
3986  >>> print("0x%.8x" % v.as_long())
3987  0x0000000a
3988  """
3989  if is_bv_sort(bv):
3990  ctx = bv.ctx
3991  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3992  else:
3993  ctx = _get_ctx(ctx)
3994  return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3995 
3996 
3997 def BitVec(name, bv, ctx=None):
3998  """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3999  If `ctx=None`, then the global context is used.
4000 
4001  >>> x = BitVec('x', 16)
4002  >>> is_bv(x)
4003  True
4004  >>> x.size()
4005  16
4006  >>> x.sort()
4007  BitVec(16)
4008  >>> word = BitVecSort(16)
4009  >>> x2 = BitVec('x', word)
4010  >>> eq(x, x2)
4011  True
4012  """
4013  if isinstance(bv, BitVecSortRef):
4014  ctx = bv.ctx
4015  else:
4016  ctx = _get_ctx(ctx)
4017  bv = BitVecSort(bv, ctx)
4018  return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4019 
4020 
4021 def BitVecs(names, bv, ctx=None):
4022  """Return a tuple of bit-vector constants of size bv.
4023 
4024  >>> x, y, z = BitVecs('x y z', 16)
4025  >>> x.size()
4026  16
4027  >>> x.sort()
4028  BitVec(16)
4029  >>> Sum(x, y, z)
4030  0 + x + y + z
4031  >>> Product(x, y, z)
4032  1*x*y*z
4033  >>> simplify(Product(x, y, z))
4034  x*y*z
4035  """
4036  ctx = _get_ctx(ctx)
4037  if isinstance(names, str):
4038  names = names.split(" ")
4039  return [BitVec(name, bv, ctx) for name in names]
4040 
4041 
4042 def Concat(*args):
4043  """Create a Z3 bit-vector concatenation expression.
4044 
4045  >>> v = BitVecVal(1, 4)
4046  >>> Concat(v, v+1, v)
4047  Concat(Concat(1, 1 + 1), 1)
4048  >>> simplify(Concat(v, v+1, v))
4049  289
4050  >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4051  121
4052  """
4053  args = _get_args(args)
4054  sz = len(args)
4055  if z3_debug():
4056  _z3_assert(sz >= 2, "At least two arguments expected.")
4057 
4058  ctx = None
4059  for a in args:
4060  if is_expr(a):
4061  ctx = a.ctx
4062  break
4063  if is_seq(args[0]) or isinstance(args[0], str):
4064  args = [_coerce_seq(s, ctx) for s in args]
4065  if z3_debug():
4066  _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4067  v = (Ast * sz)()
4068  for i in range(sz):
4069  v[i] = args[i].as_ast()
4070  return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4071 
4072  if is_re(args[0]):
4073  if z3_debug():
4074  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4075  v = (Ast * sz)()
4076  for i in range(sz):
4077  v[i] = args[i].as_ast()
4078  return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4079 
4080  if z3_debug():
4081  _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4082  r = args[0]
4083  for i in range(sz - 1):
4084  r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4085  return r
4086 
4087 
4088 def Extract(high, low, a):
4089  """Create a Z3 bit-vector extraction expression.
4090  Extract is overloaded to also work on sequence extraction.
4091  The functions SubString and SubSeq are redirected to Extract.
4092  For this case, the arguments are reinterpreted as:
4093  high - is a sequence (string)
4094  low - is an offset
4095  a - is the length to be extracted
4096 
4097  >>> x = BitVec('x', 8)
4098  >>> Extract(6, 2, x)
4099  Extract(6, 2, x)
4100  >>> Extract(6, 2, x).sort()
4101  BitVec(5)
4102  >>> simplify(Extract(StringVal("abcd"),2,1))
4103  "c"
4104  """
4105  if isinstance(high, str):
4106  high = StringVal(high)
4107  if is_seq(high):
4108  s = high
4109  offset, length = _coerce_exprs(low, a, s.ctx)
4110  return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4111  if z3_debug():
4112  _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4113  _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4114  "First and second arguments must be non negative integers")
4115  _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4116  return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4117 
4118 
4119 def _check_bv_args(a, b):
4120  if z3_debug():
4121  _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4122 
4123 
4124 def ULE(a, b):
4125  """Create the Z3 expression (unsigned) `other <= self`.
4126 
4127  Use the operator <= for signed less than or equal to.
4128 
4129  >>> x, y = BitVecs('x y', 32)
4130  >>> ULE(x, y)
4131  ULE(x, y)
4132  >>> (x <= y).sexpr()
4133  '(bvsle x y)'
4134  >>> ULE(x, y).sexpr()
4135  '(bvule x y)'
4136  """
4137  _check_bv_args(a, b)
4138  a, b = _coerce_exprs(a, b)
4139  return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4140 
4141 
4142 def ULT(a, b):
4143  """Create the Z3 expression (unsigned) `other < self`.
4144 
4145  Use the operator < for signed less than.
4146 
4147  >>> x, y = BitVecs('x y', 32)
4148  >>> ULT(x, y)
4149  ULT(x, y)
4150  >>> (x < y).sexpr()
4151  '(bvslt x y)'
4152  >>> ULT(x, y).sexpr()
4153  '(bvult x y)'
4154  """
4155  _check_bv_args(a, b)
4156  a, b = _coerce_exprs(a, b)
4157  return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4158 
4159 
4160 def UGE(a, b):
4161  """Create the Z3 expression (unsigned) `other >= self`.
4162 
4163  Use the operator >= for signed greater than or equal to.
4164 
4165  >>> x, y = BitVecs('x y', 32)
4166  >>> UGE(x, y)
4167  UGE(x, y)
4168  >>> (x >= y).sexpr()
4169  '(bvsge x y)'
4170  >>> UGE(x, y).sexpr()
4171  '(bvuge x y)'
4172  """
4173  _check_bv_args(a, b)
4174  a, b = _coerce_exprs(a, b)
4175  return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4176 
4177 
4178 def UGT(a, b):
4179  """Create the Z3 expression (unsigned) `other > self`.
4180 
4181  Use the operator > for signed greater than.
4182 
4183  >>> x, y = BitVecs('x y', 32)
4184  >>> UGT(x, y)
4185  UGT(x, y)
4186  >>> (x > y).sexpr()
4187  '(bvsgt x y)'
4188  >>> UGT(x, y).sexpr()
4189  '(bvugt x y)'
4190  """
4191  _check_bv_args(a, b)
4192  a, b = _coerce_exprs(a, b)
4193  return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4194 
4195 
4196 def UDiv(a, b):
4197  """Create the Z3 expression (unsigned) division `self / other`.
4198 
4199  Use the operator / for signed division.
4200 
4201  >>> x = BitVec('x', 32)
4202  >>> y = BitVec('y', 32)
4203  >>> UDiv(x, y)
4204  UDiv(x, y)
4205  >>> UDiv(x, y).sort()
4206  BitVec(32)
4207  >>> (x / y).sexpr()
4208  '(bvsdiv x y)'
4209  >>> UDiv(x, y).sexpr()
4210  '(bvudiv x y)'
4211  """
4212  _check_bv_args(a, b)
4213  a, b = _coerce_exprs(a, b)
4214  return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4215 
4216 
4217 def URem(a, b):
4218  """Create the Z3 expression (unsigned) remainder `self % other`.
4219 
4220  Use the operator % for signed modulus, and SRem() for signed remainder.
4221 
4222  >>> x = BitVec('x', 32)
4223  >>> y = BitVec('y', 32)
4224  >>> URem(x, y)
4225  URem(x, y)
4226  >>> URem(x, y).sort()
4227  BitVec(32)
4228  >>> (x % y).sexpr()
4229  '(bvsmod x y)'
4230  >>> URem(x, y).sexpr()
4231  '(bvurem x y)'
4232  """
4233  _check_bv_args(a, b)
4234  a, b = _coerce_exprs(a, b)
4235  return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4236 
4237 
4238 def SRem(a, b):
4239  """Create the Z3 expression signed remainder.
4240 
4241  Use the operator % for signed modulus, and URem() for unsigned remainder.
4242 
4243  >>> x = BitVec('x', 32)
4244  >>> y = BitVec('y', 32)
4245  >>> SRem(x, y)
4246  SRem(x, y)
4247  >>> SRem(x, y).sort()
4248  BitVec(32)
4249  >>> (x % y).sexpr()
4250  '(bvsmod x y)'
4251  >>> SRem(x, y).sexpr()
4252  '(bvsrem x y)'
4253  """
4254  _check_bv_args(a, b)
4255  a, b = _coerce_exprs(a, b)
4256  return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4257 
4258 
4259 def LShR(a, b):
4260  """Create the Z3 expression logical right shift.
4261 
4262  Use the operator >> for the arithmetical right shift.
4263 
4264  >>> x, y = BitVecs('x y', 32)
4265  >>> LShR(x, y)
4266  LShR(x, y)
4267  >>> (x >> y).sexpr()
4268  '(bvashr x y)'
4269  >>> LShR(x, y).sexpr()
4270  '(bvlshr x y)'
4271  >>> BitVecVal(4, 3)
4272  4
4273  >>> BitVecVal(4, 3).as_signed_long()
4274  -4
4275  >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4276  -2
4277  >>> simplify(BitVecVal(4, 3) >> 1)
4278  6
4279  >>> simplify(LShR(BitVecVal(4, 3), 1))
4280  2
4281  >>> simplify(BitVecVal(2, 3) >> 1)
4282  1
4283  >>> simplify(LShR(BitVecVal(2, 3), 1))
4284  1
4285  """
4286  _check_bv_args(a, b)
4287  a, b = _coerce_exprs(a, b)
4288  return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4289 
4290 
4291 def RotateLeft(a, b):
4292  """Return an expression representing `a` rotated to the left `b` times.
4293 
4294  >>> a, b = BitVecs('a b', 16)
4295  >>> RotateLeft(a, b)
4296  RotateLeft(a, b)
4297  >>> simplify(RotateLeft(a, 0))
4298  a
4299  >>> simplify(RotateLeft(a, 16))
4300  a
4301  """
4302  _check_bv_args(a, b)
4303  a, b = _coerce_exprs(a, b)
4304  return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4305 
4306 
4307 def RotateRight(a, b):
4308  """Return an expression representing `a` rotated to the right `b` times.
4309 
4310  >>> a, b = BitVecs('a b', 16)
4311  >>> RotateRight(a, b)
4312  RotateRight(a, b)
4313  >>> simplify(RotateRight(a, 0))
4314  a
4315  >>> simplify(RotateRight(a, 16))
4316  a
4317  """
4318  _check_bv_args(a, b)
4319  a, b = _coerce_exprs(a, b)
4320  return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4321 
4322 
4323 def SignExt(n, a):
4324  """Return a bit-vector expression with `n` extra sign-bits.
4325 
4326  >>> x = BitVec('x', 16)
4327  >>> n = SignExt(8, x)
4328  >>> n.size()
4329  24
4330  >>> n
4331  SignExt(8, x)
4332  >>> n.sort()
4333  BitVec(24)
4334  >>> v0 = BitVecVal(2, 2)
4335  >>> v0
4336  2
4337  >>> v0.size()
4338  2
4339  >>> v = simplify(SignExt(6, v0))
4340  >>> v
4341  254
4342  >>> v.size()
4343  8
4344  >>> print("%.x" % v.as_long())
4345  fe
4346  """
4347  if z3_debug():
4348  _z3_assert(_is_int(n), "First argument must be an integer")
4349  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4350  return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4351 
4352 
4353 def ZeroExt(n, a):
4354  """Return a bit-vector expression with `n` extra zero-bits.
4355 
4356  >>> x = BitVec('x', 16)
4357  >>> n = ZeroExt(8, x)
4358  >>> n.size()
4359  24
4360  >>> n
4361  ZeroExt(8, x)
4362  >>> n.sort()
4363  BitVec(24)
4364  >>> v0 = BitVecVal(2, 2)
4365  >>> v0
4366  2
4367  >>> v0.size()
4368  2
4369  >>> v = simplify(ZeroExt(6, v0))
4370  >>> v
4371  2
4372  >>> v.size()
4373  8
4374  """
4375  if z3_debug():
4376  _z3_assert(_is_int(n), "First argument must be an integer")
4377  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4378  return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4379 
4380 
4381 def RepeatBitVec(n, a):
4382  """Return an expression representing `n` copies of `a`.
4383 
4384  >>> x = BitVec('x', 8)
4385  >>> n = RepeatBitVec(4, x)
4386  >>> n
4387  RepeatBitVec(4, x)
4388  >>> n.size()
4389  32
4390  >>> v0 = BitVecVal(10, 4)
4391  >>> print("%.x" % v0.as_long())
4392  a
4393  >>> v = simplify(RepeatBitVec(4, v0))
4394  >>> v.size()
4395  16
4396  >>> print("%.x" % v.as_long())
4397  aaaa
4398  """
4399  if z3_debug():
4400  _z3_assert(_is_int(n), "First argument must be an integer")
4401  _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4402  return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4403 
4404 
4405 def BVRedAnd(a):
4406  """Return the reduction-and expression of `a`."""
4407  if z3_debug():
4408  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4409  return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4410 
4411 
4412 def BVRedOr(a):
4413  """Return the reduction-or expression of `a`."""
4414  if z3_debug():
4415  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4416  return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4417 
4418 
4419 def BVAddNoOverflow(a, b, signed):
4420  """A predicate the determines that bit-vector addition does not overflow"""
4421  _check_bv_args(a, b)
4422  a, b = _coerce_exprs(a, b)
4423  return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4424 
4425 
4427  """A predicate the determines that signed bit-vector addition does not underflow"""
4428  _check_bv_args(a, b)
4429  a, b = _coerce_exprs(a, b)
4430  return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4431 
4432 
4434  """A predicate the determines that bit-vector subtraction does not overflow"""
4435  _check_bv_args(a, b)
4436  a, b = _coerce_exprs(a, b)
4437  return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4438 
4439 
4440 def BVSubNoUnderflow(a, b, signed):
4441  """A predicate the determines that bit-vector subtraction does not underflow"""
4442  _check_bv_args(a, b)
4443  a, b = _coerce_exprs(a, b)
4444  return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4445 
4446 
4448  """A predicate the determines that bit-vector signed division does not overflow"""
4449  _check_bv_args(a, b)
4450  a, b = _coerce_exprs(a, b)
4451  return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4452 
4453 
4455  """A predicate the determines that bit-vector unary negation does not overflow"""
4456  if z3_debug():
4457  _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4458  return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4459 
4460 
4461 def BVMulNoOverflow(a, b, signed):
4462  """A predicate the determines that bit-vector multiplication does not overflow"""
4463  _check_bv_args(a, b)
4464  a, b = _coerce_exprs(a, b)
4465  return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4466 
4467 
4469  """A predicate the determines that bit-vector signed multiplication does not underflow"""
4470  _check_bv_args(a, b)
4471  a, b = _coerce_exprs(a, b)
4472  return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4473 
4474 
4475 
4480 
4482  """Array sorts."""
4483 
4484  def domain(self):
4485  """Return the domain of the array sort `self`.
4486 
4487  >>> A = ArraySort(IntSort(), BoolSort())
4488  >>> A.domain()
4489  Int
4490  """
4491  return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_refctx_ref(), self.astast), self.ctxctx)
4492 
4493  def domain_n(self, i):
4494  """Return the domain of the array sort `self`.
4495  """
4496  return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_refctx_ref(), self.astast, i), self.ctxctx)
4497 
4498  def range(self):
4499  """Return the range of the array sort `self`.
4500 
4501  >>> A = ArraySort(IntSort(), BoolSort())
4502  >>> A.range()
4503  Bool
4504  """
4505  return _to_sort_ref(Z3_get_array_sort_range(self.ctx_refctx_ref(), self.astast), self.ctxctx)
4506 
4507 
4509  """Array expressions. """
4510 
4511  def sort(self):
4512  """Return the array sort of the array expression `self`.
4513 
4514  >>> a = Array('a', IntSort(), BoolSort())
4515  >>> a.sort()
4516  Array(Int, Bool)
4517  """
4518  return ArraySortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
4519 
4520  def domain(self):
4521  """Shorthand for `self.sort().domain()`.
4522 
4523  >>> a = Array('a', IntSort(), BoolSort())
4524  >>> a.domain()
4525  Int
4526  """
4527  return self.sortsortsort().domain()
4528 
4529  def domain_n(self, i):
4530  """Shorthand for self.sort().domain_n(i)`."""
4531  return self.sortsortsort().domain_n(i)
4532 
4533  def range(self):
4534  """Shorthand for `self.sort().range()`.
4535 
4536  >>> a = Array('a', IntSort(), BoolSort())
4537  >>> a.range()
4538  Bool
4539  """
4540  return self.sortsortsort().range()
4541 
4542  def __getitem__(self, arg):
4543  """Return the Z3 expression `self[arg]`.
4544 
4545  >>> a = Array('a', IntSort(), BoolSort())
4546  >>> i = Int('i')
4547  >>> a[i]
4548  a[i]
4549  >>> a[i].sexpr()
4550  '(select a i)'
4551  """
4552  return _array_select(self, arg)
4553 
4554  def default(self):
4555  return _to_expr_ref(Z3_mk_array_default(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
4556 
4557 
4558 def _array_select(ar, arg):
4559  if isinstance(arg, tuple):
4560  args = [ar.domain_n(i).cast(arg[i]) for i in range(len(arg))]
4561  _args, sz = _to_ast_array(args)
4562  return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4563  arg = ar.domain().cast(arg)
4564  return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4565 
4566 
4568  return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4569 
4570 
4571 def is_array(a):
4572  """Return `True` if `a` is a Z3 array expression.
4573 
4574  >>> a = Array('a', IntSort(), IntSort())
4575  >>> is_array(a)
4576  True
4577  >>> is_array(Store(a, 0, 1))
4578  True
4579  >>> is_array(a[0])
4580  False
4581  """
4582  return isinstance(a, ArrayRef)
4583 
4584 
4586  """Return `True` if `a` is a Z3 constant array.
4587 
4588  >>> a = K(IntSort(), 10)
4589  >>> is_const_array(a)
4590  True
4591  >>> a = Array('a', IntSort(), IntSort())
4592  >>> is_const_array(a)
4593  False
4594  """
4595  return is_app_of(a, Z3_OP_CONST_ARRAY)
4596 
4597 
4598 def is_K(a):
4599  """Return `True` if `a` is a Z3 constant array.
4600 
4601  >>> a = K(IntSort(), 10)
4602  >>> is_K(a)
4603  True
4604  >>> a = Array('a', IntSort(), IntSort())
4605  >>> is_K(a)
4606  False
4607  """
4608  return is_app_of(a, Z3_OP_CONST_ARRAY)
4609 
4610 
4611 def is_map(a):
4612  """Return `True` if `a` is a Z3 map array expression.
4613 
4614  >>> f = Function('f', IntSort(), IntSort())
4615  >>> b = Array('b', IntSort(), IntSort())
4616  >>> a = Map(f, b)
4617  >>> a
4618  Map(f, b)
4619  >>> is_map(a)
4620  True
4621  >>> is_map(b)
4622  False
4623  """
4624  return is_app_of(a, Z3_OP_ARRAY_MAP)
4625 
4626 
4627 def is_default(a):
4628  """Return `True` if `a` is a Z3 default array expression.
4629  >>> d = Default(K(IntSort(), 10))
4630  >>> is_default(d)
4631  True
4632  """
4633  return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4634 
4635 
4637  """Return the function declaration associated with a Z3 map array expression.
4638 
4639  >>> f = Function('f', IntSort(), IntSort())
4640  >>> b = Array('b', IntSort(), IntSort())
4641  >>> a = Map(f, b)
4642  >>> eq(f, get_map_func(a))
4643  True
4644  >>> get_map_func(a)
4645  f
4646  >>> get_map_func(a)(0)
4647  f(0)
4648  """
4649  if z3_debug():
4650  _z3_assert(is_map(a), "Z3 array map expression expected.")
4651  return FuncDeclRef(
4653  a.ctx_ref(),
4654  Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4655  ),
4656  ctx=a.ctx,
4657  )
4658 
4659 
4660 def ArraySort(*sig):
4661  """Return the Z3 array sort with the given domain and range sorts.
4662 
4663  >>> A = ArraySort(IntSort(), BoolSort())
4664  >>> A
4665  Array(Int, Bool)
4666  >>> A.domain()
4667  Int
4668  >>> A.range()
4669  Bool
4670  >>> AA = ArraySort(IntSort(), A)
4671  >>> AA
4672  Array(Int, Array(Int, Bool))
4673  """
4674  sig = _get_args(sig)
4675  if z3_debug():
4676  _z3_assert(len(sig) > 1, "At least two arguments expected")
4677  arity = len(sig) - 1
4678  r = sig[arity]
4679  d = sig[0]
4680  if z3_debug():
4681  for s in sig:
4682  _z3_assert(is_sort(s), "Z3 sort expected")
4683  _z3_assert(s.ctx == r.ctx, "Context mismatch")
4684  ctx = d.ctx
4685  if len(sig) == 2:
4686  return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4687  dom = (Sort * arity)()
4688  for i in range(arity):
4689  dom[i] = sig[i].ast
4690  return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4691 
4692 
4693 def Array(name, *sorts):
4694  """Return an array constant named `name` with the given domain and range sorts.
4695 
4696  >>> a = Array('a', IntSort(), IntSort())
4697  >>> a.sort()
4698  Array(Int, Int)
4699  >>> a[0]
4700  a[0]
4701  """
4702  s = ArraySort(sorts)
4703  ctx = s.ctx
4704  return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4705 
4706 
4707 def Update(a, *args):
4708  """Return a Z3 store array expression.
4709 
4710  >>> a = Array('a', IntSort(), IntSort())
4711  >>> i, v = Ints('i v')
4712  >>> s = Update(a, i, v)
4713  >>> s.sort()
4714  Array(Int, Int)
4715  >>> prove(s[i] == v)
4716  proved
4717  >>> j = Int('j')
4718  >>> prove(Implies(i != j, s[j] == a[j]))
4719  proved
4720  """
4721  if z3_debug():
4722  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4723  args = _get_args(args)
4724  ctx = a.ctx
4725  if len(args) <= 1:
4726  raise Z3Exception("array update requires index and value arguments")
4727  if len(args) == 2:
4728  i = args[0]
4729  v = args[1]
4730  i = a.sort().domain().cast(i)
4731  v = a.sort().range().cast(v)
4732  return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4733  v = a.sort().range().cast(args[-1])
4734  idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
4735  _args, sz = _to_ast_array(idxs)
4736  return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
4737 
4738 
4739 def Default(a):
4740  """ Return a default value for array expression.
4741  >>> b = K(IntSort(), 1)
4742  >>> prove(Default(b) == 1)
4743  proved
4744  """
4745  if z3_debug():
4746  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4747  return a.default()
4748 
4749 
4750 def Store(a, *args):
4751  """Return a Z3 store array expression.
4752 
4753  >>> a = Array('a', IntSort(), IntSort())
4754  >>> i, v = Ints('i v')
4755  >>> s = Store(a, i, v)
4756  >>> s.sort()
4757  Array(Int, Int)
4758  >>> prove(s[i] == v)
4759  proved
4760  >>> j = Int('j')
4761  >>> prove(Implies(i != j, s[j] == a[j]))
4762  proved
4763  """
4764  return Update(a, args)
4765 
4766 
4767 def Select(a, *args):
4768  """Return a Z3 select array expression.
4769 
4770  >>> a = Array('a', IntSort(), IntSort())
4771  >>> i = Int('i')
4772  >>> Select(a, i)
4773  a[i]
4774  >>> eq(Select(a, i), a[i])
4775  True
4776  """
4777  args = _get_args(args)
4778  if z3_debug():
4779  _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4780  return a[args]
4781 
4782 
4783 def Map(f, *args):
4784  """Return a Z3 map array expression.
4785 
4786  >>> f = Function('f', IntSort(), IntSort(), IntSort())
4787  >>> a1 = Array('a1', IntSort(), IntSort())
4788  >>> a2 = Array('a2', IntSort(), IntSort())
4789  >>> b = Map(f, a1, a2)
4790  >>> b
4791  Map(f, a1, a2)
4792  >>> prove(b[0] == f(a1[0], a2[0]))
4793  proved
4794  """
4795  args = _get_args(args)
4796  if z3_debug():
4797  _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4798  _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4799  _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4800  _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4801  _args, sz = _to_ast_array(args)
4802  ctx = f.ctx
4803  return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4804 
4805 
4806 def K(dom, v):
4807  """Return a Z3 constant array expression.
4808 
4809  >>> a = K(IntSort(), 10)
4810  >>> a
4811  K(Int, 10)
4812  >>> a.sort()
4813  Array(Int, Int)
4814  >>> i = Int('i')
4815  >>> a[i]
4816  K(Int, 10)[i]
4817  >>> simplify(a[i])
4818  10
4819  """
4820  if z3_debug():
4821  _z3_assert(is_sort(dom), "Z3 sort expected")
4822  ctx = dom.ctx
4823  if not is_expr(v):
4824  v = _py2expr(v, ctx)
4825  return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4826 
4827 
4828 def Ext(a, b):
4829  """Return extensionality index for one-dimensional arrays.
4830  >> a, b = Consts('a b', SetSort(IntSort()))
4831  >> Ext(a, b)
4832  Ext(a, b)
4833  """
4834  ctx = a.ctx
4835  if z3_debug():
4836  _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
4837  return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4838 
4839 
4840 def SetHasSize(a, k):
4841  ctx = a.ctx
4842  k = _py2expr(k, ctx)
4843  return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4844 
4845 
4846 def is_select(a):
4847  """Return `True` if `a` is a Z3 array select application.
4848 
4849  >>> a = Array('a', IntSort(), IntSort())
4850  >>> is_select(a)
4851  False
4852  >>> i = Int('i')
4853  >>> is_select(a[i])
4854  True
4855  """
4856  return is_app_of(a, Z3_OP_SELECT)
4857 
4858 
4859 def is_store(a):
4860  """Return `True` if `a` is a Z3 array store application.
4861 
4862  >>> a = Array('a', IntSort(), IntSort())
4863  >>> is_store(a)
4864  False
4865  >>> is_store(Store(a, 0, 1))
4866  True
4867  """
4868  return is_app_of(a, Z3_OP_STORE)
4869 
4870 
4875 
4876 
4877 def SetSort(s):
4878  """ Create a set sort over element sort s"""
4879  return ArraySort(s, BoolSort())
4880 
4881 
4882 def EmptySet(s):
4883  """Create the empty set
4884  >>> EmptySet(IntSort())
4885  K(Int, False)
4886  """
4887  ctx = s.ctx
4888  return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4889 
4890 
4891 def FullSet(s):
4892  """Create the full set
4893  >>> FullSet(IntSort())
4894  K(Int, True)
4895  """
4896  ctx = s.ctx
4897  return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4898 
4899 
4900 def SetUnion(*args):
4901  """ Take the union of sets
4902  >>> a = Const('a', SetSort(IntSort()))
4903  >>> b = Const('b', SetSort(IntSort()))
4904  >>> SetUnion(a, b)
4905  union(a, b)
4906  """
4907  args = _get_args(args)
4908  ctx = _ctx_from_ast_arg_list(args)
4909  _args, sz = _to_ast_array(args)
4910  return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4911 
4912 
4913 def SetIntersect(*args):
4914  """ Take the union of sets
4915  >>> a = Const('a', SetSort(IntSort()))
4916  >>> b = Const('b', SetSort(IntSort()))
4917  >>> SetIntersect(a, b)
4918  intersection(a, b)
4919  """
4920  args = _get_args(args)
4921  ctx = _ctx_from_ast_arg_list(args)
4922  _args, sz = _to_ast_array(args)
4923  return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4924 
4925 
4926 def SetAdd(s, e):
4927  """ Add element e to set s
4928  >>> a = Const('a', SetSort(IntSort()))
4929  >>> SetAdd(a, 1)
4930  Store(a, 1, True)
4931  """
4932  ctx = _ctx_from_ast_arg_list([s, e])
4933  e = _py2expr(e, ctx)
4934  return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4935 
4936 
4937 def SetDel(s, e):
4938  """ Remove element e to set s
4939  >>> a = Const('a', SetSort(IntSort()))
4940  >>> SetDel(a, 1)
4941  Store(a, 1, False)
4942  """
4943  ctx = _ctx_from_ast_arg_list([s, e])
4944  e = _py2expr(e, ctx)
4945  return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4946 
4947 
4949  """ The complement of set s
4950  >>> a = Const('a', SetSort(IntSort()))
4951  >>> SetComplement(a)
4952  complement(a)
4953  """
4954  ctx = s.ctx
4955  return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4956 
4957 
4958 def SetDifference(a, b):
4959  """ The set difference of a and b
4960  >>> a = Const('a', SetSort(IntSort()))
4961  >>> b = Const('b', SetSort(IntSort()))
4962  >>> SetDifference(a, b)
4963  setminus(a, b)
4964  """
4965  ctx = _ctx_from_ast_arg_list([a, b])
4966  return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4967 
4968 
4969 def IsMember(e, s):
4970  """ Check if e is a member of set s
4971  >>> a = Const('a', SetSort(IntSort()))
4972  >>> IsMember(1, a)
4973  a[1]
4974  """
4975  ctx = _ctx_from_ast_arg_list([s, e])
4976  e = _py2expr(e, ctx)
4977  return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4978 
4979 
4980 def IsSubset(a, b):
4981  """ Check if a is a subset of b
4982  >>> a = Const('a', SetSort(IntSort()))
4983  >>> b = Const('b', SetSort(IntSort()))
4984  >>> IsSubset(a, b)
4985  subset(a, b)
4986  """
4987  ctx = _ctx_from_ast_arg_list([a, b])
4988  return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4989 
4990 
4991 
4996 
4997 def _valid_accessor(acc):
4998  """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4999  if not isinstance(acc, tuple):
5000  return False
5001  if len(acc) != 2:
5002  return False
5003  return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5004 
5005 
5006 class Datatype:
5007  """Helper class for declaring Z3 datatypes.
5008 
5009  >>> List = Datatype('List')
5010  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5011  >>> List.declare('nil')
5012  >>> List = List.create()
5013  >>> # List is now a Z3 declaration
5014  >>> List.nil
5015  nil
5016  >>> List.cons(10, List.nil)
5017  cons(10, nil)
5018  >>> List.cons(10, List.nil).sort()
5019  List
5020  >>> cons = List.cons
5021  >>> nil = List.nil
5022  >>> car = List.car
5023  >>> cdr = List.cdr
5024  >>> n = cons(1, cons(0, nil))
5025  >>> n
5026  cons(1, cons(0, nil))
5027  >>> simplify(cdr(n))
5028  cons(0, nil)
5029  >>> simplify(car(n))
5030  1
5031  """
5032 
5033  def __init__(self, name, ctx=None):
5034  self.ctxctx = _get_ctx(ctx)
5035  self.namename = name
5036  self.constructorsconstructors = []
5037 
5038  def __deepcopy__(self, memo={}):
5039  r = Datatype(self.namename, self.ctxctx)
5040  r.constructors = copy.deepcopy(self.constructorsconstructors)
5041  return r
5042 
5043  def declare_core(self, name, rec_name, *args):
5044  if z3_debug():
5045  _z3_assert(isinstance(name, str), "String expected")
5046  _z3_assert(isinstance(rec_name, str), "String expected")
5047  _z3_assert(
5048  all([_valid_accessor(a) for a in args]),
5049  "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5050  )
5051  self.constructorsconstructors.append((name, rec_name, args))
5052 
5053  def declare(self, name, *args):
5054  """Declare constructor named `name` with the given accessors `args`.
5055  Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5056  or a reference to the datatypes being declared.
5057 
5058  In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5059  declares the constructor named `cons` that builds a new List using an integer and a List.
5060  It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5061  of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5062  we use the method create() to create the actual datatype in Z3.
5063 
5064  >>> List = Datatype('List')
5065  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5066  >>> List.declare('nil')
5067  >>> List = List.create()
5068  """
5069  if z3_debug():
5070  _z3_assert(isinstance(name, str), "String expected")
5071  _z3_assert(name != "", "Constructor name cannot be empty")
5072  return self.declare_coredeclare_core(name, "is-" + name, *args)
5073 
5074  def __repr__(self):
5075  return "Datatype(%s, %s)" % (self.namename, self.constructorsconstructors)
5076 
5077  def create(self):
5078  """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5079 
5080  The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5081 
5082  >>> List = Datatype('List')
5083  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5084  >>> List.declare('nil')
5085  >>> List = List.create()
5086  >>> List.nil
5087  nil
5088  >>> List.cons(10, List.nil)
5089  cons(10, nil)
5090  """
5091  return CreateDatatypes([self])[0]
5092 
5093 
5095  """Auxiliary object used to create Z3 datatypes."""
5096 
5097  def __init__(self, c, ctx):
5098  self.cc = c
5099  self.ctxctx = ctx
5100 
5101  def __del__(self):
5102  if self.ctxctx.ref() is not None:
5103  Z3_del_constructor(self.ctxctx.ref(), self.cc)
5104 
5105 
5107  """Auxiliary object used to create Z3 datatypes."""
5108 
5109  def __init__(self, c, ctx):
5110  self.cc = c
5111  self.ctxctx = ctx
5112 
5113  def __del__(self):
5114  if self.ctxctx.ref() is not None:
5115  Z3_del_constructor_list(self.ctxctx.ref(), self.cc)
5116 
5117 
5119  """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5120 
5121  In the following example we define a Tree-List using two mutually recursive datatypes.
5122 
5123  >>> TreeList = Datatype('TreeList')
5124  >>> Tree = Datatype('Tree')
5125  >>> # Tree has two constructors: leaf and node
5126  >>> Tree.declare('leaf', ('val', IntSort()))
5127  >>> # a node contains a list of trees
5128  >>> Tree.declare('node', ('children', TreeList))
5129  >>> TreeList.declare('nil')
5130  >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5131  >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5132  >>> Tree.val(Tree.leaf(10))
5133  val(leaf(10))
5134  >>> simplify(Tree.val(Tree.leaf(10)))
5135  10
5136  >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5137  >>> n1
5138  node(cons(leaf(10), cons(leaf(20), nil)))
5139  >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5140  >>> simplify(n2 == n1)
5141  False
5142  >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5143  True
5144  """
5145  ds = _get_args(ds)
5146  if z3_debug():
5147  _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5148  _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5149  _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5150  _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5151  ctx = ds[0].ctx
5152  num = len(ds)
5153  names = (Symbol * num)()
5154  out = (Sort * num)()
5155  clists = (ConstructorList * num)()
5156  to_delete = []
5157  for i in range(num):
5158  d = ds[i]
5159  names[i] = to_symbol(d.name, ctx)
5160  num_cs = len(d.constructors)
5161  cs = (Constructor * num_cs)()
5162  for j in range(num_cs):
5163  c = d.constructors[j]
5164  cname = to_symbol(c[0], ctx)
5165  rname = to_symbol(c[1], ctx)
5166  fs = c[2]
5167  num_fs = len(fs)
5168  fnames = (Symbol * num_fs)()
5169  sorts = (Sort * num_fs)()
5170  refs = (ctypes.c_uint * num_fs)()
5171  for k in range(num_fs):
5172  fname = fs[k][0]
5173  ftype = fs[k][1]
5174  fnames[k] = to_symbol(fname, ctx)
5175  if isinstance(ftype, Datatype):
5176  if z3_debug():
5177  _z3_assert(
5178  ds.count(ftype) == 1,
5179  "One and only one occurrence of each datatype is expected",
5180  )
5181  sorts[k] = None
5182  refs[k] = ds.index(ftype)
5183  else:
5184  if z3_debug():
5185  _z3_assert(is_sort(ftype), "Z3 sort expected")
5186  sorts[k] = ftype.ast
5187  refs[k] = 0
5188  cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5189  to_delete.append(ScopedConstructor(cs[j], ctx))
5190  clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5191  to_delete.append(ScopedConstructorList(clists[i], ctx))
5192  Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5193  result = []
5194  # Create a field for every constructor, recognizer and accessor
5195  for i in range(num):
5196  dref = DatatypeSortRef(out[i], ctx)
5197  num_cs = dref.num_constructors()
5198  for j in range(num_cs):
5199  cref = dref.constructor(j)
5200  cref_name = cref.name()
5201  cref_arity = cref.arity()
5202  if cref.arity() == 0:
5203  cref = cref()
5204  setattr(dref, cref_name, cref)
5205  rref = dref.recognizer(j)
5206  setattr(dref, "is_" + cref_name, rref)
5207  for k in range(cref_arity):
5208  aref = dref.accessor(j, k)
5209  setattr(dref, aref.name(), aref)
5210  result.append(dref)
5211  return tuple(result)
5212 
5213 
5215  """Datatype sorts."""
5216 
5217  def num_constructors(self):
5218  """Return the number of constructors in the given Z3 datatype.
5219 
5220  >>> List = Datatype('List')
5221  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5222  >>> List.declare('nil')
5223  >>> List = List.create()
5224  >>> # List is now a Z3 declaration
5225  >>> List.num_constructors()
5226  2
5227  """
5228  return int(Z3_get_datatype_sort_num_constructors(self.ctx_refctx_ref(), self.astast))
5229 
5230  def constructor(self, idx):
5231  """Return a constructor of the datatype `self`.
5232 
5233  >>> List = Datatype('List')
5234  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5235  >>> List.declare('nil')
5236  >>> List = List.create()
5237  >>> # List is now a Z3 declaration
5238  >>> List.num_constructors()
5239  2
5240  >>> List.constructor(0)
5241  cons
5242  >>> List.constructor(1)
5243  nil
5244  """
5245  if z3_debug():
5246  _z3_assert(idx < self.num_constructorsnum_constructors(), "Invalid constructor index")
5247  return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
5248 
5249  def recognizer(self, idx):
5250  """In Z3, each constructor has an associated recognizer predicate.
5251 
5252  If the constructor is named `name`, then the recognizer `is_name`.
5253 
5254  >>> List = Datatype('List')
5255  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5256  >>> List.declare('nil')
5257  >>> List = List.create()
5258  >>> # List is now a Z3 declaration
5259  >>> List.num_constructors()
5260  2
5261  >>> List.recognizer(0)
5262  is(cons)
5263  >>> List.recognizer(1)
5264  is(nil)
5265  >>> simplify(List.is_nil(List.cons(10, List.nil)))
5266  False
5267  >>> simplify(List.is_cons(List.cons(10, List.nil)))
5268  True
5269  >>> l = Const('l', List)
5270  >>> simplify(List.is_cons(l))
5271  is(cons, l)
5272  """
5273  if z3_debug():
5274  _z3_assert(idx < self.num_constructorsnum_constructors(), "Invalid recognizer index")
5275  return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_refctx_ref(), self.astast, idx), self.ctxctx)
5276 
5277  def accessor(self, i, j):
5278  """In Z3, each constructor has 0 or more accessor.
5279  The number of accessors is equal to the arity of the constructor.
5280 
5281  >>> List = Datatype('List')
5282  >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5283  >>> List.declare('nil')
5284  >>> List = List.create()
5285  >>> List.num_constructors()
5286  2
5287  >>> List.constructor(0)
5288  cons
5289  >>> num_accs = List.constructor(0).arity()
5290  >>> num_accs
5291  2
5292  >>> List.accessor(0, 0)
5293  car
5294  >>> List.accessor(0, 1)
5295  cdr
5296  >>> List.constructor(1)
5297  nil
5298  >>> num_accs = List.constructor(1).arity()
5299  >>> num_accs
5300  0
5301  """
5302  if z3_debug():
5303  _z3_assert(i < self.num_constructorsnum_constructors(), "Invalid constructor index")
5304  _z3_assert(j < self.constructorconstructor(i).arity(), "Invalid accessor index")
5305  return FuncDeclRef(
5306  Z3_get_datatype_sort_constructor_accessor(self.ctx_refctx_ref(), self.astast, i, j),
5307  ctx=self.ctxctx,
5308  )
5309 
5310 
5312  """Datatype expressions."""
5313 
5314  def sort(self):
5315  """Return the datatype sort of the datatype expression `self`."""
5316  return DatatypeSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
5317 
5318 
5319 def TupleSort(name, sorts, ctx=None):
5320  """Create a named tuple sort base on a set of underlying sorts
5321  Example:
5322  >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5323  """
5324  tuple = Datatype(name, ctx)
5325  projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5326  tuple.declare(name, *projects)
5327  tuple = tuple.create()
5328  return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5329 
5330 
5331 def DisjointSum(name, sorts, ctx=None):
5332  """Create a named tagged union sort base on a set of underlying sorts
5333  Example:
5334  >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5335  """
5336  sum = Datatype(name, ctx)
5337  for i in range(len(sorts)):
5338  sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5339  sum = sum.create()
5340  return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5341 
5342 
5343 def EnumSort(name, values, ctx=None):
5344  """Return a new enumeration sort named `name` containing the given values.
5345 
5346  The result is a pair (sort, list of constants).
5347  Example:
5348  >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5349  """
5350  if z3_debug():
5351  _z3_assert(isinstance(name, str), "Name must be a string")
5352  _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5353  _z3_assert(len(values) > 0, "At least one value expected")
5354  ctx = _get_ctx(ctx)
5355  num = len(values)
5356  _val_names = (Symbol * num)()
5357  for i in range(num):
5358  _val_names[i] = to_symbol(values[i])
5359  _values = (FuncDecl * num)()
5360  _testers = (FuncDecl * num)()
5361  name = to_symbol(name)
5362  S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5363  V = []
5364  for i in range(num):
5365  V.append(FuncDeclRef(_values[i], ctx))
5366  V = [a() for a in V]
5367  return S, V
5368 
5369 
5374 
5375 
5377  """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5378 
5379  Consider using the function `args2params` to create instances of this object.
5380  """
5381 
5382  def __init__(self, ctx=None, params=None):
5383  self.ctxctx = _get_ctx(ctx)
5384  if params is None:
5385  self.paramsparams = Z3_mk_params(self.ctxctx.ref())
5386  else:
5387  self.paramsparams = params
5388  Z3_params_inc_ref(self.ctxctx.ref(), self.paramsparams)
5389 
5390  def __deepcopy__(self, memo={}):
5391  return ParamsRef(self.ctxctx, self.paramsparams)
5392 
5393  def __del__(self):
5394  if self.ctxctx.ref() is not None:
5395  Z3_params_dec_ref(self.ctxctx.ref(), self.paramsparams)
5396 
5397  def set(self, name, val):
5398  """Set parameter name with value val."""
5399  if z3_debug():
5400  _z3_assert(isinstance(name, str), "parameter name must be a string")
5401  name_sym = to_symbol(name, self.ctxctx)
5402  if isinstance(val, bool):
5403  Z3_params_set_bool(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5404  elif _is_int(val):
5405  Z3_params_set_uint(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5406  elif isinstance(val, float):
5407  Z3_params_set_double(self.ctxctx.ref(), self.paramsparams, name_sym, val)
5408  elif isinstance(val, str):
5409  Z3_params_set_symbol(self.ctxctx.ref(), self.paramsparams, name_sym, to_symbol(val, self.ctxctx))
5410  else:
5411  if z3_debug():
5412  _z3_assert(False, "invalid parameter value")
5413 
5414  def __repr__(self):
5415  return Z3_params_to_string(self.ctxctx.ref(), self.paramsparams)
5416 
5417  def validate(self, ds):
5418  _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5419  Z3_params_validate(self.ctxctx.ref(), self.paramsparams, ds.descr)
5420 
5421 
5422 def args2params(arguments, keywords, ctx=None):
5423  """Convert python arguments into a Z3_params object.
5424  A ':' is added to the keywords, and '_' is replaced with '-'
5425 
5426  >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5427  (params model true relevancy 2 elim_and true)
5428  """
5429  if z3_debug():
5430  _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5431  prev = None
5432  r = ParamsRef(ctx)
5433  for a in arguments:
5434  if prev is None:
5435  prev = a
5436  else:
5437  r.set(prev, a)
5438  prev = None
5439  for k in keywords:
5440  v = keywords[k]
5441  r.set(k, v)
5442  return r
5443 
5444 
5446  """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5447  """
5448 
5449  def __init__(self, descr, ctx=None):
5450  _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5451  self.ctxctx = _get_ctx(ctx)
5452  self.descrdescr = descr
5453  Z3_param_descrs_inc_ref(self.ctxctx.ref(), self.descrdescr)
5454 
5455  def __deepcopy__(self, memo={}):
5456  return ParamsDescrsRef(self.descrdescr, self.ctxctx)
5457 
5458  def __del__(self):
5459  if self.ctxctx.ref() is not None:
5460  Z3_param_descrs_dec_ref(self.ctxctx.ref(), self.descrdescr)
5461 
5462  def size(self):
5463  """Return the size of in the parameter description `self`.
5464  """
5465  return int(Z3_param_descrs_size(self.ctxctx.ref(), self.descrdescr))
5466 
5467  def __len__(self):
5468  """Return the size of in the parameter description `self`.
5469  """
5470  return self.sizesize()
5471 
5472  def get_name(self, i):
5473  """Return the i-th parameter name in the parameter description `self`.
5474  """
5475  return _symbol2py(self.ctxctx, Z3_param_descrs_get_name(self.ctxctx.ref(), self.descrdescr, i))
5476 
5477  def get_kind(self, n):
5478  """Return the kind of the parameter named `n`.
5479  """
5480  return Z3_param_descrs_get_kind(self.ctxctx.ref(), self.descrdescr, to_symbol(n, self.ctxctx))
5481 
5482  def get_documentation(self, n):
5483  """Return the documentation string of the parameter named `n`.
5484  """
5485  return Z3_param_descrs_get_documentation(self.ctxctx.ref(), self.descrdescr, to_symbol(n, self.ctxctx))
5486 
5487  def __getitem__(self, arg):
5488  if _is_int(arg):
5489  return self.get_nameget_name(arg)
5490  else:
5491  return self.get_kindget_kind(arg)
5492 
5493  def __repr__(self):
5494  return Z3_param_descrs_to_string(self.ctxctx.ref(), self.descrdescr)
5495 
5496 
5501 
5502 
5504  """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5505 
5506  Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5507  A goal has a solution if one of its subgoals has a solution.
5508  A goal is unsatisfiable if all subgoals are unsatisfiable.
5509  """
5510 
5511  def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5512  if z3_debug():
5513  _z3_assert(goal is None or ctx is not None,
5514  "If goal is different from None, then ctx must be also different from None")
5515  self.ctxctx = _get_ctx(ctx)
5516  self.goalgoal = goal
5517  if self.goalgoal is None:
5518  self.goalgoal = Z3_mk_goal(self.ctxctx.ref(), models, unsat_cores, proofs)
5519  Z3_goal_inc_ref(self.ctxctx.ref(), self.goalgoal)
5520 
5521  def __del__(self):
5522  if self.goalgoal is not None and self.ctxctx.ref() is not None:
5523  Z3_goal_dec_ref(self.ctxctx.ref(), self.goalgoal)
5524 
5525  def depth(self):
5526  """Return the depth of the goal `self`.
5527  The depth corresponds to the number of tactics applied to `self`.
5528 
5529  >>> x, y = Ints('x y')
5530  >>> g = Goal()
5531  >>> g.add(x == 0, y >= x + 1)
5532  >>> g.depth()
5533  0
5534  >>> r = Then('simplify', 'solve-eqs')(g)
5535  >>> # r has 1 subgoal
5536  >>> len(r)
5537  1
5538  >>> r[0].depth()
5539  2
5540  """
5541  return int(Z3_goal_depth(self.ctxctx.ref(), self.goalgoal))
5542 
5543  def inconsistent(self):
5544  """Return `True` if `self` contains the `False` constraints.
5545 
5546  >>> x, y = Ints('x y')
5547  >>> g = Goal()
5548  >>> g.inconsistent()
5549  False
5550  >>> g.add(x == 0, x == 1)
5551  >>> g
5552  [x == 0, x == 1]
5553  >>> g.inconsistent()
5554  False
5555  >>> g2 = Tactic('propagate-values')(g)[0]
5556  >>> g2.inconsistent()
5557  True
5558  """
5559  return Z3_goal_inconsistent(self.ctxctx.ref(), self.goalgoal)
5560 
5561  def prec(self):
5562  """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5563 
5564  >>> g = Goal()
5565  >>> g.prec() == Z3_GOAL_PRECISE
5566  True
5567  >>> x, y = Ints('x y')
5568  >>> g.add(x == y + 1)
5569  >>> g.prec() == Z3_GOAL_PRECISE
5570  True
5571  >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5572  >>> g2 = t(g)[0]
5573  >>> g2
5574  [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5575  >>> g2.prec() == Z3_GOAL_PRECISE
5576  False
5577  >>> g2.prec() == Z3_GOAL_UNDER
5578  True
5579  """
5580  return Z3_goal_precision(self.ctxctx.ref(), self.goalgoal)
5581 
5582  def precision(self):
5583  """Alias for `prec()`.
5584 
5585  >>> g = Goal()
5586  >>> g.precision() == Z3_GOAL_PRECISE
5587  True
5588  """
5589  return self.precprec()
5590 
5591  def size(self):
5592  """Return the number of constraints in the goal `self`.
5593 
5594  >>> g = Goal()
5595  >>> g.size()
5596  0
5597  >>> x, y = Ints('x y')
5598  >>> g.add(x == 0, y > x)
5599  >>> g.size()
5600  2
5601  """
5602  return int(Z3_goal_size(self.ctxctx.ref(), self.goalgoal))
5603 
5604  def __len__(self):
5605  """Return the number of constraints in the goal `self`.
5606 
5607  >>> g = Goal()
5608  >>> len(g)
5609  0
5610  >>> x, y = Ints('x y')
5611  >>> g.add(x == 0, y > x)
5612  >>> len(g)
5613  2
5614  """
5615  return self.sizesize()
5616 
5617  def get(self, i):
5618  """Return a constraint in the goal `self`.
5619 
5620  >>> g = Goal()
5621  >>> x, y = Ints('x y')
5622  >>> g.add(x == 0, y > x)
5623  >>> g.get(0)
5624  x == 0
5625  >>> g.get(1)
5626  y > x
5627  """
5628  return _to_expr_ref(Z3_goal_formula(self.ctxctx.ref(), self.goalgoal, i), self.ctxctx)
5629 
5630  def __getitem__(self, arg):
5631  """Return a constraint in the goal `self`.
5632 
5633  >>> g = Goal()
5634  >>> x, y = Ints('x y')
5635  >>> g.add(x == 0, y > x)
5636  >>> g[0]
5637  x == 0
5638  >>> g[1]
5639  y > x
5640  """
5641  if arg >= len(self):
5642  raise IndexError
5643  return self.getget(arg)
5644 
5645  def assert_exprs(self, *args):
5646  """Assert constraints into the goal.
5647 
5648  >>> x = Int('x')
5649  >>> g = Goal()
5650  >>> g.assert_exprs(x > 0, x < 2)
5651  >>> g
5652  [x > 0, x < 2]
5653  """
5654  args = _get_args(args)
5655  s = BoolSort(self.ctxctx)
5656  for arg in args:
5657  arg = s.cast(arg)
5658  Z3_goal_assert(self.ctxctx.ref(), self.goalgoal, arg.as_ast())
5659 
5660  def append(self, *args):
5661  """Add constraints.
5662 
5663  >>> x = Int('x')
5664  >>> g = Goal()
5665  >>> g.append(x > 0, x < 2)
5666  >>> g
5667  [x > 0, x < 2]
5668  """
5669  self.assert_exprsassert_exprs(*args)
5670 
5671  def insert(self, *args):
5672  """Add constraints.
5673 
5674  >>> x = Int('x')
5675  >>> g = Goal()
5676  >>> g.insert(x > 0, x < 2)
5677  >>> g
5678  [x > 0, x < 2]
5679  """
5680  self.assert_exprsassert_exprs(*args)
5681 
5682  def add(self, *args):
5683  """Add constraints.
5684 
5685  >>> x = Int('x')
5686  >>> g = Goal()
5687  >>> g.add(x > 0, x < 2)
5688  >>> g
5689  [x > 0, x < 2]
5690  """
5691  self.assert_exprsassert_exprs(*args)
5692 
5693  def convert_model(self, model):
5694  """Retrieve model from a satisfiable goal
5695  >>> a, b = Ints('a b')
5696  >>> g = Goal()
5697  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5698  >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5699  >>> r = t(g)
5700  >>> r[0]
5701  [Or(b == 0, b == 1), Not(0 <= b)]
5702  >>> r[1]
5703  [Or(b == 0, b == 1), Not(1 <= b)]
5704  >>> # Remark: the subgoal r[0] is unsatisfiable
5705  >>> # Creating a solver for solving the second subgoal
5706  >>> s = Solver()
5707  >>> s.add(r[1])
5708  >>> s.check()
5709  sat
5710  >>> s.model()
5711  [b = 0]
5712  >>> # Model s.model() does not assign a value to `a`
5713  >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5714  >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5715  >>> r[1].convert_model(s.model())
5716  [b = 0, a = 1]
5717  """
5718  if z3_debug():
5719  _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5720  return ModelRef(Z3_goal_convert_model(self.ctxctx.ref(), self.goalgoal, model.model), self.ctxctx)
5721 
5722  def __repr__(self):
5723  return obj_to_string(self)
5724 
5725  def sexpr(self):
5726  """Return a textual representation of the s-expression representing the goal."""
5727  return Z3_goal_to_string(self.ctxctx.ref(), self.goalgoal)
5728 
5729  def dimacs(self, include_names=True):
5730  """Return a textual representation of the goal in DIMACS format."""
5731  return Z3_goal_to_dimacs_string(self.ctxctx.ref(), self.goalgoal, include_names)
5732 
5733  def translate(self, target):
5734  """Copy goal `self` to context `target`.
5735 
5736  >>> x = Int('x')
5737  >>> g = Goal()
5738  >>> g.add(x > 10)
5739  >>> g
5740  [x > 10]
5741  >>> c2 = Context()
5742  >>> g2 = g.translate(c2)
5743  >>> g2
5744  [x > 10]
5745  >>> g.ctx == main_ctx()
5746  True
5747  >>> g2.ctx == c2
5748  True
5749  >>> g2.ctx == main_ctx()
5750  False
5751  """
5752  if z3_debug():
5753  _z3_assert(isinstance(target, Context), "target must be a context")
5754  return Goal(goal=Z3_goal_translate(self.ctxctx.ref(), self.goalgoal, target.ref()), ctx=target)
5755 
5756  def __copy__(self):
5757  return self.translatetranslate(self.ctxctx)
5758 
5759  def __deepcopy__(self, memo={}):
5760  return self.translatetranslate(self.ctxctx)
5761 
5762  def simplify(self, *arguments, **keywords):
5763  """Return a new simplified goal.
5764 
5765  This method is essentially invoking the simplify tactic.
5766 
5767  >>> g = Goal()
5768  >>> x = Int('x')
5769  >>> g.add(x + 1 >= 2)
5770  >>> g
5771  [x + 1 >= 2]
5772  >>> g2 = g.simplify()
5773  >>> g2
5774  [x >= 1]
5775  >>> # g was not modified
5776  >>> g
5777  [x + 1 >= 2]
5778  """
5779  t = Tactic("simplify")
5780  return t.apply(self, *arguments, **keywords)[0]
5781 
5782  def as_expr(self):
5783  """Return goal `self` as a single Z3 expression.
5784 
5785  >>> x = Int('x')
5786  >>> g = Goal()
5787  >>> g.as_expr()
5788  True
5789  >>> g.add(x > 1)
5790  >>> g.as_expr()
5791  x > 1
5792  >>> g.add(x < 10)
5793  >>> g.as_expr()
5794  And(x > 1, x < 10)
5795  """
5796  sz = len(self)
5797  if sz == 0:
5798  return BoolVal(True, self.ctxctx)
5799  elif sz == 1:
5800  return self.getget(0)
5801  else:
5802  return And([self.getget(i) for i in range(len(self))], self.ctxctx)
5803 
5804 
5809 
5810 
5812  """A collection (vector) of ASTs."""
5813 
5814  def __init__(self, v=None, ctx=None):
5815  self.vectorvector = None
5816  if v is None:
5817  self.ctxctx = _get_ctx(ctx)
5818  self.vectorvector = Z3_mk_ast_vector(self.ctxctx.ref())
5819  else:
5820  self.vectorvector = v
5821  assert ctx is not None
5822  self.ctxctx = ctx
5823  Z3_ast_vector_inc_ref(self.ctxctx.ref(), self.vectorvector)
5824 
5825  def __del__(self):
5826  if self.vectorvector is not None and self.ctxctx.ref() is not None:
5827  Z3_ast_vector_dec_ref(self.ctxctx.ref(), self.vectorvector)
5828 
5829  def __len__(self):
5830  """Return the size of the vector `self`.
5831 
5832  >>> A = AstVector()
5833  >>> len(A)
5834  0
5835  >>> A.push(Int('x'))
5836  >>> A.push(Int('x'))
5837  >>> len(A)
5838  2
5839  """
5840  return int(Z3_ast_vector_size(self.ctxctx.ref(), self.vectorvector))
5841 
5842  def __getitem__(self, i):
5843  """Return the AST at position `i`.
5844 
5845  >>> A = AstVector()
5846  >>> A.push(Int('x') + 1)
5847  >>> A.push(Int('y'))
5848  >>> A[0]
5849  x + 1
5850  >>> A[1]
5851  y
5852  """
5853 
5854  if isinstance(i, int):
5855  if i < 0:
5856  i += self.__len____len__()
5857 
5858  if i >= self.__len____len__():
5859  raise IndexError
5860  return _to_ast_ref(Z3_ast_vector_get(self.ctxctx.ref(), self.vectorvector, i), self.ctxctx)
5861 
5862  elif isinstance(i, slice):
5863  result = []
5864  for ii in range(*i.indices(self.__len____len__())):
5865  result.append(_to_ast_ref(
5866  Z3_ast_vector_get(self.ctxctx.ref(), self.vectorvector, ii),
5867  self.ctxctx,
5868  ))
5869  return result
5870 
5871  def __setitem__(self, i, v):
5872  """Update AST at position `i`.
5873 
5874  >>> A = AstVector()
5875  >>> A.push(Int('x') + 1)
5876  >>> A.push(Int('y'))
5877  >>> A[0]
5878  x + 1
5879  >>> A[0] = Int('x')
5880  >>> A[0]
5881  x
5882  """
5883  if i >= self.__len____len__():
5884  raise IndexError
5885  Z3_ast_vector_set(self.ctxctx.ref(), self.vectorvector, i, v.as_ast())
5886 
5887  def push(self, v):
5888  """Add `v` in the end of the vector.
5889 
5890  >>> A = AstVector()
5891  >>> len(A)
5892  0
5893  >>> A.push(Int('x'))
5894  >>> len(A)
5895  1
5896  """
5897  Z3_ast_vector_push(self.ctxctx.ref(), self.vectorvector, v.as_ast())
5898 
5899  def resize(self, sz):
5900  """Resize the vector to `sz` elements.
5901 
5902  >>> A = AstVector()
5903  >>> A.resize(10)
5904  >>> len(A)
5905  10
5906  >>> for i in range(10): A[i] = Int('x')
5907  >>> A[5]
5908  x
5909  """
5910  Z3_ast_vector_resize(self.ctxctx.ref(), self.vectorvector, sz)
5911 
5912  def __contains__(self, item):
5913  """Return `True` if the vector contains `item`.
5914 
5915  >>> x = Int('x')
5916  >>> A = AstVector()
5917  >>> x in A
5918  False
5919  >>> A.push(x)
5920  >>> x in A
5921  True
5922  >>> (x+1) in A
5923  False
5924  >>> A.push(x+1)
5925  >>> (x+1) in A
5926  True
5927  >>> A
5928  [x, x + 1]
5929  """
5930  for elem in self:
5931  if elem.eq(item):
5932  return True
5933  return False
5934 
5935  def translate(self, other_ctx):
5936  """Copy vector `self` to context `other_ctx`.
5937 
5938  >>> x = Int('x')
5939  >>> A = AstVector()
5940  >>> A.push(x)
5941  >>> c2 = Context()
5942  >>> B = A.translate(c2)
5943  >>> B
5944  [x]
5945  """
5946  return AstVector(
5947  Z3_ast_vector_translate(self.ctxctx.ref(), self.vectorvector, other_ctx.ref()),
5948  ctx=other_ctx,
5949  )
5950 
5951  def __copy__(self):
5952  return self.translatetranslate(self.ctxctx)
5953 
5954  def __deepcopy__(self, memo={}):
5955  return self.translatetranslate(self.ctxctx)
5956 
5957  def __repr__(self):
5958  return obj_to_string(self)
5959 
5960  def sexpr(self):
5961  """Return a textual representation of the s-expression representing the vector."""
5962  return Z3_ast_vector_to_string(self.ctxctx.ref(), self.vectorvector)
5963 
5964 
5969 
5970 
5971 class AstMap:
5972  """A mapping from ASTs to ASTs."""
5973 
5974  def __init__(self, m=None, ctx=None):
5975  self.mapmap = None
5976  if m is None:
5977  self.ctxctx = _get_ctx(ctx)
5978  self.mapmap = Z3_mk_ast_map(self.ctxctx.ref())
5979  else:
5980  self.mapmap = m
5981  assert ctx is not None
5982  self.ctxctx = ctx
5983  Z3_ast_map_inc_ref(self.ctxctx.ref(), self.mapmap)
5984 
5985  def __deepcopy__(self, memo={}):
5986  return AstMap(self.mapmap, self.ctxctx)
5987 
5988  def __del__(self):
5989  if self.mapmap is not None and self.ctxctx.ref() is not None:
5990  Z3_ast_map_dec_ref(self.ctxctx.ref(), self.mapmap)
5991 
5992  def __len__(self):
5993  """Return the size of the map.
5994 
5995  >>> M = AstMap()
5996  >>> len(M)
5997  0
5998  >>> x = Int('x')
5999  >>> M[x] = IntVal(1)
6000  >>> len(M)
6001  1
6002  """
6003  return int(Z3_ast_map_size(self.ctxctx.ref(), self.mapmap))
6004 
6005  def __contains__(self, key):
6006  """Return `True` if the map contains key `key`.
6007 
6008  >>> M = AstMap()
6009  >>> x = Int('x')
6010  >>> M[x] = x + 1
6011  >>> x in M
6012  True
6013  >>> x+1 in M
6014  False
6015  """
6016  return Z3_ast_map_contains(self.ctxctx.ref(), self.mapmap, key.as_ast())
6017 
6018  def __getitem__(self, key):
6019  """Retrieve the value associated with key `key`.
6020 
6021  >>> M = AstMap()
6022  >>> x = Int('x')
6023  >>> M[x] = x + 1
6024  >>> M[x]
6025  x + 1
6026  """
6027  return _to_ast_ref(Z3_ast_map_find(self.ctxctx.ref(), self.mapmap, key.as_ast()), self.ctxctx)
6028 
6029  def __setitem__(self, k, v):
6030  """Add/Update key `k` with value `v`.
6031 
6032  >>> M = AstMap()
6033  >>> x = Int('x')
6034  >>> M[x] = x + 1
6035  >>> len(M)
6036  1
6037  >>> M[x]
6038  x + 1
6039  >>> M[x] = IntVal(1)
6040  >>> M[x]
6041  1
6042  """
6043  Z3_ast_map_insert(self.ctxctx.ref(), self.mapmap, k.as_ast(), v.as_ast())
6044 
6045  def __repr__(self):
6046  return Z3_ast_map_to_string(self.ctxctx.ref(), self.mapmap)
6047 
6048  def erase(self, k):
6049  """Remove the entry associated with key `k`.
6050 
6051  >>> M = AstMap()
6052  >>> x = Int('x')
6053  >>> M[x] = x + 1
6054  >>> len(M)
6055  1
6056  >>> M.erase(x)
6057  >>> len(M)
6058  0
6059  """
6060  Z3_ast_map_erase(self.ctxctx.ref(), self.mapmap, k.as_ast())
6061 
6062  def reset(self):
6063  """Remove all entries from the map.
6064 
6065  >>> M = AstMap()
6066  >>> x = Int('x')
6067  >>> M[x] = x + 1
6068  >>> M[x+x] = IntVal(1)
6069  >>> len(M)
6070  2
6071  >>> M.reset()
6072  >>> len(M)
6073  0
6074  """
6075  Z3_ast_map_reset(self.ctxctx.ref(), self.mapmap)
6076 
6077  def keys(self):
6078  """Return an AstVector containing all keys in the map.
6079 
6080  >>> M = AstMap()
6081  >>> x = Int('x')
6082  >>> M[x] = x + 1
6083  >>> M[x+x] = IntVal(1)
6084  >>> M.keys()
6085  [x, x + x]
6086  """
6087  return AstVector(Z3_ast_map_keys(self.ctxctx.ref(), self.mapmap), self.ctxctx)
6088 
6089 
6094 
6095 
6097  """Store the value of the interpretation of a function in a particular point."""
6098 
6099  def __init__(self, entry, ctx):
6100  self.entryentry = entry
6101  self.ctxctx = ctx
6102  Z3_func_entry_inc_ref(self.ctxctx.ref(), self.entryentry)
6103 
6104  def __deepcopy__(self, memo={}):
6105  return FuncEntry(self.entryentry, self.ctxctx)
6106 
6107  def __del__(self):
6108  if self.ctxctx.ref() is not None:
6109  Z3_func_entry_dec_ref(self.ctxctx.ref(), self.entryentry)
6110 
6111  def num_args(self):
6112  """Return the number of arguments in the given entry.
6113 
6114  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6115  >>> s = Solver()
6116  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6117  >>> s.check()
6118  sat
6119  >>> m = s.model()
6120  >>> f_i = m[f]
6121  >>> f_i.num_entries()
6122  1
6123  >>> e = f_i.entry(0)
6124  >>> e.num_args()
6125  2
6126  """
6127  return int(Z3_func_entry_get_num_args(self.ctxctx.ref(), self.entryentry))
6128 
6129  def arg_value(self, idx):
6130  """Return the value of argument `idx`.
6131 
6132  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6133  >>> s = Solver()
6134  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6135  >>> s.check()
6136  sat
6137  >>> m = s.model()
6138  >>> f_i = m[f]
6139  >>> f_i.num_entries()
6140  1
6141  >>> e = f_i.entry(0)
6142  >>> e
6143  [1, 2, 20]
6144  >>> e.num_args()
6145  2
6146  >>> e.arg_value(0)
6147  1
6148  >>> e.arg_value(1)
6149  2
6150  >>> try:
6151  ... e.arg_value(2)
6152  ... except IndexError:
6153  ... print("index error")
6154  index error
6155  """
6156  if idx >= self.num_argsnum_args():
6157  raise IndexError
6158  return _to_expr_ref(Z3_func_entry_get_arg(self.ctxctx.ref(), self.entryentry, idx), self.ctxctx)
6159 
6160  def value(self):
6161  """Return the value of the function at point `self`.
6162 
6163  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6164  >>> s = Solver()
6165  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6166  >>> s.check()
6167  sat
6168  >>> m = s.model()
6169  >>> f_i = m[f]
6170  >>> f_i.num_entries()
6171  1
6172  >>> e = f_i.entry(0)
6173  >>> e
6174  [1, 2, 20]
6175  >>> e.num_args()
6176  2
6177  >>> e.value()
6178  20
6179  """
6180  return _to_expr_ref(Z3_func_entry_get_value(self.ctxctx.ref(), self.entryentry), self.ctxctx)
6181 
6182  def as_list(self):
6183  """Return entry `self` as a Python list.
6184  >>> f = Function('f', IntSort(), IntSort(), IntSort())
6185  >>> s = Solver()
6186  >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6187  >>> s.check()
6188  sat
6189  >>> m = s.model()
6190  >>> f_i = m[f]
6191  >>> f_i.num_entries()
6192  1
6193  >>> e = f_i.entry(0)
6194  >>> e.as_list()
6195  [1, 2, 20]
6196  """
6197  args = [self.arg_valuearg_value(i) for i in range(self.num_argsnum_args())]
6198  args.append(self.valuevalue())
6199  return args
6200 
6201  def __repr__(self):
6202  return repr(self.as_listas_list())
6203 
6204 
6206  """Stores the interpretation of a function in a Z3 model."""
6207 
6208  def __init__(self, f, ctx):
6209  self.ff = f
6210  self.ctxctx = ctx
6211  if self.ff is not None:
6212  Z3_func_interp_inc_ref(self.ctxctx.ref(), self.ff)
6213 
6214  def __del__(self):
6215  if self.ff is not None and self.ctxctx.ref() is not None:
6216  Z3_func_interp_dec_ref(self.ctxctx.ref(), self.ff)
6217 
6218  def else_value(self):
6219  """
6220  Return the `else` value for a function interpretation.
6221  Return None if Z3 did not specify the `else` value for
6222  this object.
6223 
6224  >>> f = Function('f', IntSort(), IntSort())
6225  >>> s = Solver()
6226  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6227  >>> s.check()
6228  sat
6229  >>> m = s.model()
6230  >>> m[f]
6231  [2 -> 0, else -> 1]
6232  >>> m[f].else_value()
6233  1
6234  """
6235  r = Z3_func_interp_get_else(self.ctxctx.ref(), self.ff)
6236  if r:
6237  return _to_expr_ref(r, self.ctxctx)
6238  else:
6239  return None
6240 
6241  def num_entries(self):
6242  """Return the number of entries/points in the function interpretation `self`.
6243 
6244  >>> f = Function('f', IntSort(), IntSort())
6245  >>> s = Solver()
6246  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6247  >>> s.check()
6248  sat
6249  >>> m = s.model()
6250  >>> m[f]
6251  [2 -> 0, else -> 1]
6252  >>> m[f].num_entries()
6253  1
6254  """
6255  return int(Z3_func_interp_get_num_entries(self.ctxctx.ref(), self.ff))
6256 
6257  def arity(self):
6258  """Return the number of arguments for each entry in the function interpretation `self`.
6259 
6260  >>> f = Function('f', IntSort(), IntSort())
6261  >>> s = Solver()
6262  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6263  >>> s.check()
6264  sat
6265  >>> m = s.model()
6266  >>> m[f].arity()
6267  1
6268  """
6269  return int(Z3_func_interp_get_arity(self.ctxctx.ref(), self.ff))
6270 
6271  def entry(self, idx):
6272  """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6273 
6274  >>> f = Function('f', IntSort(), IntSort())
6275  >>> s = Solver()
6276  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6277  >>> s.check()
6278  sat
6279  >>> m = s.model()
6280  >>> m[f]
6281  [2 -> 0, else -> 1]
6282  >>> m[f].num_entries()
6283  1
6284  >>> m[f].entry(0)
6285  [2, 0]
6286  """
6287  if idx >= self.num_entriesnum_entries():
6288  raise IndexError
6289  return FuncEntry(Z3_func_interp_get_entry(self.ctxctx.ref(), self.ff, idx), self.ctxctx)
6290 
6291  def translate(self, other_ctx):
6292  """Copy model 'self' to context 'other_ctx'.
6293  """
6294  return ModelRef(Z3_model_translate(self.ctxctx.ref(), self.model, other_ctx.ref()), other_ctx)
6295 
6296  def __copy__(self):
6297  return self.translatetranslate(self.ctxctx)
6298 
6299  def __deepcopy__(self, memo={}):
6300  return self.translatetranslate(self.ctxctx)
6301 
6302  def as_list(self):
6303  """Return the function interpretation as a Python list.
6304  >>> f = Function('f', IntSort(), IntSort())
6305  >>> s = Solver()
6306  >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6307  >>> s.check()
6308  sat
6309  >>> m = s.model()
6310  >>> m[f]
6311  [2 -> 0, else -> 1]
6312  >>> m[f].as_list()
6313  [[2, 0], 1]
6314  """
6315  r = [self.entryentry(i).as_list() for i in range(self.num_entriesnum_entries())]
6316  r.append(self.else_valueelse_value())
6317  return r
6318 
6319  def __repr__(self):
6320  return obj_to_string(self)
6321 
6322 
6324  """Model/Solution of a satisfiability problem (aka system of constraints)."""
6325 
6326  def __init__(self, m, ctx):
6327  assert ctx is not None
6328  self.modelmodel = m
6329  self.ctxctx = ctx
6330  Z3_model_inc_ref(self.ctxctx.ref(), self.modelmodel)
6331 
6332  def __del__(self):
6333  if self.ctxctx.ref() is not None:
6334  Z3_model_dec_ref(self.ctxctx.ref(), self.modelmodel)
6335 
6336  def __repr__(self):
6337  return obj_to_string(self)
6338 
6339  def sexpr(self):
6340  """Return a textual representation of the s-expression representing the model."""
6341  return Z3_model_to_string(self.ctxctx.ref(), self.modelmodel)
6342 
6343  def eval(self, t, model_completion=False):
6344  """Evaluate the expression `t` in the model `self`.
6345  If `model_completion` is enabled, then a default interpretation is automatically added
6346  for symbols that do not have an interpretation in the model `self`.
6347 
6348  >>> x = Int('x')
6349  >>> s = Solver()
6350  >>> s.add(x > 0, x < 2)
6351  >>> s.check()
6352  sat
6353  >>> m = s.model()
6354  >>> m.eval(x + 1)
6355  2
6356  >>> m.eval(x == 1)
6357  True
6358  >>> y = Int('y')
6359  >>> m.eval(y + x)
6360  1 + y
6361  >>> m.eval(y)
6362  y
6363  >>> m.eval(y, model_completion=True)
6364  0
6365  >>> # Now, m contains an interpretation for y
6366  >>> m.eval(y + x)
6367  1
6368  """
6369  r = (Ast * 1)()
6370  if Z3_model_eval(self.ctxctx.ref(), self.modelmodel, t.as_ast(), model_completion, r):
6371  return _to_expr_ref(r[0], self.ctxctx)
6372  raise Z3Exception("failed to evaluate expression in the model")
6373 
6374  def evaluate(self, t, model_completion=False):
6375  """Alias for `eval`.
6376 
6377  >>> x = Int('x')
6378  >>> s = Solver()
6379  >>> s.add(x > 0, x < 2)
6380  >>> s.check()
6381  sat
6382  >>> m = s.model()
6383  >>> m.evaluate(x + 1)
6384  2
6385  >>> m.evaluate(x == 1)
6386  True
6387  >>> y = Int('y')
6388  >>> m.evaluate(y + x)
6389  1 + y
6390  >>> m.evaluate(y)
6391  y
6392  >>> m.evaluate(y, model_completion=True)
6393  0
6394  >>> # Now, m contains an interpretation for y
6395  >>> m.evaluate(y + x)
6396  1
6397  """
6398  return self.evaleval(t, model_completion)
6399 
6400  def __len__(self):
6401  """Return the number of constant and function declarations in the model `self`.
6402 
6403  >>> f = Function('f', IntSort(), IntSort())
6404  >>> x = Int('x')
6405  >>> s = Solver()
6406  >>> s.add(x > 0, f(x) != x)
6407  >>> s.check()
6408  sat
6409  >>> m = s.model()
6410  >>> len(m)
6411  2
6412  """
6413  num_consts = int(Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel))
6414  num_funcs = int(Z3_model_get_num_funcs(self.ctxctx.ref(), self.modelmodel))
6415  return num_consts + num_funcs
6416 
6417  def get_interp(self, decl):
6418  """Return the interpretation for a given declaration or constant.
6419 
6420  >>> f = Function('f', IntSort(), IntSort())
6421  >>> x = Int('x')
6422  >>> s = Solver()
6423  >>> s.add(x > 0, x < 2, f(x) == 0)
6424  >>> s.check()
6425  sat
6426  >>> m = s.model()
6427  >>> m[x]
6428  1
6429  >>> m[f]
6430  [else -> 0]
6431  """
6432  if z3_debug():
6433  _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6434  if is_const(decl):
6435  decl = decl.decl()
6436  try:
6437  if decl.arity() == 0:
6438  _r = Z3_model_get_const_interp(self.ctxctx.ref(), self.modelmodel, decl.ast)
6439  if _r.value is None:
6440  return None
6441  r = _to_expr_ref(_r, self.ctxctx)
6442  if is_as_array(r):
6443  return self.get_interpget_interp(get_as_array_func(r))
6444  else:
6445  return r
6446  else:
6447  return FuncInterp(Z3_model_get_func_interp(self.ctxctx.ref(), self.modelmodel, decl.ast), self.ctxctx)
6448  except Z3Exception:
6449  return None
6450 
6451  def num_sorts(self):
6452  """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6453 
6454  >>> A = DeclareSort('A')
6455  >>> a, b = Consts('a b', A)
6456  >>> s = Solver()
6457  >>> s.add(a != b)
6458  >>> s.check()
6459  sat
6460  >>> m = s.model()
6461  >>> m.num_sorts()
6462  1
6463  """
6464  return int(Z3_model_get_num_sorts(self.ctxctx.ref(), self.modelmodel))
6465 
6466  def get_sort(self, idx):
6467  """Return the uninterpreted sort at position `idx` < self.num_sorts().
6468 
6469  >>> A = DeclareSort('A')
6470  >>> B = DeclareSort('B')
6471  >>> a1, a2 = Consts('a1 a2', A)
6472  >>> b1, b2 = Consts('b1 b2', B)
6473  >>> s = Solver()
6474  >>> s.add(a1 != a2, b1 != b2)
6475  >>> s.check()
6476  sat
6477  >>> m = s.model()
6478  >>> m.num_sorts()
6479  2
6480  >>> m.get_sort(0)
6481  A
6482  >>> m.get_sort(1)
6483  B
6484  """
6485  if idx >= self.num_sortsnum_sorts():
6486  raise IndexError
6487  return _to_sort_ref(Z3_model_get_sort(self.ctxctx.ref(), self.modelmodel, idx), self.ctxctx)
6488 
6489  def sorts(self):
6490  """Return all uninterpreted sorts that have an interpretation in the model `self`.
6491 
6492  >>> A = DeclareSort('A')
6493  >>> B = DeclareSort('B')
6494  >>> a1, a2 = Consts('a1 a2', A)
6495  >>> b1, b2 = Consts('b1 b2', B)
6496  >>> s = Solver()
6497  >>> s.add(a1 != a2, b1 != b2)
6498  >>> s.check()
6499  sat
6500  >>> m = s.model()
6501  >>> m.sorts()
6502  [A, B]
6503  """
6504  return [self.get_sortget_sort(i) for i in range(self.num_sortsnum_sorts())]
6505 
6506  def get_universe(self, s):
6507  """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6508 
6509  >>> A = DeclareSort('A')
6510  >>> a, b = Consts('a b', A)
6511  >>> s = Solver()
6512  >>> s.add(a != b)
6513  >>> s.check()
6514  sat
6515  >>> m = s.model()
6516  >>> m.get_universe(A)
6517  [A!val!1, A!val!0]
6518  """
6519  if z3_debug():
6520  _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6521  try:
6522  return AstVector(Z3_model_get_sort_universe(self.ctxctx.ref(), self.modelmodel, s.ast), self.ctxctx)
6523  except Z3Exception:
6524  return None
6525 
6526  def __getitem__(self, idx):
6527  """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6528  If `idx` is a declaration, then the actual interpretation is returned.
6529 
6530  The elements can be retrieved using position or the actual declaration.
6531 
6532  >>> f = Function('f', IntSort(), IntSort())
6533  >>> x = Int('x')
6534  >>> s = Solver()
6535  >>> s.add(x > 0, x < 2, f(x) == 0)
6536  >>> s.check()
6537  sat
6538  >>> m = s.model()
6539  >>> len(m)
6540  2
6541  >>> m[0]
6542  x
6543  >>> m[1]
6544  f
6545  >>> m[x]
6546  1
6547  >>> m[f]
6548  [else -> 0]
6549  >>> for d in m: print("%s -> %s" % (d, m[d]))
6550  x -> 1
6551  f -> [else -> 0]
6552  """
6553  if _is_int(idx):
6554  if idx >= len(self):
6555  raise IndexError
6556  num_consts = Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel)
6557  if (idx < num_consts):
6558  return FuncDeclRef(Z3_model_get_const_decl(self.ctxctx.ref(), self.modelmodel, idx), self.ctxctx)
6559  else:
6560  return FuncDeclRef(Z3_model_get_func_decl(self.ctxctx.ref(), self.modelmodel, idx - num_consts), self.ctxctx)
6561  if isinstance(idx, FuncDeclRef):
6562  return self.get_interpget_interp(idx)
6563  if is_const(idx):
6564  return self.get_interpget_interp(idx.decl())
6565  if isinstance(idx, SortRef):
6566  return self.get_universeget_universe(idx)
6567  if z3_debug():
6568  _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6569  return None
6570 
6571  def decls(self):
6572  """Return a list with all symbols that have an interpretation in the model `self`.
6573  >>> f = Function('f', IntSort(), IntSort())
6574  >>> x = Int('x')
6575  >>> s = Solver()
6576  >>> s.add(x > 0, x < 2, f(x) == 0)
6577  >>> s.check()
6578  sat
6579  >>> m = s.model()
6580  >>> m.decls()
6581  [x, f]
6582  """
6583  r = []
6584  for i in range(Z3_model_get_num_consts(self.ctxctx.ref(), self.modelmodel)):
6585  r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctxctx.ref(), self.modelmodel, i), self.ctxctx))
6586  for i in range(Z3_model_get_num_funcs(self.ctxctx.ref(), self.modelmodel)):
6587  r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctxctx.ref(), self.modelmodel, i), self.ctxctx))
6588  return r
6589 
6590  def update_value(self, x, value):
6591  """Update the interpretation of a constant"""
6592  if is_expr(x):
6593  x = x.decl()
6594  if not is_func_decl(x) or x.arity() != 0:
6595  raise Z3Exception("Expecting 0-ary function or constant expression")
6596  value = _py2expr(value)
6597  Z3_add_const_interp(x.ctx_ref(), self.modelmodel, x.ast, value.ast)
6598 
6599  def translate(self, target):
6600  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6601  """
6602  if z3_debug():
6603  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6604  model = Z3_model_translate(self.ctxctx.ref(), self.modelmodel, target.ref())
6605  return ModelRef(model, target)
6606 
6607  def __copy__(self):
6608  return self.translatetranslate(self.ctxctx)
6609 
6610  def __deepcopy__(self, memo={}):
6611  return self.translatetranslate(self.ctxctx)
6612 
6613 
6614 def Model(ctx=None):
6615  ctx = _get_ctx(ctx)
6616  return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6617 
6618 
6620  """Return true if n is a Z3 expression of the form (_ as-array f)."""
6621  return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6622 
6623 
6625  """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6626  if z3_debug():
6627  _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6628  return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6629 
6630 
6635 
6636 
6638  """Statistics for `Solver.check()`."""
6639 
6640  def __init__(self, stats, ctx):
6641  self.statsstats = stats
6642  self.ctxctx = ctx
6643  Z3_stats_inc_ref(self.ctxctx.ref(), self.statsstats)
6644 
6645  def __deepcopy__(self, memo={}):
6646  return Statistics(self.statsstats, self.ctxctx)
6647 
6648  def __del__(self):
6649  if self.ctxctx.ref() is not None:
6650  Z3_stats_dec_ref(self.ctxctx.ref(), self.statsstats)
6651 
6652  def __repr__(self):
6653  if in_html_mode():
6654  out = io.StringIO()
6655  even = True
6656  out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6657  for k, v in self:
6658  if even:
6659  out.write(u('<tr style="background-color:#CFCFCF">'))
6660  even = False
6661  else:
6662  out.write(u("<tr>"))
6663  even = True
6664  out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6665  out.write(u("</table>"))
6666  return out.getvalue()
6667  else:
6668  return Z3_stats_to_string(self.ctxctx.ref(), self.statsstats)
6669 
6670  def __len__(self):
6671  """Return the number of statistical counters.
6672 
6673  >>> x = Int('x')
6674  >>> s = Then('simplify', 'nlsat').solver()
6675  >>> s.add(x > 0)
6676  >>> s.check()
6677  sat
6678  >>> st = s.statistics()
6679  >>> len(st)
6680  6
6681  """
6682  return int(Z3_stats_size(self.ctxctx.ref(), self.statsstats))
6683 
6684  def __getitem__(self, idx):
6685  """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6686 
6687  >>> x = Int('x')
6688  >>> s = Then('simplify', 'nlsat').solver()
6689  >>> s.add(x > 0)
6690  >>> s.check()
6691  sat
6692  >>> st = s.statistics()
6693  >>> len(st)
6694  6
6695  >>> st[0]
6696  ('nlsat propagations', 2)
6697  >>> st[1]
6698  ('nlsat stages', 2)
6699  """
6700  if idx >= len(self):
6701  raise IndexError
6702  if Z3_stats_is_uint(self.ctxctx.ref(), self.statsstats, idx):
6703  val = int(Z3_stats_get_uint_value(self.ctxctx.ref(), self.statsstats, idx))
6704  else:
6705  val = Z3_stats_get_double_value(self.ctxctx.ref(), self.statsstats, idx)
6706  return (Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx), val)
6707 
6708  def keys(self):
6709  """Return the list 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  """
6718  return [Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx) for idx in range(len(self))]
6719 
6720  def get_key_value(self, key):
6721  """Return the value of a particular statistical counter.
6722 
6723  >>> x = Int('x')
6724  >>> s = Then('simplify', 'nlsat').solver()
6725  >>> s.add(x > 0)
6726  >>> s.check()
6727  sat
6728  >>> st = s.statistics()
6729  >>> st.get_key_value('nlsat propagations')
6730  2
6731  """
6732  for idx in range(len(self)):
6733  if key == Z3_stats_get_key(self.ctxctx.ref(), self.statsstats, idx):
6734  if Z3_stats_is_uint(self.ctxctx.ref(), self.statsstats, idx):
6735  return int(Z3_stats_get_uint_value(self.ctxctx.ref(), self.statsstats, idx))
6736  else:
6737  return Z3_stats_get_double_value(self.ctxctx.ref(), self.statsstats, idx)
6738  raise Z3Exception("unknown key")
6739 
6740  def __getattr__(self, name):
6741  """Access the value of statistical using attributes.
6742 
6743  Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6744  we should use '_' (e.g., 'nlsat_propagations').
6745 
6746  >>> x = Int('x')
6747  >>> s = Then('simplify', 'nlsat').solver()
6748  >>> s.add(x > 0)
6749  >>> s.check()
6750  sat
6751  >>> st = s.statistics()
6752  >>> st.nlsat_propagations
6753  2
6754  >>> st.nlsat_stages
6755  2
6756  """
6757  key = name.replace("_", " ")
6758  try:
6759  return self.get_key_valueget_key_value(key)
6760  except Z3Exception:
6761  raise AttributeError
6762 
6763 
6768 
6769 
6771  """Represents the result of a satisfiability check: sat, unsat, unknown.
6772 
6773  >>> s = Solver()
6774  >>> s.check()
6775  sat
6776  >>> r = s.check()
6777  >>> isinstance(r, CheckSatResult)
6778  True
6779  """
6780 
6781  def __init__(self, r):
6782  self.rr = r
6783 
6784  def __deepcopy__(self, memo={}):
6785  return CheckSatResult(self.rr)
6786 
6787  def __eq__(self, other):
6788  return isinstance(other, CheckSatResult) and self.rr == other.r
6789 
6790  def __ne__(self, other):
6791  return not self.__eq____eq__(other)
6792 
6793  def __repr__(self):
6794  if in_html_mode():
6795  if self.rr == Z3_L_TRUE:
6796  return "<b>sat</b>"
6797  elif self.rr == Z3_L_FALSE:
6798  return "<b>unsat</b>"
6799  else:
6800  return "<b>unknown</b>"
6801  else:
6802  if self.rr == Z3_L_TRUE:
6803  return "sat"
6804  elif self.rr == Z3_L_FALSE:
6805  return "unsat"
6806  else:
6807  return "unknown"
6808 
6809  def _repr_html_(self):
6810  in_html = in_html_mode()
6811  set_html_mode(True)
6812  res = repr(self)
6813  set_html_mode(in_html)
6814  return res
6815 
6816 
6817 sat = CheckSatResult(Z3_L_TRUE)
6818 unsat = CheckSatResult(Z3_L_FALSE)
6819 unknown = CheckSatResult(Z3_L_UNDEF)
6820 
6821 
6823  """
6824  Solver API provides methods for implementing the main SMT 2.0 commands:
6825  push, pop, check, get-model, etc.
6826  """
6827 
6828  def __init__(self, solver=None, ctx=None, logFile=None):
6829  assert solver is None or ctx is not None
6830  self.ctxctx = _get_ctx(ctx)
6831  self.backtrack_levelbacktrack_level = 4000000000
6832  self.solversolver = None
6833  if solver is None:
6834  self.solversolver = Z3_mk_solver(self.ctxctx.ref())
6835  else:
6836  self.solversolver = solver
6837  Z3_solver_inc_ref(self.ctxctx.ref(), self.solversolver)
6838  if logFile is not None:
6839  self.setset("smtlib2_log", logFile)
6840 
6841  def __del__(self):
6842  if self.solversolver is not None and self.ctxctx.ref() is not None:
6843  Z3_solver_dec_ref(self.ctxctx.ref(), self.solversolver)
6844 
6845  def set(self, *args, **keys):
6846  """Set a configuration option.
6847  The method `help()` return a string containing all available options.
6848 
6849  >>> s = Solver()
6850  >>> # The option MBQI can be set using three different approaches.
6851  >>> s.set(mbqi=True)
6852  >>> s.set('MBQI', True)
6853  >>> s.set(':mbqi', True)
6854  """
6855  p = args2params(args, keys, self.ctxctx)
6856  Z3_solver_set_params(self.ctxctx.ref(), self.solversolver, p.params)
6857 
6858  def push(self):
6859  """Create a backtracking point.
6860 
6861  >>> x = Int('x')
6862  >>> s = Solver()
6863  >>> s.add(x > 0)
6864  >>> s
6865  [x > 0]
6866  >>> s.push()
6867  >>> s.add(x < 1)
6868  >>> s
6869  [x > 0, x < 1]
6870  >>> s.check()
6871  unsat
6872  >>> s.pop()
6873  >>> s.check()
6874  sat
6875  >>> s
6876  [x > 0]
6877  """
6878  Z3_solver_push(self.ctxctx.ref(), self.solversolver)
6879 
6880  def pop(self, num=1):
6881  """Backtrack \\c num backtracking points.
6882 
6883  >>> x = Int('x')
6884  >>> s = Solver()
6885  >>> s.add(x > 0)
6886  >>> s
6887  [x > 0]
6888  >>> s.push()
6889  >>> s.add(x < 1)
6890  >>> s
6891  [x > 0, x < 1]
6892  >>> s.check()
6893  unsat
6894  >>> s.pop()
6895  >>> s.check()
6896  sat
6897  >>> s
6898  [x > 0]
6899  """
6900  Z3_solver_pop(self.ctxctx.ref(), self.solversolver, num)
6901 
6902  def num_scopes(self):
6903  """Return the current number of backtracking points.
6904 
6905  >>> s = Solver()
6906  >>> s.num_scopes()
6907  0
6908  >>> s.push()
6909  >>> s.num_scopes()
6910  1
6911  >>> s.push()
6912  >>> s.num_scopes()
6913  2
6914  >>> s.pop()
6915  >>> s.num_scopes()
6916  1
6917  """
6918  return Z3_solver_get_num_scopes(self.ctxctx.ref(), self.solversolver)
6919 
6920  def reset(self):
6921  """Remove all asserted constraints and backtracking points created using `push()`.
6922 
6923  >>> x = Int('x')
6924  >>> s = Solver()
6925  >>> s.add(x > 0)
6926  >>> s
6927  [x > 0]
6928  >>> s.reset()
6929  >>> s
6930  []
6931  """
6932  Z3_solver_reset(self.ctxctx.ref(), self.solversolver)
6933 
6934  def assert_exprs(self, *args):
6935  """Assert constraints into the solver.
6936 
6937  >>> x = Int('x')
6938  >>> s = Solver()
6939  >>> s.assert_exprs(x > 0, x < 2)
6940  >>> s
6941  [x > 0, x < 2]
6942  """
6943  args = _get_args(args)
6944  s = BoolSort(self.ctxctx)
6945  for arg in args:
6946  if isinstance(arg, Goal) or isinstance(arg, AstVector):
6947  for f in arg:
6948  Z3_solver_assert(self.ctxctx.ref(), self.solversolver, f.as_ast())
6949  else:
6950  arg = s.cast(arg)
6951  Z3_solver_assert(self.ctxctx.ref(), self.solversolver, arg.as_ast())
6952 
6953  def add(self, *args):
6954  """Assert constraints into the solver.
6955 
6956  >>> x = Int('x')
6957  >>> s = Solver()
6958  >>> s.add(x > 0, x < 2)
6959  >>> s
6960  [x > 0, x < 2]
6961  """
6962  self.assert_exprsassert_exprs(*args)
6963 
6964  def __iadd__(self, fml):
6965  self.addadd(fml)
6966  return self
6967 
6968  def append(self, *args):
6969  """Assert constraints into the solver.
6970 
6971  >>> x = Int('x')
6972  >>> s = Solver()
6973  >>> s.append(x > 0, x < 2)
6974  >>> s
6975  [x > 0, x < 2]
6976  """
6977  self.assert_exprsassert_exprs(*args)
6978 
6979  def insert(self, *args):
6980  """Assert constraints into the solver.
6981 
6982  >>> x = Int('x')
6983  >>> s = Solver()
6984  >>> s.insert(x > 0, x < 2)
6985  >>> s
6986  [x > 0, x < 2]
6987  """
6988  self.assert_exprsassert_exprs(*args)
6989 
6990  def assert_and_track(self, a, p):
6991  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6992 
6993  If `p` is a string, it will be automatically converted into a Boolean constant.
6994 
6995  >>> x = Int('x')
6996  >>> p3 = Bool('p3')
6997  >>> s = Solver()
6998  >>> s.set(unsat_core=True)
6999  >>> s.assert_and_track(x > 0, 'p1')
7000  >>> s.assert_and_track(x != 1, 'p2')
7001  >>> s.assert_and_track(x < 0, p3)
7002  >>> print(s.check())
7003  unsat
7004  >>> c = s.unsat_core()
7005  >>> len(c)
7006  2
7007  >>> Bool('p1') in c
7008  True
7009  >>> Bool('p2') in c
7010  False
7011  >>> p3 in c
7012  True
7013  """
7014  if isinstance(p, str):
7015  p = Bool(p, self.ctxctx)
7016  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7017  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7018  Z3_solver_assert_and_track(self.ctxctx.ref(), self.solversolver, a.as_ast(), p.as_ast())
7019 
7020  def check(self, *assumptions):
7021  """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7022 
7023  >>> x = Int('x')
7024  >>> s = Solver()
7025  >>> s.check()
7026  sat
7027  >>> s.add(x > 0, x < 2)
7028  >>> s.check()
7029  sat
7030  >>> s.model().eval(x)
7031  1
7032  >>> s.add(x < 1)
7033  >>> s.check()
7034  unsat
7035  >>> s.reset()
7036  >>> s.add(2**x == 4)
7037  >>> s.check()
7038  unknown
7039  """
7040  s = BoolSort(self.ctxctx)
7041  assumptions = _get_args(assumptions)
7042  num = len(assumptions)
7043  _assumptions = (Ast * num)()
7044  for i in range(num):
7045  _assumptions[i] = s.cast(assumptions[i]).as_ast()
7046  r = Z3_solver_check_assumptions(self.ctxctx.ref(), self.solversolver, num, _assumptions)
7047  return CheckSatResult(r)
7048 
7049  def model(self):
7050  """Return a model for the last `check()`.
7051 
7052  This function raises an exception if
7053  a model is not available (e.g., last `check()` returned unsat).
7054 
7055  >>> s = Solver()
7056  >>> a = Int('a')
7057  >>> s.add(a + 2 == 0)
7058  >>> s.check()
7059  sat
7060  >>> s.model()
7061  [a = -2]
7062  """
7063  try:
7064  return ModelRef(Z3_solver_get_model(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7065  except Z3Exception:
7066  raise Z3Exception("model is not available")
7067 
7068  def import_model_converter(self, other):
7069  """Import model converter from other into the current solver"""
7070  Z3_solver_import_model_converter(self.ctxctx.ref(), other.solver, self.solversolver)
7071 
7072  def unsat_core(self):
7073  """Return a subset (as an AST vector) of the assumptions provided to the last check().
7074 
7075  These are the assumptions Z3 used in the unsatisfiability proof.
7076  Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7077  They may be also used to "retract" assumptions. Note that, assumptions are not really
7078  "soft constraints", but they can be used to implement them.
7079 
7080  >>> p1, p2, p3 = Bools('p1 p2 p3')
7081  >>> x, y = Ints('x y')
7082  >>> s = Solver()
7083  >>> s.add(Implies(p1, x > 0))
7084  >>> s.add(Implies(p2, y > x))
7085  >>> s.add(Implies(p2, y < 1))
7086  >>> s.add(Implies(p3, y > -3))
7087  >>> s.check(p1, p2, p3)
7088  unsat
7089  >>> core = s.unsat_core()
7090  >>> len(core)
7091  2
7092  >>> p1 in core
7093  True
7094  >>> p2 in core
7095  True
7096  >>> p3 in core
7097  False
7098  >>> # "Retracting" p2
7099  >>> s.check(p1, p3)
7100  sat
7101  """
7102  return AstVector(Z3_solver_get_unsat_core(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7103 
7104  def consequences(self, assumptions, variables):
7105  """Determine fixed values for the variables based on the solver state and assumptions.
7106  >>> s = Solver()
7107  >>> a, b, c, d = Bools('a b c d')
7108  >>> s.add(Implies(a,b), Implies(b, c))
7109  >>> s.consequences([a],[b,c,d])
7110  (sat, [Implies(a, b), Implies(a, c)])
7111  >>> s.consequences([Not(c),d],[a,b,c,d])
7112  (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7113  """
7114  if isinstance(assumptions, list):
7115  _asms = AstVector(None, self.ctxctx)
7116  for a in assumptions:
7117  _asms.push(a)
7118  assumptions = _asms
7119  if isinstance(variables, list):
7120  _vars = AstVector(None, self.ctxctx)
7121  for a in variables:
7122  _vars.push(a)
7123  variables = _vars
7124  _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7125  _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7126  consequences = AstVector(None, self.ctxctx)
7127  r = Z3_solver_get_consequences(self.ctxctx.ref(), self.solversolver, assumptions.vector,
7128  variables.vector, consequences.vector)
7129  sz = len(consequences)
7130  consequences = [consequences[i] for i in range(sz)]
7131  return CheckSatResult(r), consequences
7132 
7133  def from_file(self, filename):
7134  """Parse assertions from a file"""
7135  Z3_solver_from_file(self.ctxctx.ref(), self.solversolver, filename)
7136 
7137  def from_string(self, s):
7138  """Parse assertions from a string"""
7139  Z3_solver_from_string(self.ctxctx.ref(), self.solversolver, s)
7140 
7141  def cube(self, vars=None):
7142  """Get set of cubes
7143  The method takes an optional set of variables that restrict which
7144  variables may be used as a starting point for cubing.
7145  If vars is not None, then the first case split is based on a variable in
7146  this set.
7147  """
7148  self.cube_vscube_vs = AstVector(None, self.ctxctx)
7149  if vars is not None:
7150  for v in vars:
7151  self.cube_vscube_vs.push(v)
7152  while True:
7153  lvl = self.backtrack_levelbacktrack_level
7154  self.backtrack_levelbacktrack_level = 4000000000
7155  r = AstVector(Z3_solver_cube(self.ctxctx.ref(), self.solversolver, self.cube_vscube_vs.vector, lvl), self.ctxctx)
7156  if (len(r) == 1 and is_false(r[0])):
7157  return
7158  yield r
7159  if (len(r) == 0):
7160  return
7161 
7162  def cube_vars(self):
7163  """Access the set of variables that were touched by the most recently generated cube.
7164  This set of variables can be used as a starting point for additional cubes.
7165  The idea is that variables that appear in clauses that are reduced by the most recent
7166  cube are likely more useful to cube on."""
7167  return self.cube_vscube_vs
7168 
7169  def proof(self):
7170  """Return a proof for the last `check()`. Proof construction must be enabled."""
7171  return _to_expr_ref(Z3_solver_get_proof(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7172 
7173  def assertions(self):
7174  """Return an AST vector containing all added constraints.
7175 
7176  >>> s = Solver()
7177  >>> s.assertions()
7178  []
7179  >>> a = Int('a')
7180  >>> s.add(a > 0)
7181  >>> s.add(a < 10)
7182  >>> s.assertions()
7183  [a > 0, a < 10]
7184  """
7185  return AstVector(Z3_solver_get_assertions(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7186 
7187  def units(self):
7188  """Return an AST vector containing all currently inferred units.
7189  """
7190  return AstVector(Z3_solver_get_units(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7191 
7192  def non_units(self):
7193  """Return an AST vector containing all atomic formulas in solver state that are not units.
7194  """
7195  return AstVector(Z3_solver_get_non_units(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7196 
7197  def trail_levels(self):
7198  """Return trail and decision levels of the solver state after a check() call.
7199  """
7200  trail = self.trailtrail()
7201  levels = (ctypes.c_uint * len(trail))()
7202  Z3_solver_get_levels(self.ctxctx.ref(), self.solversolver, trail.vector, len(trail), levels)
7203  return trail, levels
7204 
7205  def trail(self):
7206  """Return trail of the solver state after a check() call.
7207  """
7208  return AstVector(Z3_solver_get_trail(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7209 
7210  def statistics(self):
7211  """Return statistics for the last `check()`.
7212 
7213  >>> s = SimpleSolver()
7214  >>> x = Int('x')
7215  >>> s.add(x > 0)
7216  >>> s.check()
7217  sat
7218  >>> st = s.statistics()
7219  >>> st.get_key_value('final checks')
7220  1
7221  >>> len(st) > 0
7222  True
7223  >>> st[0] != 0
7224  True
7225  """
7226  return Statistics(Z3_solver_get_statistics(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7227 
7228  def reason_unknown(self):
7229  """Return a string describing why the last `check()` returned `unknown`.
7230 
7231  >>> x = Int('x')
7232  >>> s = SimpleSolver()
7233  >>> s.add(2**x == 4)
7234  >>> s.check()
7235  unknown
7236  >>> s.reason_unknown()
7237  '(incomplete (theory arithmetic))'
7238  """
7239  return Z3_solver_get_reason_unknown(self.ctxctx.ref(), self.solversolver)
7240 
7241  def help(self):
7242  """Display a string describing all available options."""
7243  print(Z3_solver_get_help(self.ctxctx.ref(), self.solversolver))
7244 
7245  def param_descrs(self):
7246  """Return the parameter description set."""
7247  return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctxctx.ref(), self.solversolver), self.ctxctx)
7248 
7249  def __repr__(self):
7250  """Return a formatted string with all added constraints."""
7251  return obj_to_string(self)
7252 
7253  def translate(self, target):
7254  """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7255 
7256  >>> c1 = Context()
7257  >>> c2 = Context()
7258  >>> s1 = Solver(ctx=c1)
7259  >>> s2 = s1.translate(c2)
7260  """
7261  if z3_debug():
7262  _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7263  solver = Z3_solver_translate(self.ctxctx.ref(), self.solversolver, target.ref())
7264  return Solver(solver, target)
7265 
7266  def __copy__(self):
7267  return self.translatetranslate(self.ctxctx)
7268 
7269  def __deepcopy__(self, memo={}):
7270  return self.translatetranslate(self.ctxctx)
7271 
7272  def sexpr(self):
7273  """Return a formatted string (in Lisp-like format) with all added constraints.
7274  We say the string is in s-expression format.
7275 
7276  >>> x = Int('x')
7277  >>> s = Solver()
7278  >>> s.add(x > 0)
7279  >>> s.add(x < 2)
7280  >>> r = s.sexpr()
7281  """
7282  return Z3_solver_to_string(self.ctxctx.ref(), self.solversolver)
7283 
7284  def dimacs(self, include_names=True):
7285  """Return a textual representation of the solver in DIMACS format."""
7286  return Z3_solver_to_dimacs_string(self.ctxctx.ref(), self.solversolver, include_names)
7287 
7288  def to_smt2(self):
7289  """return SMTLIB2 formatted benchmark for solver's assertions"""
7290  es = self.assertionsassertions()
7291  sz = len(es)
7292  sz1 = sz
7293  if sz1 > 0:
7294  sz1 -= 1
7295  v = (Ast * sz1)()
7296  for i in range(sz1):
7297  v[i] = es[i].as_ast()
7298  if sz > 0:
7299  e = es[sz1].as_ast()
7300  else:
7301  e = BoolVal(True, self.ctxctx).as_ast()
7303  self.ctxctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7304  )
7305 
7306 
7307 def SolverFor(logic, ctx=None, logFile=None):
7308  """Create a solver customized for the given logic.
7309 
7310  The parameter `logic` is a string. It should be contains
7311  the name of a SMT-LIB logic.
7312  See http://www.smtlib.org/ for the name of all available logics.
7313 
7314  >>> s = SolverFor("QF_LIA")
7315  >>> x = Int('x')
7316  >>> s.add(x > 0)
7317  >>> s.add(x < 2)
7318  >>> s.check()
7319  sat
7320  >>> s.model()
7321  [x = 1]
7322  """
7323  ctx = _get_ctx(ctx)
7324  logic = to_symbol(logic)
7325  return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7326 
7327 
7328 def SimpleSolver(ctx=None, logFile=None):
7329  """Return a simple general purpose solver with limited amount of preprocessing.
7330 
7331  >>> s = SimpleSolver()
7332  >>> x = Int('x')
7333  >>> s.add(x > 0)
7334  >>> s.check()
7335  sat
7336  """
7337  ctx = _get_ctx(ctx)
7338  return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7339 
7340 
7345 
7346 
7348  """Fixedpoint API provides methods for solving with recursive predicates"""
7349 
7350  def __init__(self, fixedpoint=None, ctx=None):
7351  assert fixedpoint is None or ctx is not None
7352  self.ctxctx = _get_ctx(ctx)
7353  self.fixedpointfixedpoint = None
7354  if fixedpoint is None:
7355  self.fixedpointfixedpoint = Z3_mk_fixedpoint(self.ctxctx.ref())
7356  else:
7357  self.fixedpointfixedpoint = fixedpoint
7358  Z3_fixedpoint_inc_ref(self.ctxctx.ref(), self.fixedpointfixedpoint)
7359  self.varsvars = []
7360 
7361  def __deepcopy__(self, memo={}):
7362  return FixedPoint(self.fixedpointfixedpoint, self.ctxctx)
7363 
7364  def __del__(self):
7365  if self.fixedpointfixedpoint is not None and self.ctxctx.ref() is not None:
7366  Z3_fixedpoint_dec_ref(self.ctxctx.ref(), self.fixedpointfixedpoint)
7367 
7368  def set(self, *args, **keys):
7369  """Set a configuration option. The method `help()` return a string containing all available options.
7370  """
7371  p = args2params(args, keys, self.ctxctx)
7372  Z3_fixedpoint_set_params(self.ctxctx.ref(), self.fixedpointfixedpoint, p.params)
7373 
7374  def help(self):
7375  """Display a string describing all available options."""
7376  print(Z3_fixedpoint_get_help(self.ctxctx.ref(), self.fixedpointfixedpoint))
7377 
7378  def param_descrs(self):
7379  """Return the parameter description set."""
7380  return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7381 
7382  def assert_exprs(self, *args):
7383  """Assert constraints as background axioms for the fixedpoint solver."""
7384  args = _get_args(args)
7385  s = BoolSort(self.ctxctx)
7386  for arg in args:
7387  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7388  for f in arg:
7389  f = self.abstractabstract(f)
7390  Z3_fixedpoint_assert(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast())
7391  else:
7392  arg = s.cast(arg)
7393  arg = self.abstractabstract(arg)
7394  Z3_fixedpoint_assert(self.ctxctx.ref(), self.fixedpointfixedpoint, arg.as_ast())
7395 
7396  def add(self, *args):
7397  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7398  self.assert_exprsassert_exprs(*args)
7399 
7400  def __iadd__(self, fml):
7401  self.addadd(fml)
7402  return self
7403 
7404  def append(self, *args):
7405  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7406  self.assert_exprsassert_exprs(*args)
7407 
7408  def insert(self, *args):
7409  """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7410  self.assert_exprsassert_exprs(*args)
7411 
7412  def add_rule(self, head, body=None, name=None):
7413  """Assert rules defining recursive predicates to the fixedpoint solver.
7414  >>> a = Bool('a')
7415  >>> b = Bool('b')
7416  >>> s = Fixedpoint()
7417  >>> s.register_relation(a.decl())
7418  >>> s.register_relation(b.decl())
7419  >>> s.fact(a)
7420  >>> s.rule(b, a)
7421  >>> s.query(b)
7422  sat
7423  """
7424  if name is None:
7425  name = ""
7426  name = to_symbol(name, self.ctxctx)
7427  if body is None:
7428  head = self.abstractabstract(head)
7429  Z3_fixedpoint_add_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, head.as_ast(), name)
7430  else:
7431  body = _get_args(body)
7432  f = self.abstractabstract(Implies(And(body, self.ctxctx), head))
7433  Z3_fixedpoint_add_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast(), name)
7434 
7435  def rule(self, head, body=None, name=None):
7436  """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7437  self.add_ruleadd_rule(head, body, name)
7438 
7439  def fact(self, head, name=None):
7440  """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7441  self.add_ruleadd_rule(head, None, name)
7442 
7443  def query(self, *query):
7444  """Query the fixedpoint engine whether formula is derivable.
7445  You can also pass an tuple or list of recursive predicates.
7446  """
7447  query = _get_args(query)
7448  sz = len(query)
7449  if sz >= 1 and isinstance(query[0], FuncDeclRef):
7450  _decls = (FuncDecl * sz)()
7451  i = 0
7452  for q in query:
7453  _decls[i] = q.ast
7454  i = i + 1
7455  r = Z3_fixedpoint_query_relations(self.ctxctx.ref(), self.fixedpointfixedpoint, sz, _decls)
7456  else:
7457  if sz == 1:
7458  query = query[0]
7459  else:
7460  query = And(query, self.ctxctx)
7461  query = self.abstractabstract(query, False)
7462  r = Z3_fixedpoint_query(self.ctxctx.ref(), self.fixedpointfixedpoint, query.as_ast())
7463  return CheckSatResult(r)
7464 
7465  def query_from_lvl(self, lvl, *query):
7466  """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7467  """
7468  query = _get_args(query)
7469  sz = len(query)
7470  if sz >= 1 and isinstance(query[0], FuncDecl):
7471  _z3_assert(False, "unsupported")
7472  else:
7473  if sz == 1:
7474  query = query[0]
7475  else:
7476  query = And(query)
7477  query = self.abstractabstract(query, False)
7478  r = Z3_fixedpoint_query_from_lvl(self.ctxctx.ref(), self.fixedpointfixedpoint, query.as_ast(), lvl)
7479  return CheckSatResult(r)
7480 
7481  def update_rule(self, head, body, name):
7482  """update rule"""
7483  if name is None:
7484  name = ""
7485  name = to_symbol(name, self.ctxctx)
7486  body = _get_args(body)
7487  f = self.abstractabstract(Implies(And(body, self.ctxctx), head))
7488  Z3_fixedpoint_update_rule(self.ctxctx.ref(), self.fixedpointfixedpoint, f.as_ast(), name)
7489 
7490  def get_answer(self):
7491  """Retrieve answer from last query call."""
7492  r = Z3_fixedpoint_get_answer(self.ctxctx.ref(), self.fixedpointfixedpoint)
7493  return _to_expr_ref(r, self.ctxctx)
7494 
7496  """Retrieve a ground cex from last query call."""
7497  r = Z3_fixedpoint_get_ground_sat_answer(self.ctxctx.ref(), self.fixedpointfixedpoint)
7498  return _to_expr_ref(r, self.ctxctx)
7499 
7501  """retrieve rules along the counterexample trace"""
7502  return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7503 
7505  """retrieve rule names along the counterexample trace"""
7506  # this is a hack as I don't know how to return a list of symbols from C++;
7507  # obtain names as a single string separated by semicolons
7508  names = _symbol2py(self.ctxctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctxctx.ref(), self.fixedpointfixedpoint))
7509  # split into individual names
7510  return names.split(";")
7511 
7512  def get_num_levels(self, predicate):
7513  """Retrieve number of levels used for predicate in PDR engine"""
7514  return Z3_fixedpoint_get_num_levels(self.ctxctx.ref(), self.fixedpointfixedpoint, predicate.ast)
7515 
7516  def get_cover_delta(self, level, predicate):
7517  """Retrieve properties known about predicate for the level'th unfolding.
7518  -1 is treated as the limit (infinity)
7519  """
7520  r = Z3_fixedpoint_get_cover_delta(self.ctxctx.ref(), self.fixedpointfixedpoint, level, predicate.ast)
7521  return _to_expr_ref(r, self.ctxctx)
7522 
7523  def add_cover(self, level, predicate, property):
7524  """Add property to predicate for the level'th unfolding.
7525  -1 is treated as infinity (infinity)
7526  """
7527  Z3_fixedpoint_add_cover(self.ctxctx.ref(), self.fixedpointfixedpoint, level, predicate.ast, property.ast)
7528 
7529  def register_relation(self, *relations):
7530  """Register relation as recursive"""
7531  relations = _get_args(relations)
7532  for f in relations:
7533  Z3_fixedpoint_register_relation(self.ctxctx.ref(), self.fixedpointfixedpoint, f.ast)
7534 
7535  def set_predicate_representation(self, f, *representations):
7536  """Control how relation is represented"""
7537  representations = _get_args(representations)
7538  representations = [to_symbol(s) for s in representations]
7539  sz = len(representations)
7540  args = (Symbol * sz)()
7541  for i in range(sz):
7542  args[i] = representations[i]
7543  Z3_fixedpoint_set_predicate_representation(self.ctxctx.ref(), self.fixedpointfixedpoint, f.ast, sz, args)
7544 
7545  def parse_string(self, s):
7546  """Parse rules and queries from a string"""
7547  return AstVector(Z3_fixedpoint_from_string(self.ctxctx.ref(), self.fixedpointfixedpoint, s), self.ctxctx)
7548 
7549  def parse_file(self, f):
7550  """Parse rules and queries from a file"""
7551  return AstVector(Z3_fixedpoint_from_file(self.ctxctx.ref(), self.fixedpointfixedpoint, f), self.ctxctx)
7552 
7553  def get_rules(self):
7554  """retrieve rules that have been added to fixedpoint context"""
7555  return AstVector(Z3_fixedpoint_get_rules(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7556 
7557  def get_assertions(self):
7558  """retrieve assertions that have been added to fixedpoint context"""
7559  return AstVector(Z3_fixedpoint_get_assertions(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7560 
7561  def __repr__(self):
7562  """Return a formatted string with all added rules and constraints."""
7563  return self.sexprsexpr()
7564 
7565  def sexpr(self):
7566  """Return a formatted string (in Lisp-like format) with all added constraints.
7567  We say the string is in s-expression format.
7568  """
7569  return Z3_fixedpoint_to_string(self.ctxctx.ref(), self.fixedpointfixedpoint, 0, (Ast * 0)())
7570 
7571  def to_string(self, queries):
7572  """Return a formatted string (in Lisp-like format) with all added constraints.
7573  We say the string is in s-expression format.
7574  Include also queries.
7575  """
7576  args, len = _to_ast_array(queries)
7577  return Z3_fixedpoint_to_string(self.ctxctx.ref(), self.fixedpointfixedpoint, len, args)
7578 
7579  def statistics(self):
7580  """Return statistics for the last `query()`.
7581  """
7582  return Statistics(Z3_fixedpoint_get_statistics(self.ctxctx.ref(), self.fixedpointfixedpoint), self.ctxctx)
7583 
7584  def reason_unknown(self):
7585  """Return a string describing why the last `query()` returned `unknown`.
7586  """
7587  return Z3_fixedpoint_get_reason_unknown(self.ctxctx.ref(), self.fixedpointfixedpoint)
7588 
7589  def declare_var(self, *vars):
7590  """Add variable or several variables.
7591  The added variable or variables will be bound in the rules
7592  and queries
7593  """
7594  vars = _get_args(vars)
7595  for v in vars:
7596  self.varsvars += [v]
7597 
7598  def abstract(self, fml, is_forall=True):
7599  if self.varsvars == []:
7600  return fml
7601  if is_forall:
7602  return ForAll(self.varsvars, fml)
7603  else:
7604  return Exists(self.varsvars, fml)
7605 
7606 
7607 
7612 
7614  """Finite domain sort."""
7615 
7616  def size(self):
7617  """Return the size of the finite domain sort"""
7618  r = (ctypes.c_ulonglong * 1)()
7619  if Z3_get_finite_domain_sort_size(self.ctx_refctx_ref(), self.astast, r):
7620  return r[0]
7621  else:
7622  raise Z3Exception("Failed to retrieve finite domain sort size")
7623 
7624 
7625 def FiniteDomainSort(name, sz, ctx=None):
7626  """Create a named finite domain sort of a given size sz"""
7627  if not isinstance(name, Symbol):
7628  name = to_symbol(name)
7629  ctx = _get_ctx(ctx)
7630  return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7631 
7632 
7634  """Return True if `s` is a Z3 finite-domain sort.
7635 
7636  >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
7637  True
7638  >>> is_finite_domain_sort(IntSort())
7639  False
7640  """
7641  return isinstance(s, FiniteDomainSortRef)
7642 
7643 
7645  """Finite-domain expressions."""
7646 
7647  def sort(self):
7648  """Return the sort of the finite-domain expression `self`."""
7649  return FiniteDomainSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
7650 
7651  def as_string(self):
7652  """Return a Z3 floating point expression as a Python string."""
7653  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
7654 
7655 
7657  """Return `True` if `a` is a Z3 finite-domain expression.
7658 
7659  >>> s = FiniteDomainSort('S', 100)
7660  >>> b = Const('b', s)
7661  >>> is_finite_domain(b)
7662  True
7663  >>> is_finite_domain(Int('x'))
7664  False
7665  """
7666  return isinstance(a, FiniteDomainRef)
7667 
7668 
7670  """Integer values."""
7671 
7672  def as_long(self):
7673  """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7674 
7675  >>> s = FiniteDomainSort('S', 100)
7676  >>> v = FiniteDomainVal(3, s)
7677  >>> v
7678  3
7679  >>> v.as_long() + 1
7680  4
7681  """
7682  return int(self.as_stringas_stringas_string())
7683 
7684  def as_string(self):
7685  """Return a Z3 finite-domain numeral as a Python string.
7686 
7687  >>> s = FiniteDomainSort('S', 100)
7688  >>> v = FiniteDomainVal(42, s)
7689  >>> v.as_string()
7690  '42'
7691  """
7692  return Z3_get_numeral_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
7693 
7694 
7695 def FiniteDomainVal(val, sort, ctx=None):
7696  """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7697 
7698  >>> s = FiniteDomainSort('S', 256)
7699  >>> FiniteDomainVal(255, s)
7700  255
7701  >>> FiniteDomainVal('100', s)
7702  100
7703  """
7704  if z3_debug():
7705  _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7706  ctx = sort.ctx
7707  return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7708 
7709 
7711  """Return `True` if `a` is a Z3 finite-domain value.
7712 
7713  >>> s = FiniteDomainSort('S', 100)
7714  >>> b = Const('b', s)
7715  >>> is_finite_domain_value(b)
7716  False
7717  >>> b = FiniteDomainVal(10, s)
7718  >>> b
7719  10
7720  >>> is_finite_domain_value(b)
7721  True
7722  """
7723  return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7724 
7725 
7726 
7731 
7733  def __init__(self, opt, value, is_max):
7734  self._opt_opt = opt
7735  self._value_value = value
7736  self._is_max_is_max = is_max
7737 
7738  def lower(self):
7739  opt = self._opt_opt
7740  return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7741 
7742  def upper(self):
7743  opt = self._opt_opt
7744  return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7745 
7746  def lower_values(self):
7747  opt = self._opt_opt
7748  return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7749 
7750  def upper_values(self):
7751  opt = self._opt_opt
7752  return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value_value), opt.ctx)
7753 
7754  def value(self):
7755  if self._is_max_is_max:
7756  return self.upperupper()
7757  else:
7758  return self.lowerlower()
7759 
7760  def __str__(self):
7761  return "%s:%s" % (self._value_value, self._is_max_is_max)
7762 
7763 
7764 _on_models = {}
7765 
7766 
7767 def _global_on_model(ctx):
7768  (fn, mdl) = _on_models[ctx]
7769  fn(mdl)
7770 
7771 
7772 _on_model_eh = on_model_eh_type(_global_on_model)
7773 
7774 
7776  """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7777 
7778  def __init__(self, ctx=None):
7779  self.ctxctx = _get_ctx(ctx)
7780  self.optimizeoptimize = Z3_mk_optimize(self.ctxctx.ref())
7781  self._on_models_id_on_models_id = None
7782  Z3_optimize_inc_ref(self.ctxctx.ref(), self.optimizeoptimize)
7783 
7784  def __deepcopy__(self, memo={}):
7785  return Optimize(self.optimizeoptimize, self.ctxctx)
7786 
7787  def __del__(self):
7788  if self.optimizeoptimize is not None and self.ctxctx.ref() is not None:
7789  Z3_optimize_dec_ref(self.ctxctx.ref(), self.optimizeoptimize)
7790  if self._on_models_id_on_models_id is not None:
7791  del _on_models[self._on_models_id_on_models_id]
7792 
7793  def set(self, *args, **keys):
7794  """Set a configuration option.
7795  The method `help()` return a string containing all available options.
7796  """
7797  p = args2params(args, keys, self.ctxctx)
7798  Z3_optimize_set_params(self.ctxctx.ref(), self.optimizeoptimize, p.params)
7799 
7800  def help(self):
7801  """Display a string describing all available options."""
7802  print(Z3_optimize_get_help(self.ctxctx.ref(), self.optimizeoptimize))
7803 
7804  def param_descrs(self):
7805  """Return the parameter description set."""
7806  return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7807 
7808  def assert_exprs(self, *args):
7809  """Assert constraints as background axioms for the optimize solver."""
7810  args = _get_args(args)
7811  s = BoolSort(self.ctxctx)
7812  for arg in args:
7813  if isinstance(arg, Goal) or isinstance(arg, AstVector):
7814  for f in arg:
7815  Z3_optimize_assert(self.ctxctx.ref(), self.optimizeoptimize, f.as_ast())
7816  else:
7817  arg = s.cast(arg)
7818  Z3_optimize_assert(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast())
7819 
7820  def add(self, *args):
7821  """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7822  self.assert_exprsassert_exprs(*args)
7823 
7824  def __iadd__(self, fml):
7825  self.addadd(fml)
7826  return self
7827 
7828  def assert_and_track(self, a, p):
7829  """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7830 
7831  If `p` is a string, it will be automatically converted into a Boolean constant.
7832 
7833  >>> x = Int('x')
7834  >>> p3 = Bool('p3')
7835  >>> s = Optimize()
7836  >>> s.assert_and_track(x > 0, 'p1')
7837  >>> s.assert_and_track(x != 1, 'p2')
7838  >>> s.assert_and_track(x < 0, p3)
7839  >>> print(s.check())
7840  unsat
7841  >>> c = s.unsat_core()
7842  >>> len(c)
7843  2
7844  >>> Bool('p1') in c
7845  True
7846  >>> Bool('p2') in c
7847  False
7848  >>> p3 in c
7849  True
7850  """
7851  if isinstance(p, str):
7852  p = Bool(p, self.ctxctx)
7853  _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7854  _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7855  Z3_optimize_assert_and_track(self.ctxctx.ref(), self.optimizeoptimize, a.as_ast(), p.as_ast())
7856 
7857  def add_soft(self, arg, weight="1", id=None):
7858  """Add soft constraint with optional weight and optional identifier.
7859  If no weight is supplied, then the penalty for violating the soft constraint
7860  is 1.
7861  Soft constraints are grouped by identifiers. Soft constraints that are
7862  added without identifiers are grouped by default.
7863  """
7864  if _is_int(weight):
7865  weight = "%d" % weight
7866  elif isinstance(weight, float):
7867  weight = "%f" % weight
7868  if not isinstance(weight, str):
7869  raise Z3Exception("weight should be a string or an integer")
7870  if id is None:
7871  id = ""
7872  id = to_symbol(id, self.ctxctx)
7873 
7874  def asoft(a):
7875  v = Z3_optimize_assert_soft(self.ctxctx.ref(), self.optimizeoptimize, a.as_ast(), weight, id)
7876  return OptimizeObjective(self, v, False)
7877  if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7878  return [asoft(a) for a in arg]
7879  return asoft(arg)
7880 
7881  def maximize(self, arg):
7882  """Add objective function to maximize."""
7883  return OptimizeObjective(
7884  self,
7885  Z3_optimize_maximize(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast()),
7886  is_max=True,
7887  )
7888 
7889  def minimize(self, arg):
7890  """Add objective function to minimize."""
7891  return OptimizeObjective(
7892  self,
7893  Z3_optimize_minimize(self.ctxctx.ref(), self.optimizeoptimize, arg.as_ast()),
7894  is_max=False,
7895  )
7896 
7897  def push(self):
7898  """create a backtracking point for added rules, facts and assertions"""
7899  Z3_optimize_push(self.ctxctx.ref(), self.optimizeoptimize)
7900 
7901  def pop(self):
7902  """restore to previously created backtracking point"""
7903  Z3_optimize_pop(self.ctxctx.ref(), self.optimizeoptimize)
7904 
7905  def check(self, *assumptions):
7906  """Check satisfiability while optimizing objective functions."""
7907  assumptions = _get_args(assumptions)
7908  num = len(assumptions)
7909  _assumptions = (Ast * num)()
7910  for i in range(num):
7911  _assumptions[i] = assumptions[i].as_ast()
7912  return CheckSatResult(Z3_optimize_check(self.ctxctx.ref(), self.optimizeoptimize, num, _assumptions))
7913 
7914  def reason_unknown(self):
7915  """Return a string that describes why the last `check()` returned `unknown`."""
7916  return Z3_optimize_get_reason_unknown(self.ctxctx.ref(), self.optimizeoptimize)
7917 
7918  def model(self):
7919  """Return a model for the last check()."""
7920  try:
7921  return ModelRef(Z3_optimize_get_model(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7922  except Z3Exception:
7923  raise Z3Exception("model is not available")
7924 
7925  def unsat_core(self):
7926  return AstVector(Z3_optimize_get_unsat_core(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7927 
7928  def lower(self, obj):
7929  if not isinstance(obj, OptimizeObjective):
7930  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7931  return obj.lower()
7932 
7933  def upper(self, obj):
7934  if not isinstance(obj, OptimizeObjective):
7935  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7936  return obj.upper()
7937 
7938  def lower_values(self, obj):
7939  if not isinstance(obj, OptimizeObjective):
7940  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7941  return obj.lower_values()
7942 
7943  def upper_values(self, obj):
7944  if not isinstance(obj, OptimizeObjective):
7945  raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7946  return obj.upper_values()
7947 
7948  def from_file(self, filename):
7949  """Parse assertions and objectives from a file"""
7950  Z3_optimize_from_file(self.ctxctx.ref(), self.optimizeoptimize, filename)
7951 
7952  def from_string(self, s):
7953  """Parse assertions and objectives from a string"""
7954  Z3_optimize_from_string(self.ctxctx.ref(), self.optimizeoptimize, s)
7955 
7956  def assertions(self):
7957  """Return an AST vector containing all added constraints."""
7958  return AstVector(Z3_optimize_get_assertions(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7959 
7960  def objectives(self):
7961  """returns set of objective functions"""
7962  return AstVector(Z3_optimize_get_objectives(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7963 
7964  def __repr__(self):
7965  """Return a formatted string with all added rules and constraints."""
7966  return self.sexprsexpr()
7967 
7968  def sexpr(self):
7969  """Return a formatted string (in Lisp-like format) with all added constraints.
7970  We say the string is in s-expression format.
7971  """
7972  return Z3_optimize_to_string(self.ctxctx.ref(), self.optimizeoptimize)
7973 
7974  def statistics(self):
7975  """Return statistics for the last check`.
7976  """
7977  return Statistics(Z3_optimize_get_statistics(self.ctxctx.ref(), self.optimizeoptimize), self.ctxctx)
7978 
7979  def set_on_model(self, on_model):
7980  """Register a callback that is invoked with every incremental improvement to
7981  objective values. The callback takes a model as argument.
7982  The life-time of the model is limited to the callback so the
7983  model has to be (deep) copied if it is to be used after the callback
7984  """
7985  id = len(_on_models) + 41
7986  mdl = Model(self.ctxctx)
7987  _on_models[id] = (on_model, mdl)
7988  self._on_models_id_on_models_id = id
7990  self.ctxctx.ref(), self.optimizeoptimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
7991  )
7992 
7993 
7994 
8000  """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8001  It also contains model and proof converters.
8002  """
8003 
8004  def __init__(self, result, ctx):
8005  self.resultresult = result
8006  self.ctxctx = ctx
8007  Z3_apply_result_inc_ref(self.ctxctx.ref(), self.resultresult)
8008 
8009  def __deepcopy__(self, memo={}):
8010  return ApplyResult(self.resultresult, self.ctxctx)
8011 
8012  def __del__(self):
8013  if self.ctxctx.ref() is not None:
8014  Z3_apply_result_dec_ref(self.ctxctx.ref(), self.resultresult)
8015 
8016  def __len__(self):
8017  """Return the number of subgoals in `self`.
8018 
8019  >>> a, b = Ints('a b')
8020  >>> g = Goal()
8021  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8022  >>> t = Tactic('split-clause')
8023  >>> r = t(g)
8024  >>> len(r)
8025  2
8026  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8027  >>> len(t(g))
8028  4
8029  >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8030  >>> len(t(g))
8031  1
8032  """
8033  return int(Z3_apply_result_get_num_subgoals(self.ctxctx.ref(), self.resultresult))
8034 
8035  def __getitem__(self, idx):
8036  """Return one of the subgoals stored in ApplyResult object `self`.
8037 
8038  >>> a, b = Ints('a b')
8039  >>> g = Goal()
8040  >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8041  >>> t = Tactic('split-clause')
8042  >>> r = t(g)
8043  >>> r[0]
8044  [a == 0, Or(b == 0, b == 1), a > b]
8045  >>> r[1]
8046  [a == 1, Or(b == 0, b == 1), a > b]
8047  """
8048  if idx >= len(self):
8049  raise IndexError
8050  return Goal(goal=Z3_apply_result_get_subgoal(self.ctxctx.ref(), self.resultresult, idx), ctx=self.ctxctx)
8051 
8052  def __repr__(self):
8053  return obj_to_string(self)
8054 
8055  def sexpr(self):
8056  """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8057  return Z3_apply_result_to_string(self.ctxctx.ref(), self.resultresult)
8058 
8059  def as_expr(self):
8060  """Return a Z3 expression consisting of all subgoals.
8061 
8062  >>> x = Int('x')
8063  >>> g = Goal()
8064  >>> g.add(x > 1)
8065  >>> g.add(Or(x == 2, x == 3))
8066  >>> r = Tactic('simplify')(g)
8067  >>> r
8068  [[Not(x <= 1), Or(x == 2, x == 3)]]
8069  >>> r.as_expr()
8070  And(Not(x <= 1), Or(x == 2, x == 3))
8071  >>> r = Tactic('split-clause')(g)
8072  >>> r
8073  [[x > 1, x == 2], [x > 1, x == 3]]
8074  >>> r.as_expr()
8075  Or(And(x > 1, x == 2), And(x > 1, x == 3))
8076  """
8077  sz = len(self)
8078  if sz == 0:
8079  return BoolVal(False, self.ctxctx)
8080  elif sz == 1:
8081  return self[0].as_expr()
8082  else:
8083  return Or([self[i].as_expr() for i in range(len(self))])
8084 
8085 
8090 
8091 
8092 class Tactic:
8093  """Tactics transform, solver and/or simplify sets of constraints (Goal).
8094  A Tactic can be converted into a Solver using the method solver().
8095 
8096  Several combinators are available for creating new tactics using the built-in ones:
8097  Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8098  """
8099 
8100  def __init__(self, tactic, ctx=None):
8101  self.ctxctx = _get_ctx(ctx)
8102  self.tactictactic = None
8103  if isinstance(tactic, TacticObj):
8104  self.tactictactic = tactic
8105  else:
8106  if z3_debug():
8107  _z3_assert(isinstance(tactic, str), "tactic name expected")
8108  try:
8109  self.tactictactic = Z3_mk_tactic(self.ctxctx.ref(), str(tactic))
8110  except Z3Exception:
8111  raise Z3Exception("unknown tactic '%s'" % tactic)
8112  Z3_tactic_inc_ref(self.ctxctx.ref(), self.tactictactic)
8113 
8114  def __deepcopy__(self, memo={}):
8115  return Tactic(self.tactictactic, self.ctxctx)
8116 
8117  def __del__(self):
8118  if self.tactictactic is not None and self.ctxctx.ref() is not None:
8119  Z3_tactic_dec_ref(self.ctxctx.ref(), self.tactictactic)
8120 
8121  def solver(self, logFile=None):
8122  """Create a solver using the tactic `self`.
8123 
8124  The solver supports the methods `push()` and `pop()`, but it
8125  will always solve each `check()` from scratch.
8126 
8127  >>> t = Then('simplify', 'nlsat')
8128  >>> s = t.solver()
8129  >>> x = Real('x')
8130  >>> s.add(x**2 == 2, x > 0)
8131  >>> s.check()
8132  sat
8133  >>> s.model()
8134  [x = 1.4142135623?]
8135  """
8136  return Solver(Z3_mk_solver_from_tactic(self.ctxctx.ref(), self.tactictactic), self.ctxctx, logFile)
8137 
8138  def apply(self, goal, *arguments, **keywords):
8139  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8140 
8141  >>> x, y = Ints('x y')
8142  >>> t = Tactic('solve-eqs')
8143  >>> t.apply(And(x == 0, y >= x + 1))
8144  [[y >= 1]]
8145  """
8146  if z3_debug():
8147  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8148  goal = _to_goal(goal)
8149  if len(arguments) > 0 or len(keywords) > 0:
8150  p = args2params(arguments, keywords, self.ctxctx)
8151  return ApplyResult(Z3_tactic_apply_ex(self.ctxctx.ref(), self.tactictactic, goal.goal, p.params), self.ctxctx)
8152  else:
8153  return ApplyResult(Z3_tactic_apply(self.ctxctx.ref(), self.tactictactic, goal.goal), self.ctxctx)
8154 
8155  def __call__(self, goal, *arguments, **keywords):
8156  """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8157 
8158  >>> x, y = Ints('x y')
8159  >>> t = Tactic('solve-eqs')
8160  >>> t(And(x == 0, y >= x + 1))
8161  [[y >= 1]]
8162  """
8163  return self.applyapply(goal, *arguments, **keywords)
8164 
8165  def help(self):
8166  """Display a string containing a description of the available options for the `self` tactic."""
8167  print(Z3_tactic_get_help(self.ctxctx.ref(), self.tactictactic))
8168 
8169  def param_descrs(self):
8170  """Return the parameter description set."""
8171  return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctxctx.ref(), self.tactictactic), self.ctxctx)
8172 
8173 
8174 def _to_goal(a):
8175  if isinstance(a, BoolRef):
8176  goal = Goal(ctx=a.ctx)
8177  goal.add(a)
8178  return goal
8179  else:
8180  return a
8181 
8182 
8183 def _to_tactic(t, ctx=None):
8184  if isinstance(t, Tactic):
8185  return t
8186  else:
8187  return Tactic(t, ctx)
8188 
8189 
8190 def _and_then(t1, t2, ctx=None):
8191  t1 = _to_tactic(t1, ctx)
8192  t2 = _to_tactic(t2, ctx)
8193  if z3_debug():
8194  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8195  return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8196 
8197 
8198 def _or_else(t1, t2, ctx=None):
8199  t1 = _to_tactic(t1, ctx)
8200  t2 = _to_tactic(t2, ctx)
8201  if z3_debug():
8202  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8203  return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8204 
8205 
8206 def AndThen(*ts, **ks):
8207  """Return a tactic that applies the tactics in `*ts` in sequence.
8208 
8209  >>> x, y = Ints('x y')
8210  >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8211  >>> t(And(x == 0, y > x + 1))
8212  [[Not(y <= 1)]]
8213  >>> t(And(x == 0, y > x + 1)).as_expr()
8214  Not(y <= 1)
8215  """
8216  if z3_debug():
8217  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8218  ctx = ks.get("ctx", None)
8219  num = len(ts)
8220  r = ts[0]
8221  for i in range(num - 1):
8222  r = _and_then(r, ts[i + 1], ctx)
8223  return r
8224 
8225 
8226 def Then(*ts, **ks):
8227  """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8228 
8229  >>> x, y = Ints('x y')
8230  >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8231  >>> t(And(x == 0, y > x + 1))
8232  [[Not(y <= 1)]]
8233  >>> t(And(x == 0, y > x + 1)).as_expr()
8234  Not(y <= 1)
8235  """
8236  return AndThen(*ts, **ks)
8237 
8238 
8239 def OrElse(*ts, **ks):
8240  """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8241 
8242  >>> x = Int('x')
8243  >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8244  >>> # Tactic split-clause fails if there is no clause in the given goal.
8245  >>> t(x == 0)
8246  [[x == 0]]
8247  >>> t(Or(x == 0, x == 1))
8248  [[x == 0], [x == 1]]
8249  """
8250  if z3_debug():
8251  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8252  ctx = ks.get("ctx", None)
8253  num = len(ts)
8254  r = ts[0]
8255  for i in range(num - 1):
8256  r = _or_else(r, ts[i + 1], ctx)
8257  return r
8258 
8259 
8260 def ParOr(*ts, **ks):
8261  """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8262 
8263  >>> x = Int('x')
8264  >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8265  >>> t(x + 1 == 2)
8266  [[x == 1]]
8267  """
8268  if z3_debug():
8269  _z3_assert(len(ts) >= 2, "At least two arguments expected")
8270  ctx = _get_ctx(ks.get("ctx", None))
8271  ts = [_to_tactic(t, ctx) for t in ts]
8272  sz = len(ts)
8273  _args = (TacticObj * sz)()
8274  for i in range(sz):
8275  _args[i] = ts[i].tactic
8276  return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8277 
8278 
8279 def ParThen(t1, t2, ctx=None):
8280  """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8281  The subgoals are processed in parallel.
8282 
8283  >>> x, y = Ints('x y')
8284  >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8285  >>> t(And(Or(x == 1, x == 2), y == x + 1))
8286  [[x == 1, y == 2], [x == 2, y == 3]]
8287  """
8288  t1 = _to_tactic(t1, ctx)
8289  t2 = _to_tactic(t2, ctx)
8290  if z3_debug():
8291  _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8292  return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8293 
8294 
8295 def ParAndThen(t1, t2, ctx=None):
8296  """Alias for ParThen(t1, t2, ctx)."""
8297  return ParThen(t1, t2, ctx)
8298 
8299 
8300 def With(t, *args, **keys):
8301  """Return a tactic that applies tactic `t` using the given configuration options.
8302 
8303  >>> x, y = Ints('x y')
8304  >>> t = With(Tactic('simplify'), som=True)
8305  >>> t((x + 1)*(y + 2) == 0)
8306  [[2*x + y + x*y == -2]]
8307  """
8308  ctx = keys.pop("ctx", None)
8309  t = _to_tactic(t, ctx)
8310  p = args2params(args, keys, t.ctx)
8311  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8312 
8313 
8314 def WithParams(t, p):
8315  """Return a tactic that applies tactic `t` using the given configuration options.
8316 
8317  >>> x, y = Ints('x y')
8318  >>> p = ParamsRef()
8319  >>> p.set("som", True)
8320  >>> t = WithParams(Tactic('simplify'), p)
8321  >>> t((x + 1)*(y + 2) == 0)
8322  [[2*x + y + x*y == -2]]
8323  """
8324  t = _to_tactic(t, None)
8325  return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8326 
8327 
8328 def Repeat(t, max=4294967295, ctx=None):
8329  """Return a tactic that keeps applying `t` until the goal is not modified anymore
8330  or the maximum number of iterations `max` is reached.
8331 
8332  >>> x, y = Ints('x y')
8333  >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8334  >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8335  >>> r = t(c)
8336  >>> for subgoal in r: print(subgoal)
8337  [x == 0, y == 0, x > y]
8338  [x == 0, y == 1, x > y]
8339  [x == 1, y == 0, x > y]
8340  [x == 1, y == 1, x > y]
8341  >>> t = Then(t, Tactic('propagate-values'))
8342  >>> t(c)
8343  [[x == 1, y == 0]]
8344  """
8345  t = _to_tactic(t, ctx)
8346  return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8347 
8348 
8349 def TryFor(t, ms, ctx=None):
8350  """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8351 
8352  If `t` does not terminate in `ms` milliseconds, then it fails.
8353  """
8354  t = _to_tactic(t, ctx)
8355  return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8356 
8357 
8358 def tactics(ctx=None):
8359  """Return a list of all available tactics in Z3.
8360 
8361  >>> l = tactics()
8362  >>> l.count('simplify') == 1
8363  True
8364  """
8365  ctx = _get_ctx(ctx)
8366  return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8367 
8368 
8369 def tactic_description(name, ctx=None):
8370  """Return a short description for the tactic named `name`.
8371 
8372  >>> d = tactic_description('simplify')
8373  """
8374  ctx = _get_ctx(ctx)
8375  return Z3_tactic_get_descr(ctx.ref(), name)
8376 
8377 
8379  """Display a (tabular) description of all available tactics in Z3."""
8380  if in_html_mode():
8381  even = True
8382  print('<table border="1" cellpadding="2" cellspacing="0">')
8383  for t in tactics():
8384  if even:
8385  print('<tr style="background-color:#CFCFCF">')
8386  even = False
8387  else:
8388  print("<tr>")
8389  even = True
8390  print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8391  print("</table>")
8392  else:
8393  for t in tactics():
8394  print("%s : %s" % (t, tactic_description(t)))
8395 
8396 
8397 class Probe:
8398  """Probes are used to inspect a goal (aka problem) and collect information that may be used
8399  to decide which solver and/or preprocessing step will be used.
8400  """
8401 
8402  def __init__(self, probe, ctx=None):
8403  self.ctxctx = _get_ctx(ctx)
8404  self.probeprobe = None
8405  if isinstance(probe, ProbeObj):
8406  self.probeprobe = probe
8407  elif isinstance(probe, float):
8408  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), probe)
8409  elif _is_int(probe):
8410  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), float(probe))
8411  elif isinstance(probe, bool):
8412  if probe:
8413  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), 1.0)
8414  else:
8415  self.probeprobe = Z3_probe_const(self.ctxctx.ref(), 0.0)
8416  else:
8417  if z3_debug():
8418  _z3_assert(isinstance(probe, str), "probe name expected")
8419  try:
8420  self.probeprobe = Z3_mk_probe(self.ctxctx.ref(), probe)
8421  except Z3Exception:
8422  raise Z3Exception("unknown probe '%s'" % probe)
8423  Z3_probe_inc_ref(self.ctxctx.ref(), self.probeprobe)
8424 
8425  def __deepcopy__(self, memo={}):
8426  return Probe(self.probeprobe, self.ctxctx)
8427 
8428  def __del__(self):
8429  if self.probeprobe is not None and self.ctxctx.ref() is not None:
8430  Z3_probe_dec_ref(self.ctxctx.ref(), self.probeprobe)
8431 
8432  def __lt__(self, other):
8433  """Return a probe that evaluates to "true" when the value returned by `self`
8434  is less than the value returned by `other`.
8435 
8436  >>> p = Probe('size') < 10
8437  >>> x = Int('x')
8438  >>> g = Goal()
8439  >>> g.add(x > 0)
8440  >>> g.add(x < 10)
8441  >>> p(g)
8442  1.0
8443  """
8444  return Probe(Z3_probe_lt(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8445 
8446  def __gt__(self, other):
8447  """Return a probe that evaluates to "true" when the value returned by `self`
8448  is greater than the value returned by `other`.
8449 
8450  >>> p = Probe('size') > 10
8451  >>> x = Int('x')
8452  >>> g = Goal()
8453  >>> g.add(x > 0)
8454  >>> g.add(x < 10)
8455  >>> p(g)
8456  0.0
8457  """
8458  return Probe(Z3_probe_gt(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8459 
8460  def __le__(self, other):
8461  """Return a probe that evaluates to "true" when the value returned by `self`
8462  is less than or equal to the value returned by `other`.
8463 
8464  >>> p = Probe('size') <= 2
8465  >>> x = Int('x')
8466  >>> g = Goal()
8467  >>> g.add(x > 0)
8468  >>> g.add(x < 10)
8469  >>> p(g)
8470  1.0
8471  """
8472  return Probe(Z3_probe_le(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8473 
8474  def __ge__(self, other):
8475  """Return a probe that evaluates to "true" when the value returned by `self`
8476  is greater than or equal to the value returned by `other`.
8477 
8478  >>> p = Probe('size') >= 2
8479  >>> x = Int('x')
8480  >>> g = Goal()
8481  >>> g.add(x > 0)
8482  >>> g.add(x < 10)
8483  >>> p(g)
8484  1.0
8485  """
8486  return Probe(Z3_probe_ge(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8487 
8488  def __eq__(self, other):
8489  """Return a probe that evaluates to "true" when the value returned by `self`
8490  is equal to the value returned by `other`.
8491 
8492  >>> p = Probe('size') == 2
8493  >>> x = Int('x')
8494  >>> g = Goal()
8495  >>> g.add(x > 0)
8496  >>> g.add(x < 10)
8497  >>> p(g)
8498  1.0
8499  """
8500  return Probe(Z3_probe_eq(self.ctxctx.ref(), self.probeprobe, _to_probe(other, self.ctxctx).probe), self.ctxctx)
8501 
8502  def __ne__(self, other):
8503  """Return a probe that evaluates to "true" when the value returned by `self`
8504  is not equal to the value returned by `other`.
8505 
8506  >>> p = Probe('size') != 2
8507  >>> x = Int('x')
8508  >>> g = Goal()
8509  >>> g.add(x > 0)
8510  >>> g.add(x < 10)
8511  >>> p(g)
8512  0.0
8513  """
8514  p = self.__eq____eq__(other)
8515  return Probe(Z3_probe_not(self.ctxctx.ref(), p.probe), self.ctxctx)
8516 
8517  def __call__(self, goal):
8518  """Evaluate the probe `self` in the given goal.
8519 
8520  >>> p = Probe('size')
8521  >>> x = Int('x')
8522  >>> g = Goal()
8523  >>> g.add(x > 0)
8524  >>> g.add(x < 10)
8525  >>> p(g)
8526  2.0
8527  >>> g.add(x < 20)
8528  >>> p(g)
8529  3.0
8530  >>> p = Probe('num-consts')
8531  >>> p(g)
8532  1.0
8533  >>> p = Probe('is-propositional')
8534  >>> p(g)
8535  0.0
8536  >>> p = Probe('is-qflia')
8537  >>> p(g)
8538  1.0
8539  """
8540  if z3_debug():
8541  _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8542  goal = _to_goal(goal)
8543  return Z3_probe_apply(self.ctxctx.ref(), self.probeprobe, goal.goal)
8544 
8545 
8546 def is_probe(p):
8547  """Return `True` if `p` is a Z3 probe.
8548 
8549  >>> is_probe(Int('x'))
8550  False
8551  >>> is_probe(Probe('memory'))
8552  True
8553  """
8554  return isinstance(p, Probe)
8555 
8556 
8557 def _to_probe(p, ctx=None):
8558  if is_probe(p):
8559  return p
8560  else:
8561  return Probe(p, ctx)
8562 
8563 
8564 def probes(ctx=None):
8565  """Return a list of all available probes in Z3.
8566 
8567  >>> l = probes()
8568  >>> l.count('memory') == 1
8569  True
8570  """
8571  ctx = _get_ctx(ctx)
8572  return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8573 
8574 
8575 def probe_description(name, ctx=None):
8576  """Return a short description for the probe named `name`.
8577 
8578  >>> d = probe_description('memory')
8579  """
8580  ctx = _get_ctx(ctx)
8581  return Z3_probe_get_descr(ctx.ref(), name)
8582 
8583 
8585  """Display a (tabular) description of all available probes in Z3."""
8586  if in_html_mode():
8587  even = True
8588  print('<table border="1" cellpadding="2" cellspacing="0">')
8589  for p in probes():
8590  if even:
8591  print('<tr style="background-color:#CFCFCF">')
8592  even = False
8593  else:
8594  print("<tr>")
8595  even = True
8596  print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8597  print("</table>")
8598  else:
8599  for p in probes():
8600  print("%s : %s" % (p, probe_description(p)))
8601 
8602 
8603 def _probe_nary(f, args, ctx):
8604  if z3_debug():
8605  _z3_assert(len(args) > 0, "At least one argument expected")
8606  num = len(args)
8607  r = _to_probe(args[0], ctx)
8608  for i in range(num - 1):
8609  r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8610  return r
8611 
8612 
8613 def _probe_and(args, ctx):
8614  return _probe_nary(Z3_probe_and, args, ctx)
8615 
8616 
8617 def _probe_or(args, ctx):
8618  return _probe_nary(Z3_probe_or, args, ctx)
8619 
8620 
8621 def FailIf(p, ctx=None):
8622  """Return a tactic that fails if the probe `p` evaluates to true.
8623  Otherwise, it returns the input goal unmodified.
8624 
8625  In the following example, the tactic applies 'simplify' if and only if there are
8626  more than 2 constraints in the goal.
8627 
8628  >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8629  >>> x, y = Ints('x y')
8630  >>> g = Goal()
8631  >>> g.add(x > 0)
8632  >>> g.add(y > 0)
8633  >>> t(g)
8634  [[x > 0, y > 0]]
8635  >>> g.add(x == y + 1)
8636  >>> t(g)
8637  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8638  """
8639  p = _to_probe(p, ctx)
8640  return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8641 
8642 
8643 def When(p, t, ctx=None):
8644  """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8645  Otherwise, it returns the input goal unmodified.
8646 
8647  >>> t = When(Probe('size') > 2, Tactic('simplify'))
8648  >>> x, y = Ints('x y')
8649  >>> g = Goal()
8650  >>> g.add(x > 0)
8651  >>> g.add(y > 0)
8652  >>> t(g)
8653  [[x > 0, y > 0]]
8654  >>> g.add(x == y + 1)
8655  >>> t(g)
8656  [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8657  """
8658  p = _to_probe(p, ctx)
8659  t = _to_tactic(t, ctx)
8660  return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8661 
8662 
8663 def Cond(p, t1, t2, ctx=None):
8664  """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8665 
8666  >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8667  """
8668  p = _to_probe(p, ctx)
8669  t1 = _to_tactic(t1, ctx)
8670  t2 = _to_tactic(t2, ctx)
8671  return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8672 
8673 
8678 
8679 
8680 def simplify(a, *arguments, **keywords):
8681  """Simplify the expression `a` using the given options.
8682 
8683  This function has many options. Use `help_simplify` to obtain the complete list.
8684 
8685  >>> x = Int('x')
8686  >>> y = Int('y')
8687  >>> simplify(x + 1 + y + x + 1)
8688  2 + 2*x + y
8689  >>> simplify((x + 1)*(y + 1), som=True)
8690  1 + x + y + x*y
8691  >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8692  And(Not(x == y), Not(x == 1), Not(y == 1))
8693  >>> simplify(And(x == 0, y == 1), elim_and=True)
8694  Not(Or(Not(x == 0), Not(y == 1)))
8695  """
8696  if z3_debug():
8697  _z3_assert(is_expr(a), "Z3 expression expected")
8698  if len(arguments) > 0 or len(keywords) > 0:
8699  p = args2params(arguments, keywords, a.ctx)
8700  return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8701  else:
8702  return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8703 
8704 
8706  """Return a string describing all options available for Z3 `simplify` procedure."""
8707  print(Z3_simplify_get_help(main_ctx().ref()))
8708 
8709 
8711  """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8713 
8714 
8715 def substitute(t, *m):
8716  """Apply substitution m on t, m is a list of pairs of the form (from, to).
8717  Every occurrence in t of from is replaced with to.
8718 
8719  >>> x = Int('x')
8720  >>> y = Int('y')
8721  >>> substitute(x + 1, (x, y + 1))
8722  y + 1 + 1
8723  >>> f = Function('f', IntSort(), IntSort())
8724  >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8725  1 + 1
8726  """
8727  if isinstance(m, tuple):
8728  m1 = _get_args(m)
8729  if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8730  m = m1
8731  if z3_debug():
8732  _z3_assert(is_expr(t), "Z3 expression expected")
8733  _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(
8734  p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
8735  num = len(m)
8736  _from = (Ast * num)()
8737  _to = (Ast * num)()
8738  for i in range(num):
8739  _from[i] = m[i][0].as_ast()
8740  _to[i] = m[i][1].as_ast()
8741  return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8742 
8743 
8744 def substitute_vars(t, *m):
8745  """Substitute the free variables in t with the expression in m.
8746 
8747  >>> v0 = Var(0, IntSort())
8748  >>> v1 = Var(1, IntSort())
8749  >>> x = Int('x')
8750  >>> f = Function('f', IntSort(), IntSort(), IntSort())
8751  >>> # replace v0 with x+1 and v1 with x
8752  >>> substitute_vars(f(v0, v1), x + 1, x)
8753  f(x + 1, x)
8754  """
8755  if z3_debug():
8756  _z3_assert(is_expr(t), "Z3 expression expected")
8757  _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8758  num = len(m)
8759  _to = (Ast * num)()
8760  for i in range(num):
8761  _to[i] = m[i].as_ast()
8762  return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8763 
8764 
8765 def Sum(*args):
8766  """Create the sum of the Z3 expressions.
8767 
8768  >>> a, b, c = Ints('a b c')
8769  >>> Sum(a, b, c)
8770  a + b + c
8771  >>> Sum([a, b, c])
8772  a + b + c
8773  >>> A = IntVector('a', 5)
8774  >>> Sum(A)
8775  a__0 + a__1 + a__2 + a__3 + a__4
8776  """
8777  args = _get_args(args)
8778  if len(args) == 0:
8779  return 0
8780  ctx = _ctx_from_ast_arg_list(args)
8781  if ctx is None:
8782  return _reduce(lambda a, b: a + b, args, 0)
8783  args = _coerce_expr_list(args, ctx)
8784  if is_bv(args[0]):
8785  return _reduce(lambda a, b: a + b, args, 0)
8786  else:
8787  _args, sz = _to_ast_array(args)
8788  return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8789 
8790 
8791 def Product(*args):
8792  """Create the product of the Z3 expressions.
8793 
8794  >>> a, b, c = Ints('a b c')
8795  >>> Product(a, b, c)
8796  a*b*c
8797  >>> Product([a, b, c])
8798  a*b*c
8799  >>> A = IntVector('a', 5)
8800  >>> Product(A)
8801  a__0*a__1*a__2*a__3*a__4
8802  """
8803  args = _get_args(args)
8804  if len(args) == 0:
8805  return 1
8806  ctx = _ctx_from_ast_arg_list(args)
8807  if ctx is None:
8808  return _reduce(lambda a, b: a * b, args, 1)
8809  args = _coerce_expr_list(args, ctx)
8810  if is_bv(args[0]):
8811  return _reduce(lambda a, b: a * b, args, 1)
8812  else:
8813  _args, sz = _to_ast_array(args)
8814  return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8815 
8816 def Abs(arg):
8817  """Create the absolute value of an arithmetic expression"""
8818  return If(arg > 0, arg, -arg)
8819 
8820 
8821 def AtMost(*args):
8822  """Create an at-most Pseudo-Boolean k constraint.
8823 
8824  >>> a, b, c = Bools('a b c')
8825  >>> f = AtMost(a, b, c, 2)
8826  """
8827  args = _get_args(args)
8828  if z3_debug():
8829  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8830  ctx = _ctx_from_ast_arg_list(args)
8831  if z3_debug():
8832  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8833  args1 = _coerce_expr_list(args[:-1], ctx)
8834  k = args[-1]
8835  _args, sz = _to_ast_array(args1)
8836  return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8837 
8838 
8839 def AtLeast(*args):
8840  """Create an at-most Pseudo-Boolean k constraint.
8841 
8842  >>> a, b, c = Bools('a b c')
8843  >>> f = AtLeast(a, b, c, 2)
8844  """
8845  args = _get_args(args)
8846  if z3_debug():
8847  _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8848  ctx = _ctx_from_ast_arg_list(args)
8849  if z3_debug():
8850  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8851  args1 = _coerce_expr_list(args[:-1], ctx)
8852  k = args[-1]
8853  _args, sz = _to_ast_array(args1)
8854  return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8855 
8856 
8857 def _reorder_pb_arg(arg):
8858  a, b = arg
8859  if not _is_int(b) and _is_int(a):
8860  return b, a
8861  return arg
8862 
8863 
8864 def _pb_args_coeffs(args, default_ctx=None):
8865  args = _get_args_ast_list(args)
8866  if len(args) == 0:
8867  return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8868  args = [_reorder_pb_arg(arg) for arg in args]
8869  args, coeffs = zip(*args)
8870  if z3_debug():
8871  _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8872  ctx = _ctx_from_ast_arg_list(args)
8873  if z3_debug():
8874  _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8875  args = _coerce_expr_list(args, ctx)
8876  _args, sz = _to_ast_array(args)
8877  _coeffs = (ctypes.c_int * len(coeffs))()
8878  for i in range(len(coeffs)):
8879  _z3_check_cint_overflow(coeffs[i], "coefficient")
8880  _coeffs[i] = coeffs[i]
8881  return ctx, sz, _args, _coeffs, args
8882 
8883 
8884 def PbLe(args, k):
8885  """Create a Pseudo-Boolean inequality k constraint.
8886 
8887  >>> a, b, c = Bools('a b c')
8888  >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8889  """
8890  _z3_check_cint_overflow(k, "k")
8891  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8892  return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8893 
8894 
8895 def PbGe(args, k):
8896  """Create a Pseudo-Boolean inequality k constraint.
8897 
8898  >>> a, b, c = Bools('a b c')
8899  >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8900  """
8901  _z3_check_cint_overflow(k, "k")
8902  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8903  return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8904 
8905 
8906 def PbEq(args, k, ctx=None):
8907  """Create a Pseudo-Boolean inequality k constraint.
8908 
8909  >>> a, b, c = Bools('a b c')
8910  >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8911  """
8912  _z3_check_cint_overflow(k, "k")
8913  ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8914  return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8915 
8916 
8917 def solve(*args, **keywords):
8918  """Solve the constraints `*args`.
8919 
8920  This is a simple function for creating demonstrations. It creates a solver,
8921  configure it using the options in `keywords`, adds the constraints
8922  in `args`, and invokes check.
8923 
8924  >>> a = Int('a')
8925  >>> solve(a > 0, a < 2)
8926  [a = 1]
8927  """
8928  show = keywords.pop("show", False)
8929  s = Solver()
8930  s.set(**keywords)
8931  s.add(*args)
8932  if show:
8933  print(s)
8934  r = s.check()
8935  if r == unsat:
8936  print("no solution")
8937  elif r == unknown:
8938  print("failed to solve")
8939  try:
8940  print(s.model())
8941  except Z3Exception:
8942  return
8943  else:
8944  print(s.model())
8945 
8946 
8947 def solve_using(s, *args, **keywords):
8948  """Solve the constraints `*args` using solver `s`.
8949 
8950  This is a simple function for creating demonstrations. It is similar to `solve`,
8951  but it uses the given solver `s`.
8952  It configures solver `s` using the options in `keywords`, adds the constraints
8953  in `args`, and invokes check.
8954  """
8955  show = keywords.pop("show", False)
8956  if z3_debug():
8957  _z3_assert(isinstance(s, Solver), "Solver object expected")
8958  s.set(**keywords)
8959  s.add(*args)
8960  if show:
8961  print("Problem:")
8962  print(s)
8963  r = s.check()
8964  if r == unsat:
8965  print("no solution")
8966  elif r == unknown:
8967  print("failed to solve")
8968  try:
8969  print(s.model())
8970  except Z3Exception:
8971  return
8972  else:
8973  if show:
8974  print("Solution:")
8975  print(s.model())
8976 
8977 
8978 def prove(claim, show=False, **keywords):
8979  """Try to prove the given claim.
8980 
8981  This is a simple function for creating demonstrations. It tries to prove
8982  `claim` by showing the negation is unsatisfiable.
8983 
8984  >>> p, q = Bools('p q')
8985  >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8986  proved
8987  """
8988  if z3_debug():
8989  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8990  s = Solver()
8991  s.set(**keywords)
8992  s.add(Not(claim))
8993  if show:
8994  print(s)
8995  r = s.check()
8996  if r == unsat:
8997  print("proved")
8998  elif r == unknown:
8999  print("failed to prove")
9000  print(s.model())
9001  else:
9002  print("counterexample")
9003  print(s.model())
9004 
9005 
9006 def _solve_html(*args, **keywords):
9007  """Version of function `solve` that renders HTML output."""
9008  show = keywords.pop("show", False)
9009  s = Solver()
9010  s.set(**keywords)
9011  s.add(*args)
9012  if show:
9013  print("<b>Problem:</b>")
9014  print(s)
9015  r = s.check()
9016  if r == unsat:
9017  print("<b>no solution</b>")
9018  elif r == unknown:
9019  print("<b>failed to solve</b>")
9020  try:
9021  print(s.model())
9022  except Z3Exception:
9023  return
9024  else:
9025  if show:
9026  print("<b>Solution:</b>")
9027  print(s.model())
9028 
9029 
9030 def _solve_using_html(s, *args, **keywords):
9031  """Version of function `solve_using` that renders HTML."""
9032  show = keywords.pop("show", False)
9033  if z3_debug():
9034  _z3_assert(isinstance(s, Solver), "Solver object expected")
9035  s.set(**keywords)
9036  s.add(*args)
9037  if show:
9038  print("<b>Problem:</b>")
9039  print(s)
9040  r = s.check()
9041  if r == unsat:
9042  print("<b>no solution</b>")
9043  elif r == unknown:
9044  print("<b>failed to solve</b>")
9045  try:
9046  print(s.model())
9047  except Z3Exception:
9048  return
9049  else:
9050  if show:
9051  print("<b>Solution:</b>")
9052  print(s.model())
9053 
9054 
9055 def _prove_html(claim, show=False, **keywords):
9056  """Version of function `prove` that renders HTML."""
9057  if z3_debug():
9058  _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9059  s = Solver()
9060  s.set(**keywords)
9061  s.add(Not(claim))
9062  if show:
9063  print(s)
9064  r = s.check()
9065  if r == unsat:
9066  print("<b>proved</b>")
9067  elif r == unknown:
9068  print("<b>failed to prove</b>")
9069  print(s.model())
9070  else:
9071  print("<b>counterexample</b>")
9072  print(s.model())
9073 
9074 
9075 def _dict2sarray(sorts, ctx):
9076  sz = len(sorts)
9077  _names = (Symbol * sz)()
9078  _sorts = (Sort * sz)()
9079  i = 0
9080  for k in sorts:
9081  v = sorts[k]
9082  if z3_debug():
9083  _z3_assert(isinstance(k, str), "String expected")
9084  _z3_assert(is_sort(v), "Z3 sort expected")
9085  _names[i] = to_symbol(k, ctx)
9086  _sorts[i] = v.ast
9087  i = i + 1
9088  return sz, _names, _sorts
9089 
9090 
9091 def _dict2darray(decls, ctx):
9092  sz = len(decls)
9093  _names = (Symbol * sz)()
9094  _decls = (FuncDecl * sz)()
9095  i = 0
9096  for k in decls:
9097  v = decls[k]
9098  if z3_debug():
9099  _z3_assert(isinstance(k, str), "String expected")
9100  _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9101  _names[i] = to_symbol(k, ctx)
9102  if is_const(v):
9103  _decls[i] = v.decl().ast
9104  else:
9105  _decls[i] = v.ast
9106  i = i + 1
9107  return sz, _names, _decls
9108 
9109 
9110 def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9111  """Parse a string in SMT 2.0 format using the given sorts and decls.
9112 
9113  The arguments sorts and decls are Python dictionaries used to initialize
9114  the symbol table used for the SMT 2.0 parser.
9115 
9116  >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9117  [x > 0, x < 10]
9118  >>> x, y = Ints('x y')
9119  >>> f = Function('f', IntSort(), IntSort())
9120  >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9121  [x + f(y) > 0]
9122  >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9123  [a > 0]
9124  """
9125  ctx = _get_ctx(ctx)
9126  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9127  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9128  return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9129 
9130 
9131 def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9132  """Parse a file in SMT 2.0 format using the given sorts and decls.
9133 
9134  This function is similar to parse_smt2_string().
9135  """
9136  ctx = _get_ctx(ctx)
9137  ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9138  dsz, dnames, ddecls = _dict2darray(decls, ctx)
9139  return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9140 
9141 
9142 
9147 
9148 
9149 # Global default rounding mode
9150 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
9151 _dflt_fpsort_ebits = 11
9152 _dflt_fpsort_sbits = 53
9153 
9154 
9156  """Retrieves the global default rounding mode."""
9157  global _dflt_rounding_mode
9158  if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9159  return RTZ(ctx)
9160  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9161  return RTN(ctx)
9162  elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9163  return RTP(ctx)
9164  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9165  return RNE(ctx)
9166  elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9167  return RNA(ctx)
9168 
9169 
9170 _ROUNDING_MODES = frozenset({
9171  Z3_OP_FPA_RM_TOWARD_ZERO,
9172  Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9173  Z3_OP_FPA_RM_TOWARD_POSITIVE,
9174  Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9175  Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9176 })
9177 
9178 
9179 def set_default_rounding_mode(rm, ctx=None):
9180  global _dflt_rounding_mode
9181  if is_fprm_value(rm):
9182  _dflt_rounding_mode = rm.decl().kind()
9183  else:
9184  _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9185  _dflt_rounding_mode = rm
9186 
9187 
9188 def get_default_fp_sort(ctx=None):
9189  return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9190 
9191 
9192 def set_default_fp_sort(ebits, sbits, ctx=None):
9193  global _dflt_fpsort_ebits
9194  global _dflt_fpsort_sbits
9195  _dflt_fpsort_ebits = ebits
9196  _dflt_fpsort_sbits = sbits
9197 
9198 
9199 def _dflt_rm(ctx=None):
9200  return get_default_rounding_mode(ctx)
9201 
9202 
9203 def _dflt_fps(ctx=None):
9204  return get_default_fp_sort(ctx)
9205 
9206 
9207 def _coerce_fp_expr_list(alist, ctx):
9208  first_fp_sort = None
9209  for a in alist:
9210  if is_fp(a):
9211  if first_fp_sort is None:
9212  first_fp_sort = a.sort()
9213  elif first_fp_sort == a.sort():
9214  pass # OK, same as before
9215  else:
9216  # we saw at least 2 different float sorts; something will
9217  # throw a sort mismatch later, for now assume None.
9218  first_fp_sort = None
9219  break
9220 
9221  r = []
9222  for i in range(len(alist)):
9223  a = alist[i]
9224  is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9225  if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9226  r.append(FPVal(a, None, first_fp_sort, ctx))
9227  else:
9228  r.append(a)
9229  return _coerce_expr_list(r, ctx)
9230 
9231 
9232 # FP Sorts
9233 
9235  """Floating-point sort."""
9236 
9237  def ebits(self):
9238  """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9239  >>> b = FPSort(8, 24)
9240  >>> b.ebits()
9241  8
9242  """
9243  return int(Z3_fpa_get_ebits(self.ctx_refctx_ref(), self.astast))
9244 
9245  def sbits(self):
9246  """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9247  >>> b = FPSort(8, 24)
9248  >>> b.sbits()
9249  24
9250  """
9251  return int(Z3_fpa_get_sbits(self.ctx_refctx_ref(), self.astast))
9252 
9253  def cast(self, val):
9254  """Try to cast `val` as a floating-point expression.
9255  >>> b = FPSort(8, 24)
9256  >>> b.cast(1.0)
9257  1
9258  >>> b.cast(1.0).sexpr()
9259  '(fp #b0 #x7f #b00000000000000000000000)'
9260  """
9261  if is_expr(val):
9262  if z3_debug():
9263  _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
9264  return val
9265  else:
9266  return FPVal(val, None, self, self.ctxctxctx)
9267 
9268 
9269 def Float16(ctx=None):
9270  """Floating-point 16-bit (half) sort."""
9271  ctx = _get_ctx(ctx)
9272  return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9273 
9274 
9275 def FloatHalf(ctx=None):
9276  """Floating-point 16-bit (half) sort."""
9277  ctx = _get_ctx(ctx)
9278  return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9279 
9280 
9281 def Float32(ctx=None):
9282  """Floating-point 32-bit (single) sort."""
9283  ctx = _get_ctx(ctx)
9284  return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9285 
9286 
9287 def FloatSingle(ctx=None):
9288  """Floating-point 32-bit (single) sort."""
9289  ctx = _get_ctx(ctx)
9290  return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9291 
9292 
9293 def Float64(ctx=None):
9294  """Floating-point 64-bit (double) sort."""
9295  ctx = _get_ctx(ctx)
9296  return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9297 
9298 
9299 def FloatDouble(ctx=None):
9300  """Floating-point 64-bit (double) sort."""
9301  ctx = _get_ctx(ctx)
9302  return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9303 
9304 
9305 def Float128(ctx=None):
9306  """Floating-point 128-bit (quadruple) sort."""
9307  ctx = _get_ctx(ctx)
9308  return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9309 
9310 
9311 def FloatQuadruple(ctx=None):
9312  """Floating-point 128-bit (quadruple) sort."""
9313  ctx = _get_ctx(ctx)
9314  return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9315 
9316 
9318  """"Floating-point rounding mode sort."""
9319 
9320 
9321 def is_fp_sort(s):
9322  """Return True if `s` is a Z3 floating-point sort.
9323 
9324  >>> is_fp_sort(FPSort(8, 24))
9325  True
9326  >>> is_fp_sort(IntSort())
9327  False
9328  """
9329  return isinstance(s, FPSortRef)
9330 
9331 
9333  """Return True if `s` is a Z3 floating-point rounding mode sort.
9334 
9335  >>> is_fprm_sort(FPSort(8, 24))
9336  False
9337  >>> is_fprm_sort(RNE().sort())
9338  True
9339  """
9340  return isinstance(s, FPRMSortRef)
9341 
9342 # FP Expressions
9343 
9344 
9346  """Floating-point expressions."""
9347 
9348  def sort(self):
9349  """Return the sort of the floating-point expression `self`.
9350 
9351  >>> x = FP('1.0', FPSort(8, 24))
9352  >>> x.sort()
9353  FPSort(8, 24)
9354  >>> x.sort() == FPSort(8, 24)
9355  True
9356  """
9357  return FPSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
9358 
9359  def ebits(self):
9360  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9361  >>> b = FPSort(8, 24)
9362  >>> b.ebits()
9363  8
9364  """
9365  return self.sortsortsort().ebits()
9366 
9367  def sbits(self):
9368  """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9369  >>> b = FPSort(8, 24)
9370  >>> b.sbits()
9371  24
9372  """
9373  return self.sortsortsort().sbits()
9374 
9375  def as_string(self):
9376  """Return a Z3 floating point expression as a Python string."""
9377  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
9378 
9379  def __le__(self, other):
9380  return fpLEQ(self, other, self.ctxctx)
9381 
9382  def __lt__(self, other):
9383  return fpLT(self, other, self.ctxctx)
9384 
9385  def __ge__(self, other):
9386  return fpGEQ(self, other, self.ctxctx)
9387 
9388  def __gt__(self, other):
9389  return fpGT(self, other, self.ctxctx)
9390 
9391  def __add__(self, other):
9392  """Create the Z3 expression `self + other`.
9393 
9394  >>> x = FP('x', FPSort(8, 24))
9395  >>> y = FP('y', FPSort(8, 24))
9396  >>> x + y
9397  x + y
9398  >>> (x + y).sort()
9399  FPSort(8, 24)
9400  """
9401  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9402  return fpAdd(_dflt_rm(), a, b, self.ctxctx)
9403 
9404  def __radd__(self, other):
9405  """Create the Z3 expression `other + self`.
9406 
9407  >>> x = FP('x', FPSort(8, 24))
9408  >>> 10 + x
9409  1.25*(2**3) + x
9410  """
9411  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9412  return fpAdd(_dflt_rm(), a, b, self.ctxctx)
9413 
9414  def __sub__(self, other):
9415  """Create the Z3 expression `self - other`.
9416 
9417  >>> x = FP('x', FPSort(8, 24))
9418  >>> y = FP('y', FPSort(8, 24))
9419  >>> x - y
9420  x - y
9421  >>> (x - y).sort()
9422  FPSort(8, 24)
9423  """
9424  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9425  return fpSub(_dflt_rm(), a, b, self.ctxctx)
9426 
9427  def __rsub__(self, other):
9428  """Create the Z3 expression `other - self`.
9429 
9430  >>> x = FP('x', FPSort(8, 24))
9431  >>> 10 - x
9432  1.25*(2**3) - x
9433  """
9434  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9435  return fpSub(_dflt_rm(), a, b, self.ctxctx)
9436 
9437  def __mul__(self, other):
9438  """Create the Z3 expression `self * other`.
9439 
9440  >>> x = FP('x', FPSort(8, 24))
9441  >>> y = FP('y', FPSort(8, 24))
9442  >>> x * y
9443  x * y
9444  >>> (x * y).sort()
9445  FPSort(8, 24)
9446  >>> 10 * y
9447  1.25*(2**3) * y
9448  """
9449  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9450  return fpMul(_dflt_rm(), a, b, self.ctxctx)
9451 
9452  def __rmul__(self, other):
9453  """Create the Z3 expression `other * self`.
9454 
9455  >>> x = FP('x', FPSort(8, 24))
9456  >>> y = FP('y', FPSort(8, 24))
9457  >>> x * y
9458  x * y
9459  >>> x * 10
9460  x * 1.25*(2**3)
9461  """
9462  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9463  return fpMul(_dflt_rm(), a, b, self.ctxctx)
9464 
9465  def __pos__(self):
9466  """Create the Z3 expression `+self`."""
9467  return self
9468 
9469  def __neg__(self):
9470  """Create the Z3 expression `-self`.
9471 
9472  >>> x = FP('x', Float32())
9473  >>> -x
9474  -x
9475  """
9476  return fpNeg(self)
9477 
9478  def __div__(self, other):
9479  """Create the Z3 expression `self / other`.
9480 
9481  >>> x = FP('x', FPSort(8, 24))
9482  >>> y = FP('y', FPSort(8, 24))
9483  >>> x / y
9484  x / y
9485  >>> (x / y).sort()
9486  FPSort(8, 24)
9487  >>> 10 / y
9488  1.25*(2**3) / y
9489  """
9490  [a, b] = _coerce_fp_expr_list([self, other], self.ctxctx)
9491  return fpDiv(_dflt_rm(), a, b, self.ctxctx)
9492 
9493  def __rdiv__(self, other):
9494  """Create the Z3 expression `other / self`.
9495 
9496  >>> x = FP('x', FPSort(8, 24))
9497  >>> y = FP('y', FPSort(8, 24))
9498  >>> x / y
9499  x / y
9500  >>> x / 10
9501  x / 1.25*(2**3)
9502  """
9503  [a, b] = _coerce_fp_expr_list([other, self], self.ctxctx)
9504  return fpDiv(_dflt_rm(), a, b, self.ctxctx)
9505 
9506  def __truediv__(self, other):
9507  """Create the Z3 expression division `self / other`."""
9508  return self.__div____div__(other)
9509 
9510  def __rtruediv__(self, other):
9511  """Create the Z3 expression division `other / self`."""
9512  return self.__rdiv____rdiv__(other)
9513 
9514  def __mod__(self, other):
9515  """Create the Z3 expression mod `self % other`."""
9516  return fpRem(self, other)
9517 
9518  def __rmod__(self, other):
9519  """Create the Z3 expression mod `other % self`."""
9520  return fpRem(other, self)
9521 
9522 
9524  """Floating-point rounding mode expressions"""
9525 
9526  def as_string(self):
9527  """Return a Z3 floating point expression as a Python string."""
9528  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
9529 
9530 
9532  ctx = _get_ctx(ctx)
9533  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9534 
9535 
9536 def RNE(ctx=None):
9537  ctx = _get_ctx(ctx)
9538  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9539 
9540 
9542  ctx = _get_ctx(ctx)
9543  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9544 
9545 
9546 def RNA(ctx=None):
9547  ctx = _get_ctx(ctx)
9548  return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9549 
9550 
9551 def RoundTowardPositive(ctx=None):
9552  ctx = _get_ctx(ctx)
9553  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9554 
9555 
9556 def RTP(ctx=None):
9557  ctx = _get_ctx(ctx)
9558  return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9559 
9560 
9561 def RoundTowardNegative(ctx=None):
9562  ctx = _get_ctx(ctx)
9563  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9564 
9565 
9566 def RTN(ctx=None):
9567  ctx = _get_ctx(ctx)
9568  return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9569 
9570 
9571 def RoundTowardZero(ctx=None):
9572  ctx = _get_ctx(ctx)
9573  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9574 
9575 
9576 def RTZ(ctx=None):
9577  ctx = _get_ctx(ctx)
9578  return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9579 
9580 
9581 def is_fprm(a):
9582  """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9583 
9584  >>> rm = RNE()
9585  >>> is_fprm(rm)
9586  True
9587  >>> rm = 1.0
9588  >>> is_fprm(rm)
9589  False
9590  """
9591  return isinstance(a, FPRMRef)
9592 
9593 
9595  """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9596  return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9597 
9598 # FP Numerals
9599 
9600 
9602  """The sign of the numeral.
9603 
9604  >>> x = FPVal(+1.0, FPSort(8, 24))
9605  >>> x.sign()
9606  False
9607  >>> x = FPVal(-1.0, FPSort(8, 24))
9608  >>> x.sign()
9609  True
9610  """
9611 
9612  def sign(self):
9613  num = (ctypes.c_int)()
9614  nsign = Z3_fpa_get_numeral_sign(self.ctxctx.ref(), self.as_astas_astas_ast(), byref(num))
9615  if nsign is False:
9616  raise Z3Exception("error retrieving the sign of a numeral.")
9617  return num.value != 0
9618 
9619  """The sign of a floating-point numeral as a bit-vector expression.
9620 
9621  Remark: NaN's are invalid arguments.
9622  """
9623 
9624  def sign_as_bv(self):
9625  return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctxctx.ref(), self.as_astas_astas_ast()), self.ctxctx)
9626 
9627  """The significand of the numeral.
9628 
9629  >>> x = FPVal(2.5, FPSort(8, 24))
9630  >>> x.significand()
9631  1.25
9632  """
9633 
9634  def significand(self):
9635  return Z3_fpa_get_numeral_significand_string(self.ctxctx.ref(), self.as_astas_astas_ast())
9636 
9637  """The significand of the numeral as a long.
9638 
9639  >>> x = FPVal(2.5, FPSort(8, 24))
9640  >>> x.significand_as_long()
9641  1.25
9642  """
9643 
9645  ptr = (ctypes.c_ulonglong * 1)()
9646  if not Z3_fpa_get_numeral_significand_uint64(self.ctxctx.ref(), self.as_astas_astas_ast(), ptr):
9647  raise Z3Exception("error retrieving the significand of a numeral.")
9648  return ptr[0]
9649 
9650  """The significand of the numeral as a bit-vector expression.
9651 
9652  Remark: NaN are invalid arguments.
9653  """
9654 
9656  return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctxctx.ref(), self.as_astas_astas_ast()), self.ctxctx)
9657 
9658  """The exponent of the numeral.
9659 
9660  >>> x = FPVal(2.5, FPSort(8, 24))
9661  >>> x.exponent()
9662  1
9663  """
9664 
9665  def exponent(self, biased=True):
9666  return Z3_fpa_get_numeral_exponent_string(self.ctxctx.ref(), self.as_astas_astas_ast(), biased)
9667 
9668  """The exponent of the numeral as a long.
9669 
9670  >>> x = FPVal(2.5, FPSort(8, 24))
9671  >>> x.exponent_as_long()
9672  1
9673  """
9674 
9675  def exponent_as_long(self, biased=True):
9676  ptr = (ctypes.c_longlong * 1)()
9677  if not Z3_fpa_get_numeral_exponent_int64(self.ctxctx.ref(), self.as_astas_astas_ast(), ptr, biased):
9678  raise Z3Exception("error retrieving the exponent of a numeral.")
9679  return ptr[0]
9680 
9681  """The exponent of the numeral as a bit-vector expression.
9682 
9683  Remark: NaNs are invalid arguments.
9684  """
9685 
9686  def exponent_as_bv(self, biased=True):
9687  return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctxctx.ref(), self.as_astas_astas_ast(), biased), self.ctxctx)
9688 
9689  """Indicates whether the numeral is a NaN."""
9690 
9691  def isNaN(self):
9692  return Z3_fpa_is_numeral_nan(self.ctxctx.ref(), self.as_astas_astas_ast())
9693 
9694  """Indicates whether the numeral is +oo or -oo."""
9695 
9696  def isInf(self):
9697  return Z3_fpa_is_numeral_inf(self.ctxctx.ref(), self.as_astas_astas_ast())
9698 
9699  """Indicates whether the numeral is +zero or -zero."""
9700 
9701  def isZero(self):
9702  return Z3_fpa_is_numeral_zero(self.ctxctx.ref(), self.as_astas_astas_ast())
9703 
9704  """Indicates whether the numeral is normal."""
9705 
9706  def isNormal(self):
9707  return Z3_fpa_is_numeral_normal(self.ctxctx.ref(), self.as_astas_astas_ast())
9708 
9709  """Indicates whether the numeral is subnormal."""
9710 
9711  def isSubnormal(self):
9712  return Z3_fpa_is_numeral_subnormal(self.ctxctx.ref(), self.as_astas_astas_ast())
9713 
9714  """Indicates whether the numeral is positive."""
9715 
9716  def isPositive(self):
9717  return Z3_fpa_is_numeral_positive(self.ctxctx.ref(), self.as_astas_astas_ast())
9718 
9719  """Indicates whether the numeral is negative."""
9720 
9721  def isNegative(self):
9722  return Z3_fpa_is_numeral_negative(self.ctxctx.ref(), self.as_astas_astas_ast())
9723 
9724  """
9725  The string representation of the numeral.
9726 
9727  >>> x = FPVal(20, FPSort(8, 24))
9728  >>> x.as_string()
9729  1.25*(2**4)
9730  """
9731 
9732  def as_string(self):
9733  s = Z3_get_numeral_string(self.ctxctx.ref(), self.as_astas_astas_ast())
9734  return ("FPVal(%s, %s)" % (s, self.sortsortsort()))
9735 
9736 
9737 def is_fp(a):
9738  """Return `True` if `a` is a Z3 floating-point expression.
9739 
9740  >>> b = FP('b', FPSort(8, 24))
9741  >>> is_fp(b)
9742  True
9743  >>> is_fp(b + 1.0)
9744  True
9745  >>> is_fp(Int('x'))
9746  False
9747  """
9748  return isinstance(a, FPRef)
9749 
9750 
9752  """Return `True` if `a` is a Z3 floating-point numeral value.
9753 
9754  >>> b = FP('b', FPSort(8, 24))
9755  >>> is_fp_value(b)
9756  False
9757  >>> b = FPVal(1.0, FPSort(8, 24))
9758  >>> b
9759  1
9760  >>> is_fp_value(b)
9761  True
9762  """
9763  return is_fp(a) and _is_numeral(a.ctx, a.ast)
9764 
9765 
9766 def FPSort(ebits, sbits, ctx=None):
9767  """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9768 
9769  >>> Single = FPSort(8, 24)
9770  >>> Double = FPSort(11, 53)
9771  >>> Single
9772  FPSort(8, 24)
9773  >>> x = Const('x', Single)
9774  >>> eq(x, FP('x', FPSort(8, 24)))
9775  True
9776  """
9777  ctx = _get_ctx(ctx)
9778  return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9779 
9780 
9781 def _to_float_str(val, exp=0):
9782  if isinstance(val, float):
9783  if math.isnan(val):
9784  res = "NaN"
9785  elif val == 0.0:
9786  sone = math.copysign(1.0, val)
9787  if sone < 0.0:
9788  return "-0.0"
9789  else:
9790  return "+0.0"
9791  elif val == float("+inf"):
9792  res = "+oo"
9793  elif val == float("-inf"):
9794  res = "-oo"
9795  else:
9796  v = val.as_integer_ratio()
9797  num = v[0]
9798  den = v[1]
9799  rvs = str(num) + "/" + str(den)
9800  res = rvs + "p" + _to_int_str(exp)
9801  elif isinstance(val, bool):
9802  if val:
9803  res = "1.0"
9804  else:
9805  res = "0.0"
9806  elif _is_int(val):
9807  res = str(val)
9808  elif isinstance(val, str):
9809  inx = val.find("*(2**")
9810  if inx == -1:
9811  res = val
9812  elif val[-1] == ")":
9813  res = val[0:inx]
9814  exp = str(int(val[inx + 5:-1]) + int(exp))
9815  else:
9816  _z3_assert(False, "String does not have floating-point numeral form.")
9817  elif z3_debug():
9818  _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9819  if exp == 0:
9820  return res
9821  else:
9822  return res + "p" + exp
9823 
9824 
9825 def fpNaN(s):
9826  """Create a Z3 floating-point NaN term.
9827 
9828  >>> s = FPSort(8, 24)
9829  >>> set_fpa_pretty(True)
9830  >>> fpNaN(s)
9831  NaN
9832  >>> pb = get_fpa_pretty()
9833  >>> set_fpa_pretty(False)
9834  >>> fpNaN(s)
9835  fpNaN(FPSort(8, 24))
9836  >>> set_fpa_pretty(pb)
9837  """
9838  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9839  return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9840 
9841 
9843  """Create a Z3 floating-point +oo term.
9844 
9845  >>> s = FPSort(8, 24)
9846  >>> pb = get_fpa_pretty()
9847  >>> set_fpa_pretty(True)
9848  >>> fpPlusInfinity(s)
9849  +oo
9850  >>> set_fpa_pretty(False)
9851  >>> fpPlusInfinity(s)
9852  fpPlusInfinity(FPSort(8, 24))
9853  >>> set_fpa_pretty(pb)
9854  """
9855  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9856  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9857 
9858 
9860  """Create a Z3 floating-point -oo term."""
9861  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9862  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9863 
9864 
9865 def fpInfinity(s, negative):
9866  """Create a Z3 floating-point +oo or -oo term."""
9867  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9868  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9869  return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9870 
9871 
9872 def fpPlusZero(s):
9873  """Create a Z3 floating-point +0.0 term."""
9874  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9875  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9876 
9877 
9879  """Create a Z3 floating-point -0.0 term."""
9880  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9881  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9882 
9883 
9884 def fpZero(s, negative):
9885  """Create a Z3 floating-point +0.0 or -0.0 term."""
9886  _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9887  _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9888  return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9889 
9890 
9891 def FPVal(sig, exp=None, fps=None, ctx=None):
9892  """Return a floating-point value of value `val` and sort `fps`.
9893  If `ctx=None`, then the global context is used.
9894 
9895  >>> v = FPVal(20.0, FPSort(8, 24))
9896  >>> v
9897  1.25*(2**4)
9898  >>> print("0x%.8x" % v.exponent_as_long(False))
9899  0x00000004
9900  >>> v = FPVal(2.25, FPSort(8, 24))
9901  >>> v
9902  1.125*(2**1)
9903  >>> v = FPVal(-2.25, FPSort(8, 24))
9904  >>> v
9905  -1.125*(2**1)
9906  >>> FPVal(-0.0, FPSort(8, 24))
9907  -0.0
9908  >>> FPVal(0.0, FPSort(8, 24))
9909  +0.0
9910  >>> FPVal(+0.0, FPSort(8, 24))
9911  +0.0
9912  """
9913  ctx = _get_ctx(ctx)
9914  if is_fp_sort(exp):
9915  fps = exp
9916  exp = None
9917  elif fps is None:
9918  fps = _dflt_fps(ctx)
9919  _z3_assert(is_fp_sort(fps), "sort mismatch")
9920  if exp is None:
9921  exp = 0
9922  val = _to_float_str(sig)
9923  if val == "NaN" or val == "nan":
9924  return fpNaN(fps)
9925  elif val == "-0.0":
9926  return fpMinusZero(fps)
9927  elif val == "0.0" or val == "+0.0":
9928  return fpPlusZero(fps)
9929  elif val == "+oo" or val == "+inf" or val == "+Inf":
9930  return fpPlusInfinity(fps)
9931  elif val == "-oo" or val == "-inf" or val == "-Inf":
9932  return fpMinusInfinity(fps)
9933  else:
9934  return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9935 
9936 
9937 def FP(name, fpsort, ctx=None):
9938  """Return a floating-point constant named `name`.
9939  `fpsort` is the floating-point sort.
9940  If `ctx=None`, then the global context is used.
9941 
9942  >>> x = FP('x', FPSort(8, 24))
9943  >>> is_fp(x)
9944  True
9945  >>> x.ebits()
9946  8
9947  >>> x.sort()
9948  FPSort(8, 24)
9949  >>> word = FPSort(8, 24)
9950  >>> x2 = FP('x', word)
9951  >>> eq(x, x2)
9952  True
9953  """
9954  if isinstance(fpsort, FPSortRef) and ctx is None:
9955  ctx = fpsort.ctx
9956  else:
9957  ctx = _get_ctx(ctx)
9958  return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9959 
9960 
9961 def FPs(names, fpsort, ctx=None):
9962  """Return an array of floating-point constants.
9963 
9964  >>> x, y, z = FPs('x y z', FPSort(8, 24))
9965  >>> x.sort()
9966  FPSort(8, 24)
9967  >>> x.sbits()
9968  24
9969  >>> x.ebits()
9970  8
9971  >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9972  fpMul(RNE(), fpAdd(RNE(), x, y), z)
9973  """
9974  ctx = _get_ctx(ctx)
9975  if isinstance(names, str):
9976  names = names.split(" ")
9977  return [FP(name, fpsort, ctx) for name in names]
9978 
9979 
9980 def fpAbs(a, ctx=None):
9981  """Create a Z3 floating-point absolute value expression.
9982 
9983  >>> s = FPSort(8, 24)
9984  >>> rm = RNE()
9985  >>> x = FPVal(1.0, s)
9986  >>> fpAbs(x)
9987  fpAbs(1)
9988  >>> y = FPVal(-20.0, s)
9989  >>> y
9990  -1.25*(2**4)
9991  >>> fpAbs(y)
9992  fpAbs(-1.25*(2**4))
9993  >>> fpAbs(-1.25*(2**4))
9994  fpAbs(-1.25*(2**4))
9995  >>> fpAbs(x).sort()
9996  FPSort(8, 24)
9997  """
9998  ctx = _get_ctx(ctx)
9999  [a] = _coerce_fp_expr_list([a], ctx)
10000  return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10001 
10002 
10003 def fpNeg(a, ctx=None):
10004  """Create a Z3 floating-point addition expression.
10005 
10006  >>> s = FPSort(8, 24)
10007  >>> rm = RNE()
10008  >>> x = FP('x', s)
10009  >>> fpNeg(x)
10010  -x
10011  >>> fpNeg(x).sort()
10012  FPSort(8, 24)
10013  """
10014  ctx = _get_ctx(ctx)
10015  [a] = _coerce_fp_expr_list([a], ctx)
10016  return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10017 
10018 
10019 def _mk_fp_unary(f, rm, a, ctx):
10020  ctx = _get_ctx(ctx)
10021  [a] = _coerce_fp_expr_list([a], ctx)
10022  if z3_debug():
10023  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10024  _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10025  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10026 
10027 
10028 def _mk_fp_unary_pred(f, a, ctx):
10029  ctx = _get_ctx(ctx)
10030  [a] = _coerce_fp_expr_list([a], ctx)
10031  if z3_debug():
10032  _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10033  return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10034 
10035 
10036 def _mk_fp_bin(f, rm, a, b, ctx):
10037  ctx = _get_ctx(ctx)
10038  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10039  if z3_debug():
10040  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10041  _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10042  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10043 
10044 
10045 def _mk_fp_bin_norm(f, a, b, ctx):
10046  ctx = _get_ctx(ctx)
10047  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10048  if z3_debug():
10049  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10050  return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10051 
10052 
10053 def _mk_fp_bin_pred(f, a, b, ctx):
10054  ctx = _get_ctx(ctx)
10055  [a, b] = _coerce_fp_expr_list([a, b], ctx)
10056  if z3_debug():
10057  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10058  return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10059 
10060 
10061 def _mk_fp_tern(f, rm, a, b, c, ctx):
10062  ctx = _get_ctx(ctx)
10063  [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
10064  if z3_debug():
10065  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10066  _z3_assert(is_fp(a) or is_fp(b) or is_fp(
10067  c), "Second, third or fourth argument must be a Z3 floating-point expression")
10068  return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10069 
10070 
10071 def fpAdd(rm, a, b, ctx=None):
10072  """Create a Z3 floating-point addition expression.
10073 
10074  >>> s = FPSort(8, 24)
10075  >>> rm = RNE()
10076  >>> x = FP('x', s)
10077  >>> y = FP('y', s)
10078  >>> fpAdd(rm, x, y)
10079  fpAdd(RNE(), x, y)
10080  >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10081  x + y
10082  >>> fpAdd(rm, x, y).sort()
10083  FPSort(8, 24)
10084  """
10085  return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10086 
10087 
10088 def fpSub(rm, a, b, ctx=None):
10089  """Create a Z3 floating-point subtraction expression.
10090 
10091  >>> s = FPSort(8, 24)
10092  >>> rm = RNE()
10093  >>> x = FP('x', s)
10094  >>> y = FP('y', s)
10095  >>> fpSub(rm, x, y)
10096  fpSub(RNE(), x, y)
10097  >>> fpSub(rm, x, y).sort()
10098  FPSort(8, 24)
10099  """
10100  return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10101 
10102 
10103 def fpMul(rm, a, b, ctx=None):
10104  """Create a Z3 floating-point multiplication expression.
10105 
10106  >>> s = FPSort(8, 24)
10107  >>> rm = RNE()
10108  >>> x = FP('x', s)
10109  >>> y = FP('y', s)
10110  >>> fpMul(rm, x, y)
10111  fpMul(RNE(), x, y)
10112  >>> fpMul(rm, x, y).sort()
10113  FPSort(8, 24)
10114  """
10115  return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10116 
10117 
10118 def fpDiv(rm, a, b, ctx=None):
10119  """Create a Z3 floating-point division expression.
10120 
10121  >>> s = FPSort(8, 24)
10122  >>> rm = RNE()
10123  >>> x = FP('x', s)
10124  >>> y = FP('y', s)
10125  >>> fpDiv(rm, x, y)
10126  fpDiv(RNE(), x, y)
10127  >>> fpDiv(rm, x, y).sort()
10128  FPSort(8, 24)
10129  """
10130  return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10131 
10132 
10133 def fpRem(a, b, ctx=None):
10134  """Create a Z3 floating-point remainder expression.
10135 
10136  >>> s = FPSort(8, 24)
10137  >>> x = FP('x', s)
10138  >>> y = FP('y', s)
10139  >>> fpRem(x, y)
10140  fpRem(x, y)
10141  >>> fpRem(x, y).sort()
10142  FPSort(8, 24)
10143  """
10144  return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10145 
10146 
10147 def fpMin(a, b, ctx=None):
10148  """Create a Z3 floating-point minimum expression.
10149 
10150  >>> s = FPSort(8, 24)
10151  >>> rm = RNE()
10152  >>> x = FP('x', s)
10153  >>> y = FP('y', s)
10154  >>> fpMin(x, y)
10155  fpMin(x, y)
10156  >>> fpMin(x, y).sort()
10157  FPSort(8, 24)
10158  """
10159  return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10160 
10161 
10162 def fpMax(a, b, ctx=None):
10163  """Create a Z3 floating-point maximum expression.
10164 
10165  >>> s = FPSort(8, 24)
10166  >>> rm = RNE()
10167  >>> x = FP('x', s)
10168  >>> y = FP('y', s)
10169  >>> fpMax(x, y)
10170  fpMax(x, y)
10171  >>> fpMax(x, y).sort()
10172  FPSort(8, 24)
10173  """
10174  return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10175 
10176 
10177 def fpFMA(rm, a, b, c, ctx=None):
10178  """Create a Z3 floating-point fused multiply-add expression.
10179  """
10180  return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10181 
10182 
10183 def fpSqrt(rm, a, ctx=None):
10184  """Create a Z3 floating-point square root expression.
10185  """
10186  return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10187 
10188 
10189 def fpRoundToIntegral(rm, a, ctx=None):
10190  """Create a Z3 floating-point roundToIntegral expression.
10191  """
10192  return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10193 
10194 
10195 def fpIsNaN(a, ctx=None):
10196  """Create a Z3 floating-point isNaN expression.
10197 
10198  >>> s = FPSort(8, 24)
10199  >>> x = FP('x', s)
10200  >>> y = FP('y', s)
10201  >>> fpIsNaN(x)
10202  fpIsNaN(x)
10203  """
10204  return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10205 
10206 
10207 def fpIsInf(a, ctx=None):
10208  """Create a Z3 floating-point isInfinite expression.
10209 
10210  >>> s = FPSort(8, 24)
10211  >>> x = FP('x', s)
10212  >>> fpIsInf(x)
10213  fpIsInf(x)
10214  """
10215  return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10216 
10217 
10218 def fpIsZero(a, ctx=None):
10219  """Create a Z3 floating-point isZero expression.
10220  """
10221  return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10222 
10223 
10224 def fpIsNormal(a, ctx=None):
10225  """Create a Z3 floating-point isNormal expression.
10226  """
10227  return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10228 
10229 
10230 def fpIsSubnormal(a, ctx=None):
10231  """Create a Z3 floating-point isSubnormal expression.
10232  """
10233  return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10234 
10235 
10236 def fpIsNegative(a, ctx=None):
10237  """Create a Z3 floating-point isNegative expression.
10238  """
10239  return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10240 
10241 
10242 def fpIsPositive(a, ctx=None):
10243  """Create a Z3 floating-point isPositive expression.
10244  """
10245  return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10246 
10247 
10248 def _check_fp_args(a, b):
10249  if z3_debug():
10250  _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10251 
10252 
10253 def fpLT(a, b, ctx=None):
10254  """Create the Z3 floating-point expression `other < self`.
10255 
10256  >>> x, y = FPs('x y', FPSort(8, 24))
10257  >>> fpLT(x, y)
10258  x < y
10259  >>> (x < y).sexpr()
10260  '(fp.lt x y)'
10261  """
10262  return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10263 
10264 
10265 def fpLEQ(a, b, ctx=None):
10266  """Create the Z3 floating-point expression `other <= self`.
10267 
10268  >>> x, y = FPs('x y', FPSort(8, 24))
10269  >>> fpLEQ(x, y)
10270  x <= y
10271  >>> (x <= y).sexpr()
10272  '(fp.leq x y)'
10273  """
10274  return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10275 
10276 
10277 def fpGT(a, b, ctx=None):
10278  """Create the Z3 floating-point expression `other > self`.
10279 
10280  >>> x, y = FPs('x y', FPSort(8, 24))
10281  >>> fpGT(x, y)
10282  x > y
10283  >>> (x > y).sexpr()
10284  '(fp.gt x y)'
10285  """
10286  return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10287 
10288 
10289 def fpGEQ(a, b, ctx=None):
10290  """Create the Z3 floating-point expression `other >= self`.
10291 
10292  >>> x, y = FPs('x y', FPSort(8, 24))
10293  >>> fpGEQ(x, y)
10294  x >= y
10295  >>> (x >= y).sexpr()
10296  '(fp.geq x y)'
10297  """
10298  return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10299 
10300 
10301 def fpEQ(a, b, ctx=None):
10302  """Create the Z3 floating-point expression `fpEQ(other, self)`.
10303 
10304  >>> x, y = FPs('x y', FPSort(8, 24))
10305  >>> fpEQ(x, y)
10306  fpEQ(x, y)
10307  >>> fpEQ(x, y).sexpr()
10308  '(fp.eq x y)'
10309  """
10310  return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10311 
10312 
10313 def fpNEQ(a, b, ctx=None):
10314  """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10315 
10316  >>> x, y = FPs('x y', FPSort(8, 24))
10317  >>> fpNEQ(x, y)
10318  Not(fpEQ(x, y))
10319  >>> (x != y).sexpr()
10320  '(distinct x y)'
10321  """
10322  return Not(fpEQ(a, b, ctx))
10323 
10324 
10325 def fpFP(sgn, exp, sig, ctx=None):
10326  """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10327 
10328  >>> s = FPSort(8, 24)
10329  >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10330  >>> print(x)
10331  fpFP(1, 127, 4194304)
10332  >>> xv = FPVal(-1.5, s)
10333  >>> print(xv)
10334  -1.5
10335  >>> slvr = Solver()
10336  >>> slvr.add(fpEQ(x, xv))
10337  >>> slvr.check()
10338  sat
10339  >>> xv = FPVal(+1.5, s)
10340  >>> print(xv)
10341  1.5
10342  >>> slvr = Solver()
10343  >>> slvr.add(fpEQ(x, xv))
10344  >>> slvr.check()
10345  unsat
10346  """
10347  _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10348  _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10349  ctx = _get_ctx(ctx)
10350  _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10351  return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10352 
10353 
10354 def fpToFP(a1, a2=None, a3=None, ctx=None):
10355  """Create a Z3 floating-point conversion expression from other term sorts
10356  to floating-point.
10357 
10358  From a bit-vector term in IEEE 754-2008 format:
10359  >>> x = FPVal(1.0, Float32())
10360  >>> x_bv = fpToIEEEBV(x)
10361  >>> simplify(fpToFP(x_bv, Float32()))
10362  1
10363 
10364  From a floating-point term with different precision:
10365  >>> x = FPVal(1.0, Float32())
10366  >>> x_db = fpToFP(RNE(), x, Float64())
10367  >>> x_db.sort()
10368  FPSort(11, 53)
10369 
10370  From a real term:
10371  >>> x_r = RealVal(1.5)
10372  >>> simplify(fpToFP(RNE(), x_r, Float32()))
10373  1.5
10374 
10375  From a signed bit-vector term:
10376  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10377  >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10378  -1.25*(2**2)
10379  """
10380  ctx = _get_ctx(ctx)
10381  if is_bv(a1) and is_fp_sort(a2):
10382  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10383  elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10384  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10385  elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10386  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10387  elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10388  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10389  else:
10390  raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10391 
10392 
10393 def fpBVToFP(v, sort, ctx=None):
10394  """Create a Z3 floating-point conversion expression that represents the
10395  conversion from a bit-vector term to a floating-point term.
10396 
10397  >>> x_bv = BitVecVal(0x3F800000, 32)
10398  >>> x_fp = fpBVToFP(x_bv, Float32())
10399  >>> x_fp
10400  fpToFP(1065353216)
10401  >>> simplify(x_fp)
10402  1
10403  """
10404  _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10405  _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10406  ctx = _get_ctx(ctx)
10407  return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10408 
10409 
10410 def fpFPToFP(rm, v, sort, ctx=None):
10411  """Create a Z3 floating-point conversion expression that represents the
10412  conversion from a floating-point term to a floating-point term of different precision.
10413 
10414  >>> x_sgl = FPVal(1.0, Float32())
10415  >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10416  >>> x_dbl
10417  fpToFP(RNE(), 1)
10418  >>> simplify(x_dbl)
10419  1
10420  >>> x_dbl.sort()
10421  FPSort(11, 53)
10422  """
10423  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10424  _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10425  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10426  ctx = _get_ctx(ctx)
10427  return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10428 
10429 
10430 def fpRealToFP(rm, v, sort, ctx=None):
10431  """Create a Z3 floating-point conversion expression that represents the
10432  conversion from a real term to a floating-point term.
10433 
10434  >>> x_r = RealVal(1.5)
10435  >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10436  >>> x_fp
10437  fpToFP(RNE(), 3/2)
10438  >>> simplify(x_fp)
10439  1.5
10440  """
10441  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10442  _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10443  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10444  ctx = _get_ctx(ctx)
10445  return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10446 
10447 
10448 def fpSignedToFP(rm, v, sort, ctx=None):
10449  """Create a Z3 floating-point conversion expression that represents the
10450  conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10451 
10452  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10453  >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10454  >>> x_fp
10455  fpToFP(RNE(), 4294967291)
10456  >>> simplify(x_fp)
10457  -1.25*(2**2)
10458  """
10459  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10460  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10461  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10462  ctx = _get_ctx(ctx)
10463  return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10464 
10465 
10466 def fpUnsignedToFP(rm, v, sort, ctx=None):
10467  """Create a Z3 floating-point conversion expression that represents the
10468  conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10469 
10470  >>> x_signed = BitVecVal(-5, BitVecSort(32))
10471  >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10472  >>> x_fp
10473  fpToFPUnsigned(RNE(), 4294967291)
10474  >>> simplify(x_fp)
10475  1*(2**32)
10476  """
10477  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10478  _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10479  _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10480  ctx = _get_ctx(ctx)
10481  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10482 
10483 
10484 def fpToFPUnsigned(rm, x, s, ctx=None):
10485  """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10486  if z3_debug():
10487  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10488  _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10489  _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10490  ctx = _get_ctx(ctx)
10491  return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10492 
10493 
10494 def fpToSBV(rm, x, s, ctx=None):
10495  """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10496 
10497  >>> x = FP('x', FPSort(8, 24))
10498  >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10499  >>> print(is_fp(x))
10500  True
10501  >>> print(is_bv(y))
10502  True
10503  >>> print(is_fp(y))
10504  False
10505  >>> print(is_bv(x))
10506  False
10507  """
10508  if z3_debug():
10509  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10510  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10511  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10512  ctx = _get_ctx(ctx)
10513  return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10514 
10515 
10516 def fpToUBV(rm, x, s, ctx=None):
10517  """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10518 
10519  >>> x = FP('x', FPSort(8, 24))
10520  >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10521  >>> print(is_fp(x))
10522  True
10523  >>> print(is_bv(y))
10524  True
10525  >>> print(is_fp(y))
10526  False
10527  >>> print(is_bv(x))
10528  False
10529  """
10530  if z3_debug():
10531  _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10532  _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10533  _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10534  ctx = _get_ctx(ctx)
10535  return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10536 
10537 
10538 def fpToReal(x, ctx=None):
10539  """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10540 
10541  >>> x = FP('x', FPSort(8, 24))
10542  >>> y = fpToReal(x)
10543  >>> print(is_fp(x))
10544  True
10545  >>> print(is_real(y))
10546  True
10547  >>> print(is_fp(y))
10548  False
10549  >>> print(is_real(x))
10550  False
10551  """
10552  if z3_debug():
10553  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10554  ctx = _get_ctx(ctx)
10555  return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10556 
10557 
10558 def fpToIEEEBV(x, ctx=None):
10559  """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10560 
10561  The size of the resulting bit-vector is automatically determined.
10562 
10563  Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10564  knows only one NaN and it will always produce the same bit-vector representation of
10565  that NaN.
10566 
10567  >>> x = FP('x', FPSort(8, 24))
10568  >>> y = fpToIEEEBV(x)
10569  >>> print(is_fp(x))
10570  True
10571  >>> print(is_bv(y))
10572  True
10573  >>> print(is_fp(y))
10574  False
10575  >>> print(is_bv(x))
10576  False
10577  """
10578  if z3_debug():
10579  _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10580  ctx = _get_ctx(ctx)
10581  return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10582 
10583 
10584 
10589 
10591  """Sequence sort."""
10592 
10593  def is_string(self):
10594  """Determine if sort is a string
10595  >>> s = StringSort()
10596  >>> s.is_string()
10597  True
10598  >>> s = SeqSort(IntSort())
10599  >>> s.is_string()
10600  False
10601  """
10602  return Z3_is_string_sort(self.ctx_refctx_ref(), self.astast)
10603 
10604  def basis(self):
10605  return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_refctx_ref(), self.astast), self.ctxctx)
10606 
10608  """Character sort."""
10609 
10610 
10611 def StringSort(ctx=None):
10612  """Create a string sort
10613  >>> s = StringSort()
10614  >>> print(s)
10615  String
10616  """
10617  ctx = _get_ctx(ctx)
10618  return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10619 
10620 def CharSort(ctx=None):
10621  """Create a character sort
10622  >>> ch = CharSort()
10623  >>> print(ch)
10624  Char
10625  """
10626  ctx = _get_ctx(ctx)
10627  return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
10628 
10629 
10630 def SeqSort(s):
10631  """Create a sequence sort over elements provided in the argument
10632  >>> s = SeqSort(IntSort())
10633  >>> s == Unit(IntVal(1)).sort()
10634  True
10635  """
10636  return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10637 
10638 
10640  """Sequence expression."""
10641 
10642  def sort(self):
10643  return SeqSortRef(Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10644 
10645  def __add__(self, other):
10646  return Concat(self, other)
10647 
10648  def __radd__(self, other):
10649  return Concat(other, self)
10650 
10651  def __getitem__(self, i):
10652  if _is_int(i):
10653  i = IntVal(i, self.ctxctx)
10654  return _to_expr_ref(Z3_mk_seq_nth(self.ctx_refctx_ref(), self.as_astas_astas_ast(), i.as_ast()), self.ctxctx)
10655 
10656  def at(self, i):
10657  if _is_int(i):
10658  i = IntVal(i, self.ctxctx)
10659  return SeqRef(Z3_mk_seq_at(self.ctx_refctx_ref(), self.as_astas_astas_ast(), i.as_ast()), self.ctxctx)
10660 
10661  def is_string(self):
10662  return Z3_is_string_sort(self.ctx_refctx_ref(), Z3_get_sort(self.ctx_refctx_ref(), self.as_astas_astas_ast()))
10663 
10664  def is_string_value(self):
10665  return Z3_is_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
10666 
10667  def as_string(self):
10668  """Return a string representation of sequence expression."""
10669  if self.is_string_valueis_string_value():
10670  string_length = ctypes.c_uint()
10671  chars = Z3_get_lstring(self.ctx_refctx_ref(), self.as_astas_astas_ast(), byref(string_length))
10672  return string_at(chars, size=string_length.value).decode("latin-1")
10673  return Z3_ast_to_string(self.ctx_refctx_ref(), self.as_astas_astas_ast())
10674 
10675  def __le__(self, other):
10676  return _to_expr_ref(Z3_mk_str_le(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10677 
10678  def __lt__(self, other):
10679  return _to_expr_ref(Z3_mk_str_lt(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10680 
10681  def __ge__(self, other):
10682  return _to_expr_ref(Z3_mk_str_le(self.ctx_refctx_ref(), other.as_ast(), self.as_astas_astas_ast()), self.ctxctx)
10683 
10684  def __gt__(self, other):
10685  return _to_expr_ref(Z3_mk_str_lt(self.ctx_refctx_ref(), other.as_ast(), self.as_astas_astas_ast()), self.ctxctx)
10686 
10687 
10688 def _coerce_char(ch, ctx=None):
10689  if isinstance(ch, str):
10690  ctx = _get_ctx(ctx)
10691  ch = CharVal(ch, ctx)
10692  if not is_expr(ch):
10693  raise Z3Exception("Character expression expected")
10694  return ch
10695 
10697  """Character expression."""
10698 
10699  def __le__(self, other):
10700  other = _coerce_char(other, self.ctxctx)
10701  return _to_expr_ref(Z3_mk_char_le(self.ctx_refctx_ref(), self.as_astas_astas_ast(), other.as_ast()), self.ctxctx)
10702 
10703  def to_int(self):
10704  return _to_expr_ref(Z3_mk_char_to_int(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10705 
10706  def to_bv(self):
10707  return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10708 
10709  def is_digit(self):
10710  return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_refctx_ref(), self.as_astas_astas_ast()), self.ctxctx)
10711 
10712 
10713 def CharVal(ch, ctx=None):
10714  ctx = _get_ctx(ctx)
10715  if isinstance(ch, str):
10716  ch = ord(ch)
10717  if not isinstance(ch, int):
10718  raise Z3Exception("character value should be an ordinal")
10719  return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
10720 
10721 def CharFromBv(ch, ctx=None):
10722  if not is_expr(ch):
10723  raise Z3Expression("Bit-vector expression needed")
10724  return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
10725 
10726 def CharToBv(ch, ctx=None):
10727  ch = _coerce_char(ch, ctx)
10728  return ch.to_bv()
10729 
10730 def CharToInt(ch, ctx=None):
10731  ch = _coerce_char(ch, ctx)
10732  return ch.to_int()
10733 
10734 def CharIsDigit(ch, ctx=None):
10735  ch = _coerce_char(ch, ctx)
10736  return ch.is_digit()
10737 
10738 def _coerce_seq(s, ctx=None):
10739  if isinstance(s, str):
10740  ctx = _get_ctx(ctx)
10741  s = StringVal(s, ctx)
10742  if not is_expr(s):
10743  raise Z3Exception("Non-expression passed as a sequence")
10744  if not is_seq(s):
10745  raise Z3Exception("Non-sequence passed as a sequence")
10746  return s
10747 
10748 
10749 def _get_ctx2(a, b, ctx=None):
10750  if is_expr(a):
10751  return a.ctx
10752  if is_expr(b):
10753  return b.ctx
10754  if ctx is None:
10755  ctx = main_ctx()
10756  return ctx
10757 
10758 
10759 def is_seq(a):
10760  """Return `True` if `a` is a Z3 sequence expression.
10761  >>> print (is_seq(Unit(IntVal(0))))
10762  True
10763  >>> print (is_seq(StringVal("abc")))
10764  True
10765  """
10766  return isinstance(a, SeqRef)
10767 
10768 
10769 def is_string(a):
10770  """Return `True` if `a` is a Z3 string expression.
10771  >>> print (is_string(StringVal("ab")))
10772  True
10773  """
10774  return isinstance(a, SeqRef) and a.is_string()
10775 
10776 
10778  """return 'True' if 'a' is a Z3 string constant expression.
10779  >>> print (is_string_value(StringVal("a")))
10780  True
10781  >>> print (is_string_value(StringVal("a") + StringVal("b")))
10782  False
10783  """
10784  return isinstance(a, SeqRef) and a.is_string_value()
10785 
10786 def StringVal(s, ctx=None):
10787  """create a string expression"""
10788  s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
10789  ctx = _get_ctx(ctx)
10790  return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
10791 
10792 
10793 def String(name, ctx=None):
10794  """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10795 
10796  >>> x = String('x')
10797  """
10798  ctx = _get_ctx(ctx)
10799  return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10800 
10801 
10802 def Strings(names, ctx=None):
10803  """Return a tuple of String constants. """
10804  ctx = _get_ctx(ctx)
10805  if isinstance(names, str):
10806  names = names.split(" ")
10807  return [String(name, ctx) for name in names]
10808 
10809 
10810 def SubString(s, offset, length):
10811  """Extract substring or subsequence starting at offset"""
10812  return Extract(s, offset, length)
10813 
10814 
10815 def SubSeq(s, offset, length):
10816  """Extract substring or subsequence starting at offset"""
10817  return Extract(s, offset, length)
10818 
10819 
10820 def Empty(s):
10821  """Create the empty sequence of the given sort
10822  >>> e = Empty(StringSort())
10823  >>> e2 = StringVal("")
10824  >>> print(e.eq(e2))
10825  True
10826  >>> e3 = Empty(SeqSort(IntSort()))
10827  >>> print(e3)
10828  Empty(Seq(Int))
10829  >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10830  >>> print(e4)
10831  Empty(ReSort(Seq(Int)))
10832  """
10833  if isinstance(s, SeqSortRef):
10834  return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10835  if isinstance(s, ReSortRef):
10836  return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10837  raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10838 
10839 
10840 def Full(s):
10841  """Create the regular expression that accepts the universal language
10842  >>> e = Full(ReSort(SeqSort(IntSort())))
10843  >>> print(e)
10844  Full(ReSort(Seq(Int)))
10845  >>> e1 = Full(ReSort(StringSort()))
10846  >>> print(e1)
10847  Full(ReSort(String))
10848  """
10849  if isinstance(s, ReSortRef):
10850  return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10851  raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10852 
10853 
10854 
10855 def Unit(a):
10856  """Create a singleton sequence"""
10857  return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10858 
10859 
10860 def PrefixOf(a, b):
10861  """Check if 'a' is a prefix of 'b'
10862  >>> s1 = PrefixOf("ab", "abc")
10863  >>> simplify(s1)
10864  True
10865  >>> s2 = PrefixOf("bc", "abc")
10866  >>> simplify(s2)
10867  False
10868  """
10869  ctx = _get_ctx2(a, b)
10870  a = _coerce_seq(a, ctx)
10871  b = _coerce_seq(b, ctx)
10872  return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10873 
10874 
10875 def SuffixOf(a, b):
10876  """Check if 'a' is a suffix of 'b'
10877  >>> s1 = SuffixOf("ab", "abc")
10878  >>> simplify(s1)
10879  False
10880  >>> s2 = SuffixOf("bc", "abc")
10881  >>> simplify(s2)
10882  True
10883  """
10884  ctx = _get_ctx2(a, b)
10885  a = _coerce_seq(a, ctx)
10886  b = _coerce_seq(b, ctx)
10887  return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10888 
10889 
10890 def Contains(a, b):
10891  """Check if 'a' contains 'b'
10892  >>> s1 = Contains("abc", "ab")
10893  >>> simplify(s1)
10894  True
10895  >>> s2 = Contains("abc", "bc")
10896  >>> simplify(s2)
10897  True
10898  >>> x, y, z = Strings('x y z')
10899  >>> s3 = Contains(Concat(x,y,z), y)
10900  >>> simplify(s3)
10901  True
10902  """
10903  ctx = _get_ctx2(a, b)
10904  a = _coerce_seq(a, ctx)
10905  b = _coerce_seq(b, ctx)
10906  return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10907 
10908 
10909 def Replace(s, src, dst):
10910  """Replace the first occurrence of 'src' by 'dst' in 's'
10911  >>> r = Replace("aaa", "a", "b")
10912  >>> simplify(r)
10913  "baa"
10914  """
10915  ctx = _get_ctx2(dst, s)
10916  if ctx is None and is_expr(src):
10917  ctx = src.ctx
10918  src = _coerce_seq(src, ctx)
10919  dst = _coerce_seq(dst, ctx)
10920  s = _coerce_seq(s, ctx)
10921  return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10922 
10923 
10924 def IndexOf(s, substr, offset=None):
10925  """Retrieve the index of substring within a string starting at a specified offset.
10926  >>> simplify(IndexOf("abcabc", "bc", 0))
10927  1
10928  >>> simplify(IndexOf("abcabc", "bc", 2))
10929  4
10930  """
10931  if offset is None:
10932  offset = IntVal(0)
10933  ctx = None
10934  if is_expr(offset):
10935  ctx = offset.ctx
10936  ctx = _get_ctx2(s, substr, ctx)
10937  s = _coerce_seq(s, ctx)
10938  substr = _coerce_seq(substr, ctx)
10939  if _is_int(offset):
10940  offset = IntVal(offset, ctx)
10941  return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10942 
10943 
10944 def LastIndexOf(s, substr):
10945  """Retrieve the last index of substring within a string"""
10946  ctx = None
10947  ctx = _get_ctx2(s, substr, ctx)
10948  s = _coerce_seq(s, ctx)
10949  substr = _coerce_seq(substr, ctx)
10950  return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10951 
10952 
10953 def Length(s):
10954  """Obtain the length of a sequence 's'
10955  >>> l = Length(StringVal("abc"))
10956  >>> simplify(l)
10957  3
10958  """
10959  s = _coerce_seq(s)
10960  return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10961 
10962 
10963 def StrToInt(s):
10964  """Convert string expression to integer
10965  >>> a = StrToInt("1")
10966  >>> simplify(1 == a)
10967  True
10968  >>> b = StrToInt("2")
10969  >>> simplify(1 == b)
10970  False
10971  >>> c = StrToInt(IntToStr(2))
10972  >>> simplify(1 == c)
10973  False
10974  """
10975  s = _coerce_seq(s)
10976  return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10977 
10978 
10979 def IntToStr(s):
10980  """Convert integer expression to string"""
10981  if not is_expr(s):
10982  s = _py2expr(s)
10983  return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10984 
10985 
10986 def StrToCode(s):
10987  """Convert a unit length string to integer code"""
10988  if not is_expr(s):
10989  s = _py2expr(s)
10990  return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
10991 
10993  """Convert code to a string"""
10994  if not is_expr(c):
10995  c = _py2expr(c)
10996  return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
10997 
10998 def Re(s, ctx=None):
10999  """The regular expression that accepts sequence 's'
11000  >>> s1 = Re("ab")
11001  >>> s2 = Re(StringVal("ab"))
11002  >>> s3 = Re(Unit(BoolVal(True)))
11003  """
11004  s = _coerce_seq(s, ctx)
11005  return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
11006 
11007 
11008 # Regular expressions
11009 
11011  """Regular expression sort."""
11012 
11013  def basis(self):
11014  return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_refctx_ref(), self.astast), self.ctxctx)
11015 
11016 
11017 def ReSort(s):
11018  if is_ast(s):
11019  return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
11020  if s is None or isinstance(s, Context):
11021  ctx = _get_ctx(s)
11022  return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
11023  raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
11024 
11025 
11027  """Regular expressions."""
11028 
11029  def __add__(self, other):
11030  return Union(self, other)
11031 
11032 
11033 def is_re(s):
11034  return isinstance(s, ReRef)
11035 
11036 
11037 def InRe(s, re):
11038  """Create regular expression membership test
11039  >>> re = Union(Re("a"),Re("b"))
11040  >>> print (simplify(InRe("a", re)))
11041  True
11042  >>> print (simplify(InRe("b", re)))
11043  True
11044  >>> print (simplify(InRe("c", re)))
11045  False
11046  """
11047  s = _coerce_seq(s, re.ctx)
11048  return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
11049 
11050 
11051 def Union(*args):
11052  """Create union of regular expressions.
11053  >>> re = Union(Re("a"), Re("b"), Re("c"))
11054  >>> print (simplify(InRe("d", re)))
11055  False
11056  """
11057  args = _get_args(args)
11058  sz = len(args)
11059  if z3_debug():
11060  _z3_assert(sz > 0, "At least one argument expected.")
11061  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11062  if sz == 1:
11063  return args[0]
11064  ctx = args[0].ctx
11065  v = (Ast * sz)()
11066  for i in range(sz):
11067  v[i] = args[i].as_ast()
11068  return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
11069 
11070 
11071 def Intersect(*args):
11072  """Create intersection of regular expressions.
11073  >>> re = Intersect(Re("a"), Re("b"), Re("c"))
11074  """
11075  args = _get_args(args)
11076  sz = len(args)
11077  if z3_debug():
11078  _z3_assert(sz > 0, "At least one argument expected.")
11079  _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11080  if sz == 1:
11081  return args[0]
11082  ctx = args[0].ctx
11083  v = (Ast * sz)()
11084  for i in range(sz):
11085  v[i] = args[i].as_ast()
11086  return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
11087 
11088 
11089 def Plus(re):
11090  """Create the regular expression accepting one or more repetitions of argument.
11091  >>> re = Plus(Re("a"))
11092  >>> print(simplify(InRe("aa", re)))
11093  True
11094  >>> print(simplify(InRe("ab", re)))
11095  False
11096  >>> print(simplify(InRe("", re)))
11097  False
11098  """
11099  return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
11100 
11101 
11102 def Option(re):
11103  """Create the regular expression that optionally accepts the argument.
11104  >>> re = Option(Re("a"))
11105  >>> print(simplify(InRe("a", re)))
11106  True
11107  >>> print(simplify(InRe("", re)))
11108  True
11109  >>> print(simplify(InRe("aa", re)))
11110  False
11111  """
11112  return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11113 
11114 
11115 def Complement(re):
11116  """Create the complement regular expression."""
11117  return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11118 
11119 
11120 def Star(re):
11121  """Create the regular expression accepting zero or more repetitions of argument.
11122  >>> re = Star(Re("a"))
11123  >>> print(simplify(InRe("aa", re)))
11124  True
11125  >>> print(simplify(InRe("ab", re)))
11126  False
11127  >>> print(simplify(InRe("", re)))
11128  True
11129  """
11130  return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11131 
11132 
11133 def Loop(re, lo, hi=0):
11134  """Create the regular expression accepting between a lower and upper bound repetitions
11135  >>> re = Loop(Re("a"), 1, 3)
11136  >>> print(simplify(InRe("aa", re)))
11137  True
11138  >>> print(simplify(InRe("aaaa", re)))
11139  False
11140  >>> print(simplify(InRe("", re)))
11141  False
11142  """
11143  return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11144 
11145 
11146 def Range(lo, hi, ctx=None):
11147  """Create the range regular expression over two sequences of length 1
11148  >>> range = Range("a","z")
11149  >>> print(simplify(InRe("b", range)))
11150  True
11151  >>> print(simplify(InRe("bb", range)))
11152  False
11153  """
11154  lo = _coerce_seq(lo, ctx)
11155  hi = _coerce_seq(hi, ctx)
11156  return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11157 
11158 def Diff(a, b, ctx=None):
11159  """Create the difference regular epression
11160  """
11161  return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
11162 
11163 def AllChar(regex_sort, ctx=None):
11164  """Create a regular expression that accepts all single character strings
11165  """
11166  return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
11167 
11168 # Special Relations
11169 
11170 
11171 def PartialOrder(a, index):
11172  return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11173 
11174 
11175 def LinearOrder(a, index):
11176  return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11177 
11178 
11179 def TreeOrder(a, index):
11180  return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11181 
11182 
11183 def PiecewiseLinearOrder(a, index):
11184  return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11185 
11186 
11188  """Given a binary relation R, such that the two arguments have the same sort
11189  create the transitive closure relation R+.
11190  The transitive closure R+ is a new relation.
11191  """
11192  return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11193 
11194 
11196  def __init__(self):
11197  self.basesbases = {}
11198  self.locklock = None
11199 
11200  def set_threaded(self):
11201  if self.locklock is None:
11202  import threading
11203  self.locklock = threading.Lock()
11204 
11205  def get(self, ctx):
11206  if self.locklock:
11207  with self.locklock:
11208  r = self.basesbases[ctx]
11209  else:
11210  r = self.basesbases[ctx]
11211  return r
11212 
11213  def set(self, ctx, r):
11214  if self.locklock:
11215  with self.locklock:
11216  self.basesbases[ctx] = r
11217  else:
11218  self.basesbases[ctx] = r
11219 
11220  def insert(self, r):
11221  if self.locklock:
11222  with self.locklock:
11223  id = len(self.basesbases) + 3
11224  self.basesbases[id] = r
11225  else:
11226  id = len(self.basesbases) + 3
11227  self.basesbases[id] = r
11228  return id
11229 
11230 
11231 _prop_closures = None
11232 
11233 
11235  global _prop_closures
11236  if _prop_closures is None:
11237  _prop_closures = PropClosures()
11238 
11239 
11241  _prop_closures.get(ctx).push()
11242 
11243 
11244 def user_prop_pop(ctx, num_scopes):
11245  _prop_closures.get(ctx).pop(num_scopes)
11246 
11247 
11248 def user_prop_fresh(id, ctx):
11249  _prop_closures.set_threaded()
11250  prop = _prop_closures.get(id)
11251  new_prop = prop.fresh()
11252  _prop_closures.set(new_prop.id, new_prop)
11253  return ctypes.c_void_p(new_prop.id)
11254 
11255 def to_Ast(ptr,):
11256  ast = Ast(ptr)
11257  super(ctypes.c_void_p, ast).__init__(ptr)
11258  return ast
11259 
11260 def user_prop_fixed(ctx, cb, id, value):
11261  prop = _prop_closures.get(ctx)
11262  prop.cb = cb
11263  id = _to_expr_ref(to_Ast(id), prop.ctx())
11264  value = _to_expr_ref(to_Ast(value), prop.ctx())
11265  prop.fixed(id, value)
11266  prop.cb = None
11267 
11268 def user_prop_final(ctx, cb):
11269  prop = _prop_closures.get(ctx)
11270  prop.cb = cb
11271  prop.final()
11272  prop.cb = None
11273 
11274 def user_prop_eq(ctx, cb, x, y):
11275  prop = _prop_closures.get(ctx)
11276  prop.cb = cb
11277  x = _to_expr_ref(to_Ast(x), prop.ctx())
11278  y = _to_expr_ref(to_Ast(y), prop.ctx())
11279  prop.eq(x, y)
11280  prop.cb = None
11281 
11282 def user_prop_diseq(ctx, cb, x, y):
11283  prop = _prop_closures.get(ctx)
11284  prop.cb = cb
11285  x = _to_expr_ref(to_Ast(x), prop.ctx())
11286  y = _to_expr_ref(to_Ast(y), prop.ctx())
11287  prop.diseq(x, y)
11288  prop.cb = None
11289 
11290 
11291 _user_prop_push = push_eh_type(user_prop_push)
11292 _user_prop_pop = pop_eh_type(user_prop_pop)
11293 _user_prop_fresh = fresh_eh_type(user_prop_fresh)
11294 _user_prop_fixed = fixed_eh_type(user_prop_fixed)
11295 _user_prop_final = final_eh_type(user_prop_final)
11296 _user_prop_eq = eq_eh_type(user_prop_eq)
11297 _user_prop_diseq = eq_eh_type(user_prop_diseq)
11298 
11299 
11301 
11302  #
11303  # Either solver is set or ctx is set.
11304  # Propagators that are created throuh callbacks
11305  # to "fresh" inherit the context of that is supplied
11306  # as argument to the callback.
11307  # This context should not be deleted. It is owned by the solver.
11308  #
11309  def __init__(self, s, ctx=None):
11310  assert s is None or ctx is None
11312  self.solversolver = s
11313  self._ctx_ctx = None
11314  self.cbcb = None
11315  self.idid = _prop_closures.insert(self)
11316  self.fixedfixed = None
11317  self.finalfinal = None
11318  self.eqeq = None
11319  self.diseqdiseq = None
11320  if ctx:
11321  # TBD fresh is broken: ctx is not of the right type when we reach here.
11322  self._ctx_ctx = Context()
11323  #Z3_del_context(self._ctx.ctx)
11324  #self._ctx.ctx = ctx
11325  #self._ctx.eh = Z3_set_error_handler(ctx, z3_error_handler)
11326  #Z3_set_ast_print_mode(ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
11327  if s:
11328  Z3_solver_propagate_init(self.ctx_refctx_ref(),
11329  s.solver,
11330  ctypes.c_void_p(self.idid),
11331  _user_prop_push,
11332  _user_prop_pop,
11333  _user_prop_fresh)
11334 
11335  def __del__(self):
11336  if self._ctx_ctx:
11337  self._ctx_ctx.ctx = None
11338 
11339  def ctx(self):
11340  if self._ctx_ctx:
11341  return self._ctx_ctx
11342  else:
11343  return self.solversolver.ctx
11344 
11345  def ctx_ref(self):
11346  return self.ctxctx().ref()
11347 
11348  def add_fixed(self, fixed):
11349  assert not self.fixedfixed
11350  assert not self._ctx_ctx
11351  Z3_solver_propagate_fixed(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_fixed)
11352  self.fixedfixed = fixed
11353 
11354  def add_final(self, final):
11355  assert not self.finalfinal
11356  assert not self._ctx_ctx
11357  Z3_solver_propagate_final(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_final)
11358  self.finalfinal = final
11359 
11360  def add_eq(self, eq):
11361  assert not self.eqeq
11362  assert not self._ctx_ctx
11363  Z3_solver_propagate_eq(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_eq)
11364  self.eqeq = eq
11365 
11366  def add_diseq(self, diseq):
11367  assert not self.diseqdiseq
11368  assert not self._ctx_ctx
11369  Z3_solver_propagate_diseq(self.ctx_refctx_ref(), self.solversolver.solver, _user_prop_diseq)
11370  self.diseqdiseq = diseq
11371 
11372  def push(self):
11373  raise Z3Exception("push needs to be overwritten")
11374 
11375  def pop(self, num_scopes):
11376  raise Z3Exception("pop needs to be overwritten")
11377 
11378  def fresh(self):
11379  raise Z3Exception("fresh needs to be overwritten")
11380 
11381  def add(self, e):
11382  assert self.solversolver
11383  assert not self._ctx_ctx
11384  Z3_solver_propagate_register(self.ctx_refctx_ref(), self.solversolver.solver, e.ast)
11385 
11386  #
11387  # Propagation can only be invoked as during a fixed or final callback.
11388  #
11389  def propagate(self, e, ids, eqs=[]):
11390  _ids, num_fixed = _to_ast_array(ids)
11391  num_eqs = len(eqs)
11392  _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
11393  _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
11394  Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11395  self.cbcb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11396 
11397  def conflict(self, deps):
11398  self.propagatepropagate(BoolVal(False, self.ctxctx()), deps, eqs=[])
def poly(self)
Definition: z3py.py:3076
def as_decimal(self, prec)
Definition: z3py.py:3064
def index(self)
Definition: z3py.py:3079
def approx(self, precision=10)
Definition: z3py.py:3052
def __del__(self)
Definition: z3py.py:8012
def __getitem__(self, idx)
Definition: z3py.py:8035
def __init__(self, result, ctx)
Definition: z3py.py:8004
def __len__(self)
Definition: z3py.py:8016
def as_expr(self)
Definition: z3py.py:8059
def __repr__(self)
Definition: z3py.py:8052
def sexpr(self)
Definition: z3py.py:8055
def __deepcopy__(self, memo={})
Definition: z3py.py:8009
def is_real(self)
Definition: z3py.py:2367
def __pos__(self)
Definition: z3py.py:2563
def sort(self)
Definition: z3py.py:2343
def __radd__(self, other)
Definition: z3py.py:2391
def __pow__(self, other)
Definition: z3py.py:2449
def __add__(self, other)
Definition: z3py.py:2378
def __lt__(self, other)
Definition: z3py.py:2585
def __neg__(self)
Definition: z3py.py:2552
def __rmul__(self, other)
Definition: z3py.py:2416
def __le__(self, other)
Definition: z3py.py:2572
def __mul__(self, other)
Definition: z3py.py:2401
def __mod__(self, other)
Definition: z3py.py:2525
def __rsub__(self, other)
Definition: z3py.py:2439
def __rtruediv__(self, other)
Definition: z3py.py:2521
def __rdiv__(self, other)
Definition: z3py.py:2504
def __ge__(self, other)
Definition: z3py.py:2611
def is_int(self)
Definition: z3py.py:2353
def __truediv__(self, other)
Definition: z3py.py:2500
def __gt__(self, other)
Definition: z3py.py:2598
def __sub__(self, other)
Definition: z3py.py:2426
def __rpow__(self, other)
Definition: z3py.py:2463
def __rmod__(self, other)
Definition: z3py.py:2540
def __div__(self, other)
Definition: z3py.py:2477
Arithmetic.
Definition: z3py.py:2251
def is_real(self)
Definition: z3py.py:2254
def subsort(self, other)
Definition: z3py.py:2282
def cast(self, val)
Definition: z3py.py:2286
def is_int(self)
Definition: z3py.py:2268
def sort(self)
Definition: z3py.py:4511
def domain_n(self, i)
Definition: z3py.py:4529
def default(self)
Definition: z3py.py:4554
def __getitem__(self, arg)
Definition: z3py.py:4542
def domain(self)
Definition: z3py.py:4520
def range(self)
Definition: z3py.py:4533
def domain_n(self, i)
Definition: z3py.py:4493
def domain(self)
Definition: z3py.py:4484
def range(self)
Definition: z3py.py:4498
def erase(self, k)
Definition: z3py.py:6048
def __del__(self)
Definition: z3py.py:5988
def reset(self)
Definition: z3py.py:6062
def __init__(self, m=None, ctx=None)
Definition: z3py.py:5974
def __len__(self)
Definition: z3py.py:5992
def keys(self)
Definition: z3py.py:6077
def __repr__(self)
Definition: z3py.py:6045
def __getitem__(self, key)
Definition: z3py.py:6018
def __deepcopy__(self, memo={})
Definition: z3py.py:5985
def __setitem__(self, k, v)
Definition: z3py.py:6029
def __contains__(self, key)
Definition: z3py.py:6005
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:5912
def resize(self, sz)
Definition: z3py.py:5899
def __del__(self)
Definition: z3py.py:5825
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5814
def __setitem__(self, i, v)
Definition: z3py.py:5871
def push(self, v)
Definition: z3py.py:5887
def __len__(self)
Definition: z3py.py:5829
def translate(self, other_ctx)
Definition: z3py.py:5935
def __repr__(self)
Definition: z3py.py:5957
def sexpr(self)
Definition: z3py.py:5960
def __deepcopy__(self, memo={})
Definition: z3py.py:5954
def __copy__(self)
Definition: z3py.py:5951
def __getitem__(self, i)
Definition: z3py.py:5842
def as_signed_long(self)
Definition: z3py.py:3874
def as_long(self)
Definition: z3py.py:3863
def as_binary_string(self)
Definition: z3py.py:3900
def as_string(self)
Definition: z3py.py:3897
def __rlshift__(self, other)
Definition: z3py.py:3845
def __pos__(self)
Definition: z3py.py:3610
def sort(self)
Definition: z3py.py:3450
def __radd__(self, other)
Definition: z3py.py:3485
def __rxor__(self, other)
Definition: z3py.py:3600
def __xor__(self, other)
Definition: z3py.py:3587
def __ror__(self, other)
Definition: z3py.py:3554
def __add__(self, other)
Definition: z3py.py:3472
def __rshift__(self, other)
Definition: z3py.py:3787
def __lt__(self, other)
Definition: z3py.py:3739
def __or__(self, other)
Definition: z3py.py:3541
def size(self)
Definition: z3py.py:3461
def __neg__(self)
Definition: z3py.py:3619
def __rand__(self, other)
Definition: z3py.py:3577
def __rmul__(self, other)
Definition: z3py.py:3508
def __le__(self, other)
Definition: z3py.py:3723
def __mul__(self, other)
Definition: z3py.py:3495
def __mod__(self, other)
Definition: z3py.py:3684
def __rsub__(self, other)
Definition: z3py.py:3531
def __invert__(self)
Definition: z3py.py:3630
def __rtruediv__(self, other)
Definition: z3py.py:3680
def __rdiv__(self, other)
Definition: z3py.py:3664
def __lshift__(self, other)
Definition: z3py.py:3817
def __ge__(self, other)
Definition: z3py.py:3771
def __and__(self, other)
Definition: z3py.py:3564
def __rrshift__(self, other)
Definition: z3py.py:3831
def __truediv__(self, other)
Definition: z3py.py:3660
def __gt__(self, other)
Definition: z3py.py:3755
def __sub__(self, other)
Definition: z3py.py:3518
def __rmod__(self, other)
Definition: z3py.py:3705
def __div__(self, other)
Definition: z3py.py:3641
Bit-Vectors.
Definition: z3py.py:3403
def subsort(self, other)
Definition: z3py.py:3415
def size(self)
Definition: z3py.py:3406
def cast(self, val)
Definition: z3py.py:3418
def sort(self)
Definition: z3py.py:1518
def __rmul__(self, other)
Definition: z3py.py:1521
def __mul__(self, other)
Definition: z3py.py:1524
Booleans.
Definition: z3py.py:1479
def subsort(self, other)
Definition: z3py.py:1505
def cast(self, val)
Definition: z3py.py:1482
def is_int(self)
Definition: z3py.py:1508
def is_bool(self)
Definition: z3py.py:1511
def to_int(self)
Definition: z3py.py:10703
def is_digit(self)
Definition: z3py.py:10709
def __le__(self, other)
Definition: z3py.py:10699
def to_bv(self)
Definition: z3py.py:10706
def __repr__(self)
Definition: z3py.py:6793
def __ne__(self, other)
Definition: z3py.py:6790
def __init__(self, r)
Definition: z3py.py:6781
def __deepcopy__(self, memo={})
Definition: z3py.py:6784
def __eq__(self, other)
Definition: z3py.py:6787
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:5077
def __init__(self, name, ctx=None)
Definition: z3py.py:5033
def declare(self, name, *args)
Definition: z3py.py:5053
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:5043
def __repr__(self)
Definition: z3py.py:5074
def __deepcopy__(self, memo={})
Definition: z3py.py:5038
def sort(self)
Definition: z3py.py:5314
def recognizer(self, idx)
Definition: z3py.py:5249
def num_constructors(self)
Definition: z3py.py:5217
def constructor(self, idx)
Definition: z3py.py:5230
def accessor(self, i, j)
Definition: z3py.py:5277
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 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 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:9706
def exponent(self, biased=True)
Definition: z3py.py:9665
def significand(self)
Definition: z3py.py:9634
def sign_as_bv(self)
Definition: z3py.py:9624
def isNegative(self)
Definition: z3py.py:9721
def significand_as_bv(self)
Definition: z3py.py:9655
def exponent_as_long(self, biased=True)
Definition: z3py.py:9675
def isInf(self)
Definition: z3py.py:9696
def isNaN(self)
Definition: z3py.py:9691
def sign(self)
Definition: z3py.py:9612
def isZero(self)
Definition: z3py.py:9701
def significand_as_long(self)
Definition: z3py.py:9644
def isSubnormal(self)
Definition: z3py.py:9711
def isPositive(self)
Definition: z3py.py:9716
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9686
def as_string(self)
Definition: z3py.py:9732
def as_string(self)
Definition: z3py.py:9526
def __pos__(self)
Definition: z3py.py:9465
def sort(self)
Definition: z3py.py:9348
def __radd__(self, other)
Definition: z3py.py:9404
def __add__(self, other)
Definition: z3py.py:9391
def sbits(self)
Definition: z3py.py:9367
def __lt__(self, other)
Definition: z3py.py:9382
def __neg__(self)
Definition: z3py.py:9469
def ebits(self)
Definition: z3py.py:9359
def __rmul__(self, other)
Definition: z3py.py:9452
def __le__(self, other)
Definition: z3py.py:9379
def __mul__(self, other)
Definition: z3py.py:9437
def __mod__(self, other)
Definition: z3py.py:9514
def __rsub__(self, other)
Definition: z3py.py:9427
def __rtruediv__(self, other)
Definition: z3py.py:9510
def __rdiv__(self, other)
Definition: z3py.py:9493
def __ge__(self, other)
Definition: z3py.py:9385
def __truediv__(self, other)
Definition: z3py.py:9506
def __gt__(self, other)
Definition: z3py.py:9388
def __sub__(self, other)
Definition: z3py.py:9414
def as_string(self)
Definition: z3py.py:9375
def __rmod__(self, other)
Definition: z3py.py:9518
def __div__(self, other)
Definition: z3py.py:9478
def sbits(self)
Definition: z3py.py:9245
def ebits(self)
Definition: z3py.py:9237
def cast(self, val)
Definition: z3py.py:9253
def as_long(self)
Definition: z3py.py:7672
def as_string(self)
Definition: z3py.py:7684
def sort(self)
Definition: z3py.py:7647
def as_string(self)
Definition: z3py.py:7651
Fixedpoint.
Definition: z3py.py:7347
def insert(self, *args)
Definition: z3py.py:7408
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7598
def fact(self, head, name=None)
Definition: z3py.py:7439
def reason_unknown(self)
Definition: z3py.py:7584
def rule(self, head, body=None, name=None)
Definition: z3py.py:7435
def to_string(self, queries)
Definition: z3py.py:7571
def add_cover(self, level, predicate, property)
Definition: z3py.py:7523
def add(self, *args)
Definition: z3py.py:7396
def __del__(self)
Definition: z3py.py:7364
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7412
def param_descrs(self)
Definition: z3py.py:7378
def assert_exprs(self, *args)
Definition: z3py.py:7382
def get_answer(self)
Definition: z3py.py:7490
def statistics(self)
Definition: z3py.py:7579
def update_rule(self, head, body, name)
Definition: z3py.py:7481
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7465
def append(self, *args)
Definition: z3py.py:7404
def query(self, *query)
Definition: z3py.py:7443
def parse_string(self, s)
Definition: z3py.py:7545
def help(self)
Definition: z3py.py:7374
def get_rules_along_trace(self)
Definition: z3py.py:7500
def get_ground_sat_answer(self)
Definition: z3py.py:7495
def __repr__(self)
Definition: z3py.py:7561
def get_rules(self)
Definition: z3py.py:7553
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7535
def sexpr(self)
Definition: z3py.py:7565
def get_assertions(self)
Definition: z3py.py:7557
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7516
def __deepcopy__(self, memo={})
Definition: z3py.py:7361
def get_num_levels(self, predicate)
Definition: z3py.py:7512
def declare_var(self, *vars)
Definition: z3py.py:7589
def parse_file(self, f)
Definition: z3py.py:7549
def set(self, *args, **keys)
Definition: z3py.py:7368
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:7350
def register_relation(self, *relations)
Definition: z3py.py:7529
def get_rule_names_along_trace(self)
Definition: z3py.py:7504
def __iadd__(self, fml)
Definition: z3py.py:7400
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:6096
def __del__(self)
Definition: z3py.py:6107
ctx
Definition: z3py.py:6101
def value(self)
Definition: z3py.py:6160
def __init__(self, entry, ctx)
Definition: z3py.py:6099
def arg_value(self, idx)
Definition: z3py.py:6129
entry
Definition: z3py.py:6100
def __repr__(self)
Definition: z3py.py:6201
def num_args(self)
Definition: z3py.py:6111
def __deepcopy__(self, memo={})
Definition: z3py.py:6104
def as_list(self)
Definition: z3py.py:6182
def __del__(self)
Definition: z3py.py:6214
def arity(self)
Definition: z3py.py:6257
def __init__(self, f, ctx)
Definition: z3py.py:6208
def translate(self, other_ctx)
Definition: z3py.py:6291
def __repr__(self)
Definition: z3py.py:6319
def num_entries(self)
Definition: z3py.py:6241
def __deepcopy__(self, memo={})
Definition: z3py.py:6299
def else_value(self)
Definition: z3py.py:6218
def __copy__(self)
Definition: z3py.py:6296
def as_list(self)
Definition: z3py.py:6302
def entry(self, idx)
Definition: z3py.py:6271
def insert(self, *args)
Definition: z3py.py:5671
def dimacs(self, include_names=True)
Definition: z3py.py:5729
def get(self, i)
Definition: z3py.py:5617
def depth(self)
Definition: z3py.py:5525
def convert_model(self, model)
Definition: z3py.py:5693
def add(self, *args)
Definition: z3py.py:5682
def __del__(self)
Definition: z3py.py:5521
def assert_exprs(self, *args)
Definition: z3py.py:5645
def __getitem__(self, arg)
Definition: z3py.py:5630
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5511
def size(self)
Definition: z3py.py:5591
def append(self, *args)
Definition: z3py.py:5660
def __len__(self)
Definition: z3py.py:5604
def as_expr(self)
Definition: z3py.py:5782
def __repr__(self)
Definition: z3py.py:5722
def sexpr(self)
Definition: z3py.py:5725
def precision(self)
Definition: z3py.py:5582
def translate(self, target)
Definition: z3py.py:5733
def __deepcopy__(self, memo={})
Definition: z3py.py:5759
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5762
def __copy__(self)
Definition: z3py.py:5756
def inconsistent(self)
Definition: z3py.py:5543
def prec(self)
Definition: z3py.py:5561
def as_long(self)
Definition: z3py.py:2922
def as_binary_string(self)
Definition: z3py.py:2943
def as_string(self)
Definition: z3py.py:2935
def decls(self)
Definition: z3py.py:6571
def get_universe(self, s)
Definition: z3py.py:6506
def __del__(self)
Definition: z3py.py:6332
def eval(self, t, model_completion=False)
Definition: z3py.py:6343
def __init__(self, m, ctx)
Definition: z3py.py:6326
def sorts(self)
Definition: z3py.py:6489
def __getitem__(self, idx)
Definition: z3py.py:6526
def __len__(self)
Definition: z3py.py:6400
def update_value(self, x, value)
Definition: z3py.py:6590
def num_sorts(self)
Definition: z3py.py:6451
def __repr__(self)
Definition: z3py.py:6336
def sexpr(self)
Definition: z3py.py:6339
def translate(self, target)
Definition: z3py.py:6599
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6374
def __deepcopy__(self, memo={})
Definition: z3py.py:6610
def __copy__(self)
Definition: z3py.py:6607
def get_interp(self, decl)
Definition: z3py.py:6417
def get_sort(self, idx)
Definition: z3py.py:6466
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7857
def reason_unknown(self)
Definition: z3py.py:7914
def objectives(self)
Definition: z3py.py:7960
def pop(self)
Definition: z3py.py:7901
def maximize(self, arg)
Definition: z3py.py:7881
def unsat_core(self)
Definition: z3py.py:7925
def from_string(self, s)
Definition: z3py.py:7952
def add(self, *args)
Definition: z3py.py:7820
def __del__(self)
Definition: z3py.py:7787
def param_descrs(self)
Definition: z3py.py:7804
def assert_exprs(self, *args)
Definition: z3py.py:7808
def model(self)
Definition: z3py.py:7918
def statistics(self)
Definition: z3py.py:7974
def help(self)
Definition: z3py.py:7800
def upper_values(self, obj)
Definition: z3py.py:7943
def __repr__(self)
Definition: z3py.py:7964
def from_file(self, filename)
Definition: z3py.py:7948
def set_on_model(self, on_model)
Definition: z3py.py:7979
def sexpr(self)
Definition: z3py.py:7968
def check(self, *assumptions)
Definition: z3py.py:7905
def push(self)
Definition: z3py.py:7897
def __deepcopy__(self, memo={})
Definition: z3py.py:7784
def minimize(self, arg)
Definition: z3py.py:7889
def lower(self, obj)
Definition: z3py.py:7928
def assert_and_track(self, a, p)
Definition: z3py.py:7828
def set(self, *args, **keys)
Definition: z3py.py:7793
def upper(self, obj)
Definition: z3py.py:7933
def lower_values(self, obj)
Definition: z3py.py:7938
def __init__(self, ctx=None)
Definition: z3py.py:7778
def assertions(self)
Definition: z3py.py:7956
def __iadd__(self, fml)
Definition: z3py.py:7824
def __str__(self)
Definition: z3py.py:7760
def upper(self)
Definition: z3py.py:7742
def value(self)
Definition: z3py.py:7754
def lower_values(self)
Definition: z3py.py:7746
def __init__(self, opt, value, is_max)
Definition: z3py.py:7733
def lower(self)
Definition: z3py.py:7738
def upper_values(self)
Definition: z3py.py:7750
def get_name(self, i)
Definition: z3py.py:5472
def get_kind(self, n)
Definition: z3py.py:5477
def __del__(self)
Definition: z3py.py:5458
def __getitem__(self, arg)
Definition: z3py.py:5487
def size(self)
Definition: z3py.py:5462
def __init__(self, descr, ctx=None)
Definition: z3py.py:5449
def __len__(self)
Definition: z3py.py:5467
def __repr__(self)
Definition: z3py.py:5493
def get_documentation(self, n)
Definition: z3py.py:5482
def __deepcopy__(self, memo={})
Definition: z3py.py:5455
Parameter Sets.
Definition: z3py.py:5376
def validate(self, ds)
Definition: z3py.py:5417
def __del__(self)
Definition: z3py.py:5393
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5382
def __repr__(self)
Definition: z3py.py:5414
def __deepcopy__(self, memo={})
Definition: z3py.py:5390
def set(self, name, val)
Definition: z3py.py:5397
Patterns.
Definition: z3py.py:1884
def get_id(self)
Definition: z3py.py:1892
def as_ast(self)
Definition: z3py.py:1889
def __del__(self)
Definition: z3py.py:8428
def __call__(self, goal)
Definition: z3py.py:8517
def __lt__(self, other)
Definition: z3py.py:8432
def __le__(self, other)
Definition: z3py.py:8460
def __init__(self, probe, ctx=None)
Definition: z3py.py:8402
def __ne__(self, other)
Definition: z3py.py:8502
def __ge__(self, other)
Definition: z3py.py:8474
def __deepcopy__(self, memo={})
Definition: z3py.py:8425
def __eq__(self, other)
Definition: z3py.py:8488
def __gt__(self, other)
Definition: z3py.py:8446
def set(self, ctx, r)
Definition: z3py.py:11213
def insert(self, r)
Definition: z3py.py:11220
def set_threaded(self)
Definition: z3py.py:11200
def get(self, ctx)
Definition: z3py.py:11205
def __init__(self)
Definition: z3py.py:11196
Quantifiers.
Definition: z3py.py:1951
def pattern(self, idx)
Definition: z3py.py:2041
def sort(self)
Definition: z3py.py:1960
def var_name(self, idx)
Definition: z3py.py:2092
def no_pattern(self, idx)
Definition: z3py.py:2063
def is_forall(self)
Definition: z3py.py:1966
def num_no_patterns(self)
Definition: z3py.py:2059
def body(self)
Definition: z3py.py:2069
def num_vars(self)
Definition: z3py.py:2080
def get_id(self)
Definition: z3py.py:1957
def __getitem__(self, arg)
Definition: z3py.py:2008
def children(self)
Definition: z3py.py:2124
def weight(self)
Definition: z3py.py:2015
def is_lambda(self)
Definition: z3py.py:1994
def as_ast(self)
Definition: z3py.py:1954
def var_sort(self, idx)
Definition: z3py.py:2108
def num_patterns(self)
Definition: z3py.py:2029
def is_exists(self)
Definition: z3py.py:1980
def is_real(self)
Definition: z3py.py:3008
def as_decimal(self, prec)
Definition: z3py.py:3018
def as_fraction(self)
Definition: z3py.py:3039
def is_int_value(self)
Definition: z3py.py:3011
def numerator_as_long(self)
Definition: z3py.py:2981
def as_long(self)
Definition: z3py.py:3014
def denominator(self)
Definition: z3py.py:2970
def denominator_as_long(self)
Definition: z3py.py:2994
def is_int(self)
Definition: z3py.py:3005
def numerator(self)
Definition: z3py.py:2955
def as_string(self)
Definition: z3py.py:3030
def __add__(self, other)
Definition: z3py.py:11029
def basis(self)
Definition: z3py.py:11013
def __del__(self)
Definition: z3py.py:5101
def __init__(self, c, ctx)
Definition: z3py.py:5097
def __init__(self, c, ctx)
Definition: z3py.py:5109
def sort(self)
Definition: z3py.py:10642
def __radd__(self, other)
Definition: z3py.py:10648
def at(self, i)
Definition: z3py.py:10656
def __add__(self, other)
Definition: z3py.py:10645
def __lt__(self, other)
Definition: z3py.py:10678
def is_string_value(self)
Definition: z3py.py:10664
def __le__(self, other)
Definition: z3py.py:10675
def __ge__(self, other)
Definition: z3py.py:10681
def __gt__(self, other)
Definition: z3py.py:10684
def is_string(self)
Definition: z3py.py:10661
def as_string(self)
Definition: z3py.py:10667
def __getitem__(self, i)
Definition: z3py.py:10651
Strings, Sequences and Regular expressions.
Definition: z3py.py:10590
def basis(self)
Definition: z3py.py:10604
def is_string(self)
Definition: z3py.py:10593
def insert(self, *args)
Definition: z3py.py:6979
def dimacs(self, include_names=True)
Definition: z3py.py:7284
def non_units(self)
Definition: z3py.py:7192
def reason_unknown(self)
Definition: z3py.py:7228
backtrack_level
Definition: z3py.py:6831
def num_scopes(self)
Definition: z3py.py:6902
def unsat_core(self)
Definition: z3py.py:7072
def trail_levels(self)
Definition: z3py.py:7197
def trail(self)
Definition: z3py.py:7205
def from_string(self, s)
Definition: z3py.py:7137
def add(self, *args)
Definition: z3py.py:6953
def __del__(self)
Definition: z3py.py:6841
def import_model_converter(self, other)
Definition: z3py.py:7068
def param_descrs(self)
Definition: z3py.py:7245
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6828
def reset(self)
Definition: z3py.py:6920
def assert_exprs(self, *args)
Definition: z3py.py:6934
def pop(self, num=1)
Definition: z3py.py:6880
def units(self)
Definition: z3py.py:7187
def cube(self, vars=None)
Definition: z3py.py:7141
def cube_vars(self)
Definition: z3py.py:7162
def model(self)
Definition: z3py.py:7049
def statistics(self)
Definition: z3py.py:7210
def append(self, *args)
Definition: z3py.py:6968
def to_smt2(self)
Definition: z3py.py:7288
def help(self)
Definition: z3py.py:7241
def __repr__(self)
Definition: z3py.py:7249
def from_file(self, filename)
Definition: z3py.py:7133
def proof(self)
Definition: z3py.py:7169
def sexpr(self)
Definition: z3py.py:7272
def check(self, *assumptions)
Definition: z3py.py:7020
def translate(self, target)
Definition: z3py.py:7253
def push(self)
Definition: z3py.py:6858
def __deepcopy__(self, memo={})
Definition: z3py.py:7269
def consequences(self, assumptions, variables)
Definition: z3py.py:7104
def assert_and_track(self, a, p)
Definition: z3py.py:6990
def set(self, *args, **keys)
Definition: z3py.py:6845
def __copy__(self)
Definition: z3py.py:7266
def assertions(self)
Definition: z3py.py:7173
def __iadd__(self, fml)
Definition: z3py.py:6964
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:6637
def __getattr__(self, name)
Definition: z3py.py:6740
def __del__(self)
Definition: z3py.py:6648
def __getitem__(self, idx)
Definition: z3py.py:6684
def __len__(self)
Definition: z3py.py:6670
def keys(self)
Definition: z3py.py:6708
def __init__(self, stats, ctx)
Definition: z3py.py:6640
def __repr__(self)
Definition: z3py.py:6652
def get_key_value(self, key)
Definition: z3py.py:6720
def __deepcopy__(self, memo={})
Definition: z3py.py:6645
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:8155
def __del__(self)
Definition: z3py.py:8117
def param_descrs(self)
Definition: z3py.py:8169
def solver(self, logFile=None)
Definition: z3py.py:8121
def __init__(self, tactic, ctx=None)
Definition: z3py.py:8100
def help(self)
Definition: z3py.py:8165
def __deepcopy__(self, memo={})
Definition: z3py.py:8114
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:8138
def ctx_ref(self)
Definition: z3py.py:11345
def add_fixed(self, fixed)
Definition: z3py.py:11348
def conflict(self, deps)
Definition: z3py.py:11397
def __del__(self)
Definition: z3py.py:11335
def add_diseq(self, diseq)
Definition: z3py.py:11366
def pop(self, num_scopes)
Definition: z3py.py:11375
def add_eq(self, eq)
Definition: z3py.py:11360
def add(self, e)
Definition: z3py.py:11381
def __init__(self, s, ctx=None)
Definition: z3py.py:11309
def propagate(self, e, ids, eqs=[])
Definition: z3py.py:11389
def add_final(self, final)
Definition: z3py.py:11354
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_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 first occurrence of substr in s starting from offset offset. If s does not contain su...
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 the last occurrence of substr in s. If s does not contain substr, then the value is -1,...
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...
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:3823
def fpIsNegative(a, ctx=None)
Definition: z3py.py:10236
def fpAbs(a, ctx=None)
Definition: z3py.py:9980
def is_pattern(a)
Definition: z3py.py:1896
def StrToInt(s)
Definition: z3py.py:10963
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:10325
def RNE(ctx=None)
Definition: z3py.py:9536
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:10354
def AtLeast(*args)
Definition: z3py.py:8839
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:11183
def BVRedOr(a)
Definition: z3py.py:4412
def is_lt(a)
Definition: z3py.py:2841
def Empty(s)
Definition: z3py.py:10820
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10430
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10466
def SRem(a, b)
Definition: z3py.py:4238
def OrElse(*ts, **ks)
Definition: z3py.py:8239
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:10071
def RealVarVector(n, ctx=None)
Definition: z3py.py:1461
def z3_debug()
Definition: z3py.py:62
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:9531
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:10189
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4461
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9110
def PbGe(args, k)
Definition: z3py.py:8895
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4447
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:9155
def is_mod(a)
Definition: z3py.py:2817
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10410
def IntSort(ctx=None)
Definition: z3py.py:3098
def Float16(ctx=None)
Definition: z3py.py:9269
def reset_params()
Definition: z3py.py:289
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8680
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:8279
def substitute_vars(t, *m)
Definition: z3py.py:8744
def is_var(a)
Definition: z3py.py:1277
def SetAdd(s, e)
Definition: z3py.py:4926
def is_gt(a)
Definition: z3py.py:2865
def is_fp_sort(s)
Definition: z3py.py:9321
def fpToReal(x, ctx=None)
Definition: z3py.py:10538
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1719
def IsSubset(a, b)
Definition: z3py.py:4980
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3997
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:8328
def EmptySet(s)
Definition: z3py.py:4882
def is_rational_value(a)
Definition: z3py.py:2716
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:4021
def Abs(arg)
Definition: z3py.py:8816
def DeclareSort(name, ctx=None)
Definition: z3py.py:687
def Float64(ctx=None)
Definition: z3py.py:9293
def user_prop_push(ctx)
Definition: z3py.py:11240
def With(t, *args, **keys)
Definition: z3py.py:8300
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5422
def PbEq(args, k, ctx=None)
Definition: z3py.py:8906
def StrToCode(s)
Definition: z3py.py:10986
def ToReal(a)
Definition: z3py.py:3318
def PrefixOf(a, b)
Definition: z3py.py:10860
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:10183
def Reals(names, ctx=None)
Definition: z3py.py:3274
def is_and(a)
Definition: z3py.py:1584
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:10289
def Xor(a, b, ctx=None)
Definition: z3py.py:1762
def Unit(a)
Definition: z3py.py:10855
def is_fprm_sort(s)
Definition: z3py.py:9332
def ULE(a, b)
Definition: z3py.py:4124
def Star(re)
Definition: z3py.py:11120
def Lambda(vs, body)
Definition: z3py.py:2224
def Diff(a, b, ctx=None)
Definition: z3py.py:11158
def is_bv(a)
Definition: z3py.py:3904
def SetDifference(a, b)
Definition: z3py.py:4958
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7695
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:9179
def is_array(a)
Definition: z3py.py:4571
def z3_error_handler(c, e)
Definition: z3py.py:174
def TryFor(t, ms, ctx=None)
Definition: z3py.py:8349
def simplify_param_descrs()
Definition: z3py.py:8710
def Length(s)
Definition: z3py.py:10953
def ensure_prop_closures()
Definition: z3py.py:11234
def help_simplify()
Definition: z3py.py:8705
def fpIsPositive(a, ctx=None)
Definition: z3py.py:10242
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2185
def Re(s, ctx=None)
Definition: z3py.py:10998
def Sqrt(a, ctx=None)
Definition: z3py.py:3371
def Select(a, *args)
Definition: z3py.py:4767
def set_option(*args, **kws)
Definition: z3py.py:295
def is_as_array(n)
Definition: z3py.py:6619
def fpEQ(a, b, ctx=None)
Definition: z3py.py:10301
def UGE(a, b)
Definition: z3py.py:4160
def CharVal(ch, ctx=None)
Definition: z3py.py:10713
def Extract(high, low, a)
Definition: z3py.py:4088
def fpNaN(s)
Definition: z3py.py:9825
def Q(a, b, ctx=None)
Definition: z3py.py:3195
def is_bv_sort(s)
Definition: z3py.py:3436
def append_log(s)
Definition: z3py.py:119
def is_string_value(a)
Definition: z3py.py:10777
def SetIntersect(*args)
Definition: z3py.py:4913
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4426
def SeqSort(s)
Definition: z3py.py:10630
def is_const_array(a)
Definition: z3py.py:4585
def get_default_fp_sort(ctx=None)
Definition: z3py.py:9188
def is_array_sort(a)
Definition: z3py.py:4567
def Product(*args)
Definition: z3py.py:8791
def Consts(names, sort)
Definition: z3py.py:1416
def fpIsZero(a, ctx=None)
Definition: z3py.py:10218
def Ext(a, b)
Definition: z3py.py:4828
def Range(lo, hi, ctx=None)
Definition: z3py.py:11146
def get_var_index(a)
Definition: z3py.py:1302
def set_param(*args, **kws)
Definition: z3py.py:265
def Bools(names, ctx=None)
Definition: z3py.py:1703
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:10484
def fpZero(s, negative)
Definition: z3py.py:9884
def CharToInt(ch, ctx=None)
Definition: z3py.py:10730
def FloatQuadruple(ctx=None)
Definition: z3py.py:9311
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:10516
def RTZ(ctx=None)
Definition: z3py.py:9576
def BVRedAnd(a)
Definition: z3py.py:4405
def Const(name, sort)
Definition: z3py.py:1404
def RealSort(ctx=None)
Definition: z3py.py:3115
def ZeroExt(n, a)
Definition: z3py.py:4353
def fpMax(a, b, ctx=None)
Definition: z3py.py:10162
def AllChar(regex_sort, ctx=None)
Definition: z3py.py:11163
def SetSort(s)
Sets.
Definition: z3py.py:4877
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9891
def get_ctx(ctx)
Definition: z3py.py:261
def fpMinusInfinity(s)
Definition: z3py.py:9859
def is_int_value(a)
Definition: z3py.py:2692
def mk_not(a)
Definition: z3py.py:1797
def is_distinct(a)
Definition: z3py.py:1642
def solve_using(s, *args, **keywords)
Definition: z3py.py:8947
def FloatDouble(ctx=None)
Definition: z3py.py:9299
def LinearOrder(a, index)
Definition: z3py.py:11175
def RTN(ctx=None)
Definition: z3py.py:9566
def probe_description(name, ctx=None)
Definition: z3py.py:8575
def get_param(name)
Definition: z3py.py:301
def IndexOf(s, substr, offset=None)
Definition: z3py.py:10924
def is_fprm(a)
Definition: z3py.py:9581
def is_store(a)
Definition: z3py.py:4859
def StrFromCode(c)
Definition: z3py.py:10992
def RotateLeft(a, b)
Definition: z3py.py:4291
def Function(name, *sig)
Definition: z3py.py:857
def user_prop_fixed(ctx, cb, id, value)
Definition: z3py.py:11260
def Update(a, *args)
Definition: z3py.py:4707
def UDiv(a, b)
Definition: z3py.py:4196
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:7328
def is_K(a)
Definition: z3py.py:4598
def FreshInt(prefix="x", ctx=None)
Definition: z3py.py:3247
def K(dom, v)
Definition: z3py.py:4806
def Replace(s, src, dst)
Definition: z3py.py:10909
def ArraySort(*sig)
Definition: z3py.py:4660
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:7307
def LShR(a, b)
Definition: z3py.py:4259
def FreshBool(prefix="b", ctx=None)
Definition: z3py.py:1734
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4419
def SignExt(n, a)
Definition: z3py.py:4323
def SubString(s, offset, length)
Definition: z3py.py:10810
def FullSet(s)
Definition: z3py.py:4891
def Not(a, ctx=None)
Definition: z3py.py:1778
def RecAddDefinition(f, args, body)
Definition: z3py.py:921
def fpRem(a, b, ctx=None)
Definition: z3py.py:10133
def is_expr(a)
Definition: z3py.py:1209
def FreshFunction(*sig)
Definition: z3py.py:880
def Var(idx, s)
Definition: z3py.py:1437
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3980
def Intersect(*args)
Definition: z3py.py:11071
def Loop(re, lo, hi=0)
Definition: z3py.py:11133
def If(a, b, c, ctx=None)
Definition: z3py.py:1348
def WithParams(t, p)
Definition: z3py.py:8314
def is_ge(a)
Definition: z3py.py:2853
def Concat(*args)
Definition: z3py.py:4042
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10448
def BV2Int(a, is_signed=False)
Definition: z3py.py:3933
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8663
def is_idiv(a)
Definition: z3py.py:2805
def FailIf(p, ctx=None)
Definition: z3py.py:8621
def is_fp(a)
Definition: z3py.py:9737
def When(p, t, ctx=None)
Definition: z3py.py:8643
def Default(a)
Definition: z3py.py:4739
def PartialOrder(a, index)
Definition: z3py.py:11171
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:9541
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3234
def get_full_version()
Definition: z3py.py:101
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9961
def BVSubNoOverflow(a, b)
Definition: z3py.py:4433
def is_add(a)
Definition: z3py.py:2752
def is_to_int(a)
Definition: z3py.py:2904
def TransitiveClosure(f)
Definition: z3py.py:11187
def solve(*args, **keywords)
Definition: z3py.py:8917
def CharFromBv(ch, ctx=None)
Definition: z3py.py:10721
def FloatSingle(ctx=None)
Definition: z3py.py:9287
def user_prop_pop(ctx, num_scopes)
Definition: z3py.py:11244
def RTP(ctx=None)
Definition: z3py.py:9556
def is_is_int(a)
Definition: z3py.py:2877
def get_version_string()
Definition: z3py.py:83
def AndThen(*ts, **ks)
Definition: z3py.py:8206
def open_log(fname)
Definition: z3py.py:114
def fpIsNaN(a, ctx=None)
Definition: z3py.py:10195
def PbLe(args, k)
Definition: z3py.py:8884
def Float32(ctx=None)
Definition: z3py.py:9281
def is_to_real(a)
Definition: z3py.py:2889
def user_prop_fresh(id, ctx)
Definition: z3py.py:11248
def AtMost(*args)
Definition: z3py.py:8821
def is_func_decl(a)
Definition: z3py.py:844
def RealVar(idx, ctx=None)
Definition: z3py.py:1450
def is_false(a)
Definition: z3py.py:1570
def describe_probes()
Definition: z3py.py:8584
def SubSeq(s, offset, length)
Definition: z3py.py:10815
def StringSort(ctx=None)
Definition: z3py.py:10611
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:10313
def Store(a, *args)
Definition: z3py.py:4750
def Ints(names, ctx=None)
Definition: z3py.py:3221
def SetHasSize(a, k)
Definition: z3py.py:4840
def fpIsNormal(a, ctx=None)
Definition: z3py.py:10224
def BoolSort(ctx=None)
Definition: z3py.py:1654
def SetComplement(s)
Definition: z3py.py:4948
def is_sub(a)
Definition: z3py.py:2776
def RatVal(a, b, ctx=None)
Definition: z3py.py:3179
def Then(*ts, **ks)
Definition: z3py.py:8226
def fpMin(a, b, ctx=None)
Definition: z3py.py:10147
def is_mul(a)
Definition: z3py.py:2764
def SuffixOf(a, b)
Definition: z3py.py:10875
def probes(ctx=None)
Definition: z3py.py:8564
def fpPlusZero(s)
Definition: z3py.py:9872
def fpLT(a, b, ctx=None)
Definition: z3py.py:10253
def is_fprm_value(a)
Definition: z3py.py:9594
def EnumSort(name, values, ctx=None)
Definition: z3py.py:5343
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2203
def RotateRight(a, b)
Definition: z3py.py:4307
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:10088
def CharIsDigit(ch, ctx=None)
Definition: z3py.py:10734
def Cbrt(a, ctx=None)
Definition: z3py.py:3384
def IsInt(a)
Definition: z3py.py:3354
def Union(*args)
Definition: z3py.py:11051
def is_finite_domain_sort(s)
Definition: z3py.py:7633
def LastIndexOf(s, substr)
Definition: z3py.py:10944
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9131
def IntToStr(s)
Definition: z3py.py:10979
def ReSort(s)
Definition: z3py.py:11017
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3289
def FloatHalf(ctx=None)
Definition: z3py.py:9275
def Array(name, *sorts)
Definition: z3py.py:4693
def is_finite_domain_value(a)
Definition: z3py.py:7710
def is_bool(a)
Definition: z3py.py:1534
def Distinct(*args)
Definition: z3py.py:1371
def is_int(a)
Definition: z3py.py:2646
def UGT(a, b)
Definition: z3py.py:4178
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:10558
def is_map(a)
Definition: z3py.py:4611
def fpMinusZero(s)
Definition: z3py.py:9878
def Map(f, *args)
Definition: z3py.py:4783
def is_bv_value(a)
Definition: z3py.py:3918
def is_const(a)
Definition: z3py.py:1258
def is_app_of(a, k)
Definition: z3py.py:1335
def is_sort(s)
Definition: z3py.py:641
def fpPlusInfinity(s)
Definition: z3py.py:9842
def ULT(a, b)
Definition: z3py.py:4142
def TreeOrder(a, index)
Definition: z3py.py:11179
def FreshConst(sort, prefix="c")
Definition: z3py.py:1431
def Implies(a, b, ctx=None)
Definition: z3py.py:1748
def BVSNegNoOverflow(a)
Definition: z3py.py:4454
def get_as_array_func(n)
Definition: z3py.py:6624
def is_quantifier(a)
Definition: z3py.py:2136
def RNA(ctx=None)
Definition: z3py.py:9546
def RoundTowardZero(ctx=None)
Definition: z3py.py:9571
def is_seq(a)
Definition: z3py.py:10759
def Float128(ctx=None)
Definition: z3py.py:9305
def RealVal(val, ctx=None)
Definition: z3py.py:3160
def Int(name, ctx=None)
Definition: z3py.py:3208
def Or(*args)
Definition: z3py.py:1845
def is_probe(p)
Definition: z3py.py:8546
def is_algebraic_value(a)
Definition: z3py.py:2738
def RepeatBitVec(n, a)
Definition: z3py.py:4381
def Option(re)
Definition: z3py.py:11102
def String(name, ctx=None)
Definition: z3py.py:10793
def tactics(ctx=None)
Definition: z3py.py:8358
def Int2BV(a, num_bits)
Definition: z3py.py:3956
def user_prop_final(ctx, cb)
Definition: z3py.py:11268
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:10265
def is_finite_domain(a)
Definition: z3py.py:7656
def is_string(a)
Definition: z3py.py:10769
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7625
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:10118
def user_prop_eq(ctx, cb, x, y)
Definition: z3py.py:11274
def CharSort(ctx=None)
Definition: z3py.py:10620
def ToInt(a)
Definition: z3py.py:3336
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9937
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4440
def RecFunction(name, *sig)
Definition: z3py.py:903
def user_prop_diseq(ctx, cb, x, y)
Definition: z3py.py:11282
def Bool(name, ctx=None)
Definition: z3py.py:1691
def Plus(re)
Definition: z3py.py:11089
def is_eq(a)
Definition: z3py.py:1632
def ParOr(*ts, **ks)
Definition: z3py.py:8260
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:10393
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9561
def is_ast(a)
Definition: z3py.py:445
def fpGT(a, b, ctx=None)
Definition: z3py.py:10277
def CharToBv(ch, ctx=None)
Definition: z3py.py:10726
def MultiPattern(*args)
Definition: z3py.py:1914
def is_not(a)
Definition: z3py.py:1620
def to_Ast(ptr)
Definition: z3py.py:11255
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9766
def eq(a, b)
Definition: z3py.py:466
def Complement(re)
Definition: z3py.py:11115
def disable_trace(msg)
Definition: z3py.py:79
def is_le(a)
Definition: z3py.py:2829
def is_real(a)
Definition: z3py.py:2665
def tactic_description(name, ctx=None)
Definition: z3py.py:8369
def is_app(a)
Definition: z3py.py:1232
def Strings(names, ctx=None)
Definition: z3py.py:10802
def Contains(a, b)
Definition: z3py.py:10890
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4468
def IsMember(e, s)
Definition: z3py.py:4969
def get_version()
Definition: z3py.py:92
def CreateDatatypes(*ds)
Definition: z3py.py:5118
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:5319
def get_map_func(a)
Definition: z3py.py:4636
def SetDel(s, e)
Definition: z3py.py:4937
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:10103
def is_default(a)
Definition: z3py.py:4627
def StringVal(s, ctx=None)
Definition: z3py.py:10786
def Full(s)
Definition: z3py.py:10840
def Sum(*args)
Definition: z3py.py:8765
def InRe(s, re)
Definition: z3py.py:11037
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:8295
def is_arith_sort(s)
Definition: z3py.py:2324
def RoundTowardPositive(ctx=None)
Definition: z3py.py:9551
def is_true(a)
Definition: z3py.py:1552
def substitute(t, *m)
Definition: z3py.py:8715
def BoolVal(val, ctx=None)
Definition: z3py.py:1672
def FreshReal(prefix="b", ctx=None)
Definition: z3py.py:3304
def URem(a, b)
Definition: z3py.py:4217
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:10177
def main_ctx()
Definition: z3py.py:233
def describe_tactics()
Definition: z3py.py:8378
def is_implies(a)
Definition: z3py.py:1608
def is_fp_value(a)
Definition: z3py.py:9751
def Real(name, ctx=None)
Definition: z3py.py:3261
def is_div(a)
Definition: z3py.py:2788
def is_select(a)
Definition: z3py.py:4846
def fpIsInf(a, ctx=None)
Definition: z3py.py:10207
def And(*args)
Definition: z3py.py:1812
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:9192
def is_arith(a)
Definition: z3py.py:2625
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:10230
def is_or(a)
Definition: z3py.py:1596
def fpNeg(a, ctx=None)
Definition: z3py.py:10003
def SetUnion(*args)
Definition: z3py.py:4900
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:5331
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:10494
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3965
def Model(ctx=None)
Definition: z3py.py:6614
def fpInfinity(s, negative)
Definition: z3py.py:9865
def is_re(s)
Definition: z3py.py:11033
def IntVal(val, ctx=None)
Definition: z3py.py:3148
def prove(claim, show=False, **keywords)
Definition: z3py.py:8978