Z3
z3py.py
Go to the documentation of this file.
8
9"""Z3 is a high performance theorem prover developed at Microsoft Research.
10
11Z3 is used in many applications such as: software/hardware verification and testing,
12constraint solving, analysis of hybrid systems, security, biology (in silico analysis),
13and geometrical problems.
14
15Several online tutorials for Z3Py are available at:
16http://rise4fun.com/Z3Py/tutorial/guide
17
18Please send feedback, comments and/or corrections on the Issue tracker for
19https://github.com/Z3prover/z3.git. Your comments are very valuable.
20
21Small example:
22
23>>> x = Int('x')
24>>> y = Int('y')
25>>> s = Solver()
26>>> s.add(x > 0)
27>>> s.add(x < 2)
28>>> s.add(y == x + 1)
29>>> s.check()
30sat
31>>> m = s.model()
32>>> m[x]
331
34>>> m[y]
352
36
37Z3 exceptions:
38
39>>> try:
40... x = BitVec('x', 32)
41... y = Bool('y')
42... # the expression x + y is type incorrect
43... n = x + y
44... except Z3Exception as ex:
45... print("failed: %s" % ex)
46failed: sort mismatch
47"""
48from . import z3core
49from .z3core import *
50from .z3types import *
51from .z3consts import *
52from .z3printer import *
53from fractions import Fraction
54import sys
55import io
56import math
57import copy
58if sys.version_info.major >= 3:
59 from typing import Iterable
60
61Z3_DEBUG = __debug__
62
63
65 global Z3_DEBUG
66 return Z3_DEBUG
67
68
69if sys.version_info.major < 3:
70 def _is_int(v):
71 return isinstance(v, (int, long))
72else:
73 def _is_int(v):
74 return isinstance(v, int)
75
76
77def enable_trace(msg):
79
80
83
84
86 major = ctypes.c_uint(0)
87 minor = ctypes.c_uint(0)
88 build = ctypes.c_uint(0)
89 rev = ctypes.c_uint(0)
90 Z3_get_version(major, minor, build, rev)
91 return "%s.%s.%s" % (major.value, minor.value, build.value)
92
93
95 major = ctypes.c_uint(0)
96 minor = ctypes.c_uint(0)
97 build = ctypes.c_uint(0)
98 rev = ctypes.c_uint(0)
99 Z3_get_version(major, minor, build, rev)
100 return (major.value, minor.value, build.value, rev.value)
101
102
104 return Z3_get_full_version()
105
106# We use _z3_assert instead of the assert command because we want to
107# produce nice error messages in Z3Py at rise4fun.com
108
109
110def _z3_assert(cond, msg):
111 if not cond:
112 raise Z3Exception(msg)
113
114
115def _z3_check_cint_overflow(n, name):
116 _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
117
118
119def open_log(fname):
120 """Log interaction to a file. This function must be invoked immediately after init(). """
121 Z3_open_log(fname)
122
123
125 """Append user-defined string to interaction log. """
127
128
129def to_symbol(s, ctx=None):
130 """Convert an integer or string into a Z3 symbol."""
131 if _is_int(s):
132 return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
133 else:
134 return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
135
136
137def _symbol2py(ctx, s):
138 """Convert a Z3 symbol back into a Python object. """
139 if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
140 return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
141 else:
142 return Z3_get_symbol_string(ctx.ref(), s)
143
144# Hack for having nary functions that can receive one argument that is the
145# list of arguments.
146# Use this when function takes a single list of arguments
147
148
149def _get_args(args):
150 try:
151 if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
152 return args[0]
153 elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
154 return [arg for arg in args[0]]
155 else:
156 return args
157 except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?)
158 return args
159
160# Use this when function takes multiple arguments
161
162
163def _get_args_ast_list(args):
164 try:
165 if isinstance(args, (set, AstVector, tuple)):
166 return [arg for arg in args]
167 else:
168 return args
169 except Exception:
170 return args
171
172
173def _to_param_value(val):
174 if isinstance(val, bool):
175 return "true" if val else "false"
176 return str(val)
177
178
180 # Do nothing error handler, just avoid exit(0)
181 # The wrappers in z3core.py will raise a Z3Exception if an error is detected
182 return
183
184
185class Context:
186 """A Context manages all other Z3 objects, global configuration options, etc.
187
188 Z3Py uses a default global context. For most applications this is sufficient.
189 An application may use multiple Z3 contexts. Objects created in one context
190 cannot be used in another one. However, several objects may be "translated" from
191 one context to another. It is not safe to access Z3 objects from multiple threads.
192 The only exception is the method `interrupt()` that can be used to interrupt() a long
193 computation.
194 The initialization method receives global configuration options for the new context.
195 """
196
197 def __init__(self, *args, **kws):
198 if z3_debug():
199 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
200 conf = Z3_mk_config()
201 for key in kws:
202 value = kws[key]
203 Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
204 prev = None
205 for a in args:
206 if prev is None:
207 prev = a
208 else:
209 Z3_set_param_value(conf, str(prev), _to_param_value(a))
210 prev = None
212 self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
213 Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
214 Z3_del_config(conf)
215
216 def __del__(self):
217 Z3_del_context(self.ctx)
218 self.ctx = None
219 self.eh = None
220
221 def ref(self):
222 """Return a reference to the actual C pointer to the Z3 context."""
223 return self.ctx
224
225 def interrupt(self):
226 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
227
228 This method can be invoked from a thread different from the one executing the
229 interruptible procedure.
230 """
231 Z3_interrupt(self.ref())
232
233
234# Global Z3 context
235_main_ctx = None
236
237
239 """Return a reference to the global Z3 context.
240
241 >>> x = Real('x')
242 >>> x.ctx == main_ctx()
243 True
244 >>> c = Context()
245 >>> c == main_ctx()
246 False
247 >>> x2 = Real('x', c)
248 >>> x2.ctx == c
249 True
250 >>> eq(x, x2)
251 False
252 """
253 global _main_ctx
254 if _main_ctx is None:
255 _main_ctx = Context()
256 return _main_ctx
257
258
259def _get_ctx(ctx):
260 if ctx is None:
261 return main_ctx()
262 else:
263 return ctx
264
265
266def get_ctx(ctx):
267 return _get_ctx(ctx)
268
269
270def set_param(*args, **kws):
271 """Set Z3 global (or module) parameters.
272
273 >>> set_param(precision=10)
274 """
275 if z3_debug():
276 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
277 new_kws = {}
278 for k in kws:
279 v = kws[k]
280 if not set_pp_option(k, v):
281 new_kws[k] = v
282 for key in new_kws:
283 value = new_kws[key]
284 Z3_global_param_set(str(key).upper(), _to_param_value(value))
285 prev = None
286 for a in args:
287 if prev is None:
288 prev = a
289 else:
290 Z3_global_param_set(str(prev), _to_param_value(a))
291 prev = None
292
293
295 """Reset all global (or module) parameters.
296 """
298
299
300def set_option(*args, **kws):
301 """Alias for 'set_param' for backward compatibility.
302 """
303 return set_param(*args, **kws)
304
305
306def get_param(name):
307 """Return the value of a Z3 global (or module) parameter
308
309 >>> get_param('nlsat.reorder')
310 'true'
311 """
312 ptr = (ctypes.c_char_p * 1)()
313 if Z3_global_param_get(str(name), ptr):
314 r = z3core._to_pystr(ptr[0])
315 return r
316 raise Z3Exception("failed to retrieve value for '%s'" % name)
317
318
323
324# Mark objects that use pretty printer
325
326
328 """Superclass for all Z3 objects that have support for pretty printing."""
329
330 def use_pp(self):
331 return True
332
333 def _repr_html_(self):
334 in_html = in_html_mode()
335 set_html_mode(True)
336 res = repr(self)
337 set_html_mode(in_html)
338 return res
339
340
342 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
343
344 def __init__(self, ast, ctx=None):
345 self.ast = ast
346 self.ctx = _get_ctx(ctx)
347 Z3_inc_ref(self.ctx.ref(), self.as_ast())
348
349 def __del__(self):
350 if self.ctx.ref() is not None and self.ast is not None:
351 Z3_dec_ref(self.ctx.ref(), self.as_ast())
352 self.ast = None
353
354 def __deepcopy__(self, memo={}):
355 return _to_ast_ref(self.ast, self.ctx)
356
357 def __str__(self):
358 return obj_to_string(self)
359
360 def __repr__(self):
361 return obj_to_string(self)
362
363 def __eq__(self, other):
364 return self.eq(other)
365
366 def __hash__(self):
367 return self.hash()
368
369 def __nonzero__(self):
370 return self.__bool__()
371
372 def __bool__(self):
373 if is_true(self):
374 return True
375 elif is_false(self):
376 return False
377 elif is_eq(self) and self.num_args() == 2:
378 return self.arg(0).eq(self.arg(1))
379 else:
380 raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
381
382 def sexpr(self):
383 """Return a string representing the AST node in s-expression notation.
384
385 >>> x = Int('x')
386 >>> ((x + 1)*x).sexpr()
387 '(* (+ x 1) x)'
388 """
389 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
390
391 def as_ast(self):
392 """Return a pointer to the corresponding C Z3_ast object."""
393 return self.ast
394
395 def get_id(self):
396 """Return unique identifier for object. It can be used for hash-tables and maps."""
397 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
398
399 def ctx_ref(self):
400 """Return a reference to the C context where this AST node is stored."""
401 return self.ctx.ref()
402
403 def eq(self, other):
404 """Return `True` if `self` and `other` are structurally identical.
405
406 >>> x = Int('x')
407 >>> n1 = x + 1
408 >>> n2 = 1 + x
409 >>> n1.eq(n2)
410 False
411 >>> n1 = simplify(n1)
412 >>> n2 = simplify(n2)
413 >>> n1.eq(n2)
414 True
415 """
416 if z3_debug():
417 _z3_assert(is_ast(other), "Z3 AST expected")
418 return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
419
420 def translate(self, target):
421 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
422
423 >>> c1 = Context()
424 >>> c2 = Context()
425 >>> x = Int('x', c1)
426 >>> y = Int('y', c2)
427 >>> # Nodes in different contexts can't be mixed.
428 >>> # However, we can translate nodes from one context to another.
429 >>> x.translate(c2) + y
430 x + y
431 """
432 if z3_debug():
433 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
434 return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
435
436 def __copy__(self):
437 return self.translate(self.ctx)
438
439 def hash(self):
440 """Return a hashcode for the `self`.
441
442 >>> n1 = simplify(Int('x') + 1)
443 >>> n2 = simplify(2 + Int('x') - 1)
444 >>> n1.hash() == n2.hash()
445 True
446 """
447 return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
448
449
450def is_ast(a):
451 """Return `True` if `a` is an AST node.
452
453 >>> is_ast(10)
454 False
455 >>> is_ast(IntVal(10))
456 True
457 >>> is_ast(Int('x'))
458 True
459 >>> is_ast(BoolSort())
460 True
461 >>> is_ast(Function('f', IntSort(), IntSort()))
462 True
463 >>> is_ast("x")
464 False
465 >>> is_ast(Solver())
466 False
467 """
468 return isinstance(a, AstRef)
469
470
471def eq(a, b):
472 """Return `True` if `a` and `b` are structurally identical AST nodes.
473
474 >>> x = Int('x')
475 >>> y = Int('y')
476 >>> eq(x, y)
477 False
478 >>> eq(x + 1, x + 1)
479 True
480 >>> eq(x + 1, 1 + x)
481 False
482 >>> eq(simplify(x + 1), simplify(1 + x))
483 True
484 """
485 if z3_debug():
486 _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
487 return a.eq(b)
488
489
490def _ast_kind(ctx, a):
491 if is_ast(a):
492 a = a.as_ast()
493 return Z3_get_ast_kind(ctx.ref(), a)
494
495
496def _ctx_from_ast_arg_list(args, default_ctx=None):
497 ctx = None
498 for a in args:
499 if is_ast(a) or is_probe(a):
500 if ctx is None:
501 ctx = a.ctx
502 else:
503 if z3_debug():
504 _z3_assert(ctx == a.ctx, "Context mismatch")
505 if ctx is None:
506 ctx = default_ctx
507 return ctx
508
509
510def _ctx_from_ast_args(*args):
511 return _ctx_from_ast_arg_list(args)
512
513
514def _to_func_decl_array(args):
515 sz = len(args)
516 _args = (FuncDecl * sz)()
517 for i in range(sz):
518 _args[i] = args[i].as_func_decl()
519 return _args, sz
520
521
522def _to_ast_array(args):
523 sz = len(args)
524 _args = (Ast * sz)()
525 for i in range(sz):
526 _args[i] = args[i].as_ast()
527 return _args, sz
528
529
530def _to_ref_array(ref, args):
531 sz = len(args)
532 _args = (ref * sz)()
533 for i in range(sz):
534 _args[i] = args[i].as_ast()
535 return _args, sz
536
537
538def _to_ast_ref(a, ctx):
539 k = _ast_kind(ctx, a)
540 if k == Z3_SORT_AST:
541 return _to_sort_ref(a, ctx)
542 elif k == Z3_FUNC_DECL_AST:
543 return _to_func_decl_ref(a, ctx)
544 else:
545 return _to_expr_ref(a, ctx)
546
547
548
553
554def _sort_kind(ctx, s):
555 return Z3_get_sort_kind(ctx.ref(), s)
556
557
559 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
560
561 def as_ast(self):
562 return Z3_sort_to_ast(self.ctx_ref(), self.ast)
563
564 def get_id(self):
565 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
566
567 def kind(self):
568 """Return the Z3 internal kind of a sort.
569 This method can be used to test if `self` is one of the Z3 builtin sorts.
570
571 >>> b = BoolSort()
572 >>> b.kind() == Z3_BOOL_SORT
573 True
574 >>> b.kind() == Z3_INT_SORT
575 False
576 >>> A = ArraySort(IntSort(), IntSort())
577 >>> A.kind() == Z3_ARRAY_SORT
578 True
579 >>> A.kind() == Z3_INT_SORT
580 False
581 """
582 return _sort_kind(self.ctx, self.ast)
583
584 def subsort(self, other):
585 """Return `True` if `self` is a subsort of `other`.
586
587 >>> IntSort().subsort(RealSort())
588 True
589 """
590 return False
591
592 def cast(self, val):
593 """Try to cast `val` as an element of sort `self`.
594
595 This method is used in Z3Py to convert Python objects such as integers,
596 floats, longs and strings into Z3 expressions.
597
598 >>> x = Int('x')
599 >>> RealSort().cast(x)
600 ToReal(x)
601 """
602 if z3_debug():
603 _z3_assert(is_expr(val), "Z3 expression expected")
604 _z3_assert(self.eq(val.sort()), "Sort mismatch")
605 return val
606
607 def name(self):
608 """Return the name (string) of sort `self`.
609
610 >>> BoolSort().name()
611 'Bool'
612 >>> ArraySort(IntSort(), IntSort()).name()
613 'Array'
614 """
615 return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
616
617 def __eq__(self, other):
618 """Return `True` if `self` and `other` are the same Z3 sort.
619
620 >>> p = Bool('p')
621 >>> p.sort() == BoolSort()
622 True
623 >>> p.sort() == IntSort()
624 False
625 """
626 if other is None:
627 return False
628 return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
629
630 def __ne__(self, other):
631 """Return `True` if `self` and `other` are not the same Z3 sort.
632
633 >>> p = Bool('p')
634 >>> p.sort() != BoolSort()
635 False
636 >>> p.sort() != IntSort()
637 True
638 """
639 return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
640
641 def __hash__(self):
642 """ Hash code. """
643 return AstRef.__hash__(self)
644
645
646def is_sort(s):
647 """Return `True` if `s` is a Z3 sort.
648
649 >>> is_sort(IntSort())
650 True
651 >>> is_sort(Int('x'))
652 False
653 >>> is_expr(Int('x'))
654 True
655 """
656 return isinstance(s, SortRef)
657
658
659def _to_sort_ref(s, ctx):
660 if z3_debug():
661 _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
662 k = _sort_kind(ctx, s)
663 if k == Z3_BOOL_SORT:
664 return BoolSortRef(s, ctx)
665 elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
666 return ArithSortRef(s, ctx)
667 elif k == Z3_BV_SORT:
668 return BitVecSortRef(s, ctx)
669 elif k == Z3_ARRAY_SORT:
670 return ArraySortRef(s, ctx)
671 elif k == Z3_DATATYPE_SORT:
672 return DatatypeSortRef(s, ctx)
673 elif k == Z3_FINITE_DOMAIN_SORT:
674 return FiniteDomainSortRef(s, ctx)
675 elif k == Z3_FLOATING_POINT_SORT:
676 return FPSortRef(s, ctx)
677 elif k == Z3_ROUNDING_MODE_SORT:
678 return FPRMSortRef(s, ctx)
679 elif k == Z3_RE_SORT:
680 return ReSortRef(s, ctx)
681 elif k == Z3_SEQ_SORT:
682 return SeqSortRef(s, ctx)
683 return SortRef(s, ctx)
684
685
686def _sort(ctx, a):
687 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
688
689
690def DeclareSort(name, ctx=None):
691 """Create a new uninterpreted sort named `name`.
692
693 If `ctx=None`, then the new sort is declared in the global Z3Py context.
694
695 >>> A = DeclareSort('A')
696 >>> a = Const('a', A)
697 >>> b = Const('b', A)
698 >>> a.sort() == A
699 True
700 >>> b.sort() == A
701 True
702 >>> a == b
703 a == b
704 """
705 ctx = _get_ctx(ctx)
706 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
707
708
713
714
716 """Function declaration. Every constant and function have an associated declaration.
717
718 The declaration assigns a name, a sort (i.e., type), and for function
719 the sort (i.e., type) of each of its arguments. Note that, in Z3,
720 a constant is a function with 0 arguments.
721 """
722
723 def as_ast(self):
724 return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
725
726 def get_id(self):
727 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
728
729 def as_func_decl(self):
730 return self.ast
731
732 def name(self):
733 """Return the name of the function declaration `self`.
734
735 >>> f = Function('f', IntSort(), IntSort())
736 >>> f.name()
737 'f'
738 >>> isinstance(f.name(), str)
739 True
740 """
741 return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
742
743 def arity(self):
744 """Return the number of arguments of a function declaration.
745 If `self` is a constant, then `self.arity()` is 0.
746
747 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
748 >>> f.arity()
749 2
750 """
751 return int(Z3_get_arity(self.ctx_ref(), self.ast))
752
753 def domain(self, i):
754 """Return the sort of the argument `i` of a function declaration.
755 This method assumes that `0 <= i < self.arity()`.
756
757 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
758 >>> f.domain(0)
759 Int
760 >>> f.domain(1)
761 Real
762 """
763 if z3_debug():
764 _z3_assert(i < self.arity(), "Index out of bounds")
765 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
766
767 def range(self):
768 """Return the sort of the range of a function declaration.
769 For constants, this is the sort of the constant.
770
771 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
772 >>> f.range()
773 Bool
774 """
775 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
776
777 def kind(self):
778 """Return the internal kind of a function declaration.
779 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
780
781 >>> x = Int('x')
782 >>> d = (x + 1).decl()
783 >>> d.kind() == Z3_OP_ADD
784 True
785 >>> d.kind() == Z3_OP_MUL
786 False
787 """
788 return Z3_get_decl_kind(self.ctx_ref(), self.ast)
789
790 def params(self):
791 ctx = self.ctx
792 n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
793 result = [None for i in range(n)]
794 for i in range(n):
795 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
796 if k == Z3_PARAMETER_INT:
797 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
798 elif k == Z3_PARAMETER_DOUBLE:
799 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
800 elif k == Z3_PARAMETER_RATIONAL:
801 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
802 elif k == Z3_PARAMETER_SYMBOL:
803 result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
804 elif k == Z3_PARAMETER_SORT:
805 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
806 elif k == Z3_PARAMETER_AST:
807 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
808 elif k == Z3_PARAMETER_FUNC_DECL:
809 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
810 else:
811 assert(False)
812 return result
813
814 def __call__(self, *args):
815 """Create a Z3 application expression using the function `self`, and the given arguments.
816
817 The arguments must be Z3 expressions. This method assumes that
818 the sorts of the elements in `args` match the sorts of the
819 domain. Limited coercion is supported. For example, if
820 args[0] is a Python integer, and the function expects a Z3
821 integer, then the argument is automatically converted into a
822 Z3 integer.
823
824 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
825 >>> x = Int('x')
826 >>> y = Real('y')
827 >>> f(x, y)
828 f(x, y)
829 >>> f(x, x)
830 f(x, ToReal(x))
831 """
832 args = _get_args(args)
833 num = len(args)
834 if z3_debug():
835 _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
836 _args = (Ast * num)()
837 saved = []
838 for i in range(num):
839 # self.domain(i).cast(args[i]) may create a new Z3 expression,
840 # then we must save in 'saved' to prevent it from being garbage collected.
841 tmp = self.domain(i).cast(args[i])
842 saved.append(tmp)
843 _args[i] = tmp.as_ast()
844 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
845
846
848 """Return `True` if `a` is a Z3 function declaration.
849
850 >>> f = Function('f', IntSort(), IntSort())
851 >>> is_func_decl(f)
852 True
853 >>> x = Real('x')
854 >>> is_func_decl(x)
855 False
856 """
857 return isinstance(a, FuncDeclRef)
858
859
860def Function(name, *sig):
861 """Create a new Z3 uninterpreted function with the given sorts.
862
863 >>> f = Function('f', IntSort(), IntSort())
864 >>> f(f(0))
865 f(f(0))
866 """
867 sig = _get_args(sig)
868 if z3_debug():
869 _z3_assert(len(sig) > 0, "At least two arguments expected")
870 arity = len(sig) - 1
871 rng = sig[arity]
872 if z3_debug():
873 _z3_assert(is_sort(rng), "Z3 sort expected")
874 dom = (Sort * arity)()
875 for i in range(arity):
876 if z3_debug():
877 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
878 dom[i] = sig[i].ast
879 ctx = rng.ctx
880 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
881
882
884 """Create a new fresh Z3 uninterpreted function with the given sorts.
885 """
886 sig = _get_args(sig)
887 if z3_debug():
888 _z3_assert(len(sig) > 0, "At least two arguments expected")
889 arity = len(sig) - 1
890 rng = sig[arity]
891 if z3_debug():
892 _z3_assert(is_sort(rng), "Z3 sort expected")
893 dom = (z3.Sort * arity)()
894 for i in range(arity):
895 if z3_debug():
896 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
897 dom[i] = sig[i].ast
898 ctx = rng.ctx
899 return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
900
901
902def _to_func_decl_ref(a, ctx):
903 return FuncDeclRef(a, ctx)
904
905
906def RecFunction(name, *sig):
907 """Create a new Z3 recursive with the given sorts."""
908 sig = _get_args(sig)
909 if z3_debug():
910 _z3_assert(len(sig) > 0, "At least two arguments expected")
911 arity = len(sig) - 1
912 rng = sig[arity]
913 if z3_debug():
914 _z3_assert(is_sort(rng), "Z3 sort expected")
915 dom = (Sort * arity)()
916 for i in range(arity):
917 if z3_debug():
918 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
919 dom[i] = sig[i].ast
920 ctx = rng.ctx
921 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
922
923
924def RecAddDefinition(f, args, body):
925 """Set the body of a recursive function.
926 Recursive definitions can be simplified if they are applied to ground
927 arguments.
928 >>> ctx = Context()
929 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
930 >>> n = Int('n', ctx)
931 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
932 >>> simplify(fac(5))
933 120
934 >>> s = Solver(ctx=ctx)
935 >>> s.add(fac(n) < 3)
936 >>> s.check()
937 sat
938 >>> s.model().eval(fac(5))
939 120
940 """
941 if is_app(args):
942 args = [args]
943 ctx = body.ctx
944 args = _get_args(args)
945 n = len(args)
946 _args = (Ast * n)()
947 for i in range(n):
948 _args[i] = args[i].ast
949 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
950
951
956
957
959 """Constraints, formulas and terms are expressions in Z3.
960
961 Expressions are ASTs. Every expression has a sort.
962 There are three main kinds of expressions:
963 function applications, quantifiers and bounded variables.
964 A constant is a function application with 0 arguments.
965 For quantifier free problems, all expressions are
966 function applications.
967 """
968
969 def as_ast(self):
970 return self.ast
971
972 def get_id(self):
973 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
974
975 def sort(self):
976 """Return the sort of expression `self`.
977
978 >>> x = Int('x')
979 >>> (x + 1).sort()
980 Int
981 >>> y = Real('y')
982 >>> (x + y).sort()
983 Real
984 """
985 return _sort(self.ctx, self.as_astas_ast())
986
987 def sort_kind(self):
988 """Shorthand for `self.sort().kind()`.
989
990 >>> a = Array('a', IntSort(), IntSort())
991 >>> a.sort_kind() == Z3_ARRAY_SORT
992 True
993 >>> a.sort_kind() == Z3_INT_SORT
994 False
995 """
996 return self.sort().kind()
997
998 def __eq__(self, other):
999 """Return a Z3 expression that represents the constraint `self == other`.
1000
1001 If `other` is `None`, then this method simply returns `False`.
1002
1003 >>> a = Int('a')
1004 >>> b = Int('b')
1005 >>> a == b
1006 a == b
1007 >>> a is None
1008 False
1009 """
1010 if other is None:
1011 return False
1012 a, b = _coerce_exprs(self, other)
1013 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
1014
1015 def __hash__(self):
1016 """ Hash code. """
1017 return AstRef.__hash__(self)
1018
1019 def __ne__(self, other):
1020 """Return a Z3 expression that represents the constraint `self != other`.
1021
1022 If `other` is `None`, then this method simply returns `True`.
1023
1024 >>> a = Int('a')
1025 >>> b = Int('b')
1026 >>> a != b
1027 a != b
1028 >>> a is not None
1029 True
1030 """
1031 if other is None:
1032 return True
1033 a, b = _coerce_exprs(self, other)
1034 _args, sz = _to_ast_array((a, b))
1035 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
1036
1037 def params(self):
1038 return self.decl().params()
1039
1040 def decl(self):
1041 """Return the Z3 function declaration associated with a Z3 application.
1042
1043 >>> f = Function('f', IntSort(), IntSort())
1044 >>> a = Int('a')
1045 >>> t = f(a)
1046 >>> eq(t.decl(), f)
1047 True
1048 >>> (a + 1).decl()
1049 +
1050 """
1051 if z3_debug():
1052 _z3_assert(is_app(self), "Z3 application expected")
1053 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1054
1055 def num_args(self):
1056 """Return the number of arguments of a Z3 application.
1057
1058 >>> a = Int('a')
1059 >>> b = Int('b')
1060 >>> (a + b).num_args()
1061 2
1062 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1063 >>> t = f(a, b, 0)
1064 >>> t.num_args()
1065 3
1066 """
1067 if z3_debug():
1068 _z3_assert(is_app(self), "Z3 application expected")
1069 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_astas_ast()))
1070
1071 def arg(self, idx):
1072 """Return argument `idx` of the application `self`.
1073
1074 This method assumes that `self` is a function application with at least `idx+1` arguments.
1075
1076 >>> a = Int('a')
1077 >>> b = Int('b')
1078 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1079 >>> t = f(a, b, 0)
1080 >>> t.arg(0)
1081 a
1082 >>> t.arg(1)
1083 b
1084 >>> t.arg(2)
1085 0
1086 """
1087 if z3_debug():
1088 _z3_assert(is_app(self), "Z3 application expected")
1089 _z3_assert(idx < self.num_args(), "Invalid argument index")
1090 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_astas_ast(), idx), self.ctx)
1091
1092 def children(self):
1093 """Return a list containing the children of the given expression
1094
1095 >>> a = Int('a')
1096 >>> b = Int('b')
1097 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1098 >>> t = f(a, b, 0)
1099 >>> t.children()
1100 [a, b, 0]
1101 """
1102 if is_app(self):
1103 return [self.arg(i) for i in range(self.num_args())]
1104 else:
1105 return []
1106
1107
1108def _to_expr_ref(a, ctx):
1109 if isinstance(a, Pattern):
1110 return PatternRef(a, ctx)
1111 ctx_ref = ctx.ref()
1112 k = Z3_get_ast_kind(ctx_ref, a)
1113 if k == Z3_QUANTIFIER_AST:
1114 return QuantifierRef(a, ctx)
1115 sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1116 if sk == Z3_BOOL_SORT:
1117 return BoolRef(a, ctx)
1118 if sk == Z3_INT_SORT:
1119 if k == Z3_NUMERAL_AST:
1120 return IntNumRef(a, ctx)
1121 return ArithRef(a, ctx)
1122 if sk == Z3_REAL_SORT:
1123 if k == Z3_NUMERAL_AST:
1124 return RatNumRef(a, ctx)
1125 if _is_algebraic(ctx, a):
1126 return AlgebraicNumRef(a, ctx)
1127 return ArithRef(a, ctx)
1128 if sk == Z3_BV_SORT:
1129 if k == Z3_NUMERAL_AST:
1130 return BitVecNumRef(a, ctx)
1131 else:
1132 return BitVecRef(a, ctx)
1133 if sk == Z3_ARRAY_SORT:
1134 return ArrayRef(a, ctx)
1135 if sk == Z3_DATATYPE_SORT:
1136 return DatatypeRef(a, ctx)
1137 if sk == Z3_FLOATING_POINT_SORT:
1138 if k == Z3_APP_AST and _is_numeral(ctx, a):
1139 return FPNumRef(a, ctx)
1140 else:
1141 return FPRef(a, ctx)
1142 if sk == Z3_FINITE_DOMAIN_SORT:
1143 if k == Z3_NUMERAL_AST:
1144 return FiniteDomainNumRef(a, ctx)
1145 else:
1146 return FiniteDomainRef(a, ctx)
1147 if sk == Z3_ROUNDING_MODE_SORT:
1148 return FPRMRef(a, ctx)
1149 if sk == Z3_SEQ_SORT:
1150 return SeqRef(a, ctx)
1151 if sk == Z3_RE_SORT:
1152 return ReRef(a, ctx)
1153 return ExprRef(a, ctx)
1154
1155
1156def _coerce_expr_merge(s, a):
1157 if is_expr(a):
1158 s1 = a.sort()
1159 if s is None:
1160 return s1
1161 if s1.eq(s):
1162 return s
1163 elif s.subsort(s1):
1164 return s1
1165 elif s1.subsort(s):
1166 return s
1167 else:
1168 if z3_debug():
1169 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1170 _z3_assert(False, "sort mismatch")
1171 else:
1172 return s
1173
1174
1175def _coerce_exprs(a, b, ctx=None):
1176 if not is_expr(a) and not is_expr(b):
1177 a = _py2expr(a, ctx)
1178 b = _py2expr(b, ctx)
1179 if isinstance(a, str) and isinstance(b, SeqRef):
1180 a = StringVal(a, b.ctx)
1181 if isinstance(b, str) and isinstance(a, SeqRef):
1182 b = StringVal(b, a.ctx)
1183 s = None
1184 s = _coerce_expr_merge(s, a)
1185 s = _coerce_expr_merge(s, b)
1186 a = s.cast(a)
1187 b = s.cast(b)
1188 return (a, b)
1189
1190
1191def _reduce(func, sequence, initial):
1192 result = initial
1193 for element in sequence:
1194 result = func(result, element)
1195 return result
1196
1197
1198def _coerce_expr_list(alist, ctx=None):
1199 has_expr = False
1200 for a in alist:
1201 if is_expr(a):
1202 has_expr = True
1203 break
1204 if not has_expr:
1205 alist = [_py2expr(a, ctx) for a in alist]
1206 s = _reduce(_coerce_expr_merge, alist, None)
1207 return [s.cast(a) for a in alist]
1208
1209
1210def is_expr(a):
1211 """Return `True` if `a` is a Z3 expression.
1212
1213 >>> a = Int('a')
1214 >>> is_expr(a)
1215 True
1216 >>> is_expr(a + 1)
1217 True
1218 >>> is_expr(IntSort())
1219 False
1220 >>> is_expr(1)
1221 False
1222 >>> is_expr(IntVal(1))
1223 True
1224 >>> x = Int('x')
1225 >>> is_expr(ForAll(x, x >= 0))
1226 True
1227 >>> is_expr(FPVal(1.0))
1228 True
1229 """
1230 return isinstance(a, ExprRef)
1231
1232
1233def is_app(a):
1234 """Return `True` if `a` is a Z3 function application.
1235
1236 Note that, constants are function applications with 0 arguments.
1237
1238 >>> a = Int('a')
1239 >>> is_app(a)
1240 True
1241 >>> is_app(a + 1)
1242 True
1243 >>> is_app(IntSort())
1244 False
1245 >>> is_app(1)
1246 False
1247 >>> is_app(IntVal(1))
1248 True
1249 >>> x = Int('x')
1250 >>> is_app(ForAll(x, x >= 0))
1251 False
1252 """
1253 if not isinstance(a, ExprRef):
1254 return False
1255 k = _ast_kind(a.ctx, a)
1256 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1257
1258
1260 """Return `True` if `a` is Z3 constant/variable expression.
1261
1262 >>> a = Int('a')
1263 >>> is_const(a)
1264 True
1265 >>> is_const(a + 1)
1266 False
1267 >>> is_const(1)
1268 False
1269 >>> is_const(IntVal(1))
1270 True
1271 >>> x = Int('x')
1272 >>> is_const(ForAll(x, x >= 0))
1273 False
1274 """
1275 return is_app(a) and a.num_args() == 0
1276
1277
1278def is_var(a):
1279 """Return `True` if `a` is variable.
1280
1281 Z3 uses de-Bruijn indices for representing bound variables in
1282 quantifiers.
1283
1284 >>> x = Int('x')
1285 >>> is_var(x)
1286 False
1287 >>> is_const(x)
1288 True
1289 >>> f = Function('f', IntSort(), IntSort())
1290 >>> # Z3 replaces x with bound variables when ForAll is executed.
1291 >>> q = ForAll(x, f(x) == x)
1292 >>> b = q.body()
1293 >>> b
1294 f(Var(0)) == Var(0)
1295 >>> b.arg(1)
1296 Var(0)
1297 >>> is_var(b.arg(1))
1298 True
1299 """
1300 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1301
1302
1304 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1305
1306 >>> x = Int('x')
1307 >>> y = Int('y')
1308 >>> is_var(x)
1309 False
1310 >>> is_const(x)
1311 True
1312 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1313 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1314 >>> q = ForAll([x, y], f(x, y) == x + y)
1315 >>> q.body()
1316 f(Var(1), Var(0)) == Var(1) + Var(0)
1317 >>> b = q.body()
1318 >>> b.arg(0)
1319 f(Var(1), Var(0))
1320 >>> v1 = b.arg(0).arg(0)
1321 >>> v2 = b.arg(0).arg(1)
1322 >>> v1
1323 Var(1)
1324 >>> v2
1325 Var(0)
1326 >>> get_var_index(v1)
1327 1
1328 >>> get_var_index(v2)
1329 0
1330 """
1331 if z3_debug():
1332 _z3_assert(is_var(a), "Z3 bound variable expected")
1333 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1334
1335
1336def is_app_of(a, k):
1337 """Return `True` if `a` is an application of the given kind `k`.
1338
1339 >>> x = Int('x')
1340 >>> n = x + 1
1341 >>> is_app_of(n, Z3_OP_ADD)
1342 True
1343 >>> is_app_of(n, Z3_OP_MUL)
1344 False
1345 """
1346 return is_app(a) and a.decl().kind() == k
1347
1348
1349def If(a, b, c, ctx=None):
1350 """Create a Z3 if-then-else expression.
1351
1352 >>> x = Int('x')
1353 >>> y = Int('y')
1354 >>> max = If(x > y, x, y)
1355 >>> max
1356 If(x > y, x, y)
1357 >>> simplify(max)
1358 If(x <= y, y, x)
1359 """
1360 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1361 return Cond(a, b, c, ctx)
1362 else:
1363 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1364 s = BoolSort(ctx)
1365 a = s.cast(a)
1366 b, c = _coerce_exprs(b, c, ctx)
1367 if z3_debug():
1368 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1369 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1370
1371
1372def Distinct(*args):
1373 """Create a Z3 distinct expression.
1374
1375 >>> x = Int('x')
1376 >>> y = Int('y')
1377 >>> Distinct(x, y)
1378 x != y
1379 >>> z = Int('z')
1380 >>> Distinct(x, y, z)
1381 Distinct(x, y, z)
1382 >>> simplify(Distinct(x, y, z))
1383 Distinct(x, y, z)
1384 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1385 And(Not(x == y), Not(x == z), Not(y == z))
1386 """
1387 args = _get_args(args)
1388 ctx = _ctx_from_ast_arg_list(args)
1389 if z3_debug():
1390 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1391 args = _coerce_expr_list(args, ctx)
1392 _args, sz = _to_ast_array(args)
1393 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1394
1395
1396def _mk_bin(f, a, b):
1397 args = (Ast * 2)()
1398 if z3_debug():
1399 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1400 args[0] = a.as_ast()
1401 args[1] = b.as_ast()
1402 return f(a.ctx.ref(), 2, args)
1403
1404
1405def Const(name, sort):
1406 """Create a constant of the given sort.
1407
1408 >>> Const('x', IntSort())
1409 x
1410 """
1411 if z3_debug():
1412 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1413 ctx = sort.ctx
1414 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1415
1416
1417def Consts(names, sort):
1418 """Create several constants of the given sort.
1419
1420 `names` is a string containing the names of all constants to be created.
1421 Blank spaces separate the names of different constants.
1422
1423 >>> x, y, z = Consts('x y z', IntSort())
1424 >>> x + y + z
1425 x + y + z
1426 """
1427 if isinstance(names, str):
1428 names = names.split(" ")
1429 return [Const(name, sort) for name in names]
1430
1431
1432def FreshConst(sort, prefix="c"):
1433 """Create a fresh constant of a specified sort"""
1434 ctx = _get_ctx(sort.ctx)
1435 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1436
1437
1438def Var(idx, s):
1439 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1440
1441 >>> Var(0, IntSort())
1442 Var(0)
1443 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1444 False
1445 """
1446 if z3_debug():
1447 _z3_assert(is_sort(s), "Z3 sort expected")
1448 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1449
1450
1451def RealVar(idx, ctx=None):
1452 """
1453 Create a real free variable. Free variables are used to create quantified formulas.
1454 They are also used to create polynomials.
1455
1456 >>> RealVar(0)
1457 Var(0)
1458 """
1459 return Var(idx, RealSort(ctx))
1460
1461
1462def RealVarVector(n, ctx=None):
1463 """
1464 Create a list of Real free variables.
1465 The variables have ids: 0, 1, ..., n-1
1466
1467 >>> x0, x1, x2, x3 = RealVarVector(4)
1468 >>> x2
1469 Var(2)
1470 """
1471 return [RealVar(i, ctx) for i in range(n)]
1472
1473
1478
1479
1481 """Boolean sort."""
1482
1483 def cast(self, val):
1484 """Try to cast `val` as a Boolean.
1485
1486 >>> x = BoolSort().cast(True)
1487 >>> x
1488 True
1489 >>> is_expr(x)
1490 True
1491 >>> is_expr(True)
1492 False
1493 >>> x.sort()
1494 Bool
1495 """
1496 if isinstance(val, bool):
1497 return BoolVal(val, self.ctx)
1498 if z3_debug():
1499 if not is_expr(val):
1500 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1501 _z3_assert(is_expr(val), msg % (val, type(val)))
1502 if not self.eq(val.sort()):
1503 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1504 return val
1505
1506 def subsort(self, other):
1507 return isinstance(other, ArithSortRef)
1508
1509 def is_int(self):
1510 return True
1511
1512 def is_bool(self):
1513 return True
1514
1515
1517 """All Boolean expressions are instances of this class."""
1518
1519 def sort(self):
1520 return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1521
1522 def __rmul__(self, other):
1523 return self * other
1524
1525 def __mul__(self, other):
1526 """Create the Z3 expression `self * other`.
1527 """
1528 if other == 1:
1529 return self
1530 if other == 0:
1531 return 0
1532 return If(self, other, 0)
1533
1534
1535def is_bool(a):
1536 """Return `True` if `a` is a Z3 Boolean expression.
1537
1538 >>> p = Bool('p')
1539 >>> is_bool(p)
1540 True
1541 >>> q = Bool('q')
1542 >>> is_bool(And(p, q))
1543 True
1544 >>> x = Real('x')
1545 >>> is_bool(x)
1546 False
1547 >>> is_bool(x == 0)
1548 True
1549 """
1550 return isinstance(a, BoolRef)
1551
1552
1553def is_true(a):
1554 """Return `True` if `a` is the Z3 true expression.
1555
1556 >>> p = Bool('p')
1557 >>> is_true(p)
1558 False
1559 >>> is_true(simplify(p == p))
1560 True
1561 >>> x = Real('x')
1562 >>> is_true(x == 0)
1563 False
1564 >>> # True is a Python Boolean expression
1565 >>> is_true(True)
1566 False
1567 """
1568 return is_app_of(a, Z3_OP_TRUE)
1569
1570
1572 """Return `True` if `a` is the Z3 false expression.
1573
1574 >>> p = Bool('p')
1575 >>> is_false(p)
1576 False
1577 >>> is_false(False)
1578 False
1579 >>> is_false(BoolVal(False))
1580 True
1581 """
1582 return is_app_of(a, Z3_OP_FALSE)
1583
1584
1585def is_and(a):
1586 """Return `True` if `a` is a Z3 and expression.
1587
1588 >>> p, q = Bools('p q')
1589 >>> is_and(And(p, q))
1590 True
1591 >>> is_and(Or(p, q))
1592 False
1593 """
1594 return is_app_of(a, Z3_OP_AND)
1595
1596
1597def is_or(a):
1598 """Return `True` if `a` is a Z3 or expression.
1599
1600 >>> p, q = Bools('p q')
1601 >>> is_or(Or(p, q))
1602 True
1603 >>> is_or(And(p, q))
1604 False
1605 """
1606 return is_app_of(a, Z3_OP_OR)
1607
1608
1610 """Return `True` if `a` is a Z3 implication expression.
1611
1612 >>> p, q = Bools('p q')
1613 >>> is_implies(Implies(p, q))
1614 True
1615 >>> is_implies(And(p, q))
1616 False
1617 """
1618 return is_app_of(a, Z3_OP_IMPLIES)
1619
1620
1621def is_not(a):
1622 """Return `True` if `a` is a Z3 not expression.
1623
1624 >>> p = Bool('p')
1625 >>> is_not(p)
1626 False
1627 >>> is_not(Not(p))
1628 True
1629 """
1630 return is_app_of(a, Z3_OP_NOT)
1631
1632
1633def is_eq(a):
1634 """Return `True` if `a` is a Z3 equality expression.
1635
1636 >>> x, y = Ints('x y')
1637 >>> is_eq(x == y)
1638 True
1639 """
1640 return is_app_of(a, Z3_OP_EQ)
1641
1642
1644 """Return `True` if `a` is a Z3 distinct expression.
1645
1646 >>> x, y, z = Ints('x y z')
1647 >>> is_distinct(x == y)
1648 False
1649 >>> is_distinct(Distinct(x, y, z))
1650 True
1651 """
1652 return is_app_of(a, Z3_OP_DISTINCT)
1653
1654
1655def BoolSort(ctx=None):
1656 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1657
1658 >>> BoolSort()
1659 Bool
1660 >>> p = Const('p', BoolSort())
1661 >>> is_bool(p)
1662 True
1663 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1664 >>> r(0, 1)
1665 r(0, 1)
1666 >>> is_bool(r(0, 1))
1667 True
1668 """
1669 ctx = _get_ctx(ctx)
1670 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1671
1672
1673def BoolVal(val, ctx=None):
1674 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1675
1676 >>> BoolVal(True)
1677 True
1678 >>> is_true(BoolVal(True))
1679 True
1680 >>> is_true(True)
1681 False
1682 >>> is_false(BoolVal(False))
1683 True
1684 """
1685 ctx = _get_ctx(ctx)
1686 if val:
1687 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1688 else:
1689 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1690
1691
1692def Bool(name, ctx=None):
1693 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1694
1695 >>> p = Bool('p')
1696 >>> q = Bool('q')
1697 >>> And(p, q)
1698 And(p, q)
1699 """
1700 ctx = _get_ctx(ctx)
1701 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1702
1703
1704def Bools(names, ctx=None):
1705 """Return a tuple of Boolean constants.
1706
1707 `names` is a single string containing all names separated by blank spaces.
1708 If `ctx=None`, then the global context is used.
1709
1710 >>> p, q, r = Bools('p q r')
1711 >>> And(p, Or(q, r))
1712 And(p, Or(q, r))
1713 """
1714 ctx = _get_ctx(ctx)
1715 if isinstance(names, str):
1716 names = names.split(" ")
1717 return [Bool(name, ctx) for name in names]
1718
1719
1720def BoolVector(prefix, sz, ctx=None):
1721 """Return a list of Boolean constants of size `sz`.
1722
1723 The constants are named using the given prefix.
1724 If `ctx=None`, then the global context is used.
1725
1726 >>> P = BoolVector('p', 3)
1727 >>> P
1728 [p__0, p__1, p__2]
1729 >>> And(P)
1730 And(p__0, p__1, p__2)
1731 """
1732 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1733
1734
1735def FreshBool(prefix="b", ctx=None):
1736 """Return a fresh Boolean constant in the given context using the given prefix.
1737
1738 If `ctx=None`, then the global context is used.
1739
1740 >>> b1 = FreshBool()
1741 >>> b2 = FreshBool()
1742 >>> eq(b1, b2)
1743 False
1744 """
1745 ctx = _get_ctx(ctx)
1746 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1747
1748
1749def Implies(a, b, ctx=None):
1750 """Create a Z3 implies expression.
1751
1752 >>> p, q = Bools('p q')
1753 >>> Implies(p, q)
1754 Implies(p, q)
1755 """
1756 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1757 s = BoolSort(ctx)
1758 a = s.cast(a)
1759 b = s.cast(b)
1760 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1761
1762
1763def Xor(a, b, ctx=None):
1764 """Create a Z3 Xor expression.
1765
1766 >>> p, q = Bools('p q')
1767 >>> Xor(p, q)
1768 Xor(p, q)
1769 >>> simplify(Xor(p, q))
1770 Not(p) == q
1771 """
1772 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1773 s = BoolSort(ctx)
1774 a = s.cast(a)
1775 b = s.cast(b)
1776 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1777
1778
1779def Not(a, ctx=None):
1780 """Create a Z3 not expression or probe.
1781
1782 >>> p = Bool('p')
1783 >>> Not(Not(p))
1784 Not(Not(p))
1785 >>> simplify(Not(Not(p)))
1786 p
1787 """
1788 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1789 if is_probe(a):
1790 # Not is also used to build probes
1791 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1792 else:
1793 s = BoolSort(ctx)
1794 a = s.cast(a)
1795 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1796
1797
1798def mk_not(a):
1799 if is_not(a):
1800 return a.arg(0)
1801 else:
1802 return Not(a)
1803
1804
1805def _has_probe(args):
1806 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1807 for arg in args:
1808 if is_probe(arg):
1809 return True
1810 return False
1811
1812
1813def And(*args):
1814 """Create a Z3 and-expression or and-probe.
1815
1816 >>> p, q, r = Bools('p q r')
1817 >>> And(p, q, r)
1818 And(p, q, r)
1819 >>> P = BoolVector('p', 5)
1820 >>> And(P)
1821 And(p__0, p__1, p__2, p__3, p__4)
1822 """
1823 last_arg = None
1824 if len(args) > 0:
1825 last_arg = args[len(args) - 1]
1826 if isinstance(last_arg, Context):
1827 ctx = args[len(args) - 1]
1828 args = args[:len(args) - 1]
1829 elif len(args) == 1 and isinstance(args[0], AstVector):
1830 ctx = args[0].ctx
1831 args = [a for a in args[0]]
1832 else:
1833 ctx = None
1834 args = _get_args(args)
1835 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1836 if z3_debug():
1837 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1838 if _has_probe(args):
1839 return _probe_and(args, ctx)
1840 else:
1841 args = _coerce_expr_list(args, ctx)
1842 _args, sz = _to_ast_array(args)
1843 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1844
1845
1846def Or(*args):
1847 """Create a Z3 or-expression or or-probe.
1848
1849 >>> p, q, r = Bools('p q r')
1850 >>> Or(p, q, r)
1851 Or(p, q, r)
1852 >>> P = BoolVector('p', 5)
1853 >>> Or(P)
1854 Or(p__0, p__1, p__2, p__3, p__4)
1855 """
1856 last_arg = None
1857 if len(args) > 0:
1858 last_arg = args[len(args) - 1]
1859 if isinstance(last_arg, Context):
1860 ctx = args[len(args) - 1]
1861 args = args[:len(args) - 1]
1862 elif len(args) == 1 and isinstance(args[0], AstVector):
1863 ctx = args[0].ctx
1864 args = [a for a in args[0]]
1865 else:
1866 ctx = None
1867 args = _get_args(args)
1868 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1869 if z3_debug():
1870 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1871 if _has_probe(args):
1872 return _probe_or(args, ctx)
1873 else:
1874 args = _coerce_expr_list(args, ctx)
1875 _args, sz = _to_ast_array(args)
1876 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1877
1878
1883
1884
1886 """Patterns are hints for quantifier instantiation.
1887
1888 """
1889
1890 def as_ast(self):
1891 return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1892
1893 def get_id(self):
1894 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1895
1896
1898 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1899
1900 >>> f = Function('f', IntSort(), IntSort())
1901 >>> x = Int('x')
1902 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1903 >>> q
1904 ForAll(x, f(x) == 0)
1905 >>> q.num_patterns()
1906 1
1907 >>> is_pattern(q.pattern(0))
1908 True
1909 >>> q.pattern(0)
1910 f(Var(0))
1911 """
1912 return isinstance(a, PatternRef)
1913
1914
1915def MultiPattern(*args):
1916 """Create a Z3 multi-pattern using the given expressions `*args`
1917
1918 >>> f = Function('f', IntSort(), IntSort())
1919 >>> g = Function('g', IntSort(), IntSort())
1920 >>> x = Int('x')
1921 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1922 >>> q
1923 ForAll(x, f(x) != g(x))
1924 >>> q.num_patterns()
1925 1
1926 >>> is_pattern(q.pattern(0))
1927 True
1928 >>> q.pattern(0)
1929 MultiPattern(f(Var(0)), g(Var(0)))
1930 """
1931 if z3_debug():
1932 _z3_assert(len(args) > 0, "At least one argument expected")
1933 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1934 ctx = args[0].ctx
1935 args, sz = _to_ast_array(args)
1936 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1937
1938
1939def _to_pattern(arg):
1940 if is_pattern(arg):
1941 return arg
1942 else:
1943 return MultiPattern(arg)
1944
1945
1950
1951
1953 """Universally and Existentially quantified formulas."""
1954
1955 def as_ast(self):
1956 return self.ast
1957
1958 def get_id(self):
1959 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1960
1961 def sort(self):
1962 """Return the Boolean sort or sort of Lambda."""
1963 if self.is_lambda():
1964 return _sort(self.ctx, self.as_astas_astas_ast())
1965 return BoolSort(self.ctx)
1966
1967 def is_forall(self):
1968 """Return `True` if `self` is a universal quantifier.
1969
1970 >>> f = Function('f', IntSort(), IntSort())
1971 >>> x = Int('x')
1972 >>> q = ForAll(x, f(x) == 0)
1973 >>> q.is_forall()
1974 True
1975 >>> q = Exists(x, f(x) != 0)
1976 >>> q.is_forall()
1977 False
1978 """
1979 return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1980
1981 def is_exists(self):
1982 """Return `True` if `self` is an existential quantifier.
1983
1984 >>> f = Function('f', IntSort(), IntSort())
1985 >>> x = Int('x')
1986 >>> q = ForAll(x, f(x) == 0)
1987 >>> q.is_exists()
1988 False
1989 >>> q = Exists(x, f(x) != 0)
1990 >>> q.is_exists()
1991 True
1992 """
1993 return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1994
1995 def is_lambda(self):
1996 """Return `True` if `self` is a lambda expression.
1997
1998 >>> f = Function('f', IntSort(), IntSort())
1999 >>> x = Int('x')
2000 >>> q = Lambda(x, f(x))
2001 >>> q.is_lambda()
2002 True
2003 >>> q = Exists(x, f(x) != 0)
2004 >>> q.is_lambda()
2005 False
2006 """
2007 return Z3_is_lambda(self.ctx_ref(), self.ast)
2008
2009 def __getitem__(self, arg):
2010 """Return the Z3 expression `self[arg]`.
2011 """
2012 if z3_debug():
2013 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2014 arg = self.sortsortsort().domain().cast(arg)
2015 return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_astas_astas_ast(), arg.as_ast()), self.ctx)
2016
2017 def weight(self):
2018 """Return the weight annotation of `self`.
2019
2020 >>> f = Function('f', IntSort(), IntSort())
2021 >>> x = Int('x')
2022 >>> q = ForAll(x, f(x) == 0)
2023 >>> q.weight()
2024 1
2025 >>> q = ForAll(x, f(x) == 0, weight=10)
2026 >>> q.weight()
2027 10
2028 """
2029 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
2030
2031 def num_patterns(self):
2032 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2033
2034 >>> f = Function('f', IntSort(), IntSort())
2035 >>> g = Function('g', IntSort(), IntSort())
2036 >>> x = Int('x')
2037 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2038 >>> q.num_patterns()
2039 2
2040 """
2041 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
2042
2043 def pattern(self, idx):
2044 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2045
2046 >>> f = Function('f', IntSort(), IntSort())
2047 >>> g = Function('g', IntSort(), IntSort())
2048 >>> x = Int('x')
2049 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2050 >>> q.num_patterns()
2051 2
2052 >>> q.pattern(0)
2053 f(Var(0))
2054 >>> q.pattern(1)
2055 g(Var(0))
2056 """
2057 if z3_debug():
2058 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2059 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2060
2062 """Return the number of no-patterns."""
2063 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
2064
2065 def no_pattern(self, idx):
2066 """Return a no-pattern."""
2067 if z3_debug():
2068 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2069 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2070
2071 def body(self):
2072 """Return the expression being quantified.
2073
2074 >>> f = Function('f', IntSort(), IntSort())
2075 >>> x = Int('x')
2076 >>> q = ForAll(x, f(x) == 0)
2077 >>> q.body()
2078 f(Var(0)) == 0
2079 """
2080 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
2081
2082 def num_vars(self):
2083 """Return the number of variables bounded by this quantifier.
2084
2085 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2086 >>> x = Int('x')
2087 >>> y = Int('y')
2088 >>> q = ForAll([x, y], f(x, y) >= x)
2089 >>> q.num_vars()
2090 2
2091 """
2092 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
2093
2094 def var_name(self, idx):
2095 """Return a string representing a name used when displaying the quantifier.
2096
2097 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2098 >>> x = Int('x')
2099 >>> y = Int('y')
2100 >>> q = ForAll([x, y], f(x, y) >= x)
2101 >>> q.var_name(0)
2102 'x'
2103 >>> q.var_name(1)
2104 'y'
2105 """
2106 if z3_debug():
2107 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2108 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
2109
2110 def var_sort(self, idx):
2111 """Return the sort of a bound variable.
2112
2113 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2114 >>> x = Int('x')
2115 >>> y = Real('y')
2116 >>> q = ForAll([x, y], f(x, y) >= x)
2117 >>> q.var_sort(0)
2118 Int
2119 >>> q.var_sort(1)
2120 Real
2121 """
2122 if z3_debug():
2123 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2124 return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
2125
2126 def children(self):
2127 """Return a list containing a single element self.body()
2128
2129 >>> f = Function('f', IntSort(), IntSort())
2130 >>> x = Int('x')
2131 >>> q = ForAll(x, f(x) == 0)
2132 >>> q.children()
2133 [f(Var(0)) == 0]
2134 """
2135 return [self.body()]
2136
2137
2139 """Return `True` if `a` is a Z3 quantifier.
2140
2141 >>> f = Function('f', IntSort(), IntSort())
2142 >>> x = Int('x')
2143 >>> q = ForAll(x, f(x) == 0)
2144 >>> is_quantifier(q)
2145 True
2146 >>> is_quantifier(f(x))
2147 False
2148 """
2149 return isinstance(a, QuantifierRef)
2150
2151
2152def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2153 if z3_debug():
2154 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2155 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2156 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2157 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2158 if is_app(vs):
2159 ctx = vs.ctx
2160 vs = [vs]
2161 else:
2162 ctx = vs[0].ctx
2163 if not is_expr(body):
2164 body = BoolVal(body, ctx)
2165 num_vars = len(vs)
2166 if num_vars == 0:
2167 return body
2168 _vs = (Ast * num_vars)()
2169 for i in range(num_vars):
2170 # TODO: Check if is constant
2171 _vs[i] = vs[i].as_ast()
2172 patterns = [_to_pattern(p) for p in patterns]
2173 num_pats = len(patterns)
2174 _pats = (Pattern * num_pats)()
2175 for i in range(num_pats):
2176 _pats[i] = patterns[i].ast
2177 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2178 qid = to_symbol(qid, ctx)
2179 skid = to_symbol(skid, ctx)
2180 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2181 num_vars, _vs,
2182 num_pats, _pats,
2183 num_no_pats, _no_pats,
2184 body.as_ast()), ctx)
2185
2186
2187def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2188 """Create a Z3 forall formula.
2189
2190 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2191
2192 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2193 >>> x = Int('x')
2194 >>> y = Int('y')
2195 >>> ForAll([x, y], f(x, y) >= x)
2196 ForAll([x, y], f(x, y) >= x)
2197 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2198 ForAll([x, y], f(x, y) >= x)
2199 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2200 ForAll([x, y], f(x, y) >= x)
2201 """
2202 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2203
2204
2205def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2206 """Create a Z3 exists formula.
2207
2208 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2209
2210
2211 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2212 >>> x = Int('x')
2213 >>> y = Int('y')
2214 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2215 >>> q
2216 Exists([x, y], f(x, y) >= x)
2217 >>> is_quantifier(q)
2218 True
2219 >>> r = Tactic('nnf')(q).as_expr()
2220 >>> is_quantifier(r)
2221 False
2222 """
2223 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2224
2225
2226def Lambda(vs, body):
2227 """Create a Z3 lambda expression.
2228
2229 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2230 >>> mem0 = Array('mem0', IntSort(), IntSort())
2231 >>> lo, hi, e, i = Ints('lo hi e i')
2232 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2233 >>> mem1
2234 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2235 """
2236 ctx = body.ctx
2237 if is_app(vs):
2238 vs = [vs]
2239 num_vars = len(vs)
2240 _vs = (Ast * num_vars)()
2241 for i in range(num_vars):
2242 # TODO: Check if is constant
2243 _vs[i] = vs[i].as_ast()
2244 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2245
2246
2251
2252
2254 """Real and Integer sorts."""
2255
2256 def is_real(self):
2257 """Return `True` if `self` is of the sort Real.
2258
2259 >>> x = Real('x')
2260 >>> x.is_real()
2261 True
2262 >>> (x + 1).is_real()
2263 True
2264 >>> x = Int('x')
2265 >>> x.is_real()
2266 False
2267 """
2268 return self.kind() == Z3_REAL_SORT
2269
2270 def is_int(self):
2271 """Return `True` if `self` is of the sort Integer.
2272
2273 >>> x = Int('x')
2274 >>> x.is_int()
2275 True
2276 >>> (x + 1).is_int()
2277 True
2278 >>> x = Real('x')
2279 >>> x.is_int()
2280 False
2281 """
2282 return self.kind() == Z3_INT_SORT
2283
2284 def subsort(self, other):
2285 """Return `True` if `self` is a subsort of `other`."""
2286 return self.is_int() and is_arith_sort(other) and other.is_real()
2287
2288 def cast(self, val):
2289 """Try to cast `val` as an Integer or Real.
2290
2291 >>> IntSort().cast(10)
2292 10
2293 >>> is_int(IntSort().cast(10))
2294 True
2295 >>> is_int(10)
2296 False
2297 >>> RealSort().cast(10)
2298 10
2299 >>> is_real(RealSort().cast(10))
2300 True
2301 """
2302 if is_expr(val):
2303 if z3_debug():
2304 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
2305 val_s = val.sort()
2306 if self.eq(val_s):
2307 return val
2308 if val_s.is_int() and self.is_real():
2309 return ToReal(val)
2310 if val_s.is_bool() and self.is_int():
2311 return If(val, 1, 0)
2312 if val_s.is_bool() and self.is_real():
2313 return ToReal(If(val, 1, 0))
2314 if z3_debug():
2315 _z3_assert(False, "Z3 Integer/Real expression expected")
2316 else:
2317 if self.is_int():
2318 return IntVal(val, self.ctxctx)
2319 if self.is_real():
2320 return RealVal(val, self.ctxctx)
2321 if z3_debug():
2322 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2323 _z3_assert(False, msg % self)
2324
2325
2327 """Return `True` if s is an arithmetical sort (type).
2328
2329 >>> is_arith_sort(IntSort())
2330 True
2331 >>> is_arith_sort(RealSort())
2332 True
2333 >>> is_arith_sort(BoolSort())
2334 False
2335 >>> n = Int('x') + 1
2336 >>> is_arith_sort(n.sort())
2337 True
2338 """
2339 return isinstance(s, ArithSortRef)
2340
2341
2343 """Integer and Real expressions."""
2344
2345 def sort(self):
2346 """Return the sort (type) of the arithmetical expression `self`.
2347
2348 >>> Int('x').sort()
2349 Int
2350 >>> (Real('x') + 1).sort()
2351 Real
2352 """
2353 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2354
2355 def is_int(self):
2356 """Return `True` if `self` is an integer expression.
2357
2358 >>> x = Int('x')
2359 >>> x.is_int()
2360 True
2361 >>> (x + 1).is_int()
2362 True
2363 >>> y = Real('y')
2364 >>> (x + y).is_int()
2365 False
2366 """
2367 return self.sortsort().is_int()
2368
2369 def is_real(self):
2370 """Return `True` if `self` is an real expression.
2371
2372 >>> x = Real('x')
2373 >>> x.is_real()
2374 True
2375 >>> (x + 1).is_real()
2376 True
2377 """
2378 return self.sortsort().is_real()
2379
2380 def __add__(self, other):
2381 """Create the Z3 expression `self + other`.
2382
2383 >>> x = Int('x')
2384 >>> y = Int('y')
2385 >>> x + y
2386 x + y
2387 >>> (x + y).sort()
2388 Int
2389 """
2390 a, b = _coerce_exprs(self, other)
2391 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2392
2393 def __radd__(self, other):
2394 """Create the Z3 expression `other + self`.
2395
2396 >>> x = Int('x')
2397 >>> 10 + x
2398 10 + x
2399 """
2400 a, b = _coerce_exprs(self, other)
2401 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2402
2403 def __mul__(self, other):
2404 """Create the Z3 expression `self * other`.
2405
2406 >>> x = Real('x')
2407 >>> y = Real('y')
2408 >>> x * y
2409 x*y
2410 >>> (x * y).sort()
2411 Real
2412 """
2413 if isinstance(other, BoolRef):
2414 return If(other, self, 0)
2415 a, b = _coerce_exprs(self, other)
2416 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2417
2418 def __rmul__(self, other):
2419 """Create the Z3 expression `other * self`.
2420
2421 >>> x = Real('x')
2422 >>> 10 * x
2423 10*x
2424 """
2425 a, b = _coerce_exprs(self, other)
2426 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2427
2428 def __sub__(self, other):
2429 """Create the Z3 expression `self - other`.
2430
2431 >>> x = Int('x')
2432 >>> y = Int('y')
2433 >>> x - y
2434 x - y
2435 >>> (x - y).sort()
2436 Int
2437 """
2438 a, b = _coerce_exprs(self, other)
2439 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2440
2441 def __rsub__(self, other):
2442 """Create the Z3 expression `other - self`.
2443
2444 >>> x = Int('x')
2445 >>> 10 - x
2446 10 - x
2447 """
2448 a, b = _coerce_exprs(self, other)
2449 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2450
2451 def __pow__(self, other):
2452 """Create the Z3 expression `self**other` (** is the power operator).
2453
2454 >>> x = Real('x')
2455 >>> x**3
2456 x**3
2457 >>> (x**3).sort()
2458 Real
2459 >>> simplify(IntVal(2)**8)
2460 256
2461 """
2462 a, b = _coerce_exprs(self, other)
2463 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2464
2465 def __rpow__(self, other):
2466 """Create the Z3 expression `other**self` (** is the power operator).
2467
2468 >>> x = Real('x')
2469 >>> 2**x
2470 2**x
2471 >>> (2**x).sort()
2472 Real
2473 >>> simplify(2**IntVal(8))
2474 256
2475 """
2476 a, b = _coerce_exprs(self, other)
2477 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2478
2479 def __div__(self, other):
2480 """Create the Z3 expression `other/self`.
2481
2482 >>> x = Int('x')
2483 >>> y = Int('y')
2484 >>> x/y
2485 x/y
2486 >>> (x/y).sort()
2487 Int
2488 >>> (x/y).sexpr()
2489 '(div x y)'
2490 >>> x = Real('x')
2491 >>> y = Real('y')
2492 >>> x/y
2493 x/y
2494 >>> (x/y).sort()
2495 Real
2496 >>> (x/y).sexpr()
2497 '(/ x y)'
2498 """
2499 a, b = _coerce_exprs(self, other)
2500 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2501
2502 def __truediv__(self, other):
2503 """Create the Z3 expression `other/self`."""
2504 return self.__div__(other)
2505
2506 def __rdiv__(self, other):
2507 """Create the Z3 expression `other/self`.
2508
2509 >>> x = Int('x')
2510 >>> 10/x
2511 10/x
2512 >>> (10/x).sexpr()
2513 '(div 10 x)'
2514 >>> x = Real('x')
2515 >>> 10/x
2516 10/x
2517 >>> (10/x).sexpr()
2518 '(/ 10.0 x)'
2519 """
2520 a, b = _coerce_exprs(self, other)
2521 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2522
2523 def __rtruediv__(self, other):
2524 """Create the Z3 expression `other/self`."""
2525 return self.__rdiv__(other)
2526
2527 def __mod__(self, other):
2528 """Create the Z3 expression `other%self`.
2529
2530 >>> x = Int('x')
2531 >>> y = Int('y')
2532 >>> x % y
2533 x%y
2534 >>> simplify(IntVal(10) % IntVal(3))
2535 1
2536 """
2537 a, b = _coerce_exprs(self, other)
2538 if z3_debug():
2539 _z3_assert(a.is_int(), "Z3 integer expression expected")
2540 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2541
2542 def __rmod__(self, other):
2543 """Create the Z3 expression `other%self`.
2544
2545 >>> x = Int('x')
2546 >>> 10 % x
2547 10%x
2548 """
2549 a, b = _coerce_exprs(self, other)
2550 if z3_debug():
2551 _z3_assert(a.is_int(), "Z3 integer expression expected")
2552 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2553
2554 def __neg__(self):
2555 """Return an expression representing `-self`.
2556
2557 >>> x = Int('x')
2558 >>> -x
2559 -x
2560 >>> simplify(-(-x))
2561 x
2562 """
2563 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2564
2565 def __pos__(self):
2566 """Return `self`.
2567
2568 >>> x = Int('x')
2569 >>> +x
2570 x
2571 """
2572 return self
2573
2574 def __le__(self, other):
2575 """Create the Z3 expression `other <= self`.
2576
2577 >>> x, y = Ints('x y')
2578 >>> x <= y
2579 x <= y
2580 >>> y = Real('y')
2581 >>> x <= y
2582 ToReal(x) <= y
2583 """
2584 a, b = _coerce_exprs(self, other)
2585 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2586
2587 def __lt__(self, other):
2588 """Create the Z3 expression `other < self`.
2589
2590 >>> x, y = Ints('x y')
2591 >>> x < y
2592 x < y
2593 >>> y = Real('y')
2594 >>> x < y
2595 ToReal(x) < y
2596 """
2597 a, b = _coerce_exprs(self, other)
2598 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2599
2600 def __gt__(self, other):
2601 """Create the Z3 expression `other > self`.
2602
2603 >>> x, y = Ints('x y')
2604 >>> x > y
2605 x > y
2606 >>> y = Real('y')
2607 >>> x > y
2608 ToReal(x) > y
2609 """
2610 a, b = _coerce_exprs(self, other)
2611 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2612
2613 def __ge__(self, other):
2614 """Create the Z3 expression `other >= self`.
2615
2616 >>> x, y = Ints('x y')
2617 >>> x >= y
2618 x >= y
2619 >>> y = Real('y')
2620 >>> x >= y
2621 ToReal(x) >= y
2622 """
2623 a, b = _coerce_exprs(self, other)
2624 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2625
2626
2628 """Return `True` if `a` is an arithmetical expression.
2629
2630 >>> x = Int('x')
2631 >>> is_arith(x)
2632 True
2633 >>> is_arith(x + 1)
2634 True
2635 >>> is_arith(1)
2636 False
2637 >>> is_arith(IntVal(1))
2638 True
2639 >>> y = Real('y')
2640 >>> is_arith(y)
2641 True
2642 >>> is_arith(y + 1)
2643 True
2644 """
2645 return isinstance(a, ArithRef)
2646
2647
2648def is_int(a):
2649 """Return `True` if `a` is an integer expression.
2650
2651 >>> x = Int('x')
2652 >>> is_int(x + 1)
2653 True
2654 >>> is_int(1)
2655 False
2656 >>> is_int(IntVal(1))
2657 True
2658 >>> y = Real('y')
2659 >>> is_int(y)
2660 False
2661 >>> is_int(y + 1)
2662 False
2663 """
2664 return is_arith(a) and a.is_int()
2665
2666
2667def is_real(a):
2668 """Return `True` if `a` is a real expression.
2669
2670 >>> x = Int('x')
2671 >>> is_real(x + 1)
2672 False
2673 >>> y = Real('y')
2674 >>> is_real(y)
2675 True
2676 >>> is_real(y + 1)
2677 True
2678 >>> is_real(1)
2679 False
2680 >>> is_real(RealVal(1))
2681 True
2682 """
2683 return is_arith(a) and a.is_real()
2684
2685
2686def _is_numeral(ctx, a):
2687 return Z3_is_numeral_ast(ctx.ref(), a)
2688
2689
2690def _is_algebraic(ctx, a):
2691 return Z3_is_algebraic_number(ctx.ref(), a)
2692
2693
2695 """Return `True` if `a` is an integer value of sort Int.
2696
2697 >>> is_int_value(IntVal(1))
2698 True
2699 >>> is_int_value(1)
2700 False
2701 >>> is_int_value(Int('x'))
2702 False
2703 >>> n = Int('x') + 1
2704 >>> n
2705 x + 1
2706 >>> n.arg(1)
2707 1
2708 >>> is_int_value(n.arg(1))
2709 True
2710 >>> is_int_value(RealVal("1/3"))
2711 False
2712 >>> is_int_value(RealVal(1))
2713 False
2714 """
2715 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2716
2717
2719 """Return `True` if `a` is rational value of sort Real.
2720
2722 True
2723 >>> is_rational_value(RealVal("3/5"))
2724 True
2726 False
2727 >>> is_rational_value(1)
2728 False
2729 >>> n = Real('x') + 1
2730 >>> n.arg(1)
2731 1
2732 >>> is_rational_value(n.arg(1))
2733 True
2734 >>> is_rational_value(Real('x'))
2735 False
2736 """
2737 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2738
2739
2741 """Return `True` if `a` is an algebraic value of sort Real.
2742
2743 >>> is_algebraic_value(RealVal("3/5"))
2744 False
2745 >>> n = simplify(Sqrt(2))
2746 >>> n
2747 1.4142135623?
2748 >>> is_algebraic_value(n)
2749 True
2750 """
2751 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2752
2753
2754def is_add(a):
2755 """Return `True` if `a` is an expression of the form b + c.
2756
2757 >>> x, y = Ints('x y')
2758 >>> is_add(x + y)
2759 True
2760 >>> is_add(x - y)
2761 False
2762 """
2763 return is_app_of(a, Z3_OP_ADD)
2764
2765
2766def is_mul(a):
2767 """Return `True` if `a` is an expression of the form b * c.
2768
2769 >>> x, y = Ints('x y')
2770 >>> is_mul(x * y)
2771 True
2772 >>> is_mul(x - y)
2773 False
2774 """
2775 return is_app_of(a, Z3_OP_MUL)
2776
2777
2778def is_sub(a):
2779 """Return `True` if `a` is an expression of the form b - c.
2780
2781 >>> x, y = Ints('x y')
2782 >>> is_sub(x - y)
2783 True
2784 >>> is_sub(x + y)
2785 False
2786 """
2787 return is_app_of(a, Z3_OP_SUB)
2788
2789
2790def is_div(a):
2791 """Return `True` if `a` is an expression of the form b / c.
2792
2793 >>> x, y = Reals('x y')
2794 >>> is_div(x / y)
2795 True
2796 >>> is_div(x + y)
2797 False
2798 >>> x, y = Ints('x y')
2799 >>> is_div(x / y)
2800 False
2801 >>> is_idiv(x / y)
2802 True
2803 """
2804 return is_app_of(a, Z3_OP_DIV)
2805
2806
2807def is_idiv(a):
2808 """Return `True` if `a` is an expression of the form b div c.
2809
2810 >>> x, y = Ints('x y')
2811 >>> is_idiv(x / y)
2812 True
2813 >>> is_idiv(x + y)
2814 False
2815 """
2816 return is_app_of(a, Z3_OP_IDIV)
2817
2818
2819def is_mod(a):
2820 """Return `True` if `a` is an expression of the form b % c.
2821
2822 >>> x, y = Ints('x y')
2823 >>> is_mod(x % y)
2824 True
2825 >>> is_mod(x + y)
2826 False
2827 """
2828 return is_app_of(a, Z3_OP_MOD)
2829
2830
2831def is_le(a):
2832 """Return `True` if `a` is an expression of the form b <= c.
2833
2834 >>> x, y = Ints('x y')
2835 >>> is_le(x <= y)
2836 True
2837 >>> is_le(x < y)
2838 False
2839 """
2840 return is_app_of(a, Z3_OP_LE)
2841
2842
2843def is_lt(a):
2844 """Return `True` if `a` is an expression of the form b < c.
2845
2846 >>> x, y = Ints('x y')
2847 >>> is_lt(x < y)
2848 True
2849 >>> is_lt(x == y)
2850 False
2851 """
2852 return is_app_of(a, Z3_OP_LT)
2853
2854
2855def is_ge(a):
2856 """Return `True` if `a` is an expression of the form b >= c.
2857
2858 >>> x, y = Ints('x y')
2859 >>> is_ge(x >= y)
2860 True
2861 >>> is_ge(x == y)
2862 False
2863 """
2864 return is_app_of(a, Z3_OP_GE)
2865
2866
2867def is_gt(a):
2868 """Return `True` if `a` is an expression of the form b > c.
2869
2870 >>> x, y = Ints('x y')
2871 >>> is_gt(x > y)
2872 True
2873 >>> is_gt(x == y)
2874 False
2875 """
2876 return is_app_of(a, Z3_OP_GT)
2877
2878
2880 """Return `True` if `a` is an expression of the form IsInt(b).
2881
2882 >>> x = Real('x')
2883 >>> is_is_int(IsInt(x))
2884 True
2885 >>> is_is_int(x)
2886 False
2887 """
2888 return is_app_of(a, Z3_OP_IS_INT)
2889
2890
2892 """Return `True` if `a` is an expression of the form ToReal(b).
2893
2894 >>> x = Int('x')
2895 >>> n = ToReal(x)
2896 >>> n
2897 ToReal(x)
2898 >>> is_to_real(n)
2899 True
2900 >>> is_to_real(x)
2901 False
2902 """
2903 return is_app_of(a, Z3_OP_TO_REAL)
2904
2905
2907 """Return `True` if `a` is an expression of the form ToInt(b).
2908
2909 >>> x = Real('x')
2910 >>> n = ToInt(x)
2911 >>> n
2912 ToInt(x)
2913 >>> is_to_int(n)
2914 True
2915 >>> is_to_int(x)
2916 False
2917 """
2918 return is_app_of(a, Z3_OP_TO_INT)
2919
2920
2922 """Integer values."""
2923
2924 def as_long(self):
2925 """Return a Z3 integer numeral as a Python long (bignum) numeral.
2926
2927 >>> v = IntVal(1)
2928 >>> v + 1
2929 1 + 1
2930 >>> v.as_long() + 1
2931 2
2932 """
2933 if z3_debug():
2934 _z3_assert(self.is_int(), "Integer value expected")
2935 return int(self.as_string())
2936
2937 def as_string(self):
2938 """Return a Z3 integer numeral as a Python string.
2939 >>> v = IntVal(100)
2940 >>> v.as_string()
2941 '100'
2942 """
2943 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
2944
2946 """Return a Z3 integer numeral as a Python binary string.
2947 >>> v = IntVal(10)
2948 >>> v.as_binary_string()
2949 '1010'
2950 """
2952
2953
2955 """Rational values."""
2956
2957 def numerator(self):
2958 """ Return the numerator of a Z3 rational numeral.
2959
2960 >>> is_rational_value(RealVal("3/5"))
2961 True
2962 >>> n = RealVal("3/5")
2963 >>> n.numerator()
2964 3
2965 >>> is_rational_value(Q(3,5))
2966 True
2967 >>> Q(3,5).numerator()
2968 3
2969 """
2970 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2971
2972 def denominator(self):
2973 """ Return the denominator of a Z3 rational numeral.
2974
2975 >>> is_rational_value(Q(3,5))
2976 True
2977 >>> n = Q(3,5)
2978 >>> n.denominator()
2979 5
2980 """
2981 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2982
2984 """ Return the numerator as a Python long.
2985
2986 >>> v = RealVal(10000000000)
2987 >>> v
2988 10000000000
2989 >>> v + 1
2990 10000000000 + 1
2991 >>> v.numerator_as_long() + 1 == 10000000001
2992 True
2993 """
2994 return self.numerator().as_long()
2995
2997 """ Return the denominator as a Python long.
2998
2999 >>> v = RealVal("1/3")
3000 >>> v
3001 1/3
3002 >>> v.denominator_as_long()
3003 3
3004 """
3005 return self.denominator().as_long()
3006
3007 def is_int(self):
3008 return False
3009
3010 def is_real(self):
3011 return True
3012
3013 def is_int_value(self):
3014 return self.denominator().is_int() and self.denominator_as_long() == 1
3015
3016 def as_long(self):
3017 _z3_assert(self.is_int_value(), "Expected integer fraction")
3018 return self.numerator_as_long()
3019
3020 def as_decimal(self, prec):
3021 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3022
3023 >>> v = RealVal("1/5")
3024 >>> v.as_decimal(3)
3025 '0.2'
3026 >>> v = RealVal("1/3")
3027 >>> v.as_decimal(3)
3028 '0.333?'
3029 """
3030 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3031
3032 def as_string(self):
3033 """Return a Z3 rational numeral as a Python string.
3034
3035 >>> v = Q(3,6)
3036 >>> v.as_string()
3037 '1/2'
3038 """
3039 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3040
3041 def as_fraction(self):
3042 """Return a Z3 rational as a Python Fraction object.
3043
3044 >>> v = RealVal("1/5")
3045 >>> v.as_fraction()
3046 Fraction(1, 5)
3047 """
3048 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3049
3050
3052 """Algebraic irrational values."""
3053
3054 def approx(self, precision=10):
3055 """Return a Z3 rational number that approximates the algebraic number `self`.
3056 The result `r` is such that |r - self| <= 1/10^precision
3057
3058 >>> x = simplify(Sqrt(2))
3059 >>> x.approx(20)
3060 6838717160008073720548335/4835703278458516698824704
3061 >>> x.approx(5)
3062 2965821/2097152
3063 """
3064 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_astas_ast(), precision), self.ctx)
3065
3066 def as_decimal(self, prec):
3067 """Return a string representation of the algebraic number `self` in decimal notation
3068 using `prec` decimal places.
3069
3070 >>> x = simplify(Sqrt(2))
3071 >>> x.as_decimal(10)
3072 '1.4142135623?'
3073 >>> x.as_decimal(20)
3074 '1.41421356237309504880?'
3075 """
3076 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3077
3078 def poly(self):
3079 return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3080
3081 def index(self):
3082 return Z3_algebraic_get_i(self.ctx_ref(), self.as_astas_ast())
3083
3084
3085def _py2expr(a, ctx=None):
3086 if isinstance(a, bool):
3087 return BoolVal(a, ctx)
3088 if _is_int(a):
3089 return IntVal(a, ctx)
3090 if isinstance(a, float):
3091 return RealVal(a, ctx)
3092 if isinstance(a, str):
3093 return StringVal(a, ctx)
3094 if is_expr(a):
3095 return a
3096 if z3_debug():
3097 _z3_assert(False, "Python bool, int, long or float expected")
3098
3099
3100def IntSort(ctx=None):
3101 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3102
3103 >>> IntSort()
3104 Int
3105 >>> x = Const('x', IntSort())
3106 >>> is_int(x)
3107 True
3108 >>> x.sort() == IntSort()
3109 True
3110 >>> x.sort() == BoolSort()
3111 False
3112 """
3113 ctx = _get_ctx(ctx)
3114 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3115
3116
3117def RealSort(ctx=None):
3118 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3119
3120 >>> RealSort()
3121 Real
3122 >>> x = Const('x', RealSort())
3123 >>> is_real(x)
3124 True
3125 >>> is_int(x)
3126 False
3127 >>> x.sort() == RealSort()
3128 True
3129 """
3130 ctx = _get_ctx(ctx)
3131 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3132
3133
3134def _to_int_str(val):
3135 if isinstance(val, float):
3136 return str(int(val))
3137 elif isinstance(val, bool):
3138 if val:
3139 return "1"
3140 else:
3141 return "0"
3142 elif _is_int(val):
3143 return str(val)
3144 elif isinstance(val, str):
3145 return val
3146 if z3_debug():
3147 _z3_assert(False, "Python value cannot be used as a Z3 integer")
3148
3149
3150def IntVal(val, ctx=None):
3151 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3152
3153 >>> IntVal(1)
3154 1
3155 >>> IntVal("100")
3156 100
3157 """
3158 ctx = _get_ctx(ctx)
3159 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3160
3161
3162def RealVal(val, ctx=None):
3163 """Return a Z3 real value.
3164
3165 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3166 If `ctx=None`, then the global context is used.
3167
3168 >>> RealVal(1)
3169 1
3170 >>> RealVal(1).sort()
3171 Real
3172 >>> RealVal("3/5")
3173 3/5
3174 >>> RealVal("1.5")
3175 3/2
3176 """
3177 ctx = _get_ctx(ctx)
3178 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3179
3180
3181def RatVal(a, b, ctx=None):
3182 """Return a Z3 rational a/b.
3183
3184 If `ctx=None`, then the global context is used.
3185
3186 >>> RatVal(3,5)
3187 3/5
3188 >>> RatVal(3,5).sort()
3189 Real
3190 """
3191 if z3_debug():
3192 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3193 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3194 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3195
3196
3197def Q(a, b, ctx=None):
3198 """Return a Z3 rational a/b.
3199
3200 If `ctx=None`, then the global context is used.
3201
3202 >>> Q(3,5)
3203 3/5
3204 >>> Q(3,5).sort()
3205 Real
3206 """
3207 return simplify(RatVal(a, b))
3208
3209
3210def Int(name, ctx=None):
3211 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3212
3213 >>> x = Int('x')
3214 >>> is_int(x)
3215 True
3216 >>> is_int(x + 1)
3217 True
3218 """
3219 ctx = _get_ctx(ctx)
3220 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3221
3222
3223def Ints(names, ctx=None):
3224 """Return a tuple of Integer constants.
3225
3226 >>> x, y, z = Ints('x y z')
3227 >>> Sum(x, y, z)
3228 x + y + z
3229 """
3230 ctx = _get_ctx(ctx)
3231 if isinstance(names, str):
3232 names = names.split(" ")
3233 return [Int(name, ctx) for name in names]
3234
3235
3236def IntVector(prefix, sz, ctx=None):
3237 """Return a list of integer constants of size `sz`.
3238
3239 >>> X = IntVector('x', 3)
3240 >>> X
3241 [x__0, x__1, x__2]
3242 >>> Sum(X)
3243 x__0 + x__1 + x__2
3244 """
3245 ctx = _get_ctx(ctx)
3246 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3247
3248
3249def FreshInt(prefix="x", ctx=None):
3250 """Return a fresh integer constant in the given context using the given prefix.
3251
3252 >>> x = FreshInt()
3253 >>> y = FreshInt()
3254 >>> eq(x, y)
3255 False
3256 >>> x.sort()
3257 Int
3258 """
3259 ctx = _get_ctx(ctx)
3260 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3261
3262
3263def Real(name, ctx=None):
3264 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3265
3266 >>> x = Real('x')
3267 >>> is_real(x)
3268 True
3269 >>> is_real(x + 1)
3270 True
3271 """
3272 ctx = _get_ctx(ctx)
3273 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3274
3275
3276def Reals(names, ctx=None):
3277 """Return a tuple of real constants.
3278
3279 >>> x, y, z = Reals('x y z')
3280 >>> Sum(x, y, z)
3281 x + y + z
3282 >>> Sum(x, y, z).sort()
3283 Real
3284 """
3285 ctx = _get_ctx(ctx)
3286 if isinstance(names, str):
3287 names = names.split(" ")
3288 return [Real(name, ctx) for name in names]
3289
3290
3291def RealVector(prefix, sz, ctx=None):
3292 """Return a list of real constants of size `sz`.
3293
3294 >>> X = RealVector('x', 3)
3295 >>> X
3296 [x__0, x__1, x__2]
3297 >>> Sum(X)
3298 x__0 + x__1 + x__2
3299 >>> Sum(X).sort()
3300 Real
3301 """
3302 ctx = _get_ctx(ctx)
3303 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3304
3305
3306def FreshReal(prefix="b", ctx=None):
3307 """Return a fresh real constant in the given context using the given prefix.
3308
3309 >>> x = FreshReal()
3310 >>> y = FreshReal()
3311 >>> eq(x, y)
3312 False
3313 >>> x.sort()
3314 Real
3315 """
3316 ctx = _get_ctx(ctx)
3317 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3318
3319
3320def ToReal(a):
3321 """ Return the Z3 expression ToReal(a).
3322
3323 >>> x = Int('x')
3324 >>> x.sort()
3325 Int
3326 >>> n = ToReal(x)
3327 >>> n
3328 ToReal(x)
3329 >>> n.sort()
3330 Real
3331 """
3332 if z3_debug():
3333 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3334 ctx = a.ctx
3335 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3336
3337
3338def ToInt(a):
3339 """ Return the Z3 expression ToInt(a).
3340
3341 >>> x = Real('x')
3342 >>> x.sort()
3343 Real
3344 >>> n = ToInt(x)
3345 >>> n
3346 ToInt(x)
3347 >>> n.sort()
3348 Int
3349 """
3350 if z3_debug():
3351 _z3_assert(a.is_real(), "Z3 real expression expected.")
3352 ctx = a.ctx
3353 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3354
3355
3356def IsInt(a):
3357 """ Return the Z3 predicate IsInt(a).
3358
3359 >>> x = Real('x')
3360 >>> IsInt(x + "1/2")
3361 IsInt(x + 1/2)
3362 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3363 [x = 1/2]
3364 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3365 no solution
3366 """
3367 if z3_debug():
3368 _z3_assert(a.is_real(), "Z3 real expression expected.")
3369 ctx = a.ctx
3370 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3371
3372
3373def Sqrt(a, ctx=None):
3374 """ Return a Z3 expression which represents the square root of a.
3375
3376 >>> x = Real('x')
3377 >>> Sqrt(x)
3378 x**(1/2)
3379 """
3380 if not is_expr(a):
3381 ctx = _get_ctx(ctx)
3382 a = RealVal(a, ctx)
3383 return a ** "1/2"
3384
3385
3386def Cbrt(a, ctx=None):
3387 """ Return a Z3 expression which represents the cubic root of a.
3388
3389 >>> x = Real('x')
3390 >>> Cbrt(x)
3391 x**(1/3)
3392 """
3393 if not is_expr(a):
3394 ctx = _get_ctx(ctx)
3395 a = RealVal(a, ctx)
3396 return a ** "1/3"
3397
3398
3403
3404
3406 """Bit-vector sort."""
3407
3408 def size(self):
3409 """Return the size (number of bits) of the bit-vector sort `self`.
3410
3411 >>> b = BitVecSort(32)
3412 >>> b.size()
3413 32
3414 """
3415 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3416
3417 def subsort(self, other):
3418 return is_bv_sort(other) and self.size() < other.size()
3419
3420 def cast(self, val):
3421 """Try to cast `val` as a Bit-Vector.
3422
3423 >>> b = BitVecSort(32)
3424 >>> b.cast(10)
3425 10
3426 >>> b.cast(10).sexpr()
3427 '#x0000000a'
3428 """
3429 if is_expr(val):
3430 if z3_debug():
3431 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
3432 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3433 return val
3434 else:
3435 return BitVecVal(val, self)
3436
3437
3439 """Return True if `s` is a Z3 bit-vector sort.
3440
3441 >>> is_bv_sort(BitVecSort(32))
3442 True
3443 >>> is_bv_sort(IntSort())
3444 False
3445 """
3446 return isinstance(s, BitVecSortRef)
3447
3448
3450 """Bit-vector expressions."""
3451
3452 def sort(self):
3453 """Return the sort of the bit-vector expression `self`.
3454
3455 >>> x = BitVec('x', 32)
3456 >>> x.sort()
3457 BitVec(32)
3458 >>> x.sort() == BitVecSort(32)
3459 True
3460 """
3461 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3462
3463 def size(self):
3464 """Return the number of bits of the bit-vector expression `self`.
3465
3466 >>> x = BitVec('x', 32)
3467 >>> (x + 1).size()
3468 32
3469 >>> Concat(x, x).size()
3470 64
3471 """
3472 return self.sortsort().size()
3473
3474 def __add__(self, other):
3475 """Create the Z3 expression `self + other`.
3476
3477 >>> x = BitVec('x', 32)
3478 >>> y = BitVec('y', 32)
3479 >>> x + y
3480 x + y
3481 >>> (x + y).sort()
3482 BitVec(32)
3483 """
3484 a, b = _coerce_exprs(self, other)
3485 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3486
3487 def __radd__(self, other):
3488 """Create the Z3 expression `other + self`.
3489
3490 >>> x = BitVec('x', 32)
3491 >>> 10 + x
3492 10 + x
3493 """
3494 a, b = _coerce_exprs(self, other)
3495 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3496
3497 def __mul__(self, other):
3498 """Create the Z3 expression `self * other`.
3499
3500 >>> x = BitVec('x', 32)
3501 >>> y = BitVec('y', 32)
3502 >>> x * y
3503 x*y
3504 >>> (x * y).sort()
3505 BitVec(32)
3506 """
3507 a, b = _coerce_exprs(self, other)
3508 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3509
3510 def __rmul__(self, other):
3511 """Create the Z3 expression `other * self`.
3512
3513 >>> x = BitVec('x', 32)
3514 >>> 10 * x
3515 10*x
3516 """
3517 a, b = _coerce_exprs(self, other)
3518 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3519
3520 def __sub__(self, other):
3521 """Create the Z3 expression `self - other`.
3522
3523 >>> x = BitVec('x', 32)
3524 >>> y = BitVec('y', 32)
3525 >>> x - y
3526 x - y
3527 >>> (x - y).sort()
3528 BitVec(32)
3529 """
3530 a, b = _coerce_exprs(self, other)
3531 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3532
3533 def __rsub__(self, other):
3534 """Create the Z3 expression `other - self`.
3535
3536 >>> x = BitVec('x', 32)
3537 >>> 10 - x
3538 10 - x
3539 """
3540 a, b = _coerce_exprs(self, other)
3541 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3542
3543 def __or__(self, other):
3544 """Create the Z3 expression bitwise-or `self | other`.
3545
3546 >>> x = BitVec('x', 32)
3547 >>> y = BitVec('y', 32)
3548 >>> x | y
3549 x | y
3550 >>> (x | y).sort()
3551 BitVec(32)
3552 """
3553 a, b = _coerce_exprs(self, other)
3554 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3555
3556 def __ror__(self, other):
3557 """Create the Z3 expression bitwise-or `other | self`.
3558
3559 >>> x = BitVec('x', 32)
3560 >>> 10 | x
3561 10 | x
3562 """
3563 a, b = _coerce_exprs(self, other)
3564 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3565
3566 def __and__(self, other):
3567 """Create the Z3 expression bitwise-and `self & other`.
3568
3569 >>> x = BitVec('x', 32)
3570 >>> y = BitVec('y', 32)
3571 >>> x & y
3572 x & y
3573 >>> (x & y).sort()
3574 BitVec(32)
3575 """
3576 a, b = _coerce_exprs(self, other)
3577 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3578
3579 def __rand__(self, other):
3580 """Create the Z3 expression bitwise-or `other & self`.
3581
3582 >>> x = BitVec('x', 32)
3583 >>> 10 & x
3584 10 & x
3585 """
3586 a, b = _coerce_exprs(self, other)
3587 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3588
3589 def __xor__(self, other):
3590 """Create the Z3 expression bitwise-xor `self ^ other`.
3591
3592 >>> x = BitVec('x', 32)
3593 >>> y = BitVec('y', 32)
3594 >>> x ^ y
3595 x ^ y
3596 >>> (x ^ y).sort()
3597 BitVec(32)
3598 """
3599 a, b = _coerce_exprs(self, other)
3600 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3601
3602 def __rxor__(self, other):
3603 """Create the Z3 expression bitwise-xor `other ^ self`.
3604
3605 >>> x = BitVec('x', 32)
3606 >>> 10 ^ x
3607 10 ^ x
3608 """
3609 a, b = _coerce_exprs(self, other)
3610 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3611
3612 def __pos__(self):
3613 """Return `self`.
3614
3615 >>> x = BitVec('x', 32)
3616 >>> +x
3617 x
3618 """
3619 return self
3620
3621 def __neg__(self):
3622 """Return an expression representing `-self`.
3623
3624 >>> x = BitVec('x', 32)
3625 >>> -x
3626 -x
3627 >>> simplify(-(-x))
3628 x
3629 """
3630 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3631
3632 def __invert__(self):
3633 """Create the Z3 expression bitwise-not `~self`.
3634
3635 >>> x = BitVec('x', 32)
3636 >>> ~x
3637 ~x
3638 >>> simplify(~(~x))
3639 x
3640 """
3641 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3642
3643 def __div__(self, other):
3644 """Create the Z3 expression (signed) division `self / other`.
3645
3646 Use the function UDiv() for unsigned division.
3647
3648 >>> x = BitVec('x', 32)
3649 >>> y = BitVec('y', 32)
3650 >>> x / y
3651 x/y
3652 >>> (x / y).sort()
3653 BitVec(32)
3654 >>> (x / y).sexpr()
3655 '(bvsdiv x y)'
3656 >>> UDiv(x, y).sexpr()
3657 '(bvudiv x y)'
3658 """
3659 a, b = _coerce_exprs(self, other)
3660 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3661
3662 def __truediv__(self, other):
3663 """Create the Z3 expression (signed) division `self / other`."""
3664 return self.__div__(other)
3665
3666 def __rdiv__(self, other):
3667 """Create the Z3 expression (signed) division `other / self`.
3668
3669 Use the function UDiv() for unsigned division.
3670
3671 >>> x = BitVec('x', 32)
3672 >>> 10 / x
3673 10/x
3674 >>> (10 / x).sexpr()
3675 '(bvsdiv #x0000000a x)'
3676 >>> UDiv(10, x).sexpr()
3677 '(bvudiv #x0000000a x)'
3678 """
3679 a, b = _coerce_exprs(self, other)
3680 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3681
3682 def __rtruediv__(self, other):
3683 """Create the Z3 expression (signed) division `other / self`."""
3684 return self.__rdiv__(other)
3685
3686 def __mod__(self, other):
3687 """Create the Z3 expression (signed) mod `self % other`.
3688
3689 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3690
3691 >>> x = BitVec('x', 32)
3692 >>> y = BitVec('y', 32)
3693 >>> x % y
3694 x%y
3695 >>> (x % y).sort()
3696 BitVec(32)
3697 >>> (x % y).sexpr()
3698 '(bvsmod x y)'
3699 >>> URem(x, y).sexpr()
3700 '(bvurem x y)'
3701 >>> SRem(x, y).sexpr()
3702 '(bvsrem x y)'
3703 """
3704 a, b = _coerce_exprs(self, other)
3705 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3706
3707 def __rmod__(self, other):
3708 """Create the Z3 expression (signed) mod `other % self`.
3709
3710 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3711
3712 >>> x = BitVec('x', 32)
3713 >>> 10 % x
3714 10%x
3715 >>> (10 % x).sexpr()
3716 '(bvsmod #x0000000a x)'
3717 >>> URem(10, x).sexpr()
3718 '(bvurem #x0000000a x)'
3719 >>> SRem(10, x).sexpr()
3720 '(bvsrem #x0000000a x)'
3721 """
3722 a, b = _coerce_exprs(self, other)
3723 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3724
3725 def __le__(self, other):
3726 """Create the Z3 expression (signed) `other <= self`.
3727
3728 Use the function ULE() for unsigned less than or equal to.
3729
3730 >>> x, y = BitVecs('x y', 32)
3731 >>> x <= y
3732 x <= y
3733 >>> (x <= y).sexpr()
3734 '(bvsle x y)'
3735 >>> ULE(x, y).sexpr()
3736 '(bvule x y)'
3737 """
3738 a, b = _coerce_exprs(self, other)
3739 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3740
3741 def __lt__(self, other):
3742 """Create the Z3 expression (signed) `other < self`.
3743
3744 Use the function ULT() for unsigned less than.
3745
3746 >>> x, y = BitVecs('x y', 32)
3747 >>> x < y
3748 x < y
3749 >>> (x < y).sexpr()
3750 '(bvslt x y)'
3751 >>> ULT(x, y).sexpr()
3752 '(bvult x y)'
3753 """
3754 a, b = _coerce_exprs(self, other)
3755 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3756
3757 def __gt__(self, other):
3758 """Create the Z3 expression (signed) `other > self`.
3759
3760 Use the function UGT() for unsigned greater than.
3761
3762 >>> x, y = BitVecs('x y', 32)
3763 >>> x > y
3764 x > y
3765 >>> (x > y).sexpr()
3766 '(bvsgt x y)'
3767 >>> UGT(x, y).sexpr()
3768 '(bvugt x y)'
3769 """
3770 a, b = _coerce_exprs(self, other)
3771 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3772
3773 def __ge__(self, other):
3774 """Create the Z3 expression (signed) `other >= self`.
3775
3776 Use the function UGE() for unsigned greater than or equal to.
3777
3778 >>> x, y = BitVecs('x y', 32)
3779 >>> x >= y
3780 x >= y
3781 >>> (x >= y).sexpr()
3782 '(bvsge x y)'
3783 >>> UGE(x, y).sexpr()
3784 '(bvuge x y)'
3785 """
3786 a, b = _coerce_exprs(self, other)
3787 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3788
3789 def __rshift__(self, other):
3790 """Create the Z3 expression (arithmetical) right shift `self >> other`
3791
3792 Use the function LShR() for the right logical shift
3793
3794 >>> x, y = BitVecs('x y', 32)
3795 >>> x >> y
3796 x >> y
3797 >>> (x >> y).sexpr()
3798 '(bvashr x y)'
3799 >>> LShR(x, y).sexpr()
3800 '(bvlshr x y)'
3801 >>> BitVecVal(4, 3)
3802 4
3803 >>> BitVecVal(4, 3).as_signed_long()
3804 -4
3805 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3806 -2
3807 >>> simplify(BitVecVal(4, 3) >> 1)
3808 6
3809 >>> simplify(LShR(BitVecVal(4, 3), 1))
3810 2
3811 >>> simplify(BitVecVal(2, 3) >> 1)
3812 1
3813 >>> simplify(LShR(BitVecVal(2, 3), 1))
3814 1
3815 """
3816 a, b = _coerce_exprs(self, other)
3817 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3818
3819 def __lshift__(self, other):
3820 """Create the Z3 expression left shift `self << other`
3821
3822 >>> x, y = BitVecs('x y', 32)
3823 >>> x << y
3824 x << y
3825 >>> (x << y).sexpr()
3826 '(bvshl x y)'
3827 >>> simplify(BitVecVal(2, 3) << 1)
3828 4
3829 """
3830 a, b = _coerce_exprs(self, other)
3831 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3832
3833 def __rrshift__(self, other):
3834 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3835
3836 Use the function LShR() for the right logical shift
3837
3838 >>> x = BitVec('x', 32)
3839 >>> 10 >> x
3840 10 >> x
3841 >>> (10 >> x).sexpr()
3842 '(bvashr #x0000000a x)'
3843 """
3844 a, b = _coerce_exprs(self, other)
3845 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3846
3847 def __rlshift__(self, other):
3848 """Create the Z3 expression left shift `other << self`.
3849
3850 Use the function LShR() for the right logical shift
3851
3852 >>> x = BitVec('x', 32)
3853 >>> 10 << x
3854 10 << x
3855 >>> (10 << x).sexpr()
3856 '(bvshl #x0000000a x)'
3857 """
3858 a, b = _coerce_exprs(self, other)
3859 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3860
3861
3863 """Bit-vector values."""
3864
3865 def as_long(self):
3866 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3867
3868 >>> v = BitVecVal(0xbadc0de, 32)
3869 >>> v
3870 195936478
3871 >>> print("0x%.8x" % v.as_long())
3872 0x0badc0de
3873 """
3874 return int(self.as_string())
3875
3877 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3878 The most significant bit is assumed to be the sign.
3879
3880 >>> BitVecVal(4, 3).as_signed_long()
3881 -4
3882 >>> BitVecVal(7, 3).as_signed_long()
3883 -1
3884 >>> BitVecVal(3, 3).as_signed_long()
3885 3
3886 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3887 -1
3888 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3889 -1
3890 """
3891 sz = self.size()
3892 val = self.as_long()
3893 if val >= 2**(sz - 1):
3894 val = val - 2**sz
3895 if val < -2**(sz - 1):
3896 val = val + 2**sz
3897 return int(val)
3898
3899 def as_string(self):
3900 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3901
3904
3905
3906def is_bv(a):
3907 """Return `True` if `a` is a Z3 bit-vector expression.
3908
3909 >>> b = BitVec('b', 32)
3910 >>> is_bv(b)
3911 True
3912 >>> is_bv(b + 10)
3913 True
3914 >>> is_bv(Int('x'))
3915 False
3916 """
3917 return isinstance(a, BitVecRef)
3918
3919
3921 """Return `True` if `a` is a Z3 bit-vector numeral value.
3922
3923 >>> b = BitVec('b', 32)
3924 >>> is_bv_value(b)
3925 False
3926 >>> b = BitVecVal(10, 32)
3927 >>> b
3928 10
3929 >>> is_bv_value(b)
3930 True
3931 """
3932 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3933
3934
3935def BV2Int(a, is_signed=False):
3936 """Return the Z3 expression BV2Int(a).
3937
3938 >>> b = BitVec('b', 3)
3939 >>> BV2Int(b).sort()
3940 Int
3941 >>> x = Int('x')
3942 >>> x > BV2Int(b)
3943 x > BV2Int(b)
3944 >>> x > BV2Int(b, is_signed=False)
3945 x > BV2Int(b)
3946 >>> x > BV2Int(b, is_signed=True)
3947 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3948 >>> solve(x > BV2Int(b), b == 1, x < 3)
3949 [x = 2, b = 1]
3950 """
3951 if z3_debug():
3952 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3953 ctx = a.ctx
3954 # investigate problem with bv2int
3955 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3956
3957
3958def Int2BV(a, num_bits):
3959 """Return the z3 expression Int2BV(a, num_bits).
3960 It is a bit-vector of width num_bits and represents the
3961 modulo of a by 2^num_bits
3962 """
3963 ctx = a.ctx
3964 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3965
3966
3967def BitVecSort(sz, ctx=None):
3968 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3969
3970 >>> Byte = BitVecSort(8)
3971 >>> Word = BitVecSort(16)
3972 >>> Byte
3973 BitVec(8)
3974 >>> x = Const('x', Byte)
3975 >>> eq(x, BitVec('x', 8))
3976 True
3977 """
3978 ctx = _get_ctx(ctx)
3979 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3980
3981
3982def BitVecVal(val, bv, ctx=None):
3983 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3984
3985 >>> v = BitVecVal(10, 32)
3986 >>> v
3987 10
3988 >>> print("0x%.8x" % v.as_long())
3989 0x0000000a
3990 """
3991 if is_bv_sort(bv):
3992 ctx = bv.ctx
3993 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3994 else:
3995 ctx = _get_ctx(ctx)
3996 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3997
3998
3999def BitVec(name, bv, ctx=None):
4000 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4001 If `ctx=None`, then the global context is used.
4002
4003 >>> x = BitVec('x', 16)
4004 >>> is_bv(x)
4005 True
4006 >>> x.size()
4007 16
4008 >>> x.sort()
4009 BitVec(16)
4010 >>> word = BitVecSort(16)
4011 >>> x2 = BitVec('x', word)
4012 >>> eq(x, x2)
4013 True
4014 """
4015 if isinstance(bv, BitVecSortRef):
4016 ctx = bv.ctx
4017 else:
4018 ctx = _get_ctx(ctx)
4019 bv = BitVecSort(bv, ctx)
4020 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4021
4022
4023def BitVecs(names, bv, ctx=None):
4024 """Return a tuple of bit-vector constants of size bv.
4025
4026 >>> x, y, z = BitVecs('x y z', 16)
4027 >>> x.size()
4028 16
4029 >>> x.sort()
4030 BitVec(16)
4031 >>> Sum(x, y, z)
4032 0 + x + y + z
4033 >>> Product(x, y, z)
4034 1*x*y*z
4035 >>> simplify(Product(x, y, z))
4036 x*y*z
4037 """
4038 ctx = _get_ctx(ctx)
4039 if isinstance(names, str):
4040 names = names.split(" ")
4041 return [BitVec(name, bv, ctx) for name in names]
4042
4043
4044def Concat(*args):
4045 """Create a Z3 bit-vector concatenation expression.
4046
4047 >>> v = BitVecVal(1, 4)
4048 >>> Concat(v, v+1, v)
4049 Concat(Concat(1, 1 + 1), 1)
4050 >>> simplify(Concat(v, v+1, v))
4051 289
4052 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4053 121
4054 """
4055 args = _get_args(args)
4056 sz = len(args)
4057 if z3_debug():
4058 _z3_assert(sz >= 2, "At least two arguments expected.")
4059
4060 ctx = None
4061 for a in args:
4062 if is_expr(a):
4063 ctx = a.ctx
4064 break
4065 if is_seq(args[0]) or isinstance(args[0], str):
4066 args = [_coerce_seq(s, ctx) for s in args]
4067 if z3_debug():
4068 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4069 v = (Ast * sz)()
4070 for i in range(sz):
4071 v[i] = args[i].as_ast()
4072 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4073
4074 if is_re(args[0]):
4075 if z3_debug():
4076 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4077 v = (Ast * sz)()
4078 for i in range(sz):
4079 v[i] = args[i].as_ast()
4080 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4081
4082 if z3_debug():
4083 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4084 r = args[0]
4085 for i in range(sz - 1):
4086 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4087 return r
4088
4089
4090def Extract(high, low, a):
4091 """Create a Z3 bit-vector extraction expression.
4092 Extract is overloaded to also work on sequence extraction.
4093 The functions SubString and SubSeq are redirected to Extract.
4094 For this case, the arguments are reinterpreted as:
4095 high - is a sequence (string)
4096 low - is an offset
4097 a - is the length to be extracted
4098
4099 >>> x = BitVec('x', 8)
4100 >>> Extract(6, 2, x)
4101 Extract(6, 2, x)
4102 >>> Extract(6, 2, x).sort()
4103 BitVec(5)
4104 >>> simplify(Extract(StringVal("abcd"),2,1))
4105 "c"
4106 """
4107 if isinstance(high, str):
4108 high = StringVal(high)
4109 if is_seq(high):
4110 s = high
4111 offset, length = _coerce_exprs(low, a, s.ctx)
4112 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4113 if z3_debug():
4114 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4115 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4116 "First and second arguments must be non negative integers")
4117 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4118 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4119
4120
4121def _check_bv_args(a, b):
4122 if z3_debug():
4123 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4124
4125
4126def ULE(a, b):
4127 """Create the Z3 expression (unsigned) `other <= self`.
4128
4129 Use the operator <= for signed less than or equal to.
4130
4131 >>> x, y = BitVecs('x y', 32)
4132 >>> ULE(x, y)
4133 ULE(x, y)
4134 >>> (x <= y).sexpr()
4135 '(bvsle x y)'
4136 >>> ULE(x, y).sexpr()
4137 '(bvule x y)'
4138 """
4139 _check_bv_args(a, b)
4140 a, b = _coerce_exprs(a, b)
4141 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4142
4143
4144def ULT(a, b):
4145 """Create the Z3 expression (unsigned) `other < self`.
4146
4147 Use the operator < for signed less than.
4148
4149 >>> x, y = BitVecs('x y', 32)
4150 >>> ULT(x, y)
4151 ULT(x, y)
4152 >>> (x < y).sexpr()
4153 '(bvslt x y)'
4154 >>> ULT(x, y).sexpr()
4155 '(bvult x y)'
4156 """
4157 _check_bv_args(a, b)
4158 a, b = _coerce_exprs(a, b)
4159 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4160
4161
4162def UGE(a, b):
4163 """Create the Z3 expression (unsigned) `other >= self`.
4164
4165 Use the operator >= for signed greater than or equal to.
4166
4167 >>> x, y = BitVecs('x y', 32)
4168 >>> UGE(x, y)
4169 UGE(x, y)
4170 >>> (x >= y).sexpr()
4171 '(bvsge x y)'
4172 >>> UGE(x, y).sexpr()
4173 '(bvuge x y)'
4174 """
4175 _check_bv_args(a, b)
4176 a, b = _coerce_exprs(a, b)
4177 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4178
4179
4180def UGT(a, b):
4181 """Create the Z3 expression (unsigned) `other > self`.
4182
4183 Use the operator > for signed greater than.
4184
4185 >>> x, y = BitVecs('x y', 32)
4186 >>> UGT(x, y)
4187 UGT(x, y)
4188 >>> (x > y).sexpr()
4189 '(bvsgt x y)'
4190 >>> UGT(x, y).sexpr()
4191 '(bvugt x y)'
4192 """
4193 _check_bv_args(a, b)
4194 a, b = _coerce_exprs(a, b)
4195 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4196
4197
4198def UDiv(a, b):
4199 """Create the Z3 expression (unsigned) division `self / other`.
4200
4201 Use the operator / for signed division.
4202
4203 >>> x = BitVec('x', 32)
4204 >>> y = BitVec('y', 32)
4205 >>> UDiv(x, y)
4206 UDiv(x, y)
4207 >>> UDiv(x, y).sort()
4208 BitVec(32)
4209 >>> (x / y).sexpr()
4210 '(bvsdiv x y)'
4211 >>> UDiv(x, y).sexpr()
4212 '(bvudiv x y)'
4213 """
4214 _check_bv_args(a, b)
4215 a, b = _coerce_exprs(a, b)
4216 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4217
4218
4219def URem(a, b):
4220 """Create the Z3 expression (unsigned) remainder `self % other`.
4221
4222 Use the operator % for signed modulus, and SRem() for signed remainder.
4223
4224 >>> x = BitVec('x', 32)
4225 >>> y = BitVec('y', 32)
4226 >>> URem(x, y)
4227 URem(x, y)
4228 >>> URem(x, y).sort()
4229 BitVec(32)
4230 >>> (x % y).sexpr()
4231 '(bvsmod x y)'
4232 >>> URem(x, y).sexpr()
4233 '(bvurem x y)'
4234 """
4235 _check_bv_args(a, b)
4236 a, b = _coerce_exprs(a, b)
4237 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4238
4239
4240def SRem(a, b):
4241 """Create the Z3 expression signed remainder.
4242
4243 Use the operator % for signed modulus, and URem() for unsigned remainder.
4244
4245 >>> x = BitVec('x', 32)
4246 >>> y = BitVec('y', 32)
4247 >>> SRem(x, y)
4248 SRem(x, y)
4249 >>> SRem(x, y).sort()
4250 BitVec(32)
4251 >>> (x % y).sexpr()
4252 '(bvsmod x y)'
4253 >>> SRem(x, y).sexpr()
4254 '(bvsrem x y)'
4255 """
4256 _check_bv_args(a, b)
4257 a, b = _coerce_exprs(a, b)
4258 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4259
4260
4261def LShR(a, b):
4262 """Create the Z3 expression logical right shift.
4263
4264 Use the operator >> for the arithmetical right shift.
4265
4266 >>> x, y = BitVecs('x y', 32)
4267 >>> LShR(x, y)
4268 LShR(x, y)
4269 >>> (x >> y).sexpr()
4270 '(bvashr x y)'
4271 >>> LShR(x, y).sexpr()
4272 '(bvlshr x y)'
4273 >>> BitVecVal(4, 3)
4274 4
4275 >>> BitVecVal(4, 3).as_signed_long()
4276 -4
4277 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4278 -2
4279 >>> simplify(BitVecVal(4, 3) >> 1)
4280 6
4281 >>> simplify(LShR(BitVecVal(4, 3), 1))
4282 2
4283 >>> simplify(BitVecVal(2, 3) >> 1)
4284 1
4285 >>> simplify(LShR(BitVecVal(2, 3), 1))
4286 1
4287 """
4288 _check_bv_args(a, b)
4289 a, b = _coerce_exprs(a, b)
4290 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4291
4292
4293def RotateLeft(a, b):
4294 """Return an expression representing `a` rotated to the left `b` times.
4295
4296 >>> a, b = BitVecs('a b', 16)
4297 >>> RotateLeft(a, b)
4298 RotateLeft(a, b)
4299 >>> simplify(RotateLeft(a, 0))
4300 a
4301 >>> simplify(RotateLeft(a, 16))
4302 a
4303 """
4304 _check_bv_args(a, b)
4305 a, b = _coerce_exprs(a, b)
4306 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4307
4308
4309def RotateRight(a, b):
4310 """Return an expression representing `a` rotated to the right `b` times.
4311
4312 >>> a, b = BitVecs('a b', 16)
4313 >>> RotateRight(a, b)
4314 RotateRight(a, b)
4315 >>> simplify(RotateRight(a, 0))
4316 a
4317 >>> simplify(RotateRight(a, 16))
4318 a
4319 """
4320 _check_bv_args(a, b)
4321 a, b = _coerce_exprs(a, b)
4322 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4323
4324
4325def SignExt(n, a):
4326 """Return a bit-vector expression with `n` extra sign-bits.
4327
4328 >>> x = BitVec('x', 16)
4329 >>> n = SignExt(8, x)
4330 >>> n.size()
4331 24
4332 >>> n
4333 SignExt(8, x)
4334 >>> n.sort()
4335 BitVec(24)
4336 >>> v0 = BitVecVal(2, 2)
4337 >>> v0
4338 2
4339 >>> v0.size()
4340 2
4341 >>> v = simplify(SignExt(6, v0))
4342 >>> v
4343 254
4344 >>> v.size()
4345 8
4346 >>> print("%.x" % v.as_long())
4347 fe
4348 """
4349 if z3_debug():
4350 _z3_assert(_is_int(n), "First argument must be an integer")
4351 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4352 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4353
4354
4355def ZeroExt(n, a):
4356 """Return a bit-vector expression with `n` extra zero-bits.
4357
4358 >>> x = BitVec('x', 16)
4359 >>> n = ZeroExt(8, x)
4360 >>> n.size()
4361 24
4362 >>> n
4363 ZeroExt(8, x)
4364 >>> n.sort()
4365 BitVec(24)
4366 >>> v0 = BitVecVal(2, 2)
4367 >>> v0
4368 2
4369 >>> v0.size()
4370 2
4371 >>> v = simplify(ZeroExt(6, v0))
4372 >>> v
4373 2
4374 >>> v.size()
4375 8
4376 """
4377 if z3_debug():
4378 _z3_assert(_is_int(n), "First argument must be an integer")
4379 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4380 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4381
4382
4384 """Return an expression representing `n` copies of `a`.
4385
4386 >>> x = BitVec('x', 8)
4387 >>> n = RepeatBitVec(4, x)
4388 >>> n
4389 RepeatBitVec(4, x)
4390 >>> n.size()
4391 32
4392 >>> v0 = BitVecVal(10, 4)
4393 >>> print("%.x" % v0.as_long())
4394 a
4395 >>> v = simplify(RepeatBitVec(4, v0))
4396 >>> v.size()
4397 16
4398 >>> print("%.x" % v.as_long())
4399 aaaa
4400 """
4401 if z3_debug():
4402 _z3_assert(_is_int(n), "First argument must be an integer")
4403 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4404 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4405
4406
4408 """Return the reduction-and expression of `a`."""
4409 if z3_debug():
4410 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4411 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4412
4413
4414def BVRedOr(a):
4415 """Return the reduction-or expression of `a`."""
4416 if z3_debug():
4417 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4418 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4419
4420
4421def BVAddNoOverflow(a, b, signed):
4422 """A predicate the determines that bit-vector addition does not overflow"""
4423 _check_bv_args(a, b)
4424 a, b = _coerce_exprs(a, b)
4425 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4426
4427
4429 """A predicate the determines that signed bit-vector addition does not underflow"""
4430 _check_bv_args(a, b)
4431 a, b = _coerce_exprs(a, b)
4432 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4433
4434
4436 """A predicate the determines that bit-vector subtraction does not overflow"""
4437 _check_bv_args(a, b)
4438 a, b = _coerce_exprs(a, b)
4439 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4440
4441
4442def BVSubNoUnderflow(a, b, signed):
4443 """A predicate the determines that bit-vector subtraction does not underflow"""
4444 _check_bv_args(a, b)
4445 a, b = _coerce_exprs(a, b)
4446 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4447
4448
4450 """A predicate the determines that bit-vector signed division does not overflow"""
4451 _check_bv_args(a, b)
4452 a, b = _coerce_exprs(a, b)
4453 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4454
4455
4457 """A predicate the determines that bit-vector unary negation does not overflow"""
4458 if z3_debug():
4459 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4460 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4461
4462
4463def BVMulNoOverflow(a, b, signed):
4464 """A predicate the determines that bit-vector multiplication does not overflow"""
4465 _check_bv_args(a, b)
4466 a, b = _coerce_exprs(a, b)
4467 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4468
4469
4471 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4472 _check_bv_args(a, b)
4473 a, b = _coerce_exprs(a, b)
4474 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4475
4476
4477
4482
4484 """Array sorts."""
4485
4486 def domain(self):
4487 """Return the domain of the array sort `self`.
4488
4489 >>> A = ArraySort(IntSort(), BoolSort())
4490 >>> A.domain()
4491 Int
4492 """
4493 return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4494
4495 def range(self):
4496 """Return the range of the array sort `self`.
4497
4498 >>> A = ArraySort(IntSort(), BoolSort())
4499 >>> A.range()
4500 Bool
4501 """
4502 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4503
4504
4506 """Array expressions. """
4507
4508 def sort(self):
4509 """Return the array sort of the array expression `self`.
4510
4511 >>> a = Array('a', IntSort(), BoolSort())
4512 >>> a.sort()
4513 Array(Int, Bool)
4514 """
4515 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4516
4517 def domain(self):
4518 """Shorthand for `self.sort().domain()`.
4519
4520 >>> a = Array('a', IntSort(), BoolSort())
4521 >>> a.domain()
4522 Int
4523 """
4524 return self.sortsort().domain()
4525
4526 def range(self):
4527 """Shorthand for `self.sort().range()`.
4528
4529 >>> a = Array('a', IntSort(), BoolSort())
4530 >>> a.range()
4531 Bool
4532 """
4533 return self.sortsort().range()
4534
4535 def __getitem__(self, arg):
4536 """Return the Z3 expression `self[arg]`.
4537
4538 >>> a = Array('a', IntSort(), BoolSort())
4539 >>> i = Int('i')
4540 >>> a[i]
4541 a[i]
4542 >>> a[i].sexpr()
4543 '(select a i)'
4544 """
4545 arg = self.domain().cast(arg)
4546 return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_astas_ast(), arg.as_ast()), self.ctx)
4547
4548 def default(self):
4549 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4550
4551
4553 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4554
4555
4557 """Return `True` if `a` is a Z3 array expression.
4558
4559 >>> a = Array('a', IntSort(), IntSort())
4560 >>> is_array(a)
4561 True
4562 >>> is_array(Store(a, 0, 1))
4563 True
4564 >>> is_array(a[0])
4565 False
4566 """
4567 return isinstance(a, ArrayRef)
4568
4569
4571 """Return `True` if `a` is a Z3 constant array.
4572
4573 >>> a = K(IntSort(), 10)
4574 >>> is_const_array(a)
4575 True
4576 >>> a = Array('a', IntSort(), IntSort())
4577 >>> is_const_array(a)
4578 False
4579 """
4580 return is_app_of(a, Z3_OP_CONST_ARRAY)
4581
4582
4583def is_K(a):
4584 """Return `True` if `a` is a Z3 constant array.
4585
4586 >>> a = K(IntSort(), 10)
4587 >>> is_K(a)
4588 True
4589 >>> a = Array('a', IntSort(), IntSort())
4590 >>> is_K(a)
4591 False
4592 """
4593 return is_app_of(a, Z3_OP_CONST_ARRAY)
4594
4595
4596def is_map(a):
4597 """Return `True` if `a` is a Z3 map array expression.
4598
4599 >>> f = Function('f', IntSort(), IntSort())
4600 >>> b = Array('b', IntSort(), IntSort())
4601 >>> a = Map(f, b)
4602 >>> a
4603 Map(f, b)
4604 >>> is_map(a)
4605 True
4606 >>> is_map(b)
4607 False
4608 """
4609 return is_app_of(a, Z3_OP_ARRAY_MAP)
4610
4611
4613 """Return `True` if `a` is a Z3 default array expression.
4614 >>> d = Default(K(IntSort(), 10))
4615 >>> is_default(d)
4616 True
4617 """
4618 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4619
4620
4622 """Return the function declaration associated with a Z3 map array expression.
4623
4624 >>> f = Function('f', IntSort(), IntSort())
4625 >>> b = Array('b', IntSort(), IntSort())
4626 >>> a = Map(f, b)
4627 >>> eq(f, get_map_func(a))
4628 True
4629 >>> get_map_func(a)
4630 f
4631 >>> get_map_func(a)(0)
4632 f(0)
4633 """
4634 if z3_debug():
4635 _z3_assert(is_map(a), "Z3 array map expression expected.")
4636 return FuncDeclRef(
4638 a.ctx_ref(),
4639 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4640 ),
4641 ctx=a.ctx,
4642 )
4643
4644
4645def ArraySort(*sig):
4646 """Return the Z3 array sort with the given domain and range sorts.
4647
4648 >>> A = ArraySort(IntSort(), BoolSort())
4649 >>> A
4650 Array(Int, Bool)
4651 >>> A.domain()
4652 Int
4653 >>> A.range()
4654 Bool
4655 >>> AA = ArraySort(IntSort(), A)
4656 >>> AA
4657 Array(Int, Array(Int, Bool))
4658 """
4659 sig = _get_args(sig)
4660 if z3_debug():
4661 _z3_assert(len(sig) > 1, "At least two arguments expected")
4662 arity = len(sig) - 1
4663 r = sig[arity]
4664 d = sig[0]
4665 if z3_debug():
4666 for s in sig:
4667 _z3_assert(is_sort(s), "Z3 sort expected")
4668 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4669 ctx = d.ctx
4670 if len(sig) == 2:
4671 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4672 dom = (Sort * arity)()
4673 for i in range(arity):
4674 dom[i] = sig[i].ast
4675 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4676
4677
4678def Array(name, dom, rng):
4679 """Return an array constant named `name` with the given domain and range sorts.
4680
4681 >>> a = Array('a', IntSort(), IntSort())
4682 >>> a.sort()
4683 Array(Int, Int)
4684 >>> a[0]
4685 a[0]
4686 """
4687 s = ArraySort(dom, rng)
4688 ctx = s.ctx
4689 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4690
4691
4692def Update(a, i, v):
4693 """Return a Z3 store array expression.
4694
4695 >>> a = Array('a', IntSort(), IntSort())
4696 >>> i, v = Ints('i v')
4697 >>> s = Update(a, i, v)
4698 >>> s.sort()
4699 Array(Int, Int)
4700 >>> prove(s[i] == v)
4701 proved
4702 >>> j = Int('j')
4703 >>> prove(Implies(i != j, s[j] == a[j]))
4704 proved
4705 """
4706 if z3_debug():
4707 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4708 i = a.sort().domain().cast(i)
4709 v = a.sort().range().cast(v)
4710 ctx = a.ctx
4711 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4712
4713
4714def Default(a):
4715 """ Return a default value for array expression.
4716 >>> b = K(IntSort(), 1)
4717 >>> prove(Default(b) == 1)
4718 proved
4719 """
4720 if z3_debug():
4721 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4722 return a.default()
4723
4724
4725def Store(a, i, v):
4726 """Return a Z3 store array expression.
4727
4728 >>> a = Array('a', IntSort(), IntSort())
4729 >>> i, v = Ints('i v')
4730 >>> s = Store(a, i, v)
4731 >>> s.sort()
4732 Array(Int, Int)
4733 >>> prove(s[i] == v)
4734 proved
4735 >>> j = Int('j')
4736 >>> prove(Implies(i != j, s[j] == a[j]))
4737 proved
4738 """
4739 return Update(a, i, v)
4740
4741
4742def Select(a, i):
4743 """Return a Z3 select array expression.
4744
4745 >>> a = Array('a', IntSort(), IntSort())
4746 >>> i = Int('i')
4747 >>> Select(a, i)
4748 a[i]
4749 >>> eq(Select(a, i), a[i])
4750 True
4751 """
4752 if z3_debug():
4753 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4754 return a[i]
4755
4756
4757def Map(f, *args):
4758 """Return a Z3 map array expression.
4759
4760 >>> f = Function('f', IntSort(), IntSort(), IntSort())
4761 >>> a1 = Array('a1', IntSort(), IntSort())
4762 >>> a2 = Array('a2', IntSort(), IntSort())
4763 >>> b = Map(f, a1, a2)
4764 >>> b
4765 Map(f, a1, a2)
4766 >>> prove(b[0] == f(a1[0], a2[0]))
4767 proved
4768 """
4769 args = _get_args(args)
4770 if z3_debug():
4771 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4772 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4773 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4774 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4775 _args, sz = _to_ast_array(args)
4776 ctx = f.ctx
4777 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4778
4779
4780def K(dom, v):
4781 """Return a Z3 constant array expression.
4782
4783 >>> a = K(IntSort(), 10)
4784 >>> a
4785 K(Int, 10)
4786 >>> a.sort()
4787 Array(Int, Int)
4788 >>> i = Int('i')
4789 >>> a[i]
4790 K(Int, 10)[i]
4791 >>> simplify(a[i])
4792 10
4793 """
4794 if z3_debug():
4795 _z3_assert(is_sort(dom), "Z3 sort expected")
4796 ctx = dom.ctx
4797 if not is_expr(v):
4798 v = _py2expr(v, ctx)
4799 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4800
4801
4802def Ext(a, b):
4803 """Return extensionality index for one-dimensional arrays.
4804 >> a, b = Consts('a b', SetSort(IntSort()))
4805 >> Ext(a, b)
4806 Ext(a, b)
4807 """
4808 ctx = a.ctx
4809 if z3_debug():
4810 _z3_assert(is_array_sort(a) and is_array(b), "arguments must be arrays")
4811 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4812
4813
4814def SetHasSize(a, k):
4815 ctx = a.ctx
4816 k = _py2expr(k, ctx)
4817 return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4818
4819
4821 """Return `True` if `a` is a Z3 array select application.
4822
4823 >>> a = Array('a', IntSort(), IntSort())
4824 >>> is_select(a)
4825 False
4826 >>> i = Int('i')
4827 >>> is_select(a[i])
4828 True
4829 """
4830 return is_app_of(a, Z3_OP_SELECT)
4831
4832
4834 """Return `True` if `a` is a Z3 array store application.
4835
4836 >>> a = Array('a', IntSort(), IntSort())
4837 >>> is_store(a)
4838 False
4839 >>> is_store(Store(a, 0, 1))
4840 True
4841 """
4842 return is_app_of(a, Z3_OP_STORE)
4843
4844
4849
4850
4851def SetSort(s):
4852 """ Create a set sort over element sort s"""
4853 return ArraySort(s, BoolSort())
4854
4855
4857 """Create the empty set
4858 >>> EmptySet(IntSort())
4859 K(Int, False)
4860 """
4861 ctx = s.ctx
4862 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4863
4864
4865def FullSet(s):
4866 """Create the full set
4867 >>> FullSet(IntSort())
4868 K(Int, True)
4869 """
4870 ctx = s.ctx
4871 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4872
4873
4874def SetUnion(*args):
4875 """ Take the union of sets
4876 >>> a = Const('a', SetSort(IntSort()))
4877 >>> b = Const('b', SetSort(IntSort()))
4878 >>> SetUnion(a, b)
4879 union(a, b)
4880 """
4881 args = _get_args(args)
4882 ctx = _ctx_from_ast_arg_list(args)
4883 _args, sz = _to_ast_array(args)
4884 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4885
4886
4887def SetIntersect(*args):
4888 """ Take the union of sets
4889 >>> a = Const('a', SetSort(IntSort()))
4890 >>> b = Const('b', SetSort(IntSort()))
4891 >>> SetIntersect(a, b)
4892 intersection(a, b)
4893 """
4894 args = _get_args(args)
4895 ctx = _ctx_from_ast_arg_list(args)
4896 _args, sz = _to_ast_array(args)
4897 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4898
4899
4900def SetAdd(s, e):
4901 """ Add element e to set s
4902 >>> a = Const('a', SetSort(IntSort()))
4903 >>> SetAdd(a, 1)
4904 Store(a, 1, True)
4905 """
4906 ctx = _ctx_from_ast_arg_list([s, e])
4907 e = _py2expr(e, ctx)
4908 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4909
4910
4911def SetDel(s, e):
4912 """ Remove element e to set s
4913 >>> a = Const('a', SetSort(IntSort()))
4914 >>> SetDel(a, 1)
4915 Store(a, 1, False)
4916 """
4917 ctx = _ctx_from_ast_arg_list([s, e])
4918 e = _py2expr(e, ctx)
4919 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4920
4921
4923 """ The complement of set s
4924 >>> a = Const('a', SetSort(IntSort()))
4925 >>> SetComplement(a)
4926 complement(a)
4927 """
4928 ctx = s.ctx
4929 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4930
4931
4933 """ The set difference of a and b
4934 >>> a = Const('a', SetSort(IntSort()))
4935 >>> b = Const('b', SetSort(IntSort()))
4936 >>> SetDifference(a, b)
4937 setminus(a, b)
4938 """
4939 ctx = _ctx_from_ast_arg_list([a, b])
4940 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4941
4942
4943def IsMember(e, s):
4944 """ Check if e is a member of set s
4945 >>> a = Const('a', SetSort(IntSort()))
4946 >>> IsMember(1, a)
4947 a[1]
4948 """
4949 ctx = _ctx_from_ast_arg_list([s, e])
4950 e = _py2expr(e, ctx)
4951 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4952
4953
4954def IsSubset(a, b):
4955 """ Check if a is a subset of b
4956 >>> a = Const('a', SetSort(IntSort()))
4957 >>> b = Const('b', SetSort(IntSort()))
4958 >>> IsSubset(a, b)
4959 subset(a, b)
4960 """
4961 ctx = _ctx_from_ast_arg_list([a, b])
4962 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4963
4964
4965
4970
4971def _valid_accessor(acc):
4972 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4973 if not isinstance(acc, tuple):
4974 return False
4975 if len(acc) != 2:
4976 return False
4977 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4978
4979
4981 """Helper class for declaring Z3 datatypes.
4982
4983 >>> List = Datatype('List')
4984 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4985 >>> List.declare('nil')
4986 >>> List = List.create()
4987 >>> # List is now a Z3 declaration
4988 >>> List.nil
4989 nil
4990 >>> List.cons(10, List.nil)
4991 cons(10, nil)
4992 >>> List.cons(10, List.nil).sort()
4993 List
4994 >>> cons = List.cons
4995 >>> nil = List.nil
4996 >>> car = List.car
4997 >>> cdr = List.cdr
4998 >>> n = cons(1, cons(0, nil))
4999 >>> n
5000 cons(1, cons(0, nil))
5001 >>> simplify(cdr(n))
5002 cons(0, nil)
5003 >>> simplify(car(n))
5004 1
5005 """
5006
5007 def __init__(self, name, ctx=None):
5008 self.ctx = _get_ctx(ctx)
5009 self.name = name
5011
5012 def __deepcopy__(self, memo={}):
5013 r = Datatype(self.name, self.ctx)
5014 r.constructors = copy.deepcopy(self.constructors)
5015 return r
5016
5017 def declare_core(self, name, rec_name, *args):
5018 if z3_debug():
5019 _z3_assert(isinstance(name, str), "String expected")
5020 _z3_assert(isinstance(rec_name, str), "String expected")
5021 _z3_assert(
5022 all([_valid_accessor(a) for a in args]),
5023 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5024 )
5025 self.constructors.append((name, rec_name, args))
5026
5027 def declare(self, name, *args):
5028 """Declare constructor named `name` with the given accessors `args`.
5029 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5030 or a reference to the datatypes being declared.
5031
5032 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5033 declares the constructor named `cons` that builds a new List using an integer and a List.
5034 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5035 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5036 we use the method create() to create the actual datatype in Z3.
5037
5038 >>> List = Datatype('List')
5039 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5040 >>> List.declare('nil')
5041 >>> List = List.create()
5042 """
5043 if z3_debug():
5044 _z3_assert(isinstance(name, str), "String expected")
5045 _z3_assert(name != "", "Constructor name cannot be empty")
5046 return self.declare_core(name, "is-" + name, *args)
5047
5048 def __repr__(self):
5049 return "Datatype(%s, %s)" % (self.name, self.constructors)
5050
5051 def create(self):
5052 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5053
5054 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5055
5056 >>> List = Datatype('List')
5057 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5058 >>> List.declare('nil')
5059 >>> List = List.create()
5060 >>> List.nil
5061 nil
5062 >>> List.cons(10, List.nil)
5063 cons(10, nil)
5064 """
5065 return CreateDatatypes([self])[0]
5066
5067
5069 """Auxiliary object used to create Z3 datatypes."""
5070
5071 def __init__(self, c, ctx):
5072 self.c = c
5073 self.ctx = ctx
5074
5075 def __del__(self):
5076 if self.ctx.ref() is not None:
5077 Z3_del_constructor(self.ctx.ref(), self.c)
5078
5079
5081 """Auxiliary object used to create Z3 datatypes."""
5082
5083 def __init__(self, c, ctx):
5084 self.c = c
5085 self.ctx = ctx
5086
5087 def __del__(self):
5088 if self.ctx.ref() is not None:
5089 Z3_del_constructor_list(self.ctx.ref(), self.c)
5090
5091
5093 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5094
5095 In the following example we define a Tree-List using two mutually recursive datatypes.
5096
5097 >>> TreeList = Datatype('TreeList')
5098 >>> Tree = Datatype('Tree')
5099 >>> # Tree has two constructors: leaf and node
5100 >>> Tree.declare('leaf', ('val', IntSort()))
5101 >>> # a node contains a list of trees
5102 >>> Tree.declare('node', ('children', TreeList))
5103 >>> TreeList.declare('nil')
5104 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5105 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5106 >>> Tree.val(Tree.leaf(10))
5107 val(leaf(10))
5108 >>> simplify(Tree.val(Tree.leaf(10)))
5109 10
5110 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5111 >>> n1
5112 node(cons(leaf(10), cons(leaf(20), nil)))
5113 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5114 >>> simplify(n2 == n1)
5115 False
5116 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5117 True
5118 """
5119 ds = _get_args(ds)
5120 if z3_debug():
5121 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5122 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5123 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5124 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5125 ctx = ds[0].ctx
5126 num = len(ds)
5127 names = (Symbol * num)()
5128 out = (Sort * num)()
5129 clists = (ConstructorList * num)()
5130 to_delete = []
5131 for i in range(num):
5132 d = ds[i]
5133 names[i] = to_symbol(d.name, ctx)
5134 num_cs = len(d.constructors)
5135 cs = (Constructor * num_cs)()
5136 for j in range(num_cs):
5137 c = d.constructors[j]
5138 cname = to_symbol(c[0], ctx)
5139 rname = to_symbol(c[1], ctx)
5140 fs = c[2]
5141 num_fs = len(fs)
5142 fnames = (Symbol * num_fs)()
5143 sorts = (Sort * num_fs)()
5144 refs = (ctypes.c_uint * num_fs)()
5145 for k in range(num_fs):
5146 fname = fs[k][0]
5147 ftype = fs[k][1]
5148 fnames[k] = to_symbol(fname, ctx)
5149 if isinstance(ftype, Datatype):
5150 if z3_debug():
5151 _z3_assert(
5152 ds.count(ftype) == 1,
5153 "One and only one occurrence of each datatype is expected",
5154 )
5155 sorts[k] = None
5156 refs[k] = ds.index(ftype)
5157 else:
5158 if z3_debug():
5159 _z3_assert(is_sort(ftype), "Z3 sort expected")
5160 sorts[k] = ftype.ast
5161 refs[k] = 0
5162 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5163 to_delete.append(ScopedConstructor(cs[j], ctx))
5164 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5165 to_delete.append(ScopedConstructorList(clists[i], ctx))
5166 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5167 result = []
5168 # Create a field for every constructor, recognizer and accessor
5169 for i in range(num):
5170 dref = DatatypeSortRef(out[i], ctx)
5171 num_cs = dref.num_constructors()
5172 for j in range(num_cs):
5173 cref = dref.constructor(j)
5174 cref_name = cref.name()
5175 cref_arity = cref.arity()
5176 if cref.arity() == 0:
5177 cref = cref()
5178 setattr(dref, cref_name, cref)
5179 rref = dref.recognizer(j)
5180 setattr(dref, "is_" + cref_name, rref)
5181 for k in range(cref_arity):
5182 aref = dref.accessor(j, k)
5183 setattr(dref, aref.name(), aref)
5184 result.append(dref)
5185 return tuple(result)
5186
5187
5189 """Datatype sorts."""
5190
5192 """Return the number of constructors in the given Z3 datatype.
5193
5194 >>> List = Datatype('List')
5195 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5196 >>> List.declare('nil')
5197 >>> List = List.create()
5198 >>> # List is now a Z3 declaration
5199 >>> List.num_constructors()
5200 2
5201 """
5202 return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
5203
5204 def constructor(self, idx):
5205 """Return a constructor of the datatype `self`.
5206
5207 >>> List = Datatype('List')
5208 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5209 >>> List.declare('nil')
5210 >>> List = List.create()
5211 >>> # List is now a Z3 declaration
5212 >>> List.num_constructors()
5213 2
5214 >>> List.constructor(0)
5215 cons
5216 >>> List.constructor(1)
5217 nil
5218 """
5219 if z3_debug():
5220 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5221 return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
5222
5223 def recognizer(self, idx):
5224 """In Z3, each constructor has an associated recognizer predicate.
5225
5226 If the constructor is named `name`, then the recognizer `is_name`.
5227
5228 >>> List = Datatype('List')
5229 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5230 >>> List.declare('nil')
5231 >>> List = List.create()
5232 >>> # List is now a Z3 declaration
5233 >>> List.num_constructors()
5234 2
5235 >>> List.recognizer(0)
5236 is(cons)
5237 >>> List.recognizer(1)
5238 is(nil)
5239 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5240 False
5241 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5242 True
5243 >>> l = Const('l', List)
5244 >>> simplify(List.is_cons(l))
5245 is(cons, l)
5246 """
5247 if z3_debug():
5248 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5249 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
5250
5251 def accessor(self, i, j):
5252 """In Z3, each constructor has 0 or more accessor.
5253 The number of accessors is equal to the arity of the constructor.
5254
5255 >>> List = Datatype('List')
5256 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5257 >>> List.declare('nil')
5258 >>> List = List.create()
5259 >>> List.num_constructors()
5260 2
5261 >>> List.constructor(0)
5262 cons
5263 >>> num_accs = List.constructor(0).arity()
5264 >>> num_accs
5265 2
5266 >>> List.accessor(0, 0)
5267 car
5268 >>> List.accessor(0, 1)
5269 cdr
5270 >>> List.constructor(1)
5271 nil
5272 >>> num_accs = List.constructor(1).arity()
5273 >>> num_accs
5274 0
5275 """
5276 if z3_debug():
5277 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5278 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5279 return FuncDeclRef(
5281 ctx=self.ctx,
5282 )
5283
5284
5286 """Datatype expressions."""
5287
5288 def sort(self):
5289 """Return the datatype sort of the datatype expression `self`."""
5290 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
5291
5292
5293def TupleSort(name, sorts, ctx=None):
5294 """Create a named tuple sort base on a set of underlying sorts
5295 Example:
5296 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5297 """
5298 tuple = Datatype(name, ctx)
5299 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5300 tuple.declare(name, *projects)
5301 tuple = tuple.create()
5302 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5303
5304
5305def DisjointSum(name, sorts, ctx=None):
5306 """Create a named tagged union sort base on a set of underlying sorts
5307 Example:
5308 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5309 """
5310 sum = Datatype(name, ctx)
5311 for i in range(len(sorts)):
5312 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5313 sum = sum.create()
5314 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5315
5316
5317def EnumSort(name, values, ctx=None):
5318 """Return a new enumeration sort named `name` containing the given values.
5319
5320 The result is a pair (sort, list of constants).
5321 Example:
5322 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5323 """
5324 if z3_debug():
5325 _z3_assert(isinstance(name, str), "Name must be a string")
5326 _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5327 _z3_assert(len(values) > 0, "At least one value expected")
5328 ctx = _get_ctx(ctx)
5329 num = len(values)
5330 _val_names = (Symbol * num)()
5331 for i in range(num):
5332 _val_names[i] = to_symbol(values[i])
5333 _values = (FuncDecl * num)()
5334 _testers = (FuncDecl * num)()
5335 name = to_symbol(name)
5336 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5337 V = []
5338 for i in range(num):
5339 V.append(FuncDeclRef(_values[i], ctx))
5340 V = [a() for a in V]
5341 return S, V
5342
5343
5348
5349
5351 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5352
5353 Consider using the function `args2params` to create instances of this object.
5354 """
5355
5356 def __init__(self, ctx=None, params=None):
5357 self.ctx = _get_ctx(ctx)
5358 if params is None:
5359 self.params = Z3_mk_params(self.ctx.ref())
5360 else:
5361 self.params = params
5362 Z3_params_inc_ref(self.ctx.ref(), self.params)
5363
5364 def __deepcopy__(self, memo={}):
5365 return ParamsRef(self.ctx, self.params)
5366
5367 def __del__(self):
5368 if self.ctx.ref() is not None:
5369 Z3_params_dec_ref(self.ctx.ref(), self.params)
5370
5371 def set(self, name, val):
5372 """Set parameter name with value val."""
5373 if z3_debug():
5374 _z3_assert(isinstance(name, str), "parameter name must be a string")
5375 name_sym = to_symbol(name, self.ctx)
5376 if isinstance(val, bool):
5377 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5378 elif _is_int(val):
5379 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5380 elif isinstance(val, float):
5381 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5382 elif isinstance(val, str):
5383 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5384 else:
5385 if z3_debug():
5386 _z3_assert(False, "invalid parameter value")
5387
5388 def __repr__(self):
5389 return Z3_params_to_string(self.ctx.ref(), self.params)
5390
5391 def validate(self, ds):
5392 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5393 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5394
5395
5396def args2params(arguments, keywords, ctx=None):
5397 """Convert python arguments into a Z3_params object.
5398 A ':' is added to the keywords, and '_' is replaced with '-'
5399
5400 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5401 (params model true relevancy 2 elim_and true)
5402 """
5403 if z3_debug():
5404 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5405 prev = None
5406 r = ParamsRef(ctx)
5407 for a in arguments:
5408 if prev is None:
5409 prev = a
5410 else:
5411 r.set(prev, a)
5412 prev = None
5413 for k in keywords:
5414 v = keywords[k]
5415 r.set(k, v)
5416 return r
5417
5418
5420 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5421 """
5422
5423 def __init__(self, descr, ctx=None):
5424 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5425 self.ctx = _get_ctx(ctx)
5426 self.descr = descr
5427 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5428
5429 def __deepcopy__(self, memo={}):
5430 return ParamsDescrsRef(self.descr, self.ctx)
5431
5432 def __del__(self):
5433 if self.ctx.ref() is not None:
5434 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5435
5436 def size(self):
5437 """Return the size of in the parameter description `self`.
5438 """
5439 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5440
5441 def __len__(self):
5442 """Return the size of in the parameter description `self`.
5443 """
5444 return self.size()
5445
5446 def get_name(self, i):
5447 """Return the i-th parameter name in the parameter description `self`.
5448 """
5449 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5450
5451 def get_kind(self, n):
5452 """Return the kind of the parameter named `n`.
5453 """
5454 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5455
5456 def get_documentation(self, n):
5457 """Return the documentation string of the parameter named `n`.
5458 """
5459 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5460
5461 def __getitem__(self, arg):
5462 if _is_int(arg):
5463 return self.get_name(arg)
5464 else:
5465 return self.get_kind(arg)
5466
5467 def __repr__(self):
5468 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5469
5470
5475
5476
5478 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5479
5480 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5481 A goal has a solution if one of its subgoals has a solution.
5482 A goal is unsatisfiable if all subgoals are unsatisfiable.
5483 """
5484
5485 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5486 if z3_debug():
5487 _z3_assert(goal is None or ctx is not None,
5488 "If goal is different from None, then ctx must be also different from None")
5489 self.ctx = _get_ctx(ctx)
5490 self.goal = goal
5491 if self.goal is None:
5492 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5493 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5494
5495 def __del__(self):
5496 if self.goal is not None and self.ctx.ref() is not None:
5497 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5498
5499 def depth(self):
5500 """Return the depth of the goal `self`.
5501 The depth corresponds to the number of tactics applied to `self`.
5502
5503 >>> x, y = Ints('x y')
5504 >>> g = Goal()
5505 >>> g.add(x == 0, y >= x + 1)
5506 >>> g.depth()
5507 0
5508 >>> r = Then('simplify', 'solve-eqs')(g)
5509 >>> # r has 1 subgoal
5510 >>> len(r)
5511 1
5512 >>> r[0].depth()
5513 2
5514 """
5515 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5516
5517 def inconsistent(self):
5518 """Return `True` if `self` contains the `False` constraints.
5519
5520 >>> x, y = Ints('x y')
5521 >>> g = Goal()
5522 >>> g.inconsistent()
5523 False
5524 >>> g.add(x == 0, x == 1)
5525 >>> g
5526 [x == 0, x == 1]
5527 >>> g.inconsistent()
5528 False
5529 >>> g2 = Tactic('propagate-values')(g)[0]
5530 >>> g2.inconsistent()
5531 True
5532 """
5533 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5534
5535 def prec(self):
5536 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5537
5538 >>> g = Goal()
5539 >>> g.prec() == Z3_GOAL_PRECISE
5540 True
5541 >>> x, y = Ints('x y')
5542 >>> g.add(x == y + 1)
5543 >>> g.prec() == Z3_GOAL_PRECISE
5544 True
5545 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5546 >>> g2 = t(g)[0]
5547 >>> g2
5548 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5549 >>> g2.prec() == Z3_GOAL_PRECISE
5550 False
5551 >>> g2.prec() == Z3_GOAL_UNDER
5552 True
5553 """
5554 return Z3_goal_precision(self.ctx.ref(), self.goal)
5555
5556 def precision(self):
5557 """Alias for `prec()`.
5558
5559 >>> g = Goal()
5560 >>> g.precision() == Z3_GOAL_PRECISE
5561 True
5562 """
5563 return self.prec()
5564
5565 def size(self):
5566 """Return the number of constraints in the goal `self`.
5567
5568 >>> g = Goal()
5569 >>> g.size()
5570 0
5571 >>> x, y = Ints('x y')
5572 >>> g.add(x == 0, y > x)
5573 >>> g.size()
5574 2
5575 """
5576 return int(Z3_goal_size(self.ctx.ref(), self.goal))
5577
5578 def __len__(self):
5579 """Return the number of constraints in the goal `self`.
5580
5581 >>> g = Goal()
5582 >>> len(g)
5583 0
5584 >>> x, y = Ints('x y')
5585 >>> g.add(x == 0, y > x)
5586 >>> len(g)
5587 2
5588 """
5589 return self.size()
5590
5591 def get(self, i):
5592 """Return a constraint in the goal `self`.
5593
5594 >>> g = Goal()
5595 >>> x, y = Ints('x y')
5596 >>> g.add(x == 0, y > x)
5597 >>> g.get(0)
5598 x == 0
5599 >>> g.get(1)
5600 y > x
5601 """
5602 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5603
5604 def __getitem__(self, arg):
5605 """Return a constraint in the goal `self`.
5606
5607 >>> g = Goal()
5608 >>> x, y = Ints('x y')
5609 >>> g.add(x == 0, y > x)
5610 >>> g[0]
5611 x == 0
5612 >>> g[1]
5613 y > x
5614 """
5615 if arg >= len(self):
5616 raise IndexError
5617 return self.get(arg)
5618
5619 def assert_exprs(self, *args):
5620 """Assert constraints into the goal.
5621
5622 >>> x = Int('x')
5623 >>> g = Goal()
5624 >>> g.assert_exprs(x > 0, x < 2)
5625 >>> g
5626 [x > 0, x < 2]
5627 """
5628 args = _get_args(args)
5629 s = BoolSort(self.ctx)
5630 for arg in args:
5631 arg = s.cast(arg)
5632 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5633
5634 def append(self, *args):
5635 """Add constraints.
5636
5637 >>> x = Int('x')
5638 >>> g = Goal()
5639 >>> g.append(x > 0, x < 2)
5640 >>> g
5641 [x > 0, x < 2]
5642 """
5643 self.assert_exprs(*args)
5644
5645 def insert(self, *args):
5646 """Add constraints.
5647
5648 >>> x = Int('x')
5649 >>> g = Goal()
5650 >>> g.insert(x > 0, x < 2)
5651 >>> g
5652 [x > 0, x < 2]
5653 """
5654 self.assert_exprs(*args)
5655
5656 def add(self, *args):
5657 """Add constraints.
5658
5659 >>> x = Int('x')
5660 >>> g = Goal()
5661 >>> g.add(x > 0, x < 2)
5662 >>> g
5663 [x > 0, x < 2]
5664 """
5665 self.assert_exprs(*args)
5666
5667 def convert_model(self, model):
5668 """Retrieve model from a satisfiable goal
5669 >>> a, b = Ints('a b')
5670 >>> g = Goal()
5671 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5672 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5673 >>> r = t(g)
5674 >>> r[0]
5675 [Or(b == 0, b == 1), Not(0 <= b)]
5676 >>> r[1]
5677 [Or(b == 0, b == 1), Not(1 <= b)]
5678 >>> # Remark: the subgoal r[0] is unsatisfiable
5679 >>> # Creating a solver for solving the second subgoal
5680 >>> s = Solver()
5681 >>> s.add(r[1])
5682 >>> s.check()
5683 sat
5684 >>> s.model()
5685 [b = 0]
5686 >>> # Model s.model() does not assign a value to `a`
5687 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5688 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5689 >>> r[1].convert_model(s.model())
5690 [b = 0, a = 1]
5691 """
5692 if z3_debug():
5693 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5694 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5695
5696 def __repr__(self):
5697 return obj_to_string(self)
5698
5699 def sexpr(self):
5700 """Return a textual representation of the s-expression representing the goal."""
5701 return Z3_goal_to_string(self.ctx.ref(), self.goal)
5702
5703 def dimacs(self, include_names=True):
5704 """Return a textual representation of the goal in DIMACS format."""
5705 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
5706
5707 def translate(self, target):
5708 """Copy goal `self` to context `target`.
5709
5710 >>> x = Int('x')
5711 >>> g = Goal()
5712 >>> g.add(x > 10)
5713 >>> g
5714 [x > 10]
5715 >>> c2 = Context()
5716 >>> g2 = g.translate(c2)
5717 >>> g2
5718 [x > 10]
5719 >>> g.ctx == main_ctx()
5720 True
5721 >>> g2.ctx == c2
5722 True
5723 >>> g2.ctx == main_ctx()
5724 False
5725 """
5726 if z3_debug():
5727 _z3_assert(isinstance(target, Context), "target must be a context")
5728 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5729
5730 def __copy__(self):
5731 return self.translate(self.ctx)
5732
5733 def __deepcopy__(self, memo={}):
5734 return self.translate(self.ctx)
5735
5736 def simplify(self, *arguments, **keywords):
5737 """Return a new simplified goal.
5738
5739 This method is essentially invoking the simplify tactic.
5740
5741 >>> g = Goal()
5742 >>> x = Int('x')
5743 >>> g.add(x + 1 >= 2)
5744 >>> g
5745 [x + 1 >= 2]
5746 >>> g2 = g.simplify()
5747 >>> g2
5748 [x >= 1]
5749 >>> # g was not modified
5750 >>> g
5751 [x + 1 >= 2]
5752 """
5753 t = Tactic("simplify")
5754 return t.apply(self, *arguments, **keywords)[0]
5755
5756 def as_expr(self):
5757 """Return goal `self` as a single Z3 expression.
5758
5759 >>> x = Int('x')
5760 >>> g = Goal()
5761 >>> g.as_expr()
5762 True
5763 >>> g.add(x > 1)
5764 >>> g.as_expr()
5765 x > 1
5766 >>> g.add(x < 10)
5767 >>> g.as_expr()
5768 And(x > 1, x < 10)
5769 """
5770 sz = len(self)
5771 if sz == 0:
5772 return BoolVal(True, self.ctx)
5773 elif sz == 1:
5774 return self.get(0)
5775 else:
5776 return And([self.get(i) for i in range(len(self))], self.ctx)
5777
5778
5783
5784
5786 """A collection (vector) of ASTs."""
5787
5788 def __init__(self, v=None, ctx=None):
5789 self.vector = None
5790 if v is None:
5791 self.ctx = _get_ctx(ctx)
5792 self.vector = Z3_mk_ast_vector(self.ctx.ref())
5793 else:
5794 self.vector = v
5795 assert ctx is not None
5796 self.ctx = ctx
5797 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5798
5799 def __del__(self):
5800 if self.vector is not None and self.ctx.ref() is not None:
5801 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5802
5803 def __len__(self):
5804 """Return the size of the vector `self`.
5805
5806 >>> A = AstVector()
5807 >>> len(A)
5808 0
5809 >>> A.push(Int('x'))
5810 >>> A.push(Int('x'))
5811 >>> len(A)
5812 2
5813 """
5814 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5815
5816 def __getitem__(self, i):
5817 """Return the AST at position `i`.
5818
5819 >>> A = AstVector()
5820 >>> A.push(Int('x') + 1)
5821 >>> A.push(Int('y'))
5822 >>> A[0]
5823 x + 1
5824 >>> A[1]
5825 y
5826 """
5827
5828 if isinstance(i, int):
5829 if i < 0:
5830 i += self.__len__()
5831
5832 if i >= self.__len__():
5833 raise IndexError
5834 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5835
5836 elif isinstance(i, slice):
5837 result = []
5838 for ii in range(*i.indices(self.__len__())):
5839 result.append(_to_ast_ref(
5840 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
5841 self.ctx,
5842 ))
5843 return result
5844
5845 def __setitem__(self, i, v):
5846 """Update AST at position `i`.
5847
5848 >>> A = AstVector()
5849 >>> A.push(Int('x') + 1)
5850 >>> A.push(Int('y'))
5851 >>> A[0]
5852 x + 1
5853 >>> A[0] = Int('x')
5854 >>> A[0]
5855 x
5856 """
5857 if i >= self.__len__():
5858 raise IndexError
5859 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5860
5861 def push(self, v):
5862 """Add `v` in the end of the vector.
5863
5864 >>> A = AstVector()
5865 >>> len(A)
5866 0
5867 >>> A.push(Int('x'))
5868 >>> len(A)
5869 1
5870 """
5871 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5872
5873 def resize(self, sz):
5874 """Resize the vector to `sz` elements.
5875
5876 >>> A = AstVector()
5877 >>> A.resize(10)
5878 >>> len(A)
5879 10
5880 >>> for i in range(10): A[i] = Int('x')
5881 >>> A[5]
5882 x
5883 """
5884 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5885
5886 def __contains__(self, item):
5887 """Return `True` if the vector contains `item`.
5888
5889 >>> x = Int('x')
5890 >>> A = AstVector()
5891 >>> x in A
5892 False
5893 >>> A.push(x)
5894 >>> x in A
5895 True
5896 >>> (x+1) in A
5897 False
5898 >>> A.push(x+1)
5899 >>> (x+1) in A
5900 True
5901 >>> A
5902 [x, x + 1]
5903 """
5904 for elem in self:
5905 if elem.eq(item):
5906 return True
5907 return False
5908
5909 def translate(self, other_ctx):
5910 """Copy vector `self` to context `other_ctx`.
5911
5912 >>> x = Int('x')
5913 >>> A = AstVector()
5914 >>> A.push(x)
5915 >>> c2 = Context()
5916 >>> B = A.translate(c2)
5917 >>> B
5918 [x]
5919 """
5920 return AstVector(
5921 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
5922 ctx=other_ctx,
5923 )
5924
5925 def __copy__(self):
5926 return self.translate(self.ctx)
5927
5928 def __deepcopy__(self, memo={}):
5929 return self.translate(self.ctx)
5930
5931 def __repr__(self):
5932 return obj_to_string(self)
5933
5934 def sexpr(self):
5935 """Return a textual representation of the s-expression representing the vector."""
5936 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5937
5938
5943
5944
5946 """A mapping from ASTs to ASTs."""
5947
5948 def __init__(self, m=None, ctx=None):
5949 self.map = None
5950 if m is None:
5951 self.ctx = _get_ctx(ctx)
5952 self.map = Z3_mk_ast_map(self.ctx.ref())
5953 else:
5954 self.map = m
5955 assert ctx is not None
5956 self.ctx = ctx
5957 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5958
5959 def __deepcopy__(self, memo={}):
5960 return AstMap(self.map, self.ctx)
5961
5962 def __del__(self):
5963 if self.map is not None and self.ctx.ref() is not None:
5964 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5965
5966 def __len__(self):
5967 """Return the size of the map.
5968
5969 >>> M = AstMap()
5970 >>> len(M)
5971 0
5972 >>> x = Int('x')
5973 >>> M[x] = IntVal(1)
5974 >>> len(M)
5975 1
5976 """
5977 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5978
5979 def __contains__(self, key):
5980 """Return `True` if the map contains key `key`.
5981
5982 >>> M = AstMap()
5983 >>> x = Int('x')
5984 >>> M[x] = x + 1
5985 >>> x in M
5986 True
5987 >>> x+1 in M
5988 False
5989 """
5990 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5991
5992 def __getitem__(self, key):
5993 """Retrieve the value associated with key `key`.
5994
5995 >>> M = AstMap()
5996 >>> x = Int('x')
5997 >>> M[x] = x + 1
5998 >>> M[x]
5999 x + 1
6000 """
6001 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6002
6003 def __setitem__(self, k, v):
6004 """Add/Update key `k` with value `v`.
6005
6006 >>> M = AstMap()
6007 >>> x = Int('x')
6008 >>> M[x] = x + 1
6009 >>> len(M)
6010 1
6011 >>> M[x]
6012 x + 1
6013 >>> M[x] = IntVal(1)
6014 >>> M[x]
6015 1
6016 """
6017 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6018
6019 def __repr__(self):
6020 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6021
6022 def erase(self, k):
6023 """Remove the entry associated with key `k`.
6024
6025 >>> M = AstMap()
6026 >>> x = Int('x')
6027 >>> M[x] = x + 1
6028 >>> len(M)
6029 1
6030 >>> M.erase(x)
6031 >>> len(M)
6032 0
6033 """
6034 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6035
6036 def reset(self):
6037 """Remove all entries from the map.
6038
6039 >>> M = AstMap()
6040 >>> x = Int('x')
6041 >>> M[x] = x + 1
6042 >>> M[x+x] = IntVal(1)
6043 >>> len(M)
6044 2
6045 >>> M.reset()
6046 >>> len(M)
6047 0
6048 """
6049 Z3_ast_map_reset(self.ctx.ref(), self.map)
6050
6051 def keys(self):
6052 """Return an AstVector containing all keys in the map.
6053
6054 >>> M = AstMap()
6055 >>> x = Int('x')
6056 >>> M[x] = x + 1
6057 >>> M[x+x] = IntVal(1)
6058 >>> M.keys()
6059 [x, x + x]
6060 """
6061 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6062
6063
6068
6069
6071 """Store the value of the interpretation of a function in a particular point."""
6072
6073 def __init__(self, entry, ctx):
6074 self.entry = entry
6075 self.ctx = ctx
6076 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6077
6078 def __deepcopy__(self, memo={}):
6079 return FuncEntry(self.entry, self.ctx)
6080
6081 def __del__(self):
6082 if self.ctx.ref() is not None:
6083 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6084
6085 def num_args(self):
6086 """Return the number of arguments in the given entry.
6087
6088 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6089 >>> s = Solver()
6090 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6091 >>> s.check()
6092 sat
6093 >>> m = s.model()
6094 >>> f_i = m[f]
6095 >>> f_i.num_entries()
6096 1
6097 >>> e = f_i.entry(0)
6098 >>> e.num_args()
6099 2
6100 """
6101 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6102
6103 def arg_value(self, idx):
6104 """Return the value of argument `idx`.
6105
6106 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6107 >>> s = Solver()
6108 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6109 >>> s.check()
6110 sat
6111 >>> m = s.model()
6112 >>> f_i = m[f]
6113 >>> f_i.num_entries()
6114 1
6115 >>> e = f_i.entry(0)
6116 >>> e
6117 [1, 2, 20]
6118 >>> e.num_args()
6119 2
6120 >>> e.arg_value(0)
6121 1
6122 >>> e.arg_value(1)
6123 2
6124 >>> try:
6125 ... e.arg_value(2)
6126 ... except IndexError:
6127 ... print("index error")
6128 index error
6129 """
6130 if idx >= self.num_args():
6131 raise IndexError
6132 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6133
6134 def value(self):
6135 """Return the value of the function at point `self`.
6136
6137 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6138 >>> s = Solver()
6139 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6140 >>> s.check()
6141 sat
6142 >>> m = s.model()
6143 >>> f_i = m[f]
6144 >>> f_i.num_entries()
6145 1
6146 >>> e = f_i.entry(0)
6147 >>> e
6148 [1, 2, 20]
6149 >>> e.num_args()
6150 2
6151 >>> e.value()
6152 20
6153 """
6154 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6155
6156 def as_list(self):
6157 """Return entry `self` as a Python list.
6158 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6159 >>> s = Solver()
6160 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6161 >>> s.check()
6162 sat
6163 >>> m = s.model()
6164 >>> f_i = m[f]
6165 >>> f_i.num_entries()
6166 1
6167 >>> e = f_i.entry(0)
6168 >>> e.as_list()
6169 [1, 2, 20]
6170 """
6171 args = [self.arg_value(i) for i in range(self.num_args())]
6172 args.append(self.value())
6173 return args
6174
6175 def __repr__(self):
6176 return repr(self.as_list())
6177
6178
6180 """Stores the interpretation of a function in a Z3 model."""
6181
6182 def __init__(self, f, ctx):
6183 self.f = f
6184 self.ctx = ctx
6185 if self.f is not None:
6186 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6187
6188 def __del__(self):
6189 if self.f is not None and self.ctx.ref() is not None:
6190 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6191
6192 def else_value(self):
6193 """
6194 Return the `else` value for a function interpretation.
6195 Return None if Z3 did not specify the `else` value for
6196 this object.
6197
6198 >>> f = Function('f', IntSort(), IntSort())
6199 >>> s = Solver()
6200 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6201 >>> s.check()
6202 sat
6203 >>> m = s.model()
6204 >>> m[f]
6205 [2 -> 0, else -> 1]
6206 >>> m[f].else_value()
6207 1
6208 """
6209 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6210 if r:
6211 return _to_expr_ref(r, self.ctx)
6212 else:
6213 return None
6214
6215 def num_entries(self):
6216 """Return the number of entries/points in the function interpretation `self`.
6217
6218 >>> f = Function('f', IntSort(), IntSort())
6219 >>> s = Solver()
6220 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6221 >>> s.check()
6222 sat
6223 >>> m = s.model()
6224 >>> m[f]
6225 [2 -> 0, else -> 1]
6226 >>> m[f].num_entries()
6227 1
6228 """
6229 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6230
6231 def arity(self):
6232 """Return the number of arguments for each entry in the function interpretation `self`.
6233
6234 >>> f = Function('f', IntSort(), IntSort())
6235 >>> s = Solver()
6236 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6237 >>> s.check()
6238 sat
6239 >>> m = s.model()
6240 >>> m[f].arity()
6241 1
6242 """
6243 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6244
6245 def entry(self, idx):
6246 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6247
6248 >>> f = Function('f', IntSort(), IntSort())
6249 >>> s = Solver()
6250 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6251 >>> s.check()
6252 sat
6253 >>> m = s.model()
6254 >>> m[f]
6255 [2 -> 0, else -> 1]
6256 >>> m[f].num_entries()
6257 1
6258 >>> m[f].entry(0)
6259 [2, 0]
6260 """
6261 if idx >= self.num_entries():
6262 raise IndexError
6263 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6264
6265 def translate(self, other_ctx):
6266 """Copy model 'self' to context 'other_ctx'.
6267 """
6268 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6269
6270 def __copy__(self):
6271 return self.translate(self.ctx)
6272
6273 def __deepcopy__(self, memo={}):
6274 return self.translate(self.ctx)
6275
6276 def as_list(self):
6277 """Return the function interpretation as a Python list.
6278 >>> f = Function('f', IntSort(), IntSort())
6279 >>> s = Solver()
6280 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6281 >>> s.check()
6282 sat
6283 >>> m = s.model()
6284 >>> m[f]
6285 [2 -> 0, else -> 1]
6286 >>> m[f].as_list()
6287 [[2, 0], 1]
6288 """
6289 r = [self.entry(i).as_list() for i in range(self.num_entries())]
6290 r.append(self.else_value())
6291 return r
6292
6293 def __repr__(self):
6294 return obj_to_string(self)
6295
6296
6298 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6299
6300 def __init__(self, m, ctx):
6301 assert ctx is not None
6302 self.model = m
6303 self.ctx = ctx
6304 Z3_model_inc_ref(self.ctx.ref(), self.model)
6305
6306 def __del__(self):
6307 if self.ctx.ref() is not None:
6308 Z3_model_dec_ref(self.ctx.ref(), self.model)
6309
6310 def __repr__(self):
6311 return obj_to_string(self)
6312
6313 def sexpr(self):
6314 """Return a textual representation of the s-expression representing the model."""
6315 return Z3_model_to_string(self.ctx.ref(), self.model)
6316
6317 def eval(self, t, model_completion=False):
6318 """Evaluate the expression `t` in the model `self`.
6319 If `model_completion` is enabled, then a default interpretation is automatically added
6320 for symbols that do not have an interpretation in the model `self`.
6321
6322 >>> x = Int('x')
6323 >>> s = Solver()
6324 >>> s.add(x > 0, x < 2)
6325 >>> s.check()
6326 sat
6327 >>> m = s.model()
6328 >>> m.eval(x + 1)
6329 2
6330 >>> m.eval(x == 1)
6331 True
6332 >>> y = Int('y')
6333 >>> m.eval(y + x)
6334 1 + y
6335 >>> m.eval(y)
6336 y
6337 >>> m.eval(y, model_completion=True)
6338 0
6339 >>> # Now, m contains an interpretation for y
6340 >>> m.eval(y + x)
6341 1
6342 """
6343 r = (Ast * 1)()
6344 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6345 return _to_expr_ref(r[0], self.ctx)
6346 raise Z3Exception("failed to evaluate expression in the model")
6347
6348 def evaluate(self, t, model_completion=False):
6349 """Alias for `eval`.
6350
6351 >>> x = Int('x')
6352 >>> s = Solver()
6353 >>> s.add(x > 0, x < 2)
6354 >>> s.check()
6355 sat
6356 >>> m = s.model()
6357 >>> m.evaluate(x + 1)
6358 2
6359 >>> m.evaluate(x == 1)
6360 True
6361 >>> y = Int('y')
6362 >>> m.evaluate(y + x)
6363 1 + y
6364 >>> m.evaluate(y)
6365 y
6366 >>> m.evaluate(y, model_completion=True)
6367 0
6368 >>> # Now, m contains an interpretation for y
6369 >>> m.evaluate(y + x)
6370 1
6371 """
6372 return self.eval(t, model_completion)
6373
6374 def __len__(self):
6375 """Return the number of constant and function declarations in the model `self`.
6376
6377 >>> f = Function('f', IntSort(), IntSort())
6378 >>> x = Int('x')
6379 >>> s = Solver()
6380 >>> s.add(x > 0, f(x) != x)
6381 >>> s.check()
6382 sat
6383 >>> m = s.model()
6384 >>> len(m)
6385 2
6386 """
6387 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
6388 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6389 return num_consts + num_funcs
6390
6391 def get_interp(self, decl):
6392 """Return the interpretation for a given declaration or constant.
6393
6394 >>> f = Function('f', IntSort(), IntSort())
6395 >>> x = Int('x')
6396 >>> s = Solver()
6397 >>> s.add(x > 0, x < 2, f(x) == 0)
6398 >>> s.check()
6399 sat
6400 >>> m = s.model()
6401 >>> m[x]
6402 1
6403 >>> m[f]
6404 [else -> 0]
6405 """
6406 if z3_debug():
6407 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6408 if is_const(decl):
6409 decl = decl.decl()
6410 try:
6411 if decl.arity() == 0:
6412 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6413 if _r.value is None:
6414 return None
6415 r = _to_expr_ref(_r, self.ctx)
6416 if is_as_array(r):
6417 return self.get_interp(get_as_array_func(r))
6418 else:
6419 return r
6420 else:
6421 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6422 except Z3Exception:
6423 return None
6424
6425 def num_sorts(self):
6426 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6427
6428 >>> A = DeclareSort('A')
6429 >>> a, b = Consts('a b', A)
6430 >>> s = Solver()
6431 >>> s.add(a != b)
6432 >>> s.check()
6433 sat
6434 >>> m = s.model()
6435 >>> m.num_sorts()
6436 1
6437 """
6438 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6439
6440 def get_sort(self, idx):
6441 """Return the uninterpreted sort at position `idx` < self.num_sorts().
6442
6443 >>> A = DeclareSort('A')
6444 >>> B = DeclareSort('B')
6445 >>> a1, a2 = Consts('a1 a2', A)
6446 >>> b1, b2 = Consts('b1 b2', B)
6447 >>> s = Solver()
6448 >>> s.add(a1 != a2, b1 != b2)
6449 >>> s.check()
6450 sat
6451 >>> m = s.model()
6452 >>> m.num_sorts()
6453 2
6454 >>> m.get_sort(0)
6455 A
6456 >>> m.get_sort(1)
6457 B
6458 """
6459 if idx >= self.num_sorts():
6460 raise IndexError
6461 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6462
6463 def sorts(self):
6464 """Return all uninterpreted sorts that have an interpretation in the model `self`.
6465
6466 >>> A = DeclareSort('A')
6467 >>> B = DeclareSort('B')
6468 >>> a1, a2 = Consts('a1 a2', A)
6469 >>> b1, b2 = Consts('b1 b2', B)
6470 >>> s = Solver()
6471 >>> s.add(a1 != a2, b1 != b2)
6472 >>> s.check()
6473 sat
6474 >>> m = s.model()
6475 >>> m.sorts()
6476 [A, B]
6477 """
6478 return [self.get_sort(i) for i in range(self.num_sorts())]
6479
6480 def get_universe(self, s):
6481 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6482
6483 >>> A = DeclareSort('A')
6484 >>> a, b = Consts('a b', A)
6485 >>> s = Solver()
6486 >>> s.add(a != b)
6487 >>> s.check()
6488 sat
6489 >>> m = s.model()
6490 >>> m.get_universe(A)
6491 [A!val!1, A!val!0]
6492 """
6493 if z3_debug():
6494 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6495 try:
6496 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6497 except Z3Exception:
6498 return None
6499
6500 def __getitem__(self, idx):
6501 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6502 If `idx` is a declaration, then the actual interpretation is returned.
6503
6504 The elements can be retrieved using position or the actual declaration.
6505
6506 >>> f = Function('f', IntSort(), IntSort())
6507 >>> x = Int('x')
6508 >>> s = Solver()
6509 >>> s.add(x > 0, x < 2, f(x) == 0)
6510 >>> s.check()
6511 sat
6512 >>> m = s.model()
6513 >>> len(m)
6514 2
6515 >>> m[0]
6516 x
6517 >>> m[1]
6518 f
6519 >>> m[x]
6520 1
6521 >>> m[f]
6522 [else -> 0]
6523 >>> for d in m: print("%s -> %s" % (d, m[d]))
6524 x -> 1
6525 f -> [else -> 0]
6526 """
6527 if _is_int(idx):
6528 if idx >= len(self):
6529 raise IndexError
6530 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6531 if (idx < num_consts):
6532 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6533 else:
6534 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6535 if isinstance(idx, FuncDeclRef):
6536 return self.get_interp(idx)
6537 if is_const(idx):
6538 return self.get_interp(idx.decl())
6539 if isinstance(idx, SortRef):
6540 return self.get_universe(idx)
6541 if z3_debug():
6542 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6543 return None
6544
6545 def decls(self):
6546 """Return a list with all symbols that have an interpretation in the model `self`.
6547 >>> f = Function('f', IntSort(), IntSort())
6548 >>> x = Int('x')
6549 >>> s = Solver()
6550 >>> s.add(x > 0, x < 2, f(x) == 0)
6551 >>> s.check()
6552 sat
6553 >>> m = s.model()
6554 >>> m.decls()
6555 [x, f]
6556 """
6557 r = []
6558 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6559 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6560 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6561 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6562 return r
6563
6564 def translate(self, target):
6565 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6566 """
6567 if z3_debug():
6568 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6569 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6570 return ModelRef(model, target)
6571
6572 def __copy__(self):
6573 return self.translate(self.ctx)
6574
6575 def __deepcopy__(self, memo={}):
6576 return self.translate(self.ctx)
6577
6578
6579def Model(ctx=None):
6580 ctx = _get_ctx(ctx)
6581 return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6582
6583
6585 """Return true if n is a Z3 expression of the form (_ as-array f)."""
6586 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6587
6588
6590 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6591 if z3_debug():
6592 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6593 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6594
6595
6600
6601
6603 """Statistics for `Solver.check()`."""
6604
6605 def __init__(self, stats, ctx):
6606 self.stats = stats
6607 self.ctx = ctx
6608 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6609
6610 def __deepcopy__(self, memo={}):
6611 return Statistics(self.stats, self.ctx)
6612
6613 def __del__(self):
6614 if self.ctx.ref() is not None:
6615 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6616
6617 def __repr__(self):
6618 if in_html_mode():
6619 out = io.StringIO()
6620 even = True
6621 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6622 for k, v in self:
6623 if even:
6624 out.write(u('<tr style="background-color:#CFCFCF">'))
6625 even = False
6626 else:
6627 out.write(u("<tr>"))
6628 even = True
6629 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6630 out.write(u("</table>"))
6631 return out.getvalue()
6632 else:
6633 return Z3_stats_to_string(self.ctx.ref(), self.stats)
6634
6635 def __len__(self):
6636 """Return the number of statistical counters.
6637
6638 >>> x = Int('x')
6639 >>> s = Then('simplify', 'nlsat').solver()
6640 >>> s.add(x > 0)
6641 >>> s.check()
6642 sat
6643 >>> st = s.statistics()
6644 >>> len(st)
6645 6
6646 """
6647 return int(Z3_stats_size(self.ctx.ref(), self.stats))
6648
6649 def __getitem__(self, idx):
6650 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6651
6652 >>> x = Int('x')
6653 >>> s = Then('simplify', 'nlsat').solver()
6654 >>> s.add(x > 0)
6655 >>> s.check()
6656 sat
6657 >>> st = s.statistics()
6658 >>> len(st)
6659 6
6660 >>> st[0]
6661 ('nlsat propagations', 2)
6662 >>> st[1]
6663 ('nlsat stages', 2)
6664 """
6665 if idx >= len(self):
6666 raise IndexError
6667 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6668 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6669 else:
6670 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6671 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6672
6673 def keys(self):
6674 """Return the list of statistical counters.
6675
6676 >>> x = Int('x')
6677 >>> s = Then('simplify', 'nlsat').solver()
6678 >>> s.add(x > 0)
6679 >>> s.check()
6680 sat
6681 >>> st = s.statistics()
6682 """
6683 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6684
6685 def get_key_value(self, key):
6686 """Return the value of a particular statistical counter.
6687
6688 >>> x = Int('x')
6689 >>> s = Then('simplify', 'nlsat').solver()
6690 >>> s.add(x > 0)
6691 >>> s.check()
6692 sat
6693 >>> st = s.statistics()
6694 >>> st.get_key_value('nlsat propagations')
6695 2
6696 """
6697 for idx in range(len(self)):
6698 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6699 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6700 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6701 else:
6702 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6703 raise Z3Exception("unknown key")
6704
6705 def __getattr__(self, name):
6706 """Access the value of statistical using attributes.
6707
6708 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6709 we should use '_' (e.g., 'nlsat_propagations').
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 >>> st.nlsat_propagations
6718 2
6719 >>> st.nlsat_stages
6720 2
6721 """
6722 key = name.replace("_", " ")
6723 try:
6724 return self.get_key_value(key)
6725 except Z3Exception:
6726 raise AttributeError
6727
6728
6733
6734
6736 """Represents the result of a satisfiability check: sat, unsat, unknown.
6737
6738 >>> s = Solver()
6739 >>> s.check()
6740 sat
6741 >>> r = s.check()
6742 >>> isinstance(r, CheckSatResult)
6743 True
6744 """
6745
6746 def __init__(self, r):
6747 self.r = r
6748
6749 def __deepcopy__(self, memo={}):
6750 return CheckSatResult(self.r)
6751
6752 def __eq__(self, other):
6753 return isinstance(other, CheckSatResult) and self.r == other.r
6754
6755 def __ne__(self, other):
6756 return not self.__eq__(other)
6757
6758 def __repr__(self):
6759 if in_html_mode():
6760 if self.r == Z3_L_TRUE:
6761 return "<b>sat</b>"
6762 elif self.r == Z3_L_FALSE:
6763 return "<b>unsat</b>"
6764 else:
6765 return "<b>unknown</b>"
6766 else:
6767 if self.r == Z3_L_TRUE:
6768 return "sat"
6769 elif self.r == Z3_L_FALSE:
6770 return "unsat"
6771 else:
6772 return "unknown"
6773
6774 def _repr_html_(self):
6775 in_html = in_html_mode()
6776 set_html_mode(True)
6777 res = repr(self)
6778 set_html_mode(in_html)
6779 return res
6780
6781
6782sat = CheckSatResult(Z3_L_TRUE)
6783unsat = CheckSatResult(Z3_L_FALSE)
6784unknown = CheckSatResult(Z3_L_UNDEF)
6785
6786
6788 """
6789 Solver API provides methods for implementing the main SMT 2.0 commands:
6790 push, pop, check, get-model, etc.
6791 """
6792
6793 def __init__(self, solver=None, ctx=None, logFile=None):
6794 assert solver is None or ctx is not None
6795 self.ctx = _get_ctx(ctx)
6796 self.backtrack_level = 4000000000
6797 self.solver = None
6798 if solver is None:
6799 self.solver = Z3_mk_solver(self.ctx.ref())
6800 else:
6801 self.solver = solver
6802 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6803 if logFile is not None:
6804 self.set("smtlib2_log", logFile)
6805
6806 def __del__(self):
6807 if self.solver is not None and self.ctx.ref() is not None:
6808 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6809
6810 def set(self, *args, **keys):
6811 """Set a configuration option.
6812 The method `help()` return a string containing all available options.
6813
6814 >>> s = Solver()
6815 >>> # The option MBQI can be set using three different approaches.
6816 >>> s.set(mbqi=True)
6817 >>> s.set('MBQI', True)
6818 >>> s.set(':mbqi', True)
6819 """
6820 p = args2params(args, keys, self.ctx)
6821 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6822
6823 def push(self):
6824 """Create a backtracking point.
6825
6826 >>> x = Int('x')
6827 >>> s = Solver()
6828 >>> s.add(x > 0)
6829 >>> s
6830 [x > 0]
6831 >>> s.push()
6832 >>> s.add(x < 1)
6833 >>> s
6834 [x > 0, x < 1]
6835 >>> s.check()
6836 unsat
6837 >>> s.pop()
6838 >>> s.check()
6839 sat
6840 >>> s
6841 [x > 0]
6842 """
6843 Z3_solver_push(self.ctx.ref(), self.solver)
6844
6845 def pop(self, num=1):
6846 """Backtrack \\c num backtracking points.
6847
6848 >>> x = Int('x')
6849 >>> s = Solver()
6850 >>> s.add(x > 0)
6851 >>> s
6852 [x > 0]
6853 >>> s.push()
6854 >>> s.add(x < 1)
6855 >>> s
6856 [x > 0, x < 1]
6857 >>> s.check()
6858 unsat
6859 >>> s.pop()
6860 >>> s.check()
6861 sat
6862 >>> s
6863 [x > 0]
6864 """
6865 Z3_solver_pop(self.ctx.ref(), self.solver, num)
6866
6867 def num_scopes(self):
6868 """Return the current number of backtracking points.
6869
6870 >>> s = Solver()
6871 >>> s.num_scopes()
6872 0
6873 >>> s.push()
6874 >>> s.num_scopes()
6875 1
6876 >>> s.push()
6877 >>> s.num_scopes()
6878 2
6879 >>> s.pop()
6880 >>> s.num_scopes()
6881 1
6882 """
6883 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6884
6885 def reset(self):
6886 """Remove all asserted constraints and backtracking points created using `push()`.
6887
6888 >>> x = Int('x')
6889 >>> s = Solver()
6890 >>> s.add(x > 0)
6891 >>> s
6892 [x > 0]
6893 >>> s.reset()
6894 >>> s
6895 []
6896 """
6897 Z3_solver_reset(self.ctx.ref(), self.solver)
6898
6899 def assert_exprs(self, *args):
6900 """Assert constraints into the solver.
6901
6902 >>> x = Int('x')
6903 >>> s = Solver()
6904 >>> s.assert_exprs(x > 0, x < 2)
6905 >>> s
6906 [x > 0, x < 2]
6907 """
6908 args = _get_args(args)
6909 s = BoolSort(self.ctx)
6910 for arg in args:
6911 if isinstance(arg, Goal) or isinstance(arg, AstVector):
6912 for f in arg:
6913 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6914 else:
6915 arg = s.cast(arg)
6916 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6917
6918 def add(self, *args):
6919 """Assert constraints into the solver.
6920
6921 >>> x = Int('x')
6922 >>> s = Solver()
6923 >>> s.add(x > 0, x < 2)
6924 >>> s
6925 [x > 0, x < 2]
6926 """
6927 self.assert_exprs(*args)
6928
6929 def __iadd__(self, fml):
6930 self.add(fml)
6931 return self
6932
6933 def append(self, *args):
6934 """Assert constraints into the solver.
6935
6936 >>> x = Int('x')
6937 >>> s = Solver()
6938 >>> s.append(x > 0, x < 2)
6939 >>> s
6940 [x > 0, x < 2]
6941 """
6942 self.assert_exprs(*args)
6943
6944 def insert(self, *args):
6945 """Assert constraints into the solver.
6946
6947 >>> x = Int('x')
6948 >>> s = Solver()
6949 >>> s.insert(x > 0, x < 2)
6950 >>> s
6951 [x > 0, x < 2]
6952 """
6953 self.assert_exprs(*args)
6954
6955 def assert_and_track(self, a, p):
6956 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6957
6958 If `p` is a string, it will be automatically converted into a Boolean constant.
6959
6960 >>> x = Int('x')
6961 >>> p3 = Bool('p3')
6962 >>> s = Solver()
6963 >>> s.set(unsat_core=True)
6964 >>> s.assert_and_track(x > 0, 'p1')
6965 >>> s.assert_and_track(x != 1, 'p2')
6966 >>> s.assert_and_track(x < 0, p3)
6967 >>> print(s.check())
6968 unsat
6969 >>> c = s.unsat_core()
6970 >>> len(c)
6971 2
6972 >>> Bool('p1') in c
6973 True
6974 >>> Bool('p2') in c
6975 False
6976 >>> p3 in c
6977 True
6978 """
6979 if isinstance(p, str):
6980 p = Bool(p, self.ctx)
6981 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6982 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6983 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6984
6985 def check(self, *assumptions):
6986 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6987
6988 >>> x = Int('x')
6989 >>> s = Solver()
6990 >>> s.check()
6991 sat
6992 >>> s.add(x > 0, x < 2)
6993 >>> s.check()
6994 sat
6995 >>> s.model().eval(x)
6996 1
6997 >>> s.add(x < 1)
6998 >>> s.check()
6999 unsat
7000 >>> s.reset()
7001 >>> s.add(2**x == 4)
7002 >>> s.check()
7003 unknown
7004 """
7005 s = BoolSort(self.ctx)
7006 assumptions = _get_args(assumptions)
7007 num = len(assumptions)
7008 _assumptions = (Ast * num)()
7009 for i in range(num):
7010 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7011 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7012 return CheckSatResult(r)
7013
7014 def model(self):
7015 """Return a model for the last `check()`.
7016
7017 This function raises an exception if
7018 a model is not available (e.g., last `check()` returned unsat).
7019
7020 >>> s = Solver()
7021 >>> a = Int('a')
7022 >>> s.add(a + 2 == 0)
7023 >>> s.check()
7024 sat
7025 >>> s.model()
7026 [a = -2]
7027 """
7028 try:
7029 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7030 except Z3Exception:
7031 raise Z3Exception("model is not available")
7032
7033 def import_model_converter(self, other):
7034 """Import model converter from other into the current solver"""
7035 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7036
7037 def unsat_core(self):
7038 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7039
7040 These are the assumptions Z3 used in the unsatisfiability proof.
7041 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7042 They may be also used to "retract" assumptions. Note that, assumptions are not really
7043 "soft constraints", but they can be used to implement them.
7044
7045 >>> p1, p2, p3 = Bools('p1 p2 p3')
7046 >>> x, y = Ints('x y')
7047 >>> s = Solver()
7048 >>> s.add(Implies(p1, x > 0))
7049 >>> s.add(Implies(p2, y > x))
7050 >>> s.add(Implies(p2, y < 1))
7051 >>> s.add(Implies(p3, y > -3))
7052 >>> s.check(p1, p2, p3)
7053 unsat
7054 >>> core = s.unsat_core()
7055 >>> len(core)
7056 2
7057 >>> p1 in core
7058 True
7059 >>> p2 in core
7060 True
7061 >>> p3 in core
7062 False
7063 >>> # "Retracting" p2
7064 >>> s.check(p1, p3)
7065 sat
7066 """
7067 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7068
7069 def consequences(self, assumptions, variables):
7070 """Determine fixed values for the variables based on the solver state and assumptions.
7071 >>> s = Solver()
7072 >>> a, b, c, d = Bools('a b c d')
7073 >>> s.add(Implies(a,b), Implies(b, c))
7074 >>> s.consequences([a],[b,c,d])
7075 (sat, [Implies(a, b), Implies(a, c)])
7076 >>> s.consequences([Not(c),d],[a,b,c,d])
7077 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7078 """
7079 if isinstance(assumptions, list):
7080 _asms = AstVector(None, self.ctx)
7081 for a in assumptions:
7082 _asms.push(a)
7083 assumptions = _asms
7084 if isinstance(variables, list):
7085 _vars = AstVector(None, self.ctx)
7086 for a in variables:
7087 _vars.push(a)
7088 variables = _vars
7089 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7090 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7091 consequences = AstVector(None, self.ctx)
7092 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7093 variables.vector, consequences.vector)
7094 sz = len(consequences)
7095 consequences = [consequences[i] for i in range(sz)]
7096 return CheckSatResult(r), consequences
7097
7098 def from_file(self, filename):
7099 """Parse assertions from a file"""
7100 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7101
7102 def from_string(self, s):
7103 """Parse assertions from a string"""
7104 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7105
7106 def cube(self, vars=None):
7107 """Get set of cubes
7108 The method takes an optional set of variables that restrict which
7109 variables may be used as a starting point for cubing.
7110 If vars is not None, then the first case split is based on a variable in
7111 this set.
7112 """
7113 self.cube_vs = AstVector(None, self.ctx)
7114 if vars is not None:
7115 for v in vars:
7116 self.cube_vs.push(v)
7117 while True:
7118 lvl = self.backtrack_level
7119 self.backtrack_level = 4000000000
7120 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7121 if (len(r) == 1 and is_false(r[0])):
7122 return
7123 yield r
7124 if (len(r) == 0):
7125 return
7126
7127 def cube_vars(self):
7128 """Access the set of variables that were touched by the most recently generated cube.
7129 This set of variables can be used as a starting point for additional cubes.
7130 The idea is that variables that appear in clauses that are reduced by the most recent
7131 cube are likely more useful to cube on."""
7132 return self.cube_vs
7133
7134 def proof(self):
7135 """Return a proof for the last `check()`. Proof construction must be enabled."""
7136 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7137
7138 def assertions(self):
7139 """Return an AST vector containing all added constraints.
7140
7141 >>> s = Solver()
7142 >>> s.assertions()
7143 []
7144 >>> a = Int('a')
7145 >>> s.add(a > 0)
7146 >>> s.add(a < 10)
7147 >>> s.assertions()
7148 [a > 0, a < 10]
7149 """
7150 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7151
7152 def units(self):
7153 """Return an AST vector containing all currently inferred units.
7154 """
7155 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7156
7157 def non_units(self):
7158 """Return an AST vector containing all atomic formulas in solver state that are not units.
7159 """
7160 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7161
7162 def trail_levels(self):
7163 """Return trail and decision levels of the solver state after a check() call.
7164 """
7165 trail = self.trail()
7166 levels = (ctypes.c_uint * len(trail))()
7167 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7168 return trail, levels
7169
7170 def trail(self):
7171 """Return trail of the solver state after a check() call.
7172 """
7173 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7174
7175 def statistics(self):
7176 """Return statistics for the last `check()`.
7177
7178 >>> s = SimpleSolver()
7179 >>> x = Int('x')
7180 >>> s.add(x > 0)
7181 >>> s.check()
7182 sat
7183 >>> st = s.statistics()
7184 >>> st.get_key_value('final checks')
7185 1
7186 >>> len(st) > 0
7187 True
7188 >>> st[0] != 0
7189 True
7190 """
7191 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
7192
7194 """Return a string describing why the last `check()` returned `unknown`.
7195
7196 >>> x = Int('x')
7197 >>> s = SimpleSolver()
7198 >>> s.add(2**x == 4)
7199 >>> s.check()
7200 unknown
7201 >>> s.reason_unknown()
7202 '(incomplete (theory arithmetic))'
7203 """
7204 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
7205
7206 def help(self):
7207 """Display a string describing all available options."""
7208 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
7209
7210 def param_descrs(self):
7211 """Return the parameter description set."""
7212 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
7213
7214 def __repr__(self):
7215 """Return a formatted string with all added constraints."""
7216 return obj_to_string(self)
7217
7218 def translate(self, target):
7219 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7220
7221 >>> c1 = Context()
7222 >>> c2 = Context()
7223 >>> s1 = Solver(ctx=c1)
7224 >>> s2 = s1.translate(c2)
7225 """
7226 if z3_debug():
7227 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7228 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
7229 return Solver(solver, target)
7230
7231 def __copy__(self):
7232 return self.translate(self.ctx)
7233
7234 def __deepcopy__(self, memo={}):
7235 return self.translate(self.ctx)
7236
7237 def sexpr(self):
7238 """Return a formatted string (in Lisp-like format) with all added constraints.
7239 We say the string is in s-expression format.
7240
7241 >>> x = Int('x')
7242 >>> s = Solver()
7243 >>> s.add(x > 0)
7244 >>> s.add(x < 2)
7245 >>> r = s.sexpr()
7246 """
7247 return Z3_solver_to_string(self.ctx.ref(), self.solver)
7248
7249 def dimacs(self, include_names=True):
7250 """Return a textual representation of the solver in DIMACS format."""
7251 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
7252
7253 def to_smt2(self):
7254 """return SMTLIB2 formatted benchmark for solver's assertions"""
7255 es = self.assertions()
7256 sz = len(es)
7257 sz1 = sz
7258 if sz1 > 0:
7259 sz1 -= 1
7260 v = (Ast * sz1)()
7261 for i in range(sz1):
7262 v[i] = es[i].as_ast()
7263 if sz > 0:
7264 e = es[sz1].as_ast()
7265 else:
7266 e = BoolVal(True, self.ctx).as_ast()
7268 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7269 )
7270
7271
7272def SolverFor(logic, ctx=None, logFile=None):
7273 """Create a solver customized for the given logic.
7274
7275 The parameter `logic` is a string. It should be contains
7276 the name of a SMT-LIB logic.
7277 See http://www.smtlib.org/ for the name of all available logics.
7278
7279 >>> s = SolverFor("QF_LIA")
7280 >>> x = Int('x')
7281 >>> s.add(x > 0)
7282 >>> s.add(x < 2)
7283 >>> s.check()
7284 sat
7285 >>> s.model()
7286 [x = 1]
7287 """
7288 ctx = _get_ctx(ctx)
7289 logic = to_symbol(logic)
7290 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7291
7292
7293def SimpleSolver(ctx=None, logFile=None):
7294 """Return a simple general purpose solver with limited amount of preprocessing.
7295
7296 >>> s = SimpleSolver()
7297 >>> x = Int('x')
7298 >>> s.add(x > 0)
7299 >>> s.check()
7300 sat
7301 """
7302 ctx = _get_ctx(ctx)
7303 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7304
7305
7310
7311
7313 """Fixedpoint API provides methods for solving with recursive predicates"""
7314
7315 def __init__(self, fixedpoint=None, ctx=None):
7316 assert fixedpoint is None or ctx is not None
7317 self.ctx = _get_ctx(ctx)
7318 self.fixedpoint = None
7319 if fixedpoint is None:
7320 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
7321 else:
7322 self.fixedpoint = fixedpoint
7323 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
7324 self.vars = []
7325
7326 def __deepcopy__(self, memo={}):
7327 return FixedPoint(self.fixedpoint, self.ctx)
7328
7329 def __del__(self):
7330 if self.fixedpoint is not None and self.ctx.ref() is not None:
7331 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
7332
7333 def set(self, *args, **keys):
7334 """Set a configuration option. The method `help()` return a string containing all available options.
7335 """
7336 p = args2params(args, keys, self.ctx)
7337 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
7338
7339 def help(self):
7340 """Display a string describing all available options."""
7341 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
7342
7343 def param_descrs(self):
7344 """Return the parameter description set."""
7345 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
7346
7347 def assert_exprs(self, *args):
7348 """Assert constraints as background axioms for the fixedpoint solver."""
7349 args = _get_args(args)
7350 s = BoolSort(self.ctx)
7351 for arg in args:
7352 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7353 for f in arg:
7354 f = self.abstract(f)
7355 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
7356 else:
7357 arg = s.cast(arg)
7358 arg = self.abstract(arg)
7359 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
7360
7361 def add(self, *args):
7362 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7363 self.assert_exprs(*args)
7364
7365 def __iadd__(self, fml):
7366 self.add(fml)
7367 return self
7368
7369 def append(self, *args):
7370 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7371 self.assert_exprs(*args)
7372
7373 def insert(self, *args):
7374 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7375 self.assert_exprs(*args)
7376
7377 def add_rule(self, head, body=None, name=None):
7378 """Assert rules defining recursive predicates to the fixedpoint solver.
7379 >>> a = Bool('a')
7380 >>> b = Bool('b')
7381 >>> s = Fixedpoint()
7382 >>> s.register_relation(a.decl())
7383 >>> s.register_relation(b.decl())
7384 >>> s.fact(a)
7385 >>> s.rule(b, a)
7386 >>> s.query(b)
7387 sat
7388 """
7389 if name is None:
7390 name = ""
7391 name = to_symbol(name, self.ctx)
7392 if body is None:
7393 head = self.abstract(head)
7394 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7395 else:
7396 body = _get_args(body)
7397 f = self.abstract(Implies(And(body, self.ctx), head))
7398 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7399
7400 def rule(self, head, body=None, name=None):
7401 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7402 self.add_rule(head, body, name)
7403
7404 def fact(self, head, name=None):
7405 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7406 self.add_rule(head, None, name)
7407
7408 def query(self, *query):
7409 """Query the fixedpoint engine whether formula is derivable.
7410 You can also pass an tuple or list of recursive predicates.
7411 """
7412 query = _get_args(query)
7413 sz = len(query)
7414 if sz >= 1 and isinstance(query[0], FuncDeclRef):
7415 _decls = (FuncDecl * sz)()
7416 i = 0
7417 for q in query:
7418 _decls[i] = q.ast
7419 i = i + 1
7420 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7421 else:
7422 if sz == 1:
7423 query = query[0]
7424 else:
7425 query = And(query, self.ctx)
7426 query = self.abstract(query, False)
7427 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7428 return CheckSatResult(r)
7429
7430 def query_from_lvl(self, lvl, *query):
7431 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7432 """
7433 query = _get_args(query)
7434 sz = len(query)
7435 if sz >= 1 and isinstance(query[0], FuncDecl):
7436 _z3_assert(False, "unsupported")
7437 else:
7438 if sz == 1:
7439 query = query[0]
7440 else:
7441 query = And(query)
7442 query = self.abstract(query, False)
7443 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7444 return CheckSatResult(r)
7445
7446 def update_rule(self, head, body, name):
7447 """update rule"""
7448 if name is None:
7449 name = ""
7450 name = to_symbol(name, self.ctx)
7451 body = _get_args(body)
7452 f = self.abstract(Implies(And(body, self.ctx), head))
7453 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7454
7455 def get_answer(self):
7456 """Retrieve answer from last query call."""
7457 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7458 return _to_expr_ref(r, self.ctx)
7459
7461 """Retrieve a ground cex from last query call."""
7462 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7463 return _to_expr_ref(r, self.ctx)
7464
7466 """retrieve rules along the counterexample trace"""
7467 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7468
7470 """retrieve rule names along the counterexample trace"""
7471 # this is a hack as I don't know how to return a list of symbols from C++;
7472 # obtain names as a single string separated by semicolons
7473 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7474 # split into individual names
7475 return names.split(";")
7476
7477 def get_num_levels(self, predicate):
7478 """Retrieve number of levels used for predicate in PDR engine"""
7479 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7480
7481 def get_cover_delta(self, level, predicate):
7482 """Retrieve properties known about predicate for the level'th unfolding.
7483 -1 is treated as the limit (infinity)
7484 """
7485 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7486 return _to_expr_ref(r, self.ctx)
7487
7488 def add_cover(self, level, predicate, property):
7489 """Add property to predicate for the level'th unfolding.
7490 -1 is treated as infinity (infinity)
7491 """
7492 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7493
7494 def register_relation(self, *relations):
7495 """Register relation as recursive"""
7496 relations = _get_args(relations)
7497 for f in relations:
7498 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7499
7500 def set_predicate_representation(self, f, *representations):
7501 """Control how relation is represented"""
7502 representations = _get_args(representations)
7503 representations = [to_symbol(s) for s in representations]
7504 sz = len(representations)
7505 args = (Symbol * sz)()
7506 for i in range(sz):
7507 args[i] = representations[i]
7508 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7509
7510 def parse_string(self, s):
7511 """Parse rules and queries from a string"""
7512 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7513
7514 def parse_file(self, f):
7515 """Parse rules and queries from a file"""
7516 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7517
7518 def get_rules(self):
7519 """retrieve rules that have been added to fixedpoint context"""
7520 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7521
7523 """retrieve assertions that have been added to fixedpoint context"""
7524 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7525
7526 def __repr__(self):
7527 """Return a formatted string with all added rules and constraints."""
7528 return self.sexpr()
7529
7530 def sexpr(self):
7531 """Return a formatted string (in Lisp-like format) with all added constraints.
7532 We say the string is in s-expression format.
7533 """
7534 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7535
7536 def to_string(self, queries):
7537 """Return a formatted string (in Lisp-like format) with all added constraints.
7538 We say the string is in s-expression format.
7539 Include also queries.
7540 """
7541 args, len = _to_ast_array(queries)
7542 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7543
7544 def statistics(self):
7545 """Return statistics for the last `query()`.
7546 """
7547 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7548
7550 """Return a string describing why the last `query()` returned `unknown`.
7551 """
7552 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7553
7554 def declare_var(self, *vars):
7555 """Add variable or several variables.
7556 The added variable or variables will be bound in the rules
7557 and queries
7558 """
7559 vars = _get_args(vars)
7560 for v in vars:
7561 self.vars += [v]
7562
7563 def abstract(self, fml, is_forall=True):
7564 if self.vars == []:
7565 return fml
7566 if is_forall:
7567 return ForAll(self.vars, fml)
7568 else:
7569 return Exists(self.vars, fml)
7570
7571
7572
7577
7579 """Finite domain sort."""
7580
7581 def size(self):
7582 """Return the size of the finite domain sort"""
7583 r = (ctypes.c_ulonglong * 1)()
7584 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7585 return r[0]
7586 else:
7587 raise Z3Exception("Failed to retrieve finite domain sort size")
7588
7589
7590def FiniteDomainSort(name, sz, ctx=None):
7591 """Create a named finite domain sort of a given size sz"""
7592 if not isinstance(name, Symbol):
7593 name = to_symbol(name)
7594 ctx = _get_ctx(ctx)
7595 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7596
7597
7599 """Return True if `s` is a Z3 finite-domain sort.
7600
7602 True
7604 False
7605 """
7606 return isinstance(s, FiniteDomainSortRef)
7607
7608
7610 """Finite-domain expressions."""
7611
7612 def sort(self):
7613 """Return the sort of the finite-domain expression `self`."""
7614 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
7615
7616 def as_string(self):
7617 """Return a Z3 floating point expression as a Python string."""
7618 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
7619
7620
7622 """Return `True` if `a` is a Z3 finite-domain expression.
7623
7624 >>> s = FiniteDomainSort('S', 100)
7625 >>> b = Const('b', s)
7626 >>> is_finite_domain(b)
7627 True
7628 >>> is_finite_domain(Int('x'))
7629 False
7630 """
7631 return isinstance(a, FiniteDomainRef)
7632
7633
7635 """Integer values."""
7636
7637 def as_long(self):
7638 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7639
7640 >>> s = FiniteDomainSort('S', 100)
7641 >>> v = FiniteDomainVal(3, s)
7642 >>> v
7643 3
7644 >>> v.as_long() + 1
7645 4
7646 """
7647 return int(self.as_stringas_string())
7648
7649 def as_string(self):
7650 """Return a Z3 finite-domain numeral as a Python string.
7651
7652 >>> s = FiniteDomainSort('S', 100)
7653 >>> v = FiniteDomainVal(42, s)
7654 >>> v.as_string()
7655 '42'
7656 """
7657 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
7658
7659
7660def FiniteDomainVal(val, sort, ctx=None):
7661 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7662
7663 >>> s = FiniteDomainSort('S', 256)
7664 >>> FiniteDomainVal(255, s)
7665 255
7666 >>> FiniteDomainVal('100', s)
7667 100
7668 """
7669 if z3_debug():
7670 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7671 ctx = sort.ctx
7672 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7673
7674
7676 """Return `True` if `a` is a Z3 finite-domain value.
7677
7678 >>> s = FiniteDomainSort('S', 100)
7679 >>> b = Const('b', s)
7681 False
7682 >>> b = FiniteDomainVal(10, s)
7683 >>> b
7684 10
7686 True
7687 """
7688 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7689
7690
7691
7696
7698 def __init__(self, opt, value, is_max):
7699 self._opt = opt
7700 self._value = value
7701 self._is_max = is_max
7702
7703 def lower(self):
7704 opt = self._opt
7705 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7706
7707 def upper(self):
7708 opt = self._opt
7709 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7710
7711 def lower_values(self):
7712 opt = self._opt
7713 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7714
7715 def upper_values(self):
7716 opt = self._opt
7717 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7718
7719 def value(self):
7720 if self._is_max:
7721 return self.upper()
7722 else:
7723 return self.lower()
7724
7725 def __str__(self):
7726 return "%s:%s" % (self._value, self._is_max)
7727
7728
7729_on_models = {}
7730
7731
7732def _global_on_model(ctx):
7733 (fn, mdl) = _on_models[ctx]
7734 fn(mdl)
7735
7736
7737_on_model_eh = on_model_eh_type(_global_on_model)
7738
7739
7741 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7742
7743 def __init__(self, ctx=None):
7744 self.ctx = _get_ctx(ctx)
7745 self.optimize = Z3_mk_optimize(self.ctx.ref())
7746 self._on_models_id = None
7747 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7748
7749 def __deepcopy__(self, memo={}):
7750 return Optimize(self.optimize, self.ctx)
7751
7752 def __del__(self):
7753 if self.optimize is not None and self.ctx.ref() is not None:
7754 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7755 if self._on_models_id is not None:
7756 del _on_models[self._on_models_id]
7757
7758 def set(self, *args, **keys):
7759 """Set a configuration option.
7760 The method `help()` return a string containing all available options.
7761 """
7762 p = args2params(args, keys, self.ctx)
7763 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7764
7765 def help(self):
7766 """Display a string describing all available options."""
7767 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7768
7769 def param_descrs(self):
7770 """Return the parameter description set."""
7771 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7772
7773 def assert_exprs(self, *args):
7774 """Assert constraints as background axioms for the optimize solver."""
7775 args = _get_args(args)
7776 s = BoolSort(self.ctx)
7777 for arg in args:
7778 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7779 for f in arg:
7780 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7781 else:
7782 arg = s.cast(arg)
7783 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7784
7785 def add(self, *args):
7786 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7787 self.assert_exprs(*args)
7788
7789 def __iadd__(self, fml):
7790 self.add(fml)
7791 return self
7792
7793 def assert_and_track(self, a, p):
7794 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7795
7796 If `p` is a string, it will be automatically converted into a Boolean constant.
7797
7798 >>> x = Int('x')
7799 >>> p3 = Bool('p3')
7800 >>> s = Optimize()
7801 >>> s.assert_and_track(x > 0, 'p1')
7802 >>> s.assert_and_track(x != 1, 'p2')
7803 >>> s.assert_and_track(x < 0, p3)
7804 >>> print(s.check())
7805 unsat
7806 >>> c = s.unsat_core()
7807 >>> len(c)
7808 2
7809 >>> Bool('p1') in c
7810 True
7811 >>> Bool('p2') in c
7812 False
7813 >>> p3 in c
7814 True
7815 """
7816 if isinstance(p, str):
7817 p = Bool(p, self.ctx)
7818 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7819 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7820 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7821
7822 def add_soft(self, arg, weight="1", id=None):
7823 """Add soft constraint with optional weight and optional identifier.
7824 If no weight is supplied, then the penalty for violating the soft constraint
7825 is 1.
7826 Soft constraints are grouped by identifiers. Soft constraints that are
7827 added without identifiers are grouped by default.
7828 """
7829 if _is_int(weight):
7830 weight = "%d" % weight
7831 elif isinstance(weight, float):
7832 weight = "%f" % weight
7833 if not isinstance(weight, str):
7834 raise Z3Exception("weight should be a string or an integer")
7835 if id is None:
7836 id = ""
7837 id = to_symbol(id, self.ctx)
7838
7839 def asoft(a):
7840 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
7841 return OptimizeObjective(self, v, False)
7842 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7843 return [asoft(a) for a in arg]
7844 return asoft(arg)
7845
7846 def maximize(self, arg):
7847 """Add objective function to maximize."""
7848 return OptimizeObjective(
7849 self,
7850 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
7851 is_max=True,
7852 )
7853
7854 def minimize(self, arg):
7855 """Add objective function to minimize."""
7856 return OptimizeObjective(
7857 self,
7858 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
7859 is_max=False,
7860 )
7861
7862 def push(self):
7863 """create a backtracking point for added rules, facts and assertions"""
7864 Z3_optimize_push(self.ctx.ref(), self.optimize)
7865
7866 def pop(self):
7867 """restore to previously created backtracking point"""
7868 Z3_optimize_pop(self.ctx.ref(), self.optimize)
7869
7870 def check(self, *assumptions):
7871 """Check satisfiability while optimizing objective functions."""
7872 assumptions = _get_args(assumptions)
7873 num = len(assumptions)
7874 _assumptions = (Ast * num)()
7875 for i in range(num):
7876 _assumptions[i] = assumptions[i].as_ast()
7877 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7878
7880 """Return a string that describes why the last `check()` returned `unknown`."""
7881 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7882
7883 def model(self):
7884 """Return a model for the last check()."""
7885 try:
7886 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7887 except Z3Exception:
7888 raise Z3Exception("model is not available")
7889
7890 def unsat_core(self):
7891 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7892
7893 def lower(self, obj):
7894 if not isinstance(obj, OptimizeObjective):
7895 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7896 return obj.lower()
7897
7898 def upper(self, obj):
7899 if not isinstance(obj, OptimizeObjective):
7900 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7901 return obj.upper()
7902
7903 def lower_values(self, obj):
7904 if not isinstance(obj, OptimizeObjective):
7905 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7906 return obj.lower_values()
7907
7908 def upper_values(self, obj):
7909 if not isinstance(obj, OptimizeObjective):
7910 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7911 return obj.upper_values()
7912
7913 def from_file(self, filename):
7914 """Parse assertions and objectives from a file"""
7915 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7916
7917 def from_string(self, s):
7918 """Parse assertions and objectives from a string"""
7919 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7920
7921 def assertions(self):
7922 """Return an AST vector containing all added constraints."""
7923 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7924
7925 def objectives(self):
7926 """returns set of objective functions"""
7927 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7928
7929 def __repr__(self):
7930 """Return a formatted string with all added rules and constraints."""
7931 return self.sexpr()
7932
7933 def sexpr(self):
7934 """Return a formatted string (in Lisp-like format) with all added constraints.
7935 We say the string is in s-expression format.
7936 """
7937 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7938
7939 def statistics(self):
7940 """Return statistics for the last check`.
7941 """
7942 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7943
7944 def set_on_model(self, on_model):
7945 """Register a callback that is invoked with every incremental improvement to
7946 objective values. The callback takes a model as argument.
7947 The life-time of the model is limited to the callback so the
7948 model has to be (deep) copied if it is to be used after the callback
7949 """
7950 id = len(_on_models) + 41
7951 mdl = Model(self.ctx)
7952 _on_models[id] = (on_model, mdl)
7953 self._on_models_id = id
7955 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
7956 )
7957
7958
7959
7965 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
7966 It also contains model and proof converters.
7967 """
7968
7969 def __init__(self, result, ctx):
7970 self.result = result
7971 self.ctx = ctx
7972 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7973
7974 def __deepcopy__(self, memo={}):
7975 return ApplyResult(self.result, self.ctx)
7976
7977 def __del__(self):
7978 if self.ctx.ref() is not None:
7979 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7980
7981 def __len__(self):
7982 """Return the number of subgoals in `self`.
7983
7984 >>> a, b = Ints('a b')
7985 >>> g = Goal()
7986 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7987 >>> t = Tactic('split-clause')
7988 >>> r = t(g)
7989 >>> len(r)
7990 2
7991 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7992 >>> len(t(g))
7993 4
7994 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7995 >>> len(t(g))
7996 1
7997 """
7998 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7999
8000 def __getitem__(self, idx):
8001 """Return one of the subgoals stored in ApplyResult object `self`.
8002
8003 >>> a, b = Ints('a b')
8004 >>> g = Goal()
8005 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8006 >>> t = Tactic('split-clause')
8007 >>> r = t(g)
8008 >>> r[0]
8009 [a == 0, Or(b == 0, b == 1), a > b]
8010 >>> r[1]
8011 [a == 1, Or(b == 0, b == 1), a > b]
8012 """
8013 if idx >= len(self):
8014 raise IndexError
8015 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8016
8017 def __repr__(self):
8018 return obj_to_string(self)
8019
8020 def sexpr(self):
8021 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8022 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8023
8024 def as_expr(self):
8025 """Return a Z3 expression consisting of all subgoals.
8026
8027 >>> x = Int('x')
8028 >>> g = Goal()
8029 >>> g.add(x > 1)
8030 >>> g.add(Or(x == 2, x == 3))
8031 >>> r = Tactic('simplify')(g)
8032 >>> r
8033 [[Not(x <= 1), Or(x == 2, x == 3)]]
8034 >>> r.as_expr()
8035 And(Not(x <= 1), Or(x == 2, x == 3))
8036 >>> r = Tactic('split-clause')(g)
8037 >>> r
8038 [[x > 1, x == 2], [x > 1, x == 3]]
8039 >>> r.as_expr()
8040 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8041 """
8042 sz = len(self)
8043 if sz == 0:
8044 return BoolVal(False, self.ctx)
8045 elif sz == 1:
8046 return self[0].as_expr()
8047 else:
8048 return Or([self[i].as_expr() for i in range(len(self))])
8049
8050
8055
8056
8058 """Tactics transform, solver and/or simplify sets of constraints (Goal).
8059 A Tactic can be converted into a Solver using the method solver().
8060
8061 Several combinators are available for creating new tactics using the built-in ones:
8062 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8063 """
8064
8065 def __init__(self, tactic, ctx=None):
8066 self.ctx = _get_ctx(ctx)
8067 self.tactic = None
8068 if isinstance(tactic, TacticObj):
8069 self.tactic = tactic
8070 else:
8071 if z3_debug():
8072 _z3_assert(isinstance(tactic, str), "tactic name expected")
8073 try:
8074 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
8075 except Z3Exception:
8076 raise Z3Exception("unknown tactic '%s'" % tactic)
8077 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
8078
8079 def __deepcopy__(self, memo={}):
8080 return Tactic(self.tactic, self.ctx)
8081
8082 def __del__(self):
8083 if self.tactic is not None and self.ctx.ref() is not None:
8084 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
8085
8086 def solver(self, logFile=None):
8087 """Create a solver using the tactic `self`.
8088
8089 The solver supports the methods `push()` and `pop()`, but it
8090 will always solve each `check()` from scratch.
8091
8092 >>> t = Then('simplify', 'nlsat')
8093 >>> s = t.solver()
8094 >>> x = Real('x')
8095 >>> s.add(x**2 == 2, x > 0)
8096 >>> s.check()
8097 sat
8098 >>> s.model()
8099 [x = 1.4142135623?]
8100 """
8101 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
8102
8103 def apply(self, goal, *arguments, **keywords):
8104 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8105
8106 >>> x, y = Ints('x y')
8107 >>> t = Tactic('solve-eqs')
8108 >>> t.apply(And(x == 0, y >= x + 1))
8109 [[y >= 1]]
8110 """
8111 if z3_debug():
8112 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8113 goal = _to_goal(goal)
8114 if len(arguments) > 0 or len(keywords) > 0:
8115 p = args2params(arguments, keywords, self.ctx)
8116 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
8117 else:
8118 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
8119
8120 def __call__(self, goal, *arguments, **keywords):
8121 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8122
8123 >>> x, y = Ints('x y')
8124 >>> t = Tactic('solve-eqs')
8125 >>> t(And(x == 0, y >= x + 1))
8126 [[y >= 1]]
8127 """
8128 return self.apply(goal, *arguments, **keywords)
8129
8130 def help(self):
8131 """Display a string containing a description of the available options for the `self` tactic."""
8132 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
8133
8134 def param_descrs(self):
8135 """Return the parameter description set."""
8136 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
8137
8138
8139def _to_goal(a):
8140 if isinstance(a, BoolRef):
8141 goal = Goal(ctx=a.ctx)
8142 goal.add(a)
8143 return goal
8144 else:
8145 return a
8146
8147
8148def _to_tactic(t, ctx=None):
8149 if isinstance(t, Tactic):
8150 return t
8151 else:
8152 return Tactic(t, ctx)
8153
8154
8155def _and_then(t1, t2, ctx=None):
8156 t1 = _to_tactic(t1, ctx)
8157 t2 = _to_tactic(t2, ctx)
8158 if z3_debug():
8159 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8160 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8161
8162
8163def _or_else(t1, t2, ctx=None):
8164 t1 = _to_tactic(t1, ctx)
8165 t2 = _to_tactic(t2, ctx)
8166 if z3_debug():
8167 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8168 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8169
8170
8171def AndThen(*ts, **ks):
8172 """Return a tactic that applies the tactics in `*ts` in sequence.
8173
8174 >>> x, y = Ints('x y')
8175 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8176 >>> t(And(x == 0, y > x + 1))
8177 [[Not(y <= 1)]]
8178 >>> t(And(x == 0, y > x + 1)).as_expr()
8179 Not(y <= 1)
8180 """
8181 if z3_debug():
8182 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8183 ctx = ks.get("ctx", None)
8184 num = len(ts)
8185 r = ts[0]
8186 for i in range(num - 1):
8187 r = _and_then(r, ts[i + 1], ctx)
8188 return r
8189
8190
8191def Then(*ts, **ks):
8192 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8193
8194 >>> x, y = Ints('x y')
8195 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8196 >>> t(And(x == 0, y > x + 1))
8197 [[Not(y <= 1)]]
8198 >>> t(And(x == 0, y > x + 1)).as_expr()
8199 Not(y <= 1)
8200 """
8201 return AndThen(*ts, **ks)
8202
8203
8204def OrElse(*ts, **ks):
8205 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8206
8207 >>> x = Int('x')
8208 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8209 >>> # Tactic split-clause fails if there is no clause in the given goal.
8210 >>> t(x == 0)
8211 [[x == 0]]
8212 >>> t(Or(x == 0, x == 1))
8213 [[x == 0], [x == 1]]
8214 """
8215 if z3_debug():
8216 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8217 ctx = ks.get("ctx", None)
8218 num = len(ts)
8219 r = ts[0]
8220 for i in range(num - 1):
8221 r = _or_else(r, ts[i + 1], ctx)
8222 return r
8223
8224
8225def ParOr(*ts, **ks):
8226 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8227
8228 >>> x = Int('x')
8229 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8230 >>> t(x + 1 == 2)
8231 [[x == 1]]
8232 """
8233 if z3_debug():
8234 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8235 ctx = _get_ctx(ks.get("ctx", None))
8236 ts = [_to_tactic(t, ctx) for t in ts]
8237 sz = len(ts)
8238 _args = (TacticObj * sz)()
8239 for i in range(sz):
8240 _args[i] = ts[i].tactic
8241 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8242
8243
8244def ParThen(t1, t2, ctx=None):
8245 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8246 The subgoals are processed in parallel.
8247
8248 >>> x, y = Ints('x y')
8249 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8250 >>> t(And(Or(x == 1, x == 2), y == x + 1))
8251 [[x == 1, y == 2], [x == 2, y == 3]]
8252 """
8253 t1 = _to_tactic(t1, ctx)
8254 t2 = _to_tactic(t2, ctx)
8255 if z3_debug():
8256 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8257 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8258
8259
8260def ParAndThen(t1, t2, ctx=None):
8261 """Alias for ParThen(t1, t2, ctx)."""
8262 return ParThen(t1, t2, ctx)
8263
8264
8265def With(t, *args, **keys):
8266 """Return a tactic that applies tactic `t` using the given configuration options.
8267
8268 >>> x, y = Ints('x y')
8269 >>> t = With(Tactic('simplify'), som=True)
8270 >>> t((x + 1)*(y + 2) == 0)
8271 [[2*x + y + x*y == -2]]
8272 """
8273 ctx = keys.pop("ctx", None)
8274 t = _to_tactic(t, ctx)
8275 p = args2params(args, keys, t.ctx)
8276 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8277
8278
8279def WithParams(t, p):
8280 """Return a tactic that applies tactic `t` using the given configuration options.
8281
8282 >>> x, y = Ints('x y')
8283 >>> p = ParamsRef()
8284 >>> p.set("som", True)
8285 >>> t = WithParams(Tactic('simplify'), p)
8286 >>> t((x + 1)*(y + 2) == 0)
8287 [[2*x + y + x*y == -2]]
8288 """
8289 t = _to_tactic(t, None)
8290 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8291
8292
8293def Repeat(t, max=4294967295, ctx=None):
8294 """Return a tactic that keeps applying `t` until the goal is not modified anymore
8295 or the maximum number of iterations `max` is reached.
8296
8297 >>> x, y = Ints('x y')
8298 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8299 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8300 >>> r = t(c)
8301 >>> for subgoal in r: print(subgoal)
8302 [x == 0, y == 0, x > y]
8303 [x == 0, y == 1, x > y]
8304 [x == 1, y == 0, x > y]
8305 [x == 1, y == 1, x > y]
8306 >>> t = Then(t, Tactic('propagate-values'))
8307 >>> t(c)
8308 [[x == 1, y == 0]]
8309 """
8310 t = _to_tactic(t, ctx)
8311 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8312
8313
8314def TryFor(t, ms, ctx=None):
8315 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8316
8317 If `t` does not terminate in `ms` milliseconds, then it fails.
8318 """
8319 t = _to_tactic(t, ctx)
8320 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8321
8322
8323def tactics(ctx=None):
8324 """Return a list of all available tactics in Z3.
8325
8326 >>> l = tactics()
8327 >>> l.count('simplify') == 1
8328 True
8329 """
8330 ctx = _get_ctx(ctx)
8331 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8332
8333
8334def tactic_description(name, ctx=None):
8335 """Return a short description for the tactic named `name`.
8336
8337 >>> d = tactic_description('simplify')
8338 """
8339 ctx = _get_ctx(ctx)
8340 return Z3_tactic_get_descr(ctx.ref(), name)
8341
8342
8344 """Display a (tabular) description of all available tactics in Z3."""
8345 if in_html_mode():
8346 even = True
8347 print('<table border="1" cellpadding="2" cellspacing="0">')
8348 for t in tactics():
8349 if even:
8350 print('<tr style="background-color:#CFCFCF">')
8351 even = False
8352 else:
8353 print("<tr>")
8354 even = True
8355 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8356 print("</table>")
8357 else:
8358 for t in tactics():
8359 print("%s : %s" % (t, tactic_description(t)))
8360
8361
8362class Probe:
8363 """Probes are used to inspect a goal (aka problem) and collect information that may be used
8364 to decide which solver and/or preprocessing step will be used.
8365 """
8366
8367 def __init__(self, probe, ctx=None):
8368 self.ctx = _get_ctx(ctx)
8369 self.probe = None
8370 if isinstance(probe, ProbeObj):
8371 self.probe = probe
8372 elif isinstance(probe, float):
8373 self.probe = Z3_probe_const(self.ctx.ref(), probe)
8374 elif _is_int(probe):
8375 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
8376 elif isinstance(probe, bool):
8377 if probe:
8378 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
8379 else:
8380 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
8381 else:
8382 if z3_debug():
8383 _z3_assert(isinstance(probe, str), "probe name expected")
8384 try:
8385 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
8386 except Z3Exception:
8387 raise Z3Exception("unknown probe '%s'" % probe)
8388 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
8389
8390 def __deepcopy__(self, memo={}):
8391 return Probe(self.probe, self.ctx)
8392
8393 def __del__(self):
8394 if self.probe is not None and self.ctx.ref() is not None:
8395 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
8396
8397 def __lt__(self, other):
8398 """Return a probe that evaluates to "true" when the value returned by `self`
8399 is less than the value returned by `other`.
8400
8401 >>> p = Probe('size') < 10
8402 >>> x = Int('x')
8403 >>> g = Goal()
8404 >>> g.add(x > 0)
8405 >>> g.add(x < 10)
8406 >>> p(g)
8407 1.0
8408 """
8409 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8410
8411 def __gt__(self, other):
8412 """Return a probe that evaluates to "true" when the value returned by `self`
8413 is greater than the value returned by `other`.
8414
8415 >>> p = Probe('size') > 10
8416 >>> x = Int('x')
8417 >>> g = Goal()
8418 >>> g.add(x > 0)
8419 >>> g.add(x < 10)
8420 >>> p(g)
8421 0.0
8422 """
8423 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8424
8425 def __le__(self, other):
8426 """Return a probe that evaluates to "true" when the value returned by `self`
8427 is less than or equal to the value returned by `other`.
8428
8429 >>> p = Probe('size') <= 2
8430 >>> x = Int('x')
8431 >>> g = Goal()
8432 >>> g.add(x > 0)
8433 >>> g.add(x < 10)
8434 >>> p(g)
8435 1.0
8436 """
8437 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8438
8439 def __ge__(self, other):
8440 """Return a probe that evaluates to "true" when the value returned by `self`
8441 is greater than or equal to the value returned by `other`.
8442
8443 >>> p = Probe('size') >= 2
8444 >>> x = Int('x')
8445 >>> g = Goal()
8446 >>> g.add(x > 0)
8447 >>> g.add(x < 10)
8448 >>> p(g)
8449 1.0
8450 """
8451 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8452
8453 def __eq__(self, other):
8454 """Return a probe that evaluates to "true" when the value returned by `self`
8455 is equal to the value returned by `other`.
8456
8457 >>> p = Probe('size') == 2
8458 >>> x = Int('x')
8459 >>> g = Goal()
8460 >>> g.add(x > 0)
8461 >>> g.add(x < 10)
8462 >>> p(g)
8463 1.0
8464 """
8465 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8466
8467 def __ne__(self, other):
8468 """Return a probe that evaluates to "true" when the value returned by `self`
8469 is not equal to the value returned by `other`.
8470
8471 >>> p = Probe('size') != 2
8472 >>> x = Int('x')
8473 >>> g = Goal()
8474 >>> g.add(x > 0)
8475 >>> g.add(x < 10)
8476 >>> p(g)
8477 0.0
8478 """
8479 p = self.__eq__(other)
8480 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8481
8482 def __call__(self, goal):
8483 """Evaluate the probe `self` in the given goal.
8484
8485 >>> p = Probe('size')
8486 >>> x = Int('x')
8487 >>> g = Goal()
8488 >>> g.add(x > 0)
8489 >>> g.add(x < 10)
8490 >>> p(g)
8491 2.0
8492 >>> g.add(x < 20)
8493 >>> p(g)
8494 3.0
8495 >>> p = Probe('num-consts')
8496 >>> p(g)
8497 1.0
8498 >>> p = Probe('is-propositional')
8499 >>> p(g)
8500 0.0
8501 >>> p = Probe('is-qflia')
8502 >>> p(g)
8503 1.0
8504 """
8505 if z3_debug():
8506 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8507 goal = _to_goal(goal)
8508 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8509
8510
8512 """Return `True` if `p` is a Z3 probe.
8513
8514 >>> is_probe(Int('x'))
8515 False
8516 >>> is_probe(Probe('memory'))
8517 True
8518 """
8519 return isinstance(p, Probe)
8520
8521
8522def _to_probe(p, ctx=None):
8523 if is_probe(p):
8524 return p
8525 else:
8526 return Probe(p, ctx)
8527
8528
8529def probes(ctx=None):
8530 """Return a list of all available probes in Z3.
8531
8532 >>> l = probes()
8533 >>> l.count('memory') == 1
8534 True
8535 """
8536 ctx = _get_ctx(ctx)
8537 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8538
8539
8540def probe_description(name, ctx=None):
8541 """Return a short description for the probe named `name`.
8542
8543 >>> d = probe_description('memory')
8544 """
8545 ctx = _get_ctx(ctx)
8546 return Z3_probe_get_descr(ctx.ref(), name)
8547
8548
8550 """Display a (tabular) description of all available probes in Z3."""
8551 if in_html_mode():
8552 even = True
8553 print('<table border="1" cellpadding="2" cellspacing="0">')
8554 for p in probes():
8555 if even:
8556 print('<tr style="background-color:#CFCFCF">')
8557 even = False
8558 else:
8559 print("<tr>")
8560 even = True
8561 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8562 print("</table>")
8563 else:
8564 for p in probes():
8565 print("%s : %s" % (p, probe_description(p)))
8566
8567
8568def _probe_nary(f, args, ctx):
8569 if z3_debug():
8570 _z3_assert(len(args) > 0, "At least one argument expected")
8571 num = len(args)
8572 r = _to_probe(args[0], ctx)
8573 for i in range(num - 1):
8574 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8575 return r
8576
8577
8578def _probe_and(args, ctx):
8579 return _probe_nary(Z3_probe_and, args, ctx)
8580
8581
8582def _probe_or(args, ctx):
8583 return _probe_nary(Z3_probe_or, args, ctx)
8584
8585
8586def FailIf(p, ctx=None):
8587 """Return a tactic that fails if the probe `p` evaluates to true.
8588 Otherwise, it returns the input goal unmodified.
8589
8590 In the following example, the tactic applies 'simplify' if and only if there are
8591 more than 2 constraints in the goal.
8592
8593 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8594 >>> x, y = Ints('x y')
8595 >>> g = Goal()
8596 >>> g.add(x > 0)
8597 >>> g.add(y > 0)
8598 >>> t(g)
8599 [[x > 0, y > 0]]
8600 >>> g.add(x == y + 1)
8601 >>> t(g)
8602 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8603 """
8604 p = _to_probe(p, ctx)
8605 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8606
8607
8608def When(p, t, ctx=None):
8609 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8610 Otherwise, it returns the input goal unmodified.
8611
8612 >>> t = When(Probe('size') > 2, Tactic('simplify'))
8613 >>> x, y = Ints('x y')
8614 >>> g = Goal()
8615 >>> g.add(x > 0)
8616 >>> g.add(y > 0)
8617 >>> t(g)
8618 [[x > 0, y > 0]]
8619 >>> g.add(x == y + 1)
8620 >>> t(g)
8621 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8622 """
8623 p = _to_probe(p, ctx)
8624 t = _to_tactic(t, ctx)
8625 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8626
8627
8628def Cond(p, t1, t2, ctx=None):
8629 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8630
8631 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8632 """
8633 p = _to_probe(p, ctx)
8634 t1 = _to_tactic(t1, ctx)
8635 t2 = _to_tactic(t2, ctx)
8636 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8637
8638
8643
8644
8645def simplify(a, *arguments, **keywords):
8646 """Simplify the expression `a` using the given options.
8647
8648 This function has many options. Use `help_simplify` to obtain the complete list.
8649
8650 >>> x = Int('x')
8651 >>> y = Int('y')
8652 >>> simplify(x + 1 + y + x + 1)
8653 2 + 2*x + y
8654 >>> simplify((x + 1)*(y + 1), som=True)
8655 1 + x + y + x*y
8656 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8657 And(Not(x == y), Not(x == 1), Not(y == 1))
8658 >>> simplify(And(x == 0, y == 1), elim_and=True)
8659 Not(Or(Not(x == 0), Not(y == 1)))
8660 """
8661 if z3_debug():
8662 _z3_assert(is_expr(a), "Z3 expression expected")
8663 if len(arguments) > 0 or len(keywords) > 0:
8664 p = args2params(arguments, keywords, a.ctx)
8665 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8666 else:
8667 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8668
8669
8671 """Return a string describing all options available for Z3 `simplify` procedure."""
8672 print(Z3_simplify_get_help(main_ctx().ref()))
8673
8674
8676 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8678
8679
8680def substitute(t, *m):
8681 """Apply substitution m on t, m is a list of pairs of the form (from, to).
8682 Every occurrence in t of from is replaced with to.
8683
8684 >>> x = Int('x')
8685 >>> y = Int('y')
8686 >>> substitute(x + 1, (x, y + 1))
8687 y + 1 + 1
8688 >>> f = Function('f', IntSort(), IntSort())
8689 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8690 1 + 1
8691 """
8692 if isinstance(m, tuple):
8693 m1 = _get_args(m)
8694 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8695 m = m1
8696 if z3_debug():
8697 _z3_assert(is_expr(t), "Z3 expression expected")
8698 _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(
8699 p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
8700 num = len(m)
8701 _from = (Ast * num)()
8702 _to = (Ast * num)()
8703 for i in range(num):
8704 _from[i] = m[i][0].as_ast()
8705 _to[i] = m[i][1].as_ast()
8706 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8707
8708
8710 """Substitute the free variables in t with the expression in m.
8711
8712 >>> v0 = Var(0, IntSort())
8713 >>> v1 = Var(1, IntSort())
8714 >>> x = Int('x')
8715 >>> f = Function('f', IntSort(), IntSort(), IntSort())
8716 >>> # replace v0 with x+1 and v1 with x
8717 >>> substitute_vars(f(v0, v1), x + 1, x)
8718 f(x + 1, x)
8719 """
8720 if z3_debug():
8721 _z3_assert(is_expr(t), "Z3 expression expected")
8722 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8723 num = len(m)
8724 _to = (Ast * num)()
8725 for i in range(num):
8726 _to[i] = m[i].as_ast()
8727 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8728
8729
8730def Sum(*args):
8731 """Create the sum of the Z3 expressions.
8732
8733 >>> a, b, c = Ints('a b c')
8734 >>> Sum(a, b, c)
8735 a + b + c
8736 >>> Sum([a, b, c])
8737 a + b + c
8738 >>> A = IntVector('a', 5)
8739 >>> Sum(A)
8740 a__0 + a__1 + a__2 + a__3 + a__4
8741 """
8742 args = _get_args(args)
8743 if len(args) == 0:
8744 return 0
8745 ctx = _ctx_from_ast_arg_list(args)
8746 if ctx is None:
8747 return _reduce(lambda a, b: a + b, args, 0)
8748 args = _coerce_expr_list(args, ctx)
8749 if is_bv(args[0]):
8750 return _reduce(lambda a, b: a + b, args, 0)
8751 else:
8752 _args, sz = _to_ast_array(args)
8753 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8754
8755
8756def Product(*args):
8757 """Create the product of the Z3 expressions.
8758
8759 >>> a, b, c = Ints('a b c')
8760 >>> Product(a, b, c)
8761 a*b*c
8762 >>> Product([a, b, c])
8763 a*b*c
8764 >>> A = IntVector('a', 5)
8765 >>> Product(A)
8766 a__0*a__1*a__2*a__3*a__4
8767 """
8768 args = _get_args(args)
8769 if len(args) == 0:
8770 return 1
8771 ctx = _ctx_from_ast_arg_list(args)
8772 if ctx is None:
8773 return _reduce(lambda a, b: a * b, args, 1)
8774 args = _coerce_expr_list(args, ctx)
8775 if is_bv(args[0]):
8776 return _reduce(lambda a, b: a * b, args, 1)
8777 else:
8778 _args, sz = _to_ast_array(args)
8779 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8780
8781
8782def AtMost(*args):
8783 """Create an at-most Pseudo-Boolean k constraint.
8784
8785 >>> a, b, c = Bools('a b c')
8786 >>> f = AtMost(a, b, c, 2)
8787 """
8788 args = _get_args(args)
8789 if z3_debug():
8790 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8791 ctx = _ctx_from_ast_arg_list(args)
8792 if z3_debug():
8793 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8794 args1 = _coerce_expr_list(args[:-1], ctx)
8795 k = args[-1]
8796 _args, sz = _to_ast_array(args1)
8797 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8798
8799
8800def AtLeast(*args):
8801 """Create an at-most Pseudo-Boolean k constraint.
8802
8803 >>> a, b, c = Bools('a b c')
8804 >>> f = AtLeast(a, b, c, 2)
8805 """
8806 args = _get_args(args)
8807 if z3_debug():
8808 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8809 ctx = _ctx_from_ast_arg_list(args)
8810 if z3_debug():
8811 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8812 args1 = _coerce_expr_list(args[:-1], ctx)
8813 k = args[-1]
8814 _args, sz = _to_ast_array(args1)
8815 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8816
8817
8818def _reorder_pb_arg(arg):
8819 a, b = arg
8820 if not _is_int(b) and _is_int(a):
8821 return b, a
8822 return arg
8823
8824
8825def _pb_args_coeffs(args, default_ctx=None):
8826 args = _get_args_ast_list(args)
8827 if len(args) == 0:
8828 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8829 args = [_reorder_pb_arg(arg) for arg in args]
8830 args, coeffs = zip(*args)
8831 if z3_debug():
8832 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8833 ctx = _ctx_from_ast_arg_list(args)
8834 if z3_debug():
8835 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8836 args = _coerce_expr_list(args, ctx)
8837 _args, sz = _to_ast_array(args)
8838 _coeffs = (ctypes.c_int * len(coeffs))()
8839 for i in range(len(coeffs)):
8840 _z3_check_cint_overflow(coeffs[i], "coefficient")
8841 _coeffs[i] = coeffs[i]
8842 return ctx, sz, _args, _coeffs
8843
8844
8845def PbLe(args, k):
8846 """Create a Pseudo-Boolean inequality k constraint.
8847
8848 >>> a, b, c = Bools('a b c')
8849 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8850 """
8851 _z3_check_cint_overflow(k, "k")
8852 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8853 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8854
8855
8856def PbGe(args, k):
8857 """Create a Pseudo-Boolean inequality k constraint.
8858
8859 >>> a, b, c = Bools('a b c')
8860 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8861 """
8862 _z3_check_cint_overflow(k, "k")
8863 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8864 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8865
8866
8867def PbEq(args, k, ctx=None):
8868 """Create a Pseudo-Boolean inequality k constraint.
8869
8870 >>> a, b, c = Bools('a b c')
8871 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8872 """
8873 _z3_check_cint_overflow(k, "k")
8874 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8875 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8876
8877
8878def solve(*args, **keywords):
8879 """Solve the constraints `*args`.
8880
8881 This is a simple function for creating demonstrations. It creates a solver,
8882 configure it using the options in `keywords`, adds the constraints
8883 in `args`, and invokes check.
8884
8885 >>> a = Int('a')
8886 >>> solve(a > 0, a < 2)
8887 [a = 1]
8888 """
8889 show = keywords.pop("show", False)
8890 s = Solver()
8891 s.set(**keywords)
8892 s.add(*args)
8893 if show:
8894 print(s)
8895 r = s.check()
8896 if r == unsat:
8897 print("no solution")
8898 elif r == unknown:
8899 print("failed to solve")
8900 try:
8901 print(s.model())
8902 except Z3Exception:
8903 return
8904 else:
8905 print(s.model())
8906
8907
8908def solve_using(s, *args, **keywords):
8909 """Solve the constraints `*args` using solver `s`.
8910
8911 This is a simple function for creating demonstrations. It is similar to `solve`,
8912 but it uses the given solver `s`.
8913 It configures solver `s` using the options in `keywords`, adds the constraints
8914 in `args`, and invokes check.
8915 """
8916 show = keywords.pop("show", False)
8917 if z3_debug():
8918 _z3_assert(isinstance(s, Solver), "Solver object expected")
8919 s.set(**keywords)
8920 s.add(*args)
8921 if show:
8922 print("Problem:")
8923 print(s)
8924 r = s.check()
8925 if r == unsat:
8926 print("no solution")
8927 elif r == unknown:
8928 print("failed to solve")
8929 try:
8930 print(s.model())
8931 except Z3Exception:
8932 return
8933 else:
8934 if show:
8935 print("Solution:")
8936 print(s.model())
8937
8938
8939def prove(claim, show=False, **keywords):
8940 """Try to prove the given claim.
8941
8942 This is a simple function for creating demonstrations. It tries to prove
8943 `claim` by showing the negation is unsatisfiable.
8944
8945 >>> p, q = Bools('p q')
8946 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8947 proved
8948 """
8949 if z3_debug():
8950 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8951 s = Solver()
8952 s.set(**keywords)
8953 s.add(Not(claim))
8954 if show:
8955 print(s)
8956 r = s.check()
8957 if r == unsat:
8958 print("proved")
8959 elif r == unknown:
8960 print("failed to prove")
8961 print(s.model())
8962 else:
8963 print("counterexample")
8964 print(s.model())
8965
8966
8967def _solve_html(*args, **keywords):
8968 """Version of function `solve` used in RiSE4Fun."""
8969 show = keywords.pop("show", False)
8970 s = Solver()
8971 s.set(**keywords)
8972 s.add(*args)
8973 if show:
8974 print("<b>Problem:</b>")
8975 print(s)
8976 r = s.check()
8977 if r == unsat:
8978 print("<b>no solution</b>")
8979 elif r == unknown:
8980 print("<b>failed to solve</b>")
8981 try:
8982 print(s.model())
8983 except Z3Exception:
8984 return
8985 else:
8986 if show:
8987 print("<b>Solution:</b>")
8988 print(s.model())
8989
8990
8991def _solve_using_html(s, *args, **keywords):
8992 """Version of function `solve_using` used in RiSE4Fun."""
8993 show = keywords.pop("show", False)
8994 if z3_debug():
8995 _z3_assert(isinstance(s, Solver), "Solver object expected")
8996 s.set(**keywords)
8997 s.add(*args)
8998 if show:
8999 print("<b>Problem:</b>")
9000 print(s)
9001 r = s.check()
9002 if r == unsat:
9003 print("<b>no solution</b>")
9004 elif r == unknown:
9005 print("<b>failed to solve</b>")
9006 try:
9007 print(s.model())
9008 except Z3Exception:
9009 return
9010 else:
9011 if show:
9012 print("<b>Solution:</b>")
9013 print(s.model())
9014
9015
9016def _prove_html(claim, show=False, **keywords):
9017 """Version of function `prove` used in RiSE4Fun."""
9018 if z3_debug():
9019 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9020 s = Solver()
9021 s.set(**keywords)
9022 s.add(Not(claim))
9023 if show:
9024 print(s)
9025 r = s.check()
9026 if r == unsat:
9027 print("<b>proved</b>")
9028 elif r == unknown:
9029 print("<b>failed to prove</b>")
9030 print(s.model())
9031 else:
9032 print("<b>counterexample</b>")
9033 print(s.model())
9034
9035
9036def _dict2sarray(sorts, ctx):
9037 sz = len(sorts)
9038 _names = (Symbol * sz)()
9039 _sorts = (Sort * sz)()
9040 i = 0
9041 for k in sorts:
9042 v = sorts[k]
9043 if z3_debug():
9044 _z3_assert(isinstance(k, str), "String expected")
9045 _z3_assert(is_sort(v), "Z3 sort expected")
9046 _names[i] = to_symbol(k, ctx)
9047 _sorts[i] = v.ast
9048 i = i + 1
9049 return sz, _names, _sorts
9050
9051
9052def _dict2darray(decls, ctx):
9053 sz = len(decls)
9054 _names = (Symbol * sz)()
9055 _decls = (FuncDecl * sz)()
9056 i = 0
9057 for k in decls:
9058 v = decls[k]
9059 if z3_debug():
9060 _z3_assert(isinstance(k, str), "String expected")
9061 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9062 _names[i] = to_symbol(k, ctx)
9063 if is_const(v):
9064 _decls[i] = v.decl().ast
9065 else:
9066 _decls[i] = v.ast
9067 i = i + 1
9068 return sz, _names, _decls
9069
9070
9071def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9072 """Parse a string in SMT 2.0 format using the given sorts and decls.
9073
9074 The arguments sorts and decls are Python dictionaries used to initialize
9075 the symbol table used for the SMT 2.0 parser.
9076
9077 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9078 [x > 0, x < 10]
9079 >>> x, y = Ints('x y')
9080 >>> f = Function('f', IntSort(), IntSort())
9081 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9082 [x + f(y) > 0]
9083 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9084 [a > 0]
9085 """
9086 ctx = _get_ctx(ctx)
9087 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9088 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9089 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9090
9091
9092def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9093 """Parse a file in SMT 2.0 format using the given sorts and decls.
9094
9095 This function is similar to parse_smt2_string().
9096 """
9097 ctx = _get_ctx(ctx)
9098 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9099 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9100 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9101
9102
9103
9108
9109
9110# Global default rounding mode
9111_dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
9112_dflt_fpsort_ebits = 11
9113_dflt_fpsort_sbits = 53
9114
9115
9117 """Retrieves the global default rounding mode."""
9118 global _dflt_rounding_mode
9119 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9120 return RTZ(ctx)
9121 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9122 return RTN(ctx)
9123 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9124 return RTP(ctx)
9125 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9126 return RNE(ctx)
9127 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9128 return RNA(ctx)
9129
9130
9131_ROUNDING_MODES = frozenset({
9132 Z3_OP_FPA_RM_TOWARD_ZERO,
9133 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9134 Z3_OP_FPA_RM_TOWARD_POSITIVE,
9135 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9136 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9137})
9138
9139
9141 global _dflt_rounding_mode
9142 if is_fprm_value(rm):
9143 _dflt_rounding_mode = rm.decl().kind()
9144 else:
9145 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9146 _dflt_rounding_mode = rm
9147
9148
9150 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9151
9152
9153def set_default_fp_sort(ebits, sbits, ctx=None):
9154 global _dflt_fpsort_ebits
9155 global _dflt_fpsort_sbits
9156 _dflt_fpsort_ebits = ebits
9157 _dflt_fpsort_sbits = sbits
9158
9159
9160def _dflt_rm(ctx=None):
9161 return get_default_rounding_mode(ctx)
9162
9163
9164def _dflt_fps(ctx=None):
9165 return get_default_fp_sort(ctx)
9166
9167
9168def _coerce_fp_expr_list(alist, ctx):
9169 first_fp_sort = None
9170 for a in alist:
9171 if is_fp(a):
9172 if first_fp_sort is None:
9173 first_fp_sort = a.sort()
9174 elif first_fp_sort == a.sort():
9175 pass # OK, same as before
9176 else:
9177 # we saw at least 2 different float sorts; something will
9178 # throw a sort mismatch later, for now assume None.
9179 first_fp_sort = None
9180 break
9181
9182 r = []
9183 for i in range(len(alist)):
9184 a = alist[i]
9185 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9186 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9187 r.append(FPVal(a, None, first_fp_sort, ctx))
9188 else:
9189 r.append(a)
9190 return _coerce_expr_list(r, ctx)
9191
9192
9193# FP Sorts
9194
9196 """Floating-point sort."""
9197
9198 def ebits(self):
9199 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9200 >>> b = FPSort(8, 24)
9201 >>> b.ebits()
9202 8
9203 """
9204 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
9205
9206 def sbits(self):
9207 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9208 >>> b = FPSort(8, 24)
9209 >>> b.sbits()
9210 24
9211 """
9212 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
9213
9214 def cast(self, val):
9215 """Try to cast `val` as a floating-point expression.
9216 >>> b = FPSort(8, 24)
9217 >>> b.cast(1.0)
9218 1
9219 >>> b.cast(1.0).sexpr()
9220 '(fp #b0 #x7f #b00000000000000000000000)'
9221 """
9222 if is_expr(val):
9223 if z3_debug():
9224 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
9225 return val
9226 else:
9227 return FPVal(val, None, self, self.ctxctx)
9228
9229
9230def Float16(ctx=None):
9231 """Floating-point 16-bit (half) sort."""
9232 ctx = _get_ctx(ctx)
9233 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9234
9235
9236def FloatHalf(ctx=None):
9237 """Floating-point 16-bit (half) sort."""
9238 ctx = _get_ctx(ctx)
9239 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9240
9241
9242def Float32(ctx=None):
9243 """Floating-point 32-bit (single) sort."""
9244 ctx = _get_ctx(ctx)
9245 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9246
9247
9248def FloatSingle(ctx=None):
9249 """Floating-point 32-bit (single) sort."""
9250 ctx = _get_ctx(ctx)
9251 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9252
9253
9254def Float64(ctx=None):
9255 """Floating-point 64-bit (double) sort."""
9256 ctx = _get_ctx(ctx)
9257 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9258
9259
9260def FloatDouble(ctx=None):
9261 """Floating-point 64-bit (double) sort."""
9262 ctx = _get_ctx(ctx)
9263 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9264
9265
9266def Float128(ctx=None):
9267 """Floating-point 128-bit (quadruple) sort."""
9268 ctx = _get_ctx(ctx)
9269 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9270
9271
9272def FloatQuadruple(ctx=None):
9273 """Floating-point 128-bit (quadruple) sort."""
9274 ctx = _get_ctx(ctx)
9275 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9276
9277
9279 """"Floating-point rounding mode sort."""
9280
9281
9283 """Return True if `s` is a Z3 floating-point sort.
9284
9285 >>> is_fp_sort(FPSort(8, 24))
9286 True
9287 >>> is_fp_sort(IntSort())
9288 False
9289 """
9290 return isinstance(s, FPSortRef)
9291
9292
9294 """Return True if `s` is a Z3 floating-point rounding mode sort.
9295
9296 >>> is_fprm_sort(FPSort(8, 24))
9297 False
9298 >>> is_fprm_sort(RNE().sort())
9299 True
9300 """
9301 return isinstance(s, FPRMSortRef)
9302
9303# FP Expressions
9304
9305
9307 """Floating-point expressions."""
9308
9309 def sort(self):
9310 """Return the sort of the floating-point expression `self`.
9311
9312 >>> x = FP('1.0', FPSort(8, 24))
9313 >>> x.sort()
9314 FPSort(8, 24)
9315 >>> x.sort() == FPSort(8, 24)
9316 True
9317 """
9318 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
9319
9320 def ebits(self):
9321 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9322 >>> b = FPSort(8, 24)
9323 >>> b.ebits()
9324 8
9325 """
9326 return self.sortsort().ebits()
9327
9328 def sbits(self):
9329 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9330 >>> b = FPSort(8, 24)
9331 >>> b.sbits()
9332 24
9333 """
9334 return self.sortsort().sbits()
9335
9336 def as_string(self):
9337 """Return a Z3 floating point expression as a Python string."""
9338 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9339
9340 def __le__(self, other):
9341 return fpLEQ(self, other, self.ctx)
9342
9343 def __lt__(self, other):
9344 return fpLT(self, other, self.ctx)
9345
9346 def __ge__(self, other):
9347 return fpGEQ(self, other, self.ctx)
9348
9349 def __gt__(self, other):
9350 return fpGT(self, other, self.ctx)
9351
9352 def __add__(self, other):
9353 """Create the Z3 expression `self + other`.
9354
9355 >>> x = FP('x', FPSort(8, 24))
9356 >>> y = FP('y', FPSort(8, 24))
9357 >>> x + y
9358 x + y
9359 >>> (x + y).sort()
9360 FPSort(8, 24)
9361 """
9362 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9363 return fpAdd(_dflt_rm(), a, b, self.ctx)
9364
9365 def __radd__(self, other):
9366 """Create the Z3 expression `other + self`.
9367
9368 >>> x = FP('x', FPSort(8, 24))
9369 >>> 10 + x
9370 1.25*(2**3) + x
9371 """
9372 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9373 return fpAdd(_dflt_rm(), a, b, self.ctx)
9374
9375 def __sub__(self, other):
9376 """Create the Z3 expression `self - other`.
9377
9378 >>> x = FP('x', FPSort(8, 24))
9379 >>> y = FP('y', FPSort(8, 24))
9380 >>> x - y
9381 x - y
9382 >>> (x - y).sort()
9383 FPSort(8, 24)
9384 """
9385 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9386 return fpSub(_dflt_rm(), a, b, self.ctx)
9387
9388 def __rsub__(self, other):
9389 """Create the Z3 expression `other - self`.
9390
9391 >>> x = FP('x', FPSort(8, 24))
9392 >>> 10 - x
9393 1.25*(2**3) - x
9394 """
9395 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9396 return fpSub(_dflt_rm(), a, b, self.ctx)
9397
9398 def __mul__(self, other):
9399 """Create the Z3 expression `self * other`.
9400
9401 >>> x = FP('x', FPSort(8, 24))
9402 >>> y = FP('y', FPSort(8, 24))
9403 >>> x * y
9404 x * y
9405 >>> (x * y).sort()
9406 FPSort(8, 24)
9407 >>> 10 * y
9408 1.25*(2**3) * y
9409 """
9410 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9411 return fpMul(_dflt_rm(), a, b, self.ctx)
9412
9413 def __rmul__(self, other):
9414 """Create the Z3 expression `other * self`.
9415
9416 >>> x = FP('x', FPSort(8, 24))
9417 >>> y = FP('y', FPSort(8, 24))
9418 >>> x * y
9419 x * y
9420 >>> x * 10
9421 x * 1.25*(2**3)
9422 """
9423 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9424 return fpMul(_dflt_rm(), a, b, self.ctx)
9425
9426 def __pos__(self):
9427 """Create the Z3 expression `+self`."""
9428 return self
9429
9430 def __neg__(self):
9431 """Create the Z3 expression `-self`.
9432
9433 >>> x = FP('x', Float32())
9434 >>> -x
9435 -x
9436 """
9437 return fpNeg(self)
9438
9439 def __div__(self, other):
9440 """Create the Z3 expression `self / other`.
9441
9442 >>> x = FP('x', FPSort(8, 24))
9443 >>> y = FP('y', FPSort(8, 24))
9444 >>> x / y
9445 x / y
9446 >>> (x / y).sort()
9447 FPSort(8, 24)
9448 >>> 10 / y
9449 1.25*(2**3) / y
9450 """
9451 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9452 return fpDiv(_dflt_rm(), a, b, self.ctx)
9453
9454 def __rdiv__(self, other):
9455 """Create the Z3 expression `other / self`.
9456
9457 >>> x = FP('x', FPSort(8, 24))
9458 >>> y = FP('y', FPSort(8, 24))
9459 >>> x / y
9460 x / y
9461 >>> x / 10
9462 x / 1.25*(2**3)
9463 """
9464 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9465 return fpDiv(_dflt_rm(), a, b, self.ctx)
9466
9467 def __truediv__(self, other):
9468 """Create the Z3 expression division `self / other`."""
9469 return self.__div__(other)
9470
9471 def __rtruediv__(self, other):
9472 """Create the Z3 expression division `other / self`."""
9473 return self.__rdiv__(other)
9474
9475 def __mod__(self, other):
9476 """Create the Z3 expression mod `self % other`."""
9477 return fpRem(self, other)
9478
9479 def __rmod__(self, other):
9480 """Create the Z3 expression mod `other % self`."""
9481 return fpRem(other, self)
9482
9483
9485 """Floating-point rounding mode expressions"""
9486
9487 def as_string(self):
9488 """Return a Z3 floating point expression as a Python string."""
9489 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9490
9491
9493 ctx = _get_ctx(ctx)
9494 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9495
9496
9497def RNE(ctx=None):
9498 ctx = _get_ctx(ctx)
9499 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9500
9501
9503 ctx = _get_ctx(ctx)
9504 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9505
9506
9507def RNA(ctx=None):
9508 ctx = _get_ctx(ctx)
9509 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9510
9511
9513 ctx = _get_ctx(ctx)
9514 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9515
9516
9517def RTP(ctx=None):
9518 ctx = _get_ctx(ctx)
9519 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9520
9521
9523 ctx = _get_ctx(ctx)
9524 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9525
9526
9527def RTN(ctx=None):
9528 ctx = _get_ctx(ctx)
9529 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9530
9531
9532def RoundTowardZero(ctx=None):
9533 ctx = _get_ctx(ctx)
9534 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9535
9536
9537def RTZ(ctx=None):
9538 ctx = _get_ctx(ctx)
9539 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9540
9541
9542def is_fprm(a):
9543 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9544
9545 >>> rm = RNE()
9546 >>> is_fprm(rm)
9547 True
9548 >>> rm = 1.0
9549 >>> is_fprm(rm)
9550 False
9551 """
9552 return isinstance(a, FPRMRef)
9553
9554
9556 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9557 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9558
9559# FP Numerals
9560
9561
9563 """The sign of the numeral.
9564
9565 >>> x = FPVal(+1.0, FPSort(8, 24))
9566 >>> x.sign()
9567 False
9568 >>> x = FPVal(-1.0, FPSort(8, 24))
9569 >>> x.sign()
9570 True
9571 """
9572
9573 def sign(self):
9574 num = (ctypes.c_int)()
9575 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_astas_ast(), byref(l))
9576 if nsign is False:
9577 raise Z3Exception("error retrieving the sign of a numeral.")
9578 return num.value != 0
9579
9580 """The sign of a floating-point numeral as a bit-vector expression.
9581
9582 Remark: NaN's are invalid arguments.
9583 """
9584
9585 def sign_as_bv(self):
9586 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9587
9588 """The significand of the numeral.
9589
9590 >>> x = FPVal(2.5, FPSort(8, 24))
9591 >>> x.significand()
9592 1.25
9593 """
9594
9595 def significand(self):
9596 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_astas_ast())
9597
9598 """The significand of the numeral as a long.
9599
9600 >>> x = FPVal(2.5, FPSort(8, 24))
9601 >>> x.significand_as_long()
9602 1.25
9603 """
9604
9606 ptr = (ctypes.c_ulonglong * 1)()
9607 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_astas_ast(), ptr):
9608 raise Z3Exception("error retrieving the significand of a numeral.")
9609 return ptr[0]
9610
9611 """The significand of the numeral as a bit-vector expression.
9612
9613 Remark: NaN are invalid arguments.
9614 """
9615
9617 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9618
9619 """The exponent of the numeral.
9620
9621 >>> x = FPVal(2.5, FPSort(8, 24))
9622 >>> x.exponent()
9623 1
9624 """
9625
9626 def exponent(self, biased=True):
9627 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_astas_ast(), biased)
9628
9629 """The exponent of the numeral as a long.
9630
9631 >>> x = FPVal(2.5, FPSort(8, 24))
9632 >>> x.exponent_as_long()
9633 1
9634 """
9635
9636 def exponent_as_long(self, biased=True):
9637 ptr = (ctypes.c_longlong * 1)()
9638 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_astas_ast(), ptr, biased):
9639 raise Z3Exception("error retrieving the exponent of a numeral.")
9640 return ptr[0]
9641
9642 """The exponent of the numeral as a bit-vector expression.
9643
9644 Remark: NaNs are invalid arguments.
9645 """
9646
9647 def exponent_as_bv(self, biased=True):
9648 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_astas_ast(), biased), self.ctx)
9649
9650 """Indicates whether the numeral is a NaN."""
9651
9652 def isNaN(self):
9653 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_astas_ast())
9654
9655 """Indicates whether the numeral is +oo or -oo."""
9656
9657 def isInf(self):
9658 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_astas_ast())
9659
9660 """Indicates whether the numeral is +zero or -zero."""
9661
9662 def isZero(self):
9663 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_astas_ast())
9664
9665 """Indicates whether the numeral is normal."""
9666
9667 def isNormal(self):
9668 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_astas_ast())
9669
9670 """Indicates whether the numeral is subnormal."""
9671
9672 def isSubnormal(self):
9673 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_astas_ast())
9674
9675 """Indicates whether the numeral is positive."""
9676
9677 def isPositive(self):
9678 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_astas_ast())
9679
9680 """Indicates whether the numeral is negative."""
9681
9682 def isNegative(self):
9683 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_astas_ast())
9684
9685 """
9686 The string representation of the numeral.
9687
9688 >>> x = FPVal(20, FPSort(8, 24))
9689 >>> x.as_string()
9690 1.25*(2**4)
9691 """
9692
9693 def as_string(self):
9694 s = Z3_get_numeral_string(self.ctx.ref(), self.as_astas_ast())
9695 return ("FPVal(%s, %s)" % (s, self.sortsort()))
9696
9697
9698def is_fp(a):
9699 """Return `True` if `a` is a Z3 floating-point expression.
9700
9701 >>> b = FP('b', FPSort(8, 24))
9702 >>> is_fp(b)
9703 True
9704 >>> is_fp(b + 1.0)
9705 True
9706 >>> is_fp(Int('x'))
9707 False
9708 """
9709 return isinstance(a, FPRef)
9710
9711
9713 """Return `True` if `a` is a Z3 floating-point numeral value.
9714
9715 >>> b = FP('b', FPSort(8, 24))
9716 >>> is_fp_value(b)
9717 False
9718 >>> b = FPVal(1.0, FPSort(8, 24))
9719 >>> b
9720 1
9721 >>> is_fp_value(b)
9722 True
9723 """
9724 return is_fp(a) and _is_numeral(a.ctx, a.ast)
9725
9726
9727def FPSort(ebits, sbits, ctx=None):
9728 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9729
9730 >>> Single = FPSort(8, 24)
9731 >>> Double = FPSort(11, 53)
9732 >>> Single
9733 FPSort(8, 24)
9734 >>> x = Const('x', Single)
9735 >>> eq(x, FP('x', FPSort(8, 24)))
9736 True
9737 """
9738 ctx = _get_ctx(ctx)
9739 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9740
9741
9742def _to_float_str(val, exp=0):
9743 if isinstance(val, float):
9744 if math.isnan(val):
9745 res = "NaN"
9746 elif val == 0.0:
9747 sone = math.copysign(1.0, val)
9748 if sone < 0.0:
9749 return "-0.0"
9750 else:
9751 return "+0.0"
9752 elif val == float("+inf"):
9753 res = "+oo"
9754 elif val == float("-inf"):
9755 res = "-oo"
9756 else:
9757 v = val.as_integer_ratio()
9758 num = v[0]
9759 den = v[1]
9760 rvs = str(num) + "/" + str(den)
9761 res = rvs + "p" + _to_int_str(exp)
9762 elif isinstance(val, bool):
9763 if val:
9764 res = "1.0"
9765 else:
9766 res = "0.0"
9767 elif _is_int(val):
9768 res = str(val)
9769 elif isinstance(val, str):
9770 inx = val.find("*(2**")
9771 if inx == -1:
9772 res = val
9773 elif val[-1] == ")":
9774 res = val[0:inx]
9775 exp = str(int(val[inx + 5:-1]) + int(exp))
9776 else:
9777 _z3_assert(False, "String does not have floating-point numeral form.")
9778 elif z3_debug():
9779 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9780 if exp == 0:
9781 return res
9782 else:
9783 return res + "p" + exp
9784
9785
9786def fpNaN(s):
9787 """Create a Z3 floating-point NaN term.
9788
9789 >>> s = FPSort(8, 24)
9790 >>> set_fpa_pretty(True)
9791 >>> fpNaN(s)
9792 NaN
9793 >>> pb = get_fpa_pretty()
9794 >>> set_fpa_pretty(False)
9795 >>> fpNaN(s)
9796 fpNaN(FPSort(8, 24))
9797 >>> set_fpa_pretty(pb)
9798 """
9799 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9800 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9801
9802
9804 """Create a Z3 floating-point +oo term.
9805
9806 >>> s = FPSort(8, 24)
9807 >>> pb = get_fpa_pretty()
9808 >>> set_fpa_pretty(True)
9809 >>> fpPlusInfinity(s)
9810 +oo
9811 >>> set_fpa_pretty(False)
9812 >>> fpPlusInfinity(s)
9813 fpPlusInfinity(FPSort(8, 24))
9814 >>> set_fpa_pretty(pb)
9815 """
9816 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9817 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9818
9819
9821 """Create a Z3 floating-point -oo term."""
9822 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9823 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9824
9825
9826def fpInfinity(s, negative):
9827 """Create a Z3 floating-point +oo or -oo term."""
9828 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9829 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9830 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9831
9832
9834 """Create a Z3 floating-point +0.0 term."""
9835 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9836 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9837
9838
9840 """Create a Z3 floating-point -0.0 term."""
9841 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9842 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9843
9844
9845def fpZero(s, negative):
9846 """Create a Z3 floating-point +0.0 or -0.0 term."""
9847 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9848 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9849 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9850
9851
9852def FPVal(sig, exp=None, fps=None, ctx=None):
9853 """Return a floating-point value of value `val` and sort `fps`.
9854 If `ctx=None`, then the global context is used.
9855
9856 >>> v = FPVal(20.0, FPSort(8, 24))
9857 >>> v
9858 1.25*(2**4)
9859 >>> print("0x%.8x" % v.exponent_as_long(False))
9860 0x00000004
9861 >>> v = FPVal(2.25, FPSort(8, 24))
9862 >>> v
9863 1.125*(2**1)
9864 >>> v = FPVal(-2.25, FPSort(8, 24))
9865 >>> v
9866 -1.125*(2**1)
9867 >>> FPVal(-0.0, FPSort(8, 24))
9868 -0.0
9869 >>> FPVal(0.0, FPSort(8, 24))
9870 +0.0
9871 >>> FPVal(+0.0, FPSort(8, 24))
9872 +0.0
9873 """
9874 ctx = _get_ctx(ctx)
9875 if is_fp_sort(exp):
9876 fps = exp
9877 exp = None
9878 elif fps is None:
9879 fps = _dflt_fps(ctx)
9880 _z3_assert(is_fp_sort(fps), "sort mismatch")
9881 if exp is None:
9882 exp = 0
9883 val = _to_float_str(sig)
9884 if val == "NaN" or val == "nan":
9885 return fpNaN(fps)
9886 elif val == "-0.0":
9887 return fpMinusZero(fps)
9888 elif val == "0.0" or val == "+0.0":
9889 return fpPlusZero(fps)
9890 elif val == "+oo" or val == "+inf" or val == "+Inf":
9891 return fpPlusInfinity(fps)
9892 elif val == "-oo" or val == "-inf" or val == "-Inf":
9893 return fpMinusInfinity(fps)
9894 else:
9895 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9896
9897
9898def FP(name, fpsort, ctx=None):
9899 """Return a floating-point constant named `name`.
9900 `fpsort` is the floating-point sort.
9901 If `ctx=None`, then the global context is used.
9902
9903 >>> x = FP('x', FPSort(8, 24))
9904 >>> is_fp(x)
9905 True
9906 >>> x.ebits()
9907 8
9908 >>> x.sort()
9909 FPSort(8, 24)
9910 >>> word = FPSort(8, 24)
9911 >>> x2 = FP('x', word)
9912 >>> eq(x, x2)
9913 True
9914 """
9915 if isinstance(fpsort, FPSortRef) and ctx is None:
9916 ctx = fpsort.ctx
9917 else:
9918 ctx = _get_ctx(ctx)
9919 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9920
9921
9922def FPs(names, fpsort, ctx=None):
9923 """Return an array of floating-point constants.
9924
9925 >>> x, y, z = FPs('x y z', FPSort(8, 24))
9926 >>> x.sort()
9927 FPSort(8, 24)
9928 >>> x.sbits()
9929 24
9930 >>> x.ebits()
9931 8
9932 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9933 fpMul(RNE(), fpAdd(RNE(), x, y), z)
9934 """
9935 ctx = _get_ctx(ctx)
9936 if isinstance(names, str):
9937 names = names.split(" ")
9938 return [FP(name, fpsort, ctx) for name in names]
9939
9940
9941def fpAbs(a, ctx=None):
9942 """Create a Z3 floating-point absolute value expression.
9943
9944 >>> s = FPSort(8, 24)
9945 >>> rm = RNE()
9946 >>> x = FPVal(1.0, s)
9947 >>> fpAbs(x)
9948 fpAbs(1)
9949 >>> y = FPVal(-20.0, s)
9950 >>> y
9951 -1.25*(2**4)
9952 >>> fpAbs(y)
9953 fpAbs(-1.25*(2**4))
9954 >>> fpAbs(-1.25*(2**4))
9955 fpAbs(-1.25*(2**4))
9956 >>> fpAbs(x).sort()
9957 FPSort(8, 24)
9958 """
9959 ctx = _get_ctx(ctx)
9960 [a] = _coerce_fp_expr_list([a], ctx)
9961 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9962
9963
9964def fpNeg(a, ctx=None):
9965 """Create a Z3 floating-point addition expression.
9966
9967 >>> s = FPSort(8, 24)
9968 >>> rm = RNE()
9969 >>> x = FP('x', s)
9970 >>> fpNeg(x)
9971 -x
9972 >>> fpNeg(x).sort()
9973 FPSort(8, 24)
9974 """
9975 ctx = _get_ctx(ctx)
9976 [a] = _coerce_fp_expr_list([a], ctx)
9977 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9978
9979
9980def _mk_fp_unary(f, rm, a, ctx):
9981 ctx = _get_ctx(ctx)
9982 [a] = _coerce_fp_expr_list([a], ctx)
9983 if z3_debug():
9984 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9985 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9986 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9987
9988
9989def _mk_fp_unary_pred(f, a, ctx):
9990 ctx = _get_ctx(ctx)
9991 [a] = _coerce_fp_expr_list([a], ctx)
9992 if z3_debug():
9993 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9994 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9995
9996
9997def _mk_fp_bin(f, rm, a, b, ctx):
9998 ctx = _get_ctx(ctx)
9999 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10000 if z3_debug():
10001 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10002 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10003 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10004
10005
10006def _mk_fp_bin_norm(f, a, b, ctx):
10007 ctx = _get_ctx(ctx)
10008 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10009 if z3_debug():
10010 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10011 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10012
10013
10014def _mk_fp_bin_pred(f, a, b, ctx):
10015 ctx = _get_ctx(ctx)
10016 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10017 if z3_debug():
10018 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10019 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10020
10021
10022def _mk_fp_tern(f, rm, a, b, c, ctx):
10023 ctx = _get_ctx(ctx)
10024 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
10025 if z3_debug():
10026 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10027 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
10028 c), "Second, third or fourth argument must be a Z3 floating-point expression")
10029 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10030
10031
10032def fpAdd(rm, a, b, ctx=None):
10033 """Create a Z3 floating-point addition expression.
10034
10035 >>> s = FPSort(8, 24)
10036 >>> rm = RNE()
10037 >>> x = FP('x', s)
10038 >>> y = FP('y', s)
10039 >>> fpAdd(rm, x, y)
10040 fpAdd(RNE(), x, y)
10041 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10042 x + y
10043 >>> fpAdd(rm, x, y).sort()
10044 FPSort(8, 24)
10045 """
10046 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10047
10048
10049def fpSub(rm, a, b, ctx=None):
10050 """Create a Z3 floating-point subtraction expression.
10051
10052 >>> s = FPSort(8, 24)
10053 >>> rm = RNE()
10054 >>> x = FP('x', s)
10055 >>> y = FP('y', s)
10056 >>> fpSub(rm, x, y)
10057 fpSub(RNE(), x, y)
10058 >>> fpSub(rm, x, y).sort()
10059 FPSort(8, 24)
10060 """
10061 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10062
10063
10064def fpMul(rm, a, b, ctx=None):
10065 """Create a Z3 floating-point multiplication expression.
10066
10067 >>> s = FPSort(8, 24)
10068 >>> rm = RNE()
10069 >>> x = FP('x', s)
10070 >>> y = FP('y', s)
10071 >>> fpMul(rm, x, y)
10072 fpMul(RNE(), x, y)
10073 >>> fpMul(rm, x, y).sort()
10074 FPSort(8, 24)
10075 """
10076 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10077
10078
10079def fpDiv(rm, a, b, ctx=None):
10080 """Create a Z3 floating-point division expression.
10081
10082 >>> s = FPSort(8, 24)
10083 >>> rm = RNE()
10084 >>> x = FP('x', s)
10085 >>> y = FP('y', s)
10086 >>> fpDiv(rm, x, y)
10087 fpDiv(RNE(), x, y)
10088 >>> fpDiv(rm, x, y).sort()
10089 FPSort(8, 24)
10090 """
10091 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10092
10093
10094def fpRem(a, b, ctx=None):
10095 """Create a Z3 floating-point remainder expression.
10096
10097 >>> s = FPSort(8, 24)
10098 >>> x = FP('x', s)
10099 >>> y = FP('y', s)
10100 >>> fpRem(x, y)
10101 fpRem(x, y)
10102 >>> fpRem(x, y).sort()
10103 FPSort(8, 24)
10104 """
10105 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10106
10107
10108def fpMin(a, b, ctx=None):
10109 """Create a Z3 floating-point minimum expression.
10110
10111 >>> s = FPSort(8, 24)
10112 >>> rm = RNE()
10113 >>> x = FP('x', s)
10114 >>> y = FP('y', s)
10115 >>> fpMin(x, y)
10116 fpMin(x, y)
10117 >>> fpMin(x, y).sort()
10118 FPSort(8, 24)
10119 """
10120 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10121
10122
10123def fpMax(a, b, ctx=None):
10124 """Create a Z3 floating-point maximum expression.
10125
10126 >>> s = FPSort(8, 24)
10127 >>> rm = RNE()
10128 >>> x = FP('x', s)
10129 >>> y = FP('y', s)
10130 >>> fpMax(x, y)
10131 fpMax(x, y)
10132 >>> fpMax(x, y).sort()
10133 FPSort(8, 24)
10134 """
10135 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10136
10137
10138def fpFMA(rm, a, b, c, ctx=None):
10139 """Create a Z3 floating-point fused multiply-add expression.
10140 """
10141 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10142
10143
10144def fpSqrt(rm, a, ctx=None):
10145 """Create a Z3 floating-point square root expression.
10146 """
10147 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10148
10149
10150def fpRoundToIntegral(rm, a, ctx=None):
10151 """Create a Z3 floating-point roundToIntegral expression.
10152 """
10153 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10154
10155
10156def fpIsNaN(a, ctx=None):
10157 """Create a Z3 floating-point isNaN expression.
10158
10159 >>> s = FPSort(8, 24)
10160 >>> x = FP('x', s)
10161 >>> y = FP('y', s)
10162 >>> fpIsNaN(x)
10163 fpIsNaN(x)
10164 """
10165 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10166
10167
10168def fpIsInf(a, ctx=None):
10169 """Create a Z3 floating-point isInfinite expression.
10170
10171 >>> s = FPSort(8, 24)
10172 >>> x = FP('x', s)
10173 >>> fpIsInf(x)
10174 fpIsInf(x)
10175 """
10176 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10177
10178
10179def fpIsZero(a, ctx=None):
10180 """Create a Z3 floating-point isZero expression.
10181 """
10182 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10183
10184
10185def fpIsNormal(a, ctx=None):
10186 """Create a Z3 floating-point isNormal expression.
10187 """
10188 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10189
10190
10191def fpIsSubnormal(a, ctx=None):
10192 """Create a Z3 floating-point isSubnormal expression.
10193 """
10194 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10195
10196
10197def fpIsNegative(a, ctx=None):
10198 """Create a Z3 floating-point isNegative expression.
10199 """
10200 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10201
10202
10203def fpIsPositive(a, ctx=None):
10204 """Create a Z3 floating-point isPositive expression.
10205 """
10206 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10207
10208
10209def _check_fp_args(a, b):
10210 if z3_debug():
10211 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10212
10213
10214def fpLT(a, b, ctx=None):
10215 """Create the Z3 floating-point expression `other < self`.
10216
10217 >>> x, y = FPs('x y', FPSort(8, 24))
10218 >>> fpLT(x, y)
10219 x < y
10220 >>> (x < y).sexpr()
10221 '(fp.lt x y)'
10222 """
10223 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10224
10225
10226def fpLEQ(a, b, ctx=None):
10227 """Create the Z3 floating-point expression `other <= self`.
10228
10229 >>> x, y = FPs('x y', FPSort(8, 24))
10230 >>> fpLEQ(x, y)
10231 x <= y
10232 >>> (x <= y).sexpr()
10233 '(fp.leq x y)'
10234 """
10235 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10236
10237
10238def fpGT(a, b, ctx=None):
10239 """Create the Z3 floating-point expression `other > self`.
10240
10241 >>> x, y = FPs('x y', FPSort(8, 24))
10242 >>> fpGT(x, y)
10243 x > y
10244 >>> (x > y).sexpr()
10245 '(fp.gt x y)'
10246 """
10247 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10248
10249
10250def fpGEQ(a, b, ctx=None):
10251 """Create the Z3 floating-point expression `other >= self`.
10252
10253 >>> x, y = FPs('x y', FPSort(8, 24))
10254 >>> fpGEQ(x, y)
10255 x >= y
10256 >>> (x >= y).sexpr()
10257 '(fp.geq x y)'
10258 """
10259 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10260
10261
10262def fpEQ(a, b, ctx=None):
10263 """Create the Z3 floating-point expression `fpEQ(other, self)`.
10264
10265 >>> x, y = FPs('x y', FPSort(8, 24))
10266 >>> fpEQ(x, y)
10267 fpEQ(x, y)
10268 >>> fpEQ(x, y).sexpr()
10269 '(fp.eq x y)'
10270 """
10271 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10272
10273
10274def fpNEQ(a, b, ctx=None):
10275 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10276
10277 >>> x, y = FPs('x y', FPSort(8, 24))
10278 >>> fpNEQ(x, y)
10279 Not(fpEQ(x, y))
10280 >>> (x != y).sexpr()
10281 '(distinct x y)'
10282 """
10283 return Not(fpEQ(a, b, ctx))
10284
10285
10286def fpFP(sgn, exp, sig, ctx=None):
10287 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10288
10289 >>> s = FPSort(8, 24)
10290 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10291 >>> print(x)
10292 fpFP(1, 127, 4194304)
10293 >>> xv = FPVal(-1.5, s)
10294 >>> print(xv)
10295 -1.5
10296 >>> slvr = Solver()
10297 >>> slvr.add(fpEQ(x, xv))
10298 >>> slvr.check()
10299 sat
10300 >>> xv = FPVal(+1.5, s)
10301 >>> print(xv)
10302 1.5
10303 >>> slvr = Solver()
10304 >>> slvr.add(fpEQ(x, xv))
10305 >>> slvr.check()
10306 unsat
10307 """
10308 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10309 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10310 ctx = _get_ctx(ctx)
10311 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10312 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10313
10314
10315def fpToFP(a1, a2=None, a3=None, ctx=None):
10316 """Create a Z3 floating-point conversion expression from other term sorts
10317 to floating-point.
10318
10319 From a bit-vector term in IEEE 754-2008 format:
10320 >>> x = FPVal(1.0, Float32())
10321 >>> x_bv = fpToIEEEBV(x)
10322 >>> simplify(fpToFP(x_bv, Float32()))
10323 1
10324
10325 From a floating-point term with different precision:
10326 >>> x = FPVal(1.0, Float32())
10327 >>> x_db = fpToFP(RNE(), x, Float64())
10328 >>> x_db.sort()
10329 FPSort(11, 53)
10330
10331 From a real term:
10332 >>> x_r = RealVal(1.5)
10333 >>> simplify(fpToFP(RNE(), x_r, Float32()))
10334 1.5
10335
10336 From a signed bit-vector term:
10337 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10338 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10339 -1.25*(2**2)
10340 """
10341 ctx = _get_ctx(ctx)
10342 if is_bv(a1) and is_fp_sort(a2):
10343 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10344 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10345 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10346 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10347 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10348 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10349 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10350 else:
10351 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10352
10353
10354def fpBVToFP(v, sort, ctx=None):
10355 """Create a Z3 floating-point conversion expression that represents the
10356 conversion from a bit-vector term to a floating-point term.
10357
10358 >>> x_bv = BitVecVal(0x3F800000, 32)
10359 >>> x_fp = fpBVToFP(x_bv, Float32())
10360 >>> x_fp
10361 fpToFP(1065353216)
10362 >>> simplify(x_fp)
10363 1
10364 """
10365 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10366 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10367 ctx = _get_ctx(ctx)
10368 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10369
10370
10371def fpFPToFP(rm, v, sort, ctx=None):
10372 """Create a Z3 floating-point conversion expression that represents the
10373 conversion from a floating-point term to a floating-point term of different precision.
10374
10375 >>> x_sgl = FPVal(1.0, Float32())
10376 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10377 >>> x_dbl
10378 fpToFP(RNE(), 1)
10379 >>> simplify(x_dbl)
10380 1
10381 >>> x_dbl.sort()
10382 FPSort(11, 53)
10383 """
10384 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10385 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10386 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10387 ctx = _get_ctx(ctx)
10388 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10389
10390
10391def fpRealToFP(rm, v, sort, ctx=None):
10392 """Create a Z3 floating-point conversion expression that represents the
10393 conversion from a real term to a floating-point term.
10394
10395 >>> x_r = RealVal(1.5)
10396 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10397 >>> x_fp
10398 fpToFP(RNE(), 3/2)
10399 >>> simplify(x_fp)
10400 1.5
10401 """
10402 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10403 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10404 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10405 ctx = _get_ctx(ctx)
10406 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10407
10408
10409def fpSignedToFP(rm, v, sort, ctx=None):
10410 """Create a Z3 floating-point conversion expression that represents the
10411 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10412
10413 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10414 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10415 >>> x_fp
10416 fpToFP(RNE(), 4294967291)
10417 >>> simplify(x_fp)
10418 -1.25*(2**2)
10419 """
10420 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10421 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10422 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10423 ctx = _get_ctx(ctx)
10424 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10425
10426
10427def fpUnsignedToFP(rm, v, sort, ctx=None):
10428 """Create a Z3 floating-point conversion expression that represents the
10429 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10430
10431 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10432 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10433 >>> x_fp
10434 fpToFPUnsigned(RNE(), 4294967291)
10435 >>> simplify(x_fp)
10436 1*(2**32)
10437 """
10438 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10439 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10440 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10441 ctx = _get_ctx(ctx)
10442 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10443
10444
10445def fpToFPUnsigned(rm, x, s, ctx=None):
10446 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10447 if z3_debug():
10448 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10449 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10450 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10451 ctx = _get_ctx(ctx)
10452 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10453
10454
10455def fpToSBV(rm, x, s, ctx=None):
10456 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10457
10458 >>> x = FP('x', FPSort(8, 24))
10459 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10460 >>> print(is_fp(x))
10461 True
10462 >>> print(is_bv(y))
10463 True
10464 >>> print(is_fp(y))
10465 False
10466 >>> print(is_bv(x))
10467 False
10468 """
10469 if z3_debug():
10470 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10471 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10472 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10473 ctx = _get_ctx(ctx)
10474 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10475
10476
10477def fpToUBV(rm, x, s, ctx=None):
10478 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10479
10480 >>> x = FP('x', FPSort(8, 24))
10481 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10482 >>> print(is_fp(x))
10483 True
10484 >>> print(is_bv(y))
10485 True
10486 >>> print(is_fp(y))
10487 False
10488 >>> print(is_bv(x))
10489 False
10490 """
10491 if z3_debug():
10492 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10493 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10494 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10495 ctx = _get_ctx(ctx)
10496 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10497
10498
10499def fpToReal(x, ctx=None):
10500 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10501
10502 >>> x = FP('x', FPSort(8, 24))
10503 >>> y = fpToReal(x)
10504 >>> print(is_fp(x))
10505 True
10506 >>> print(is_real(y))
10507 True
10508 >>> print(is_fp(y))
10509 False
10510 >>> print(is_real(x))
10511 False
10512 """
10513 if z3_debug():
10514 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10515 ctx = _get_ctx(ctx)
10516 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10517
10518
10519def fpToIEEEBV(x, ctx=None):
10520 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10521
10522 The size of the resulting bit-vector is automatically determined.
10523
10524 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10525 knows only one NaN and it will always produce the same bit-vector representation of
10526 that NaN.
10527
10528 >>> x = FP('x', FPSort(8, 24))
10529 >>> y = fpToIEEEBV(x)
10530 >>> print(is_fp(x))
10531 True
10532 >>> print(is_bv(y))
10533 True
10534 >>> print(is_fp(y))
10535 False
10536 >>> print(is_bv(x))
10537 False
10538 """
10539 if z3_debug():
10540 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10541 ctx = _get_ctx(ctx)
10542 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10543
10544
10545
10550
10552 """Sequence sort."""
10553
10554 def is_string(self):
10555 """Determine if sort is a string
10556 >>> s = StringSort()
10557 >>> s.is_string()
10558 True
10559 >>> s = SeqSort(IntSort())
10560 >>> s.is_string()
10561 False
10562 """
10563 return Z3_is_string_sort(self.ctx_ref(), self.ast)
10564
10565 def basis(self):
10566 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10567
10568
10569def StringSort(ctx=None):
10570 """Create a string sort
10571 >>> s = StringSort()
10572 >>> print(s)
10573 String
10574 """
10575 ctx = _get_ctx(ctx)
10576 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10577
10578
10579def SeqSort(s):
10580 """Create a sequence sort over elements provided in the argument
10581 >>> s = SeqSort(IntSort())
10582 >>> s == Unit(IntVal(1)).sort()
10583 True
10584 """
10585 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10586
10587
10589 """Sequence expression."""
10590
10591 def sort(self):
10592 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10593
10594 def __add__(self, other):
10595 return Concat(self, other)
10596
10597 def __radd__(self, other):
10598 return Concat(other, self)
10599
10600 def __getitem__(self, i):
10601 if _is_int(i):
10602 i = IntVal(i, self.ctx)
10603 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10604
10605 def at(self, i):
10606 if _is_int(i):
10607 i = IntVal(i, self.ctx)
10608 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10609
10610 def is_string(self):
10611 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_astas_ast()))
10612
10614 return Z3_is_string(self.ctx_ref(), self.as_astas_ast())
10615
10616 def as_string(self):
10617 """Return a string representation of sequence expression."""
10618 if self.is_string_value():
10619 string_length = ctypes.c_uint()
10620 chars = Z3_get_lstring(self.ctx_ref(), self.as_astas_ast(), byref(string_length))
10621 return string_at(chars, size=string_length.value).decode("latin-1")
10622 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
10623
10624 def __le__(self, other):
10625 return SeqRef(Z3_mk_str_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10626
10627 def __lt__(self, other):
10628 return SeqRef(Z3_mk_str_lt(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10629
10630 def __ge__(self, other):
10631 return SeqRef(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10632
10633 def __gt__(self, other):
10634 return SeqRef(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10635
10636
10637def _coerce_seq(s, ctx=None):
10638 if isinstance(s, str):
10639 ctx = _get_ctx(ctx)
10640 s = StringVal(s, ctx)
10641 if not is_expr(s):
10642 raise Z3Exception("Non-expression passed as a sequence")
10643 if not is_seq(s):
10644 raise Z3Exception("Non-sequence passed as a sequence")
10645 return s
10646
10647
10648def _get_ctx2(a, b, ctx=None):
10649 if is_expr(a):
10650 return a.ctx
10651 if is_expr(b):
10652 return b.ctx
10653 if ctx is None:
10654 ctx = main_ctx()
10655 return ctx
10656
10657
10658def is_seq(a):
10659 """Return `True` if `a` is a Z3 sequence expression.
10660 >>> print (is_seq(Unit(IntVal(0))))
10661 True
10662 >>> print (is_seq(StringVal("abc")))
10663 True
10664 """
10665 return isinstance(a, SeqRef)
10666
10667
10669 """Return `True` if `a` is a Z3 string expression.
10670 >>> print (is_string(StringVal("ab")))
10671 True
10672 """
10673 return isinstance(a, SeqRef) and a.is_string()
10674
10675
10677 """return 'True' if 'a' is a Z3 string constant expression.
10678 >>> print (is_string_value(StringVal("a")))
10679 True
10680 >>> print (is_string_value(StringVal("a") + StringVal("b")))
10681 False
10682 """
10683 return isinstance(a, SeqRef) and a.is_string_value()
10684
10685
10686def StringVal(s, ctx=None):
10687 """create a string expression"""
10688 s = "".join(str(ch) if ord(ch) < 128 else "\\u{%x}" % (ord(ch)) for ch in s)
10689 ctx = _get_ctx(ctx)
10690 return SeqRef(Z3_mk_lstring(ctx.ref(), len(s), s), ctx)
10691
10692
10693def String(name, ctx=None):
10694 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10695
10696 >>> x = String('x')
10697 """
10698 ctx = _get_ctx(ctx)
10699 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10700
10701
10702def Strings(names, ctx=None):
10703 """Return a tuple of String constants. """
10704 ctx = _get_ctx(ctx)
10705 if isinstance(names, str):
10706 names = names.split(" ")
10707 return [String(name, ctx) for name in names]
10708
10709
10710def SubString(s, offset, length):
10711 """Extract substring or subsequence starting at offset"""
10712 return Extract(s, offset, length)
10713
10714
10715def SubSeq(s, offset, length):
10716 """Extract substring or subsequence starting at offset"""
10717 return Extract(s, offset, length)
10718
10719
10720def Empty(s):
10721 """Create the empty sequence of the given sort
10722 >>> e = Empty(StringSort())
10723 >>> e2 = StringVal("")
10724 >>> print(e.eq(e2))
10725 True
10726 >>> e3 = Empty(SeqSort(IntSort()))
10727 >>> print(e3)
10728 Empty(Seq(Int))
10729 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10730 >>> print(e4)
10731 Empty(ReSort(Seq(Int)))
10732 """
10733 if isinstance(s, SeqSortRef):
10734 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10735 if isinstance(s, ReSortRef):
10736 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10737 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10738
10739
10740def Full(s):
10741 """Create the regular expression that accepts the universal language
10742 >>> e = Full(ReSort(SeqSort(IntSort())))
10743 >>> print(e)
10744 Full(ReSort(Seq(Int)))
10745 >>> e1 = Full(ReSort(StringSort()))
10746 >>> print(e1)
10747 Full(ReSort(String))
10748 """
10749 if isinstance(s, ReSortRef):
10750 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10751 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10752
10753
10754def Unit(a):
10755 """Create a singleton sequence"""
10756 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10757
10758
10759def PrefixOf(a, b):
10760 """Check if 'a' is a prefix of 'b'
10761 >>> s1 = PrefixOf("ab", "abc")
10762 >>> simplify(s1)
10763 True
10764 >>> s2 = PrefixOf("bc", "abc")
10765 >>> simplify(s2)
10766 False
10767 """
10768 ctx = _get_ctx2(a, b)
10769 a = _coerce_seq(a, ctx)
10770 b = _coerce_seq(b, ctx)
10771 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10772
10773
10774def SuffixOf(a, b):
10775 """Check if 'a' is a suffix of 'b'
10776 >>> s1 = SuffixOf("ab", "abc")
10777 >>> simplify(s1)
10778 False
10779 >>> s2 = SuffixOf("bc", "abc")
10780 >>> simplify(s2)
10781 True
10782 """
10783 ctx = _get_ctx2(a, b)
10784 a = _coerce_seq(a, ctx)
10785 b = _coerce_seq(b, ctx)
10786 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10787
10788
10789def Contains(a, b):
10790 """Check if 'a' contains 'b'
10791 >>> s1 = Contains("abc", "ab")
10792 >>> simplify(s1)
10793 True
10794 >>> s2 = Contains("abc", "bc")
10795 >>> simplify(s2)
10796 True
10797 >>> x, y, z = Strings('x y z')
10798 >>> s3 = Contains(Concat(x,y,z), y)
10799 >>> simplify(s3)
10800 True
10801 """
10802 ctx = _get_ctx2(a, b)
10803 a = _coerce_seq(a, ctx)
10804 b = _coerce_seq(b, ctx)
10805 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10806
10807
10808def Replace(s, src, dst):
10809 """Replace the first occurrence of 'src' by 'dst' in 's'
10810 >>> r = Replace("aaa", "a", "b")
10811 >>> simplify(r)
10812 "baa"
10813 """
10814 ctx = _get_ctx2(dst, s)
10815 if ctx is None and is_expr(src):
10816 ctx = src.ctx
10817 src = _coerce_seq(src, ctx)
10818 dst = _coerce_seq(dst, ctx)
10819 s = _coerce_seq(s, ctx)
10820 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10821
10822
10823def IndexOf(s, substr, offset=None):
10824 """Retrieve the index of substring within a string starting at a specified offset.
10825 >>> simplify(IndexOf("abcabc", "bc", 0))
10826 1
10827 >>> simplify(IndexOf("abcabc", "bc", 2))
10828 4
10829 """
10830 if offset is None:
10831 offset = IntVal(0)
10832 ctx = None
10833 if is_expr(offset):
10834 ctx = offset.ctx
10835 ctx = _get_ctx2(s, substr, ctx)
10836 s = _coerce_seq(s, ctx)
10837 substr = _coerce_seq(substr, ctx)
10838 if _is_int(offset):
10839 offset = IntVal(offset, ctx)
10840 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10841
10842
10843def LastIndexOf(s, substr):
10844 """Retrieve the last index of substring within a string"""
10845 ctx = None
10846 ctx = _get_ctx2(s, substr, ctx)
10847 s = _coerce_seq(s, ctx)
10848 substr = _coerce_seq(substr, ctx)
10849 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10850
10851
10852def Length(s):
10853 """Obtain the length of a sequence 's'
10854 >>> l = Length(StringVal("abc"))
10855 >>> simplify(l)
10856 3
10857 """
10858 s = _coerce_seq(s)
10859 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10860
10861
10863 """Convert string expression to integer
10864 >>> a = StrToInt("1")
10865 >>> simplify(1 == a)
10866 True
10867 >>> b = StrToInt("2")
10868 >>> simplify(1 == b)
10869 False
10870 >>> c = StrToInt(IntToStr(2))
10871 >>> simplify(1 == c)
10872 False
10873 """
10874 s = _coerce_seq(s)
10875 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10876
10877
10879 """Convert integer expression to string"""
10880 if not is_expr(s):
10881 s = _py2expr(s)
10882 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10883
10884
10885def Re(s, ctx=None):
10886 """The regular expression that accepts sequence 's'
10887 >>> s1 = Re("ab")
10888 >>> s2 = Re(StringVal("ab"))
10889 >>> s3 = Re(Unit(BoolVal(True)))
10890 """
10891 s = _coerce_seq(s, ctx)
10892 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10893
10894
10895# Regular expressions
10896
10898 """Regular expression sort."""
10899
10900 def basis(self):
10901 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10902
10903
10904def ReSort(s):
10905 if is_ast(s):
10906 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10907 if s is None or isinstance(s, Context):
10908 ctx = _get_ctx(s)
10909 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10910 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10911
10912
10914 """Regular expressions."""
10915
10916 def __add__(self, other):
10917 return Union(self, other)
10918
10919
10920def is_re(s):
10921 return isinstance(s, ReRef)
10922
10923
10924def InRe(s, re):
10925 """Create regular expression membership test
10926 >>> re = Union(Re("a"),Re("b"))
10927 >>> print (simplify(InRe("a", re)))
10928 True
10929 >>> print (simplify(InRe("b", re)))
10930 True
10931 >>> print (simplify(InRe("c", re)))
10932 False
10933 """
10934 s = _coerce_seq(s, re.ctx)
10935 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10936
10937
10938def Union(*args):
10939 """Create union of regular expressions.
10940 >>> re = Union(Re("a"), Re("b"), Re("c"))
10941 >>> print (simplify(InRe("d", re)))
10942 False
10943 """
10944 args = _get_args(args)
10945 sz = len(args)
10946 if z3_debug():
10947 _z3_assert(sz > 0, "At least one argument expected.")
10948 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10949 if sz == 1:
10950 return args[0]
10951 ctx = args[0].ctx
10952 v = (Ast * sz)()
10953 for i in range(sz):
10954 v[i] = args[i].as_ast()
10955 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10956
10957
10958def Intersect(*args):
10959 """Create intersection of regular expressions.
10960 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
10961 """
10962 args = _get_args(args)
10963 sz = len(args)
10964 if z3_debug():
10965 _z3_assert(sz > 0, "At least one argument expected.")
10966 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10967 if sz == 1:
10968 return args[0]
10969 ctx = args[0].ctx
10970 v = (Ast * sz)()
10971 for i in range(sz):
10972 v[i] = args[i].as_ast()
10973 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
10974
10975
10976def Plus(re):
10977 """Create the regular expression accepting one or more repetitions of argument.
10978 >>> re = Plus(Re("a"))
10979 >>> print(simplify(InRe("aa", re)))
10980 True
10981 >>> print(simplify(InRe("ab", re)))
10982 False
10983 >>> print(simplify(InRe("", re)))
10984 False
10985 """
10986 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10987
10988
10989def Option(re):
10990 """Create the regular expression that optionally accepts the argument.
10991 >>> re = Option(Re("a"))
10992 >>> print(simplify(InRe("a", re)))
10993 True
10994 >>> print(simplify(InRe("", re)))
10995 True
10996 >>> print(simplify(InRe("aa", re)))
10997 False
10998 """
10999 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11000
11001
11003 """Create the complement regular expression."""
11004 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11005
11006
11007def Star(re):
11008 """Create the regular expression accepting zero or more repetitions of argument.
11009 >>> re = Star(Re("a"))
11010 >>> print(simplify(InRe("aa", re)))
11011 True
11012 >>> print(simplify(InRe("ab", re)))
11013 False
11014 >>> print(simplify(InRe("", re)))
11015 True
11016 """
11017 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11018
11019
11020def Loop(re, lo, hi=0):
11021 """Create the regular expression accepting between a lower and upper bound repetitions
11022 >>> re = Loop(Re("a"), 1, 3)
11023 >>> print(simplify(InRe("aa", re)))
11024 True
11025 >>> print(simplify(InRe("aaaa", re)))
11026 False
11027 >>> print(simplify(InRe("", re)))
11028 False
11029 """
11030 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11031
11032
11033def Range(lo, hi, ctx=None):
11034 """Create the range regular expression over two sequences of length 1
11035 >>> range = Range("a","z")
11036 >>> print(simplify(InRe("b", range)))
11037 True
11038 >>> print(simplify(InRe("bb", range)))
11039 False
11040 """
11041 lo = _coerce_seq(lo, ctx)
11042 hi = _coerce_seq(hi, ctx)
11043 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11044
11045# Special Relations
11046
11047
11048def PartialOrder(a, index):
11049 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11050
11051
11052def LinearOrder(a, index):
11053 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11054
11055
11056def TreeOrder(a, index):
11057 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11058
11059
11061 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11062
11063
11065 """Given a binary relation R, such that the two arguments have the same sort
11066 create the transitive closure relation R+.
11067 The transitive closure R+ is a new relation.
11068 """
11069 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11070
11071
11073 def __init__(self):
11074 self.bases = {}
11075 self.lock = None
11076
11078 if self.lock is None:
11079 import threading
11080 self.lock = threading.thread.Lock()
11081
11082 def get(self, ctx):
11083 if self.lock:
11084 self.lock.acquire()
11085 r = self.bases[ctx]
11086 if self.lock:
11087 self.lock.release()
11088 return r
11089
11090 def set(self, ctx, r):
11091 if self.lock:
11092 self.lock.acquire()
11093 self.bases[ctx] = r
11094 if self.lock:
11095 self.lock.release()
11096
11097 def insert(self, r):
11098 if self.lock:
11099 self.lock.acquire()
11100 id = len(self.bases) + 3
11101 self.bases[id] = r
11102 if self.lock:
11103 self.lock.release()
11104 return id
11105
11106
11107_prop_closures = None
11108
11109
11111 global _prop_closures
11112 if _prop_closures is None:
11113 _prop_closures = PropClosures()
11114
11115
11117 _prop_closures.get(ctx).push()
11118
11119
11120def user_prop_pop(ctx, num_scopes):
11121 _prop_closures.get(ctx).pop(num_scopes)
11122
11123
11124def user_prop_fresh(id, ctx):
11125 _prop_closures.set_threaded()
11126 new_prop = UsePropagateBase(None, ctx)
11127 _prop_closures.set(new_prop.id, new_prop.fresh())
11128 return ctypes.c_void_p(new_prop.id)
11129
11130
11131def user_prop_fixed(ctx, cb, id, value):
11132 prop = _prop_closures.get(ctx)
11133 prop.cb = cb
11134 prop.fixed(id, _to_expr_ref(ctypes.c_void_p(value), prop.ctx()))
11135 prop.cb = None
11136
11137
11138def user_prop_final(ctx, cb):
11139 prop = _prop_closures.get(ctx)
11140 prop.cb = cb
11141 prop.final()
11142 prop.cb = None
11143
11144
11145def user_prop_eq(ctx, cb, x, y):
11146 prop = _prop_closures.get(ctx)
11147 prop.cb = cb
11148 prop.eq(x, y)
11149 prop.cb = None
11150
11151
11152def user_prop_diseq(ctx, cb, x, y):
11153 prop = _prop_closures.get(ctx)
11154 prop.cb = cb
11155 prop.diseq(x, y)
11156 prop.cb = None
11157
11158
11159_user_prop_push = push_eh_type(user_prop_push)
11160_user_prop_pop = pop_eh_type(user_prop_pop)
11161_user_prop_fresh = fresh_eh_type(user_prop_fresh)
11162_user_prop_fixed = fixed_eh_type(user_prop_fixed)
11163_user_prop_final = final_eh_type(user_prop_final)
11164_user_prop_eq = eq_eh_type(user_prop_eq)
11165_user_prop_diseq = eq_eh_type(user_prop_diseq)
11166
11167
11169
11170 #
11171 # Either solver is set or ctx is set.
11172 # Propagators that are created throuh callbacks
11173 # to "fresh" inherit the context of that is supplied
11174 # as argument to the callback.
11175 # This context should not be deleted. It is owned by the solver.
11176 #
11177 def __init__(self, s, ctx=None):
11178 assert s is None or ctx is None
11180 self.solver = s
11181 self._ctx = None
11182 self.cb = None
11183 self.id = _prop_closures.insert(self)
11184 self.fixed = None
11185 self.final = None
11186 self.eq = None
11187 self.diseq = None
11188 if ctx:
11189 self._ctx = Context()
11190 Z3_del_context(self._ctx.ctx)
11191 self._ctx.ctx = ctx
11192 self._ctx.eh = Z3_set_error_handler(ctx, z3_error_handler)
11193 Z3_set_ast_print_mode(ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
11194 if s:
11196 s.solver,
11197 ctypes.c_void_p(self.id),
11198 _user_prop_push,
11199 _user_prop_pop,
11200 _user_prop_fresh)
11201
11202 def __del__(self):
11203 if self._ctx:
11204 self._ctx.ctx = None
11205
11206 def ctx(self):
11207 if self._ctx:
11208 return self._ctx
11209 else:
11210 return self.solver.ctx
11211
11212 def ctx_ref(self):
11213 return self.ctx().ref()
11214
11215 def add_fixed(self, fixed):
11216 assert not self.fixed
11217 assert not self._ctx
11218 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
11219 self.fixed = fixed
11220
11221 def add_final(self, final):
11222 assert not self.final
11223 assert not self._ctx
11224 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
11225 self.final = final
11226
11227 def add_eq(self, eq):
11228 assert not self.eq
11229 assert not self._ctx
11230 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
11231 self.eq = eq
11232
11233 def add_diseq(self, diseq):
11234 assert not self.diseq
11235 assert not self._ctx
11236 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
11237 self.diseq = diseq
11238
11239 def push(self):
11240 raise Z3Exception("push needs to be overwritten")
11241
11242 def pop(self, num_scopes):
11243 raise Z3Exception("pop needs to be overwritten")
11244
11245 def fresh(self):
11246 raise Z3Exception("fresh needs to be overwritten")
11247
11248 def add(self, e):
11249 assert self.solver
11250 assert not self._ctx
11251 return Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
11252
11253 #
11254 # Propagation can only be invoked as during a fixed or final callback.
11255 #
11256 def propagate(self, e, ids, eqs=[]):
11257 num_fixed = len(ids)
11258 _ids = (ctypes.c_uint * num_fixed)()
11259 for i in range(num_fixed):
11260 _ids[i] = ids[i]
11261 num_eqs = len(eqs)
11262 _lhs = (ctypes.c_uint * num_eqs)()
11263 _rhs = (ctypes.c_uint * num_eqs)()
11264 for i in range(num_eqs):
11265 _lhs[i] = eqs[i][0]
11266 _rhs[i] = eqs[i][1]
11267 Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11268 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11269
11270 def conflict(self, ids):
11271 self.propagate(BoolVal(False, self.ctx()), ids, eqs=[])
def poly(self)
Definition: z3py.py:3078
def as_decimal(self, prec)
Definition: z3py.py:3066
def index(self)
Definition: z3py.py:3081
def approx(self, precision=10)
Definition: z3py.py:3054
def __del__(self)
Definition: z3py.py:7977
def __getitem__(self, idx)
Definition: z3py.py:8000
def __init__(self, result, ctx)
Definition: z3py.py:7969
def __len__(self)
Definition: z3py.py:7981
def as_expr(self)
Definition: z3py.py:8024
def __repr__(self)
Definition: z3py.py:8017
def sexpr(self)
Definition: z3py.py:8020
def __deepcopy__(self, memo={})
Definition: z3py.py:7974
def is_real(self)
Definition: z3py.py:2369
def __pos__(self)
Definition: z3py.py:2565
def sort(self)
Definition: z3py.py:2345
def __radd__(self, other)
Definition: z3py.py:2393
def __pow__(self, other)
Definition: z3py.py:2451
def __add__(self, other)
Definition: z3py.py:2380
def __lt__(self, other)
Definition: z3py.py:2587
def __neg__(self)
Definition: z3py.py:2554
def __rmul__(self, other)
Definition: z3py.py:2418
def __le__(self, other)
Definition: z3py.py:2574
def __mul__(self, other)
Definition: z3py.py:2403
def __mod__(self, other)
Definition: z3py.py:2527
def __rsub__(self, other)
Definition: z3py.py:2441
def __rtruediv__(self, other)
Definition: z3py.py:2523
def __rdiv__(self, other)
Definition: z3py.py:2506
def __ge__(self, other)
Definition: z3py.py:2613
def is_int(self)
Definition: z3py.py:2355
def __truediv__(self, other)
Definition: z3py.py:2502
def __gt__(self, other)
Definition: z3py.py:2600
def __sub__(self, other)
Definition: z3py.py:2428
def __rpow__(self, other)
Definition: z3py.py:2465
def __rmod__(self, other)
Definition: z3py.py:2542
def __div__(self, other)
Definition: z3py.py:2479
Arithmetic.
Definition: z3py.py:2253
def is_real(self)
Definition: z3py.py:2256
def subsort(self, other)
Definition: z3py.py:2284
def cast(self, val)
Definition: z3py.py:2288
def is_int(self)
Definition: z3py.py:2270
def sort(self)
Definition: z3py.py:4508
def default(self)
Definition: z3py.py:4548
def __getitem__(self, arg)
Definition: z3py.py:4535
def domain(self)
Definition: z3py.py:4517
def range(self)
Definition: z3py.py:4526
def domain(self)
Definition: z3py.py:4486
def range(self)
Definition: z3py.py:4495
def erase(self, k)
Definition: z3py.py:6022
def __del__(self)
Definition: z3py.py:5962
def reset(self)
Definition: z3py.py:6036
def __init__(self, m=None, ctx=None)
Definition: z3py.py:5948
def __len__(self)
Definition: z3py.py:5966
def keys(self)
Definition: z3py.py:6051
def __repr__(self)
Definition: z3py.py:6019
def __getitem__(self, key)
Definition: z3py.py:5992
def __deepcopy__(self, memo={})
Definition: z3py.py:5959
def __setitem__(self, k, v)
Definition: z3py.py:6003
def __contains__(self, key)
Definition: z3py.py:5979
def ctx_ref(self)
Definition: z3py.py:399
def __str__(self)
Definition: z3py.py:357
def __hash__(self)
Definition: z3py.py:366
def __nonzero__(self)
Definition: z3py.py:369
def __bool__(self)
Definition: z3py.py:372
def __del__(self)
Definition: z3py.py:349
def hash(self)
Definition: z3py.py:439
def get_id(self)
Definition: z3py.py:395
def as_ast(self)
Definition: z3py.py:391
def __repr__(self)
Definition: z3py.py:360
def __init__(self, ast, ctx=None)
Definition: z3py.py:344
def sexpr(self)
Definition: z3py.py:382
def translate(self, target)
Definition: z3py.py:420
def __deepcopy__(self, memo={})
Definition: z3py.py:354
def __copy__(self)
Definition: z3py.py:436
def __eq__(self, other)
Definition: z3py.py:363
def eq(self, other)
Definition: z3py.py:403
def __contains__(self, item)
Definition: z3py.py:5886
def resize(self, sz)
Definition: z3py.py:5873
def __del__(self)
Definition: z3py.py:5799
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5788
def __setitem__(self, i, v)
Definition: z3py.py:5845
def push(self, v)
Definition: z3py.py:5861
def __len__(self)
Definition: z3py.py:5803
def translate(self, other_ctx)
Definition: z3py.py:5909
def __repr__(self)
Definition: z3py.py:5931
def sexpr(self)
Definition: z3py.py:5934
def __deepcopy__(self, memo={})
Definition: z3py.py:5928
def __copy__(self)
Definition: z3py.py:5925
def __getitem__(self, i)
Definition: z3py.py:5816
def as_signed_long(self)
Definition: z3py.py:3876
def as_long(self)
Definition: z3py.py:3865
def as_binary_string(self)
Definition: z3py.py:3902
def as_string(self)
Definition: z3py.py:3899
def __rlshift__(self, other)
Definition: z3py.py:3847
def __pos__(self)
Definition: z3py.py:3612
def sort(self)
Definition: z3py.py:3452
def __radd__(self, other)
Definition: z3py.py:3487
def __rxor__(self, other)
Definition: z3py.py:3602
def __xor__(self, other)
Definition: z3py.py:3589
def __ror__(self, other)
Definition: z3py.py:3556
def __add__(self, other)
Definition: z3py.py:3474
def __rshift__(self, other)
Definition: z3py.py:3789
def __lt__(self, other)
Definition: z3py.py:3741
def __or__(self, other)
Definition: z3py.py:3543
def size(self)
Definition: z3py.py:3463
def __neg__(self)
Definition: z3py.py:3621
def __rand__(self, other)
Definition: z3py.py:3579
def __rmul__(self, other)
Definition: z3py.py:3510
def __le__(self, other)
Definition: z3py.py:3725
def __mul__(self, other)
Definition: z3py.py:3497
def __mod__(self, other)
Definition: z3py.py:3686
def __rsub__(self, other)
Definition: z3py.py:3533
def __invert__(self)
Definition: z3py.py:3632
def __rtruediv__(self, other)
Definition: z3py.py:3682
def __rdiv__(self, other)
Definition: z3py.py:3666
def __lshift__(self, other)
Definition: z3py.py:3819
def __ge__(self, other)
Definition: z3py.py:3773
def __and__(self, other)
Definition: z3py.py:3566
def __rrshift__(self, other)
Definition: z3py.py:3833
def __truediv__(self, other)
Definition: z3py.py:3662
def __gt__(self, other)
Definition: z3py.py:3757
def __sub__(self, other)
Definition: z3py.py:3520
def __rmod__(self, other)
Definition: z3py.py:3707
def __div__(self, other)
Definition: z3py.py:3643
Bit-Vectors.
Definition: z3py.py:3405
def subsort(self, other)
Definition: z3py.py:3417
def size(self)
Definition: z3py.py:3408
def cast(self, val)
Definition: z3py.py:3420
def sort(self)
Definition: z3py.py:1519
def __rmul__(self, other)
Definition: z3py.py:1522
def __mul__(self, other)
Definition: z3py.py:1525
Booleans.
Definition: z3py.py:1480
def subsort(self, other)
Definition: z3py.py:1506
def cast(self, val)
Definition: z3py.py:1483
def is_int(self)
Definition: z3py.py:1509
def is_bool(self)
Definition: z3py.py:1512
def __repr__(self)
Definition: z3py.py:6758
def __ne__(self, other)
Definition: z3py.py:6755
def __init__(self, r)
Definition: z3py.py:6746
def __deepcopy__(self, memo={})
Definition: z3py.py:6749
def __eq__(self, other)
Definition: z3py.py:6752
def interrupt(self)
Definition: z3py.py:225
def __init__(self, *args, **kws)
Definition: z3py.py:197
def __del__(self)
Definition: z3py.py:216
def ref(self)
Definition: z3py.py:221
def create(self)
Definition: z3py.py:5051
def __init__(self, name, ctx=None)
Definition: z3py.py:5007
def declare(self, name, *args)
Definition: z3py.py:5027
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:5017
def __repr__(self)
Definition: z3py.py:5048
def __deepcopy__(self, memo={})
Definition: z3py.py:5012
def sort(self)
Definition: z3py.py:5288
def recognizer(self, idx)
Definition: z3py.py:5223
def num_constructors(self)
Definition: z3py.py:5191
def constructor(self, idx)
Definition: z3py.py:5204
def accessor(self, i, j)
Definition: z3py.py:5251
Expressions.
Definition: z3py.py:958
def params(self)
Definition: z3py.py:1037
def sort(self)
Definition: z3py.py:975
def __hash__(self)
Definition: z3py.py:1015
def get_id(self)
Definition: z3py.py:972
def children(self)
Definition: z3py.py:1092
def as_ast(self)
Definition: z3py.py:969
def decl(self)
Definition: z3py.py:1040
def __ne__(self, other)
Definition: z3py.py:1019
def num_args(self)
Definition: z3py.py:1055
def arg(self, idx)
Definition: z3py.py:1071
def sort_kind(self)
Definition: z3py.py:987
def __eq__(self, other)
Definition: z3py.py:998
def isNormal(self)
Definition: z3py.py:9667
def exponent(self, biased=True)
Definition: z3py.py:9626
def significand(self)
Definition: z3py.py:9595
def sign_as_bv(self)
Definition: z3py.py:9585
def isNegative(self)
Definition: z3py.py:9682
def significand_as_bv(self)
Definition: z3py.py:9616
def exponent_as_long(self, biased=True)
Definition: z3py.py:9636
def isInf(self)
Definition: z3py.py:9657
def isNaN(self)
Definition: z3py.py:9652
def sign(self)
Definition: z3py.py:9573
def isZero(self)
Definition: z3py.py:9662
def significand_as_long(self)
Definition: z3py.py:9605
def isSubnormal(self)
Definition: z3py.py:9672
def isPositive(self)
Definition: z3py.py:9677
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9647
def as_string(self)
Definition: z3py.py:9693
def as_string(self)
Definition: z3py.py:9487
def __pos__(self)
Definition: z3py.py:9426
def sort(self)
Definition: z3py.py:9309
def __radd__(self, other)
Definition: z3py.py:9365
def __add__(self, other)
Definition: z3py.py:9352
def sbits(self)
Definition: z3py.py:9328
def __lt__(self, other)
Definition: z3py.py:9343
def __neg__(self)
Definition: z3py.py:9430
def ebits(self)
Definition: z3py.py:9320
def __rmul__(self, other)
Definition: z3py.py:9413
def __le__(self, other)
Definition: z3py.py:9340
def __mul__(self, other)
Definition: z3py.py:9398
def __mod__(self, other)
Definition: z3py.py:9475
def __rsub__(self, other)
Definition: z3py.py:9388
def __rtruediv__(self, other)
Definition: z3py.py:9471
def __rdiv__(self, other)
Definition: z3py.py:9454
def __ge__(self, other)
Definition: z3py.py:9346
def __truediv__(self, other)
Definition: z3py.py:9467
def __gt__(self, other)
Definition: z3py.py:9349
def __sub__(self, other)
Definition: z3py.py:9375
def as_string(self)
Definition: z3py.py:9336
def __rmod__(self, other)
Definition: z3py.py:9479
def __div__(self, other)
Definition: z3py.py:9439
def sbits(self)
Definition: z3py.py:9206
def ebits(self)
Definition: z3py.py:9198
def cast(self, val)
Definition: z3py.py:9214
def as_long(self)
Definition: z3py.py:7637
def as_string(self)
Definition: z3py.py:7649
def sort(self)
Definition: z3py.py:7612
def as_string(self)
Definition: z3py.py:7616
Fixedpoint.
Definition: z3py.py:7312
def insert(self, *args)
Definition: z3py.py:7373
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7563
def fact(self, head, name=None)
Definition: z3py.py:7404
def reason_unknown(self)
Definition: z3py.py:7549
def rule(self, head, body=None, name=None)
Definition: z3py.py:7400
def to_string(self, queries)
Definition: z3py.py:7536
def add_cover(self, level, predicate, property)
Definition: z3py.py:7488
def add(self, *args)
Definition: z3py.py:7361
def __del__(self)
Definition: z3py.py:7329
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7377
def param_descrs(self)
Definition: z3py.py:7343
def assert_exprs(self, *args)
Definition: z3py.py:7347
def get_answer(self)
Definition: z3py.py:7455
def statistics(self)
Definition: z3py.py:7544
def update_rule(self, head, body, name)
Definition: z3py.py:7446
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7430
def append(self, *args)
Definition: z3py.py:7369
def query(self, *query)
Definition: z3py.py:7408
def parse_string(self, s)
Definition: z3py.py:7510
def help(self)
Definition: z3py.py:7339
def get_rules_along_trace(self)
Definition: z3py.py:7465
def get_ground_sat_answer(self)
Definition: z3py.py:7460
def __repr__(self)
Definition: z3py.py:7526
def get_rules(self)
Definition: z3py.py:7518
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7500
def sexpr(self)
Definition: z3py.py:7530
def get_assertions(self)
Definition: z3py.py:7522
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7481
def __deepcopy__(self, memo={})
Definition: z3py.py:7326
def get_num_levels(self, predicate)
Definition: z3py.py:7477
def declare_var(self, *vars)
Definition: z3py.py:7554
def parse_file(self, f)
Definition: z3py.py:7514
def set(self, *args, **keys)
Definition: z3py.py:7333
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:7315
def register_relation(self, *relations)
Definition: z3py.py:7494
def get_rule_names_along_trace(self)
Definition: z3py.py:7469
def __iadd__(self, fml)
Definition: z3py.py:7365
Function Declarations.
Definition: z3py.py:715
def params(self)
Definition: z3py.py:790
def get_id(self)
Definition: z3py.py:726
def name(self)
Definition: z3py.py:732
def __call__(self, *args)
Definition: z3py.py:814
def arity(self)
Definition: z3py.py:743
def kind(self)
Definition: z3py.py:777
def as_ast(self)
Definition: z3py.py:723
def as_func_decl(self)
Definition: z3py.py:729
def domain(self, i)
Definition: z3py.py:753
def range(self)
Definition: z3py.py:767
Definition: z3py.py:6070
def __del__(self)
Definition: z3py.py:6081
ctx
Definition: z3py.py:6075
def value(self)
Definition: z3py.py:6134
def __init__(self, entry, ctx)
Definition: z3py.py:6073
def arg_value(self, idx)
Definition: z3py.py:6103
entry
Definition: z3py.py:6074
def __repr__(self)
Definition: z3py.py:6175
def num_args(self)
Definition: z3py.py:6085
def __deepcopy__(self, memo={})
Definition: z3py.py:6078
def as_list(self)
Definition: z3py.py:6156
def __del__(self)
Definition: z3py.py:6188
def arity(self)
Definition: z3py.py:6231
def __init__(self, f, ctx)
Definition: z3py.py:6182
def translate(self, other_ctx)
Definition: z3py.py:6265
def __repr__(self)
Definition: z3py.py:6293
def num_entries(self)
Definition: z3py.py:6215
def __deepcopy__(self, memo={})
Definition: z3py.py:6273
def else_value(self)
Definition: z3py.py:6192
def __copy__(self)
Definition: z3py.py:6270
def as_list(self)
Definition: z3py.py:6276
def entry(self, idx)
Definition: z3py.py:6245
def insert(self, *args)
Definition: z3py.py:5645
def dimacs(self, include_names=True)
Definition: z3py.py:5703
def get(self, i)
Definition: z3py.py:5591
def depth(self)
Definition: z3py.py:5499
def convert_model(self, model)
Definition: z3py.py:5667
def add(self, *args)
Definition: z3py.py:5656
def __del__(self)
Definition: z3py.py:5495
def assert_exprs(self, *args)
Definition: z3py.py:5619
def __getitem__(self, arg)
Definition: z3py.py:5604
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5485
def size(self)
Definition: z3py.py:5565
def append(self, *args)
Definition: z3py.py:5634
def __len__(self)
Definition: z3py.py:5578
def as_expr(self)
Definition: z3py.py:5756
def __repr__(self)
Definition: z3py.py:5696
def sexpr(self)
Definition: z3py.py:5699
def precision(self)
Definition: z3py.py:5556
def translate(self, target)
Definition: z3py.py:5707
def __deepcopy__(self, memo={})
Definition: z3py.py:5733
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5736
def __copy__(self)
Definition: z3py.py:5730
def inconsistent(self)
Definition: z3py.py:5517
def prec(self)
Definition: z3py.py:5535
def as_long(self)
Definition: z3py.py:2924
def as_binary_string(self)
Definition: z3py.py:2945
def as_string(self)
Definition: z3py.py:2937
def decls(self)
Definition: z3py.py:6545
def get_universe(self, s)
Definition: z3py.py:6480
def __del__(self)
Definition: z3py.py:6306
def eval(self, t, model_completion=False)
Definition: z3py.py:6317
def __init__(self, m, ctx)
Definition: z3py.py:6300
def sorts(self)
Definition: z3py.py:6463
def __getitem__(self, idx)
Definition: z3py.py:6500
def __len__(self)
Definition: z3py.py:6374
def num_sorts(self)
Definition: z3py.py:6425
def __repr__(self)
Definition: z3py.py:6310
def sexpr(self)
Definition: z3py.py:6313
def translate(self, target)
Definition: z3py.py:6564
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6348
def __deepcopy__(self, memo={})
Definition: z3py.py:6575
def __copy__(self)
Definition: z3py.py:6572
def get_interp(self, decl)
Definition: z3py.py:6391
def get_sort(self, idx)
Definition: z3py.py:6440
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7822
def reason_unknown(self)
Definition: z3py.py:7879
def objectives(self)
Definition: z3py.py:7925
def pop(self)
Definition: z3py.py:7866
def maximize(self, arg)
Definition: z3py.py:7846
def unsat_core(self)
Definition: z3py.py:7890
def from_string(self, s)
Definition: z3py.py:7917
def add(self, *args)
Definition: z3py.py:7785
def __del__(self)
Definition: z3py.py:7752
def param_descrs(self)
Definition: z3py.py:7769
def assert_exprs(self, *args)
Definition: z3py.py:7773
def model(self)
Definition: z3py.py:7883
def statistics(self)
Definition: z3py.py:7939
def help(self)
Definition: z3py.py:7765
def upper_values(self, obj)
Definition: z3py.py:7908
def __repr__(self)
Definition: z3py.py:7929
def from_file(self, filename)
Definition: z3py.py:7913
def set_on_model(self, on_model)
Definition: z3py.py:7944
def sexpr(self)
Definition: z3py.py:7933
def check(self, *assumptions)
Definition: z3py.py:7870
def push(self)
Definition: z3py.py:7862
def __deepcopy__(self, memo={})
Definition: z3py.py:7749
def minimize(self, arg)
Definition: z3py.py:7854
def lower(self, obj)
Definition: z3py.py:7893
def assert_and_track(self, a, p)
Definition: z3py.py:7793
def set(self, *args, **keys)
Definition: z3py.py:7758
def upper(self, obj)
Definition: z3py.py:7898
def lower_values(self, obj)
Definition: z3py.py:7903
def __init__(self, ctx=None)
Definition: z3py.py:7743
def assertions(self)
Definition: z3py.py:7921
def __iadd__(self, fml)
Definition: z3py.py:7789
def __str__(self)
Definition: z3py.py:7725
def upper(self)
Definition: z3py.py:7707
def value(self)
Definition: z3py.py:7719
def lower_values(self)
Definition: z3py.py:7711
def __init__(self, opt, value, is_max)
Definition: z3py.py:7698
def lower(self)
Definition: z3py.py:7703
def upper_values(self)
Definition: z3py.py:7715
def get_name(self, i)
Definition: z3py.py:5446
def get_kind(self, n)
Definition: z3py.py:5451
def __del__(self)
Definition: z3py.py:5432
def __getitem__(self, arg)
Definition: z3py.py:5461
def size(self)
Definition: z3py.py:5436
def __init__(self, descr, ctx=None)
Definition: z3py.py:5423
def __len__(self)
Definition: z3py.py:5441
def __repr__(self)
Definition: z3py.py:5467
def get_documentation(self, n)
Definition: z3py.py:5456
def __deepcopy__(self, memo={})
Definition: z3py.py:5429
Parameter Sets.
Definition: z3py.py:5350
def validate(self, ds)
Definition: z3py.py:5391
def __del__(self)
Definition: z3py.py:5367
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5356
def __repr__(self)
Definition: z3py.py:5388
def __deepcopy__(self, memo={})
Definition: z3py.py:5364
def set(self, name, val)
Definition: z3py.py:5371
Patterns.
Definition: z3py.py:1885
def get_id(self)
Definition: z3py.py:1893
def as_ast(self)
Definition: z3py.py:1890
def __del__(self)
Definition: z3py.py:8393
def __call__(self, goal)
Definition: z3py.py:8482
def __lt__(self, other)
Definition: z3py.py:8397
def __le__(self, other)
Definition: z3py.py:8425
def __init__(self, probe, ctx=None)
Definition: z3py.py:8367
def __ne__(self, other)
Definition: z3py.py:8467
def __ge__(self, other)
Definition: z3py.py:8439
def __deepcopy__(self, memo={})
Definition: z3py.py:8390
def __eq__(self, other)
Definition: z3py.py:8453
def __gt__(self, other)
Definition: z3py.py:8411
def set_threaded()
Definition: z3py.py:11077
def set(self, ctx, r)
Definition: z3py.py:11090
def insert(self, r)
Definition: z3py.py:11097
def get(self, ctx)
Definition: z3py.py:11082
def __init__(self)
Definition: z3py.py:11073
Quantifiers.
Definition: z3py.py:1952
def pattern(self, idx)
Definition: z3py.py:2043
def sort(self)
Definition: z3py.py:1961
def var_name(self, idx)
Definition: z3py.py:2094
def no_pattern(self, idx)
Definition: z3py.py:2065
def is_forall(self)
Definition: z3py.py:1967
def num_no_patterns(self)
Definition: z3py.py:2061
def body(self)
Definition: z3py.py:2071
def num_vars(self)
Definition: z3py.py:2082
def get_id(self)
Definition: z3py.py:1958
def __getitem__(self, arg)
Definition: z3py.py:2009
def children(self)
Definition: z3py.py:2126
def weight(self)
Definition: z3py.py:2017
def is_lambda(self)
Definition: z3py.py:1995
def as_ast(self)
Definition: z3py.py:1955
def var_sort(self, idx)
Definition: z3py.py:2110
def num_patterns(self)
Definition: z3py.py:2031
def is_exists(self)
Definition: z3py.py:1981
def is_real(self)
Definition: z3py.py:3010
def as_decimal(self, prec)
Definition: z3py.py:3020
def as_fraction(self)
Definition: z3py.py:3041
def is_int_value(self)
Definition: z3py.py:3013
def numerator_as_long(self)
Definition: z3py.py:2983
def as_long(self)
Definition: z3py.py:3016
def denominator(self)
Definition: z3py.py:2972
def denominator_as_long(self)
Definition: z3py.py:2996
def is_int(self)
Definition: z3py.py:3007
def numerator(self)
Definition: z3py.py:2957
def as_string(self)
Definition: z3py.py:3032
def __add__(self, other)
Definition: z3py.py:10916
def basis(self)
Definition: z3py.py:10900
def __del__(self)
Definition: z3py.py:5075
def __init__(self, c, ctx)
Definition: z3py.py:5071
def __init__(self, c, ctx)
Definition: z3py.py:5083
def sort(self)
Definition: z3py.py:10591
def __radd__(self, other)
Definition: z3py.py:10597
def at(self, i)
Definition: z3py.py:10605
def __add__(self, other)
Definition: z3py.py:10594
def __lt__(self, other)
Definition: z3py.py:10627
def is_string_value(self)
Definition: z3py.py:10613
def __le__(self, other)
Definition: z3py.py:10624
def __ge__(self, other)
Definition: z3py.py:10630
def __gt__(self, other)
Definition: z3py.py:10633
def is_string(self)
Definition: z3py.py:10610
def as_string(self)
Definition: z3py.py:10616
def __getitem__(self, i)
Definition: z3py.py:10600
Strings, Sequences and Regular expressions.
Definition: z3py.py:10551
def basis(self)
Definition: z3py.py:10565
def is_string(self)
Definition: z3py.py:10554
def insert(self, *args)
Definition: z3py.py:6944
def dimacs(self, include_names=True)
Definition: z3py.py:7249
def non_units(self)
Definition: z3py.py:7157
def reason_unknown(self)
Definition: z3py.py:7193
backtrack_level
Definition: z3py.py:6796
def num_scopes(self)
Definition: z3py.py:6867
def unsat_core(self)
Definition: z3py.py:7037
def trail_levels(self)
Definition: z3py.py:7162
def trail(self)
Definition: z3py.py:7170
def from_string(self, s)
Definition: z3py.py:7102
def add(self, *args)
Definition: z3py.py:6918
def __del__(self)
Definition: z3py.py:6806
def import_model_converter(self, other)
Definition: z3py.py:7033
def param_descrs(self)
Definition: z3py.py:7210
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6793
def reset(self)
Definition: z3py.py:6885
def assert_exprs(self, *args)
Definition: z3py.py:6899
def pop(self, num=1)
Definition: z3py.py:6845
def units(self)
Definition: z3py.py:7152
def cube(self, vars=None)
Definition: z3py.py:7106
def cube_vars(self)
Definition: z3py.py:7127
def model(self)
Definition: z3py.py:7014
def statistics(self)
Definition: z3py.py:7175
def append(self, *args)
Definition: z3py.py:6933
def to_smt2(self)
Definition: z3py.py:7253
def help(self)
Definition: z3py.py:7206
def __repr__(self)
Definition: z3py.py:7214
def from_file(self, filename)
Definition: z3py.py:7098
def proof(self)
Definition: z3py.py:7134
def sexpr(self)
Definition: z3py.py:7237
def check(self, *assumptions)
Definition: z3py.py:6985
def translate(self, target)
Definition: z3py.py:7218
def push(self)
Definition: z3py.py:6823
def __deepcopy__(self, memo={})
Definition: z3py.py:7234
def consequences(self, assumptions, variables)
Definition: z3py.py:7069
def assert_and_track(self, a, p)
Definition: z3py.py:6955
def set(self, *args, **keys)
Definition: z3py.py:6810
def __copy__(self)
Definition: z3py.py:7231
def assertions(self)
Definition: z3py.py:7138
def __iadd__(self, fml)
Definition: z3py.py:6929
def __hash__(self)
Definition: z3py.py:641
def subsort(self, other)
Definition: z3py.py:584
def get_id(self)
Definition: z3py.py:564
def name(self)
Definition: z3py.py:607
def kind(self)
Definition: z3py.py:567
def as_ast(self)
Definition: z3py.py:561
def __ne__(self, other)
Definition: z3py.py:630
def cast(self, val)
Definition: z3py.py:592
def __eq__(self, other)
Definition: z3py.py:617
Statistics.
Definition: z3py.py:6602
def __getattr__(self, name)
Definition: z3py.py:6705
def __del__(self)
Definition: z3py.py:6613
def __getitem__(self, idx)
Definition: z3py.py:6649
def __len__(self)
Definition: z3py.py:6635
def keys(self)
Definition: z3py.py:6673
def __init__(self, stats, ctx)
Definition: z3py.py:6605
def __repr__(self)
Definition: z3py.py:6617
def get_key_value(self, key)
Definition: z3py.py:6685
def __deepcopy__(self, memo={})
Definition: z3py.py:6610
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:8120
def __del__(self)
Definition: z3py.py:8082
def param_descrs(self)
Definition: z3py.py:8134
def solver(self, logFile=None)
Definition: z3py.py:8086
def __init__(self, tactic, ctx=None)
Definition: z3py.py:8065
def help(self)
Definition: z3py.py:8130
def __deepcopy__(self, memo={})
Definition: z3py.py:8079
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:8103
def ctx_ref(self)
Definition: z3py.py:11212
def add_fixed(self, fixed)
Definition: z3py.py:11215
def __del__(self)
Definition: z3py.py:11202
def add_diseq(self, diseq)
Definition: z3py.py:11233
def pop(self, num_scopes)
Definition: z3py.py:11242
def add_eq(self, eq)
Definition: z3py.py:11227
def add(self, e)
Definition: z3py.py:11248
def __init__(self, s, ctx=None)
Definition: z3py.py:11177
def propagate(self, e, ids, eqs=[])
Definition: z3py.py:11256
def conflict(self, ids)
Definition: z3py.py:11270
def add_final(self, final)
Definition: z3py.py:11221
ASTs base class.
Definition: z3py.py:327
def use_pp(self)
Definition: z3py.py:330
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3725
def fpIsNegative(a, ctx=None)
Definition: z3py.py:10197
def fpAbs(a, ctx=None)
Definition: z3py.py:9941
def is_pattern(a)
Definition: z3py.py:1897
def StrToInt(s)
Definition: z3py.py:10862
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:10286
def RNE(ctx=None)
Definition: z3py.py:9497
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:10315
def AtLeast(*args)
Definition: z3py.py:8800
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:11060
def BVRedOr(a)
Definition: z3py.py:4414
def is_lt(a)
Definition: z3py.py:2843
def Empty(s)
Definition: z3py.py:10720
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10391
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10427
def SRem(a, b)
Definition: z3py.py:4240
def OrElse(*ts, **ks)
Definition: z3py.py:8204
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:10032
def RealVarVector(n, ctx=None)
Definition: z3py.py:1462
def z3_debug()
Definition: z3py.py:64
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:9492
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:10150
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4463
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9071
def PbGe(args, k)
Definition: z3py.py:8856
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4449
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:9116
def is_mod(a)
Definition: z3py.py:2819
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10371
def IntSort(ctx=None)
Definition: z3py.py:3100
def Float16(ctx=None)
Definition: z3py.py:9230
def reset_params()
Definition: z3py.py:294
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8645
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:8244
def substitute_vars(t, *m)
Definition: z3py.py:8709
def is_var(a)
Definition: z3py.py:1278
def SetAdd(s, e)
Definition: z3py.py:4900
def is_gt(a)
Definition: z3py.py:2867
def is_fp_sort(s)
Definition: z3py.py:9282
def fpToReal(x, ctx=None)
Definition: z3py.py:10499
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1720
def IsSubset(a, b)
Definition: z3py.py:4954
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3999
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:8293
def EmptySet(s)
Definition: z3py.py:4856
def is_rational_value(a)
Definition: z3py.py:2718
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:4023
def DeclareSort(name, ctx=None)
Definition: z3py.py:690
def Float64(ctx=None)
Definition: z3py.py:9254
def user_prop_push(ctx)
Definition: z3py.py:11116
def With(t, *args, **keys)
Definition: z3py.py:8265
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5396
def PbEq(args, k, ctx=None)
Definition: z3py.py:8867
def ToReal(a)
Definition: z3py.py:3320
def PrefixOf(a, b)
Definition: z3py.py:10759
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:10144
def Reals(names, ctx=None)
Definition: z3py.py:3276
def is_and(a)
Definition: z3py.py:1585
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:10250
def Xor(a, b, ctx=None)
Definition: z3py.py:1763
def Unit(a)
Definition: z3py.py:10754
def is_fprm_sort(s)
Definition: z3py.py:9293
def ULE(a, b)
Definition: z3py.py:4126
def Star(re)
Definition: z3py.py:11007
def Lambda(vs, body)
Definition: z3py.py:2226
def is_bv(a)
Definition: z3py.py:3906
def SetDifference(a, b)
Definition: z3py.py:4932
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7660
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:9140
def is_array(a)
Definition: z3py.py:4556
def z3_error_handler(c, e)
Definition: z3py.py:179
def TryFor(t, ms, ctx=None)
Definition: z3py.py:8314
def simplify_param_descrs()
Definition: z3py.py:8675
def Length(s)
Definition: z3py.py:10852
def ensure_prop_closures()
Definition: z3py.py:11110
def help_simplify()
Definition: z3py.py:8670
def fpIsPositive(a, ctx=None)
Definition: z3py.py:10203
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2187
def Re(s, ctx=None)
Definition: z3py.py:10885
def Sqrt(a, ctx=None)
Definition: z3py.py:3373
def set_option(*args, **kws)
Definition: z3py.py:300
def is_as_array(n)
Definition: z3py.py:6584
def fpEQ(a, b, ctx=None)
Definition: z3py.py:10262
def UGE(a, b)
Definition: z3py.py:4162
def Extract(high, low, a)
Definition: z3py.py:4090
def fpNaN(s)
Definition: z3py.py:9786
def Q(a, b, ctx=None)
Definition: z3py.py:3197
def is_bv_sort(s)
Definition: z3py.py:3438
def append_log(s)
Definition: z3py.py:124
def is_string_value(a)
Definition: z3py.py:10676
def SetIntersect(*args)
Definition: z3py.py:4887
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4428
def Select(a, i)
Definition: z3py.py:4742
def SeqSort(s)
Definition: z3py.py:10579
def is_const_array(a)
Definition: z3py.py:4570
def get_default_fp_sort(ctx=None)
Definition: z3py.py:9149
def is_array_sort(a)
Definition: z3py.py:4552
def Product(*args)
Definition: z3py.py:8756
def Consts(names, sort)
Definition: z3py.py:1417
def fpIsZero(a, ctx=None)
Definition: z3py.py:10179
def Ext(a, b)
Definition: z3py.py:4802
def Range(lo, hi, ctx=None)
Definition: z3py.py:11033
def get_var_index(a)
Definition: z3py.py:1303
def set_param(*args, **kws)
Definition: z3py.py:270
def Bools(names, ctx=None)
Definition: z3py.py:1704
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:10445
def fpZero(s, negative)
Definition: z3py.py:9845
def FloatQuadruple(ctx=None)
Definition: z3py.py:9272
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:10477
def RTZ(ctx=None)
Definition: z3py.py:9537
def BVRedAnd(a)
Definition: z3py.py:4407
def Const(name, sort)
Definition: z3py.py:1405
def RealSort(ctx=None)
Definition: z3py.py:3117
def ZeroExt(n, a)
Definition: z3py.py:4355
def fpMax(a, b, ctx=None)
Definition: z3py.py:10123
def SetSort(s)
Sets.
Definition: z3py.py:4851
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9852
def get_ctx(ctx)
Definition: z3py.py:266
def fpMinusInfinity(s)
Definition: z3py.py:9820
def is_int_value(a)
Definition: z3py.py:2694
def mk_not(a)
Definition: z3py.py:1798
def is_distinct(a)
Definition: z3py.py:1643
def solve_using(s, *args, **keywords)
Definition: z3py.py:8908
def FloatDouble(ctx=None)
Definition: z3py.py:9260
def LinearOrder(a, index)
Definition: z3py.py:11052
def RTN(ctx=None)
Definition: z3py.py:9527
def probe_description(name, ctx=None)
Definition: z3py.py:8540
def get_param(name)
Definition: z3py.py:306
def IndexOf(s, substr, offset=None)
Definition: z3py.py:10823
def is_fprm(a)
Definition: z3py.py:9542
def is_store(a)
Definition: z3py.py:4833
def RotateLeft(a, b)
Definition: z3py.py:4293
def Function(name, *sig)
Definition: z3py.py:860
def user_prop_fixed(ctx, cb, id, value)
Definition: z3py.py:11131
def UDiv(a, b)
Definition: z3py.py:4198
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:7293
def is_K(a)
Definition: z3py.py:4583
def FreshInt(prefix="x", ctx=None)
Definition: z3py.py:3249
def K(dom, v)
Definition: z3py.py:4780
def Replace(s, src, dst)
Definition: z3py.py:10808
def ArraySort(*sig)
Definition: z3py.py:4645
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:7272
def LShR(a, b)
Definition: z3py.py:4261
def FreshBool(prefix="b", ctx=None)
Definition: z3py.py:1735
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4421
def SignExt(n, a)
Definition: z3py.py:4325
def SubString(s, offset, length)
Definition: z3py.py:10710
def FullSet(s)
Definition: z3py.py:4865
def Not(a, ctx=None)
Definition: z3py.py:1779
def RecAddDefinition(f, args, body)
Definition: z3py.py:924
def fpRem(a, b, ctx=None)
Definition: z3py.py:10094
def is_expr(a)
Definition: z3py.py:1210
def FreshFunction(*sig)
Definition: z3py.py:883
def Var(idx, s)
Definition: z3py.py:1438
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3982
def Intersect(*args)
Definition: z3py.py:10958
def Loop(re, lo, hi=0)
Definition: z3py.py:11020
def If(a, b, c, ctx=None)
Definition: z3py.py:1349
def WithParams(t, p)
Definition: z3py.py:8279
def is_ge(a)
Definition: z3py.py:2855
def Concat(*args)
Definition: z3py.py:4044
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10409
def BV2Int(a, is_signed=False)
Definition: z3py.py:3935
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8628
def is_idiv(a)
Definition: z3py.py:2807
def FailIf(p, ctx=None)
Definition: z3py.py:8586
def is_fp(a)
Definition: z3py.py:9698
def When(p, t, ctx=None)
Definition: z3py.py:8608
def Default(a)
Definition: z3py.py:4714
def PartialOrder(a, index)
Definition: z3py.py:11048
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:9502
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3236
def get_full_version()
Definition: z3py.py:103
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9922
def BVSubNoOverflow(a, b)
Definition: z3py.py:4435
def is_add(a)
Definition: z3py.py:2754
def is_to_int(a)
Definition: z3py.py:2906
def TransitiveClosure(f)
Definition: z3py.py:11064
def solve(*args, **keywords)
Definition: z3py.py:8878
def FloatSingle(ctx=None)
Definition: z3py.py:9248
def user_prop_pop(ctx, num_scopes)
Definition: z3py.py:11120
def RTP(ctx=None)
Definition: z3py.py:9517
def is_is_int(a)
Definition: z3py.py:2879
def get_version_string()
Definition: z3py.py:85
def AndThen(*ts, **ks)
Definition: z3py.py:8171
def open_log(fname)
Definition: z3py.py:119
def fpIsNaN(a, ctx=None)
Definition: z3py.py:10156
def PbLe(args, k)
Definition: z3py.py:8845
def Float32(ctx=None)
Definition: z3py.py:9242
def is_to_real(a)
Definition: z3py.py:2891
def user_prop_fresh(id, ctx)
Definition: z3py.py:11124
def AtMost(*args)
Definition: z3py.py:8782
def is_func_decl(a)
Definition: z3py.py:847
def RealVar(idx, ctx=None)
Definition: z3py.py:1451
def is_false(a)
Definition: z3py.py:1571
def describe_probes()
Definition: z3py.py:8549
def SubSeq(s, offset, length)
Definition: z3py.py:10715
def StringSort(ctx=None)
Definition: z3py.py:10569
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:10274
def Ints(names, ctx=None)
Definition: z3py.py:3223
def SetHasSize(a, k)
Definition: z3py.py:4814
def fpIsNormal(a, ctx=None)
Definition: z3py.py:10185
def BoolSort(ctx=None)
Definition: z3py.py:1655
def SetComplement(s)
Definition: z3py.py:4922
def is_sub(a)
Definition: z3py.py:2778
def RatVal(a, b, ctx=None)
Definition: z3py.py:3181
def Then(*ts, **ks)
Definition: z3py.py:8191
def fpMin(a, b, ctx=None)
Definition: z3py.py:10108
def is_mul(a)
Definition: z3py.py:2766
def SuffixOf(a, b)
Definition: z3py.py:10774
def probes(ctx=None)
Definition: z3py.py:8529
def fpPlusZero(s)
Definition: z3py.py:9833
def fpLT(a, b, ctx=None)
Definition: z3py.py:10214
def is_fprm_value(a)
Definition: z3py.py:9555
def EnumSort(name, values, ctx=None)
Definition: z3py.py:5317
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2205
def RotateRight(a, b)
Definition: z3py.py:4309
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:10049
def Cbrt(a, ctx=None)
Definition: z3py.py:3386
def IsInt(a)
Definition: z3py.py:3356
def Union(*args)
Definition: z3py.py:10938
def is_finite_domain_sort(s)
Definition: z3py.py:7598
def LastIndexOf(s, substr)
Definition: z3py.py:10843
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9092
def IntToStr(s)
Definition: z3py.py:10878
def ReSort(s)
Definition: z3py.py:10904
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3291
def FloatHalf(ctx=None)
Definition: z3py.py:9236
def is_finite_domain_value(a)
Definition: z3py.py:7675
def is_bool(a)
Definition: z3py.py:1535
def Distinct(*args)
Definition: z3py.py:1372
def is_int(a)
Definition: z3py.py:2648
def UGT(a, b)
Definition: z3py.py:4180
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:10519
def is_map(a)
Definition: z3py.py:4596
def fpMinusZero(s)
Definition: z3py.py:9839
def Map(f, *args)
Definition: z3py.py:4757
def is_bv_value(a)
Definition: z3py.py:3920
def is_const(a)
Definition: z3py.py:1259
def is_app_of(a, k)
Definition: z3py.py:1336
def is_sort(s)
Definition: z3py.py:646
def fpPlusInfinity(s)
Definition: z3py.py:9803
def ULT(a, b)
Definition: z3py.py:4144
def TreeOrder(a, index)
Definition: z3py.py:11056
def FreshConst(sort, prefix="c")
Definition: z3py.py:1432
def Implies(a, b, ctx=None)
Definition: z3py.py:1749
def BVSNegNoOverflow(a)
Definition: z3py.py:4456
def get_as_array_func(n)
Definition: z3py.py:6589
def is_quantifier(a)
Definition: z3py.py:2138
def RNA(ctx=None)
Definition: z3py.py:9507
def RoundTowardZero(ctx=None)
Definition: z3py.py:9532
def is_seq(a)
Definition: z3py.py:10658
def Float128(ctx=None)
Definition: z3py.py:9266
def RealVal(val, ctx=None)
Definition: z3py.py:3162
def Int(name, ctx=None)
Definition: z3py.py:3210
def Or(*args)
Definition: z3py.py:1846
def is_probe(p)
Definition: z3py.py:8511
def is_algebraic_value(a)
Definition: z3py.py:2740
def RepeatBitVec(n, a)
Definition: z3py.py:4383
def Option(re)
Definition: z3py.py:10989
def String(name, ctx=None)
Definition: z3py.py:10693
def tactics(ctx=None)
Definition: z3py.py:8323
def Int2BV(a, num_bits)
Definition: z3py.py:3958
def user_prop_final(ctx, cb)
Definition: z3py.py:11138
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:10226
def is_finite_domain(a)
Definition: z3py.py:7621
def is_string(a)
Definition: z3py.py:10668
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7590
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:10079
def user_prop_eq(ctx, cb, x, y)
Definition: z3py.py:11145
def ToInt(a)
Definition: z3py.py:3338
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9898
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4442
def RecFunction(name, *sig)
Definition: z3py.py:906
def user_prop_diseq(ctx, cb, x, y)
Definition: z3py.py:11152
def Bool(name, ctx=None)
Definition: z3py.py:1692
def Plus(re)
Definition: z3py.py:10976
def is_eq(a)
Definition: z3py.py:1633
def ParOr(*ts, **ks)
Definition: z3py.py:8225
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:10354
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9522
def Update(a, i, v)
Definition: z3py.py:4692
def is_ast(a)
Definition: z3py.py:450
def fpGT(a, b, ctx=None)
Definition: z3py.py:10238
def MultiPattern(*args)
Definition: z3py.py:1915
def is_not(a)
Definition: z3py.py:1621
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9727
def eq(a, b)
Definition: z3py.py:471
def Complement(re)
Definition: z3py.py:11002
def disable_trace(msg)
Definition: z3py.py:81
def is_le(a)
Definition: z3py.py:2831
def is_real(a)
Definition: z3py.py:2667
def tactic_description(name, ctx=None)
Definition: z3py.py:8334
def is_app(a)
Definition: z3py.py:1233
def Strings(names, ctx=None)
Definition: z3py.py:10702
def Contains(a, b)
Definition: z3py.py:10789
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4470
def IsMember(e, s)
Definition: z3py.py:4943
def get_version()
Definition: z3py.py:94
def CreateDatatypes(*ds)
Definition: z3py.py:5092
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:5293
def get_map_func(a)
Definition: z3py.py:4621
def SetDel(s, e)
Definition: z3py.py:4911
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:10064
def is_default(a)
Definition: z3py.py:4612
def StringVal(s, ctx=None)
Definition: z3py.py:10686
def Full(s)
Definition: z3py.py:10740
def Sum(*args)
Definition: z3py.py:8730
def InRe(s, re)
Definition: z3py.py:10924
def enable_trace(msg)
Definition: z3py.py:77
def to_symbol(s, ctx=None)
Definition: z3py.py:129
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:8260
def is_arith_sort(s)
Definition: z3py.py:2326
def RoundTowardPositive(ctx=None)
Definition: z3py.py:9512
def is_true(a)
Definition: z3py.py:1553
def substitute(t, *m)
Definition: z3py.py:8680
def BoolVal(val, ctx=None)
Definition: z3py.py:1673
def FreshReal(prefix="b", ctx=None)
Definition: z3py.py:3306
def URem(a, b)
Definition: z3py.py:4219
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:10138
def Store(a, i, v)
Definition: z3py.py:4725
def main_ctx()
Definition: z3py.py:238
def describe_tactics()
Definition: z3py.py:8343
def is_implies(a)
Definition: z3py.py:1609
def is_fp_value(a)
Definition: z3py.py:9712
def Real(name, ctx=None)
Definition: z3py.py:3263
def is_div(a)
Definition: z3py.py:2790
def is_select(a)
Definition: z3py.py:4820
def fpIsInf(a, ctx=None)
Definition: z3py.py:10168
def And(*args)
Definition: z3py.py:1813
def Array(name, dom, rng)
Definition: z3py.py:4678
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:9153
def is_arith(a)
Definition: z3py.py:2627
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:10191
def is_or(a)
Definition: z3py.py:1597
def fpNeg(a, ctx=None)
Definition: z3py.py:9964
def SetUnion(*args)
Definition: z3py.py:4874
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:5305
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:10455
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3967
def Model(ctx=None)
Definition: z3py.py:6579
def fpInfinity(s, negative)
Definition: z3py.py:9826
def is_re(s)
Definition: z3py.py:10920
def IntVal(val, ctx=None)
Definition: z3py.py:3150
def prove(claim, show=False, **keywords)
Definition: z3py.py:8939
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a)
Return which root of the polynomial the algebraic number represents.
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 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.
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.
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.
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 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_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_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_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 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.
unsigned 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...
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_true(Z3_context c)
Create an AST node representing true.
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.
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.
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_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
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_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.
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.
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_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_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
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_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....
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.
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 unescaped string constant stored in s.
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.
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.
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.
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.
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.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
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...
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.
bool Z3_API Z3_is_string_sort(Z3_context c, Z3_sort s)
Check if s is a string sort.
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_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_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
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.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
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...
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.
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_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
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.
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_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
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_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.
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.
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 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 Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
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.
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.
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...
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.
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*.
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.
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_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_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.
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_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...
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
void Z3_API Z3_solver_propagate_consequence(Z3_context c, Z3_solver_callback, unsigned num_fixed, unsigned const *fixed_ids, unsigned num_eqs, unsigned const *eq_lhs, unsigned const *eq_rhs, Z3_ast conseq)
propagate a consequence based on fixed values. This is a callback a client may invoke during the fixe...
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.
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.
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_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_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
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_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.
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_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.
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_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_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.
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.
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_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.
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.
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_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_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_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_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_lstring(Z3_context c, unsigned len, Z3_string s)
Create a string constant out of the string that is passed in It takes the length of the string as wel...
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
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_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).
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_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_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
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.
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_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
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.
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
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...
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_sort Z3_API Z3_mk_string_sort(Z3_context c)
Create a sort for 8 bit 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...
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_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.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
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_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
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.
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_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
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.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
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.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
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.
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.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_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:
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_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_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.
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created.
Z3_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_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
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_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_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_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
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_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
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...
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_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_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_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_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 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.
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_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_sort Z3_API Z3_mk_fpa_sort_half(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
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.
bool Z3_API Z3_fpa_is_numeral_positive(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is positive.
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.
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 Z3_API Z3_mk_fpa_round_toward_negative(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardNegative rounding mode.
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.
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_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 Z3_API Z3_mk_fpa_inf(Z3_context c, Z3_sort s, bool negative)
Create a floating-point infinity of sort s.
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.
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_sort Z3_API Z3_mk_fpa_sort_16(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
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_sort Z3_API Z3_mk_fpa_sort_quadruple(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
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.
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_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_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_ast Z3_API Z3_mk_fpa_abs(Z3_context c, Z3_ast t)
Floating-point absolute value.
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_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_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_fpa_neg(Z3_context c, Z3_ast t)
Floating-point negation.
Z3_sort Z3_API Z3_mk_fpa_sort_32(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
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_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.
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_sort Z3_API Z3_mk_fpa_sort(Z3_context c, unsigned ebits, unsigned sbits)
Create a FloatingPoint sort.
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_fpa_get_numeral_sign_bv(Z3_context c, Z3_ast t)
Retrieves the sign of a floating-point literal as a bit-vector expression.
bool Z3_API Z3_fpa_is_numeral_normal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is normal.
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_fpa_zero(Z3_context c, Z3_sort s, bool negative)
Create a floating-point zero of sort s.
Z3_sort Z3_API Z3_mk_fpa_sort_double(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
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.
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.
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_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 ...
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.
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_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_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives....
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
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 ...
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_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.
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
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_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
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...
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
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_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
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.
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....
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.
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.