Z3
 
Loading...
Searching...
No Matches
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
15
16Please send feedback, comments and/or corrections on the Issue tracker for
17https://github.com/Z3prover/z3.git. Your comments are very valuable.
18
19Small example:
20
21>>> x = Int('x')
22>>> y = Int('y')
23>>> s = Solver()
24>>> s.add(x > 0)
25>>> s.add(x < 2)
26>>> s.add(y == x + 1)
27>>> s.check()
28sat
29>>> m = s.model()
30>>> m[x]
311
32>>> m[y]
332
34
35Z3 exceptions:
36
37>>> try:
38... x = BitVec('x', 32)
39... y = Bool('y')
40... # the expression x + y is type incorrect
41... n = x + y
42... except Z3Exception as ex:
43... print("failed: %s" % ex)
44failed: sort mismatch
45"""
46from . import z3core
47from .z3core import *
48from .z3types import *
49from .z3consts import *
50from .z3printer import *
51from fractions import Fraction
52import sys
53import io
54import math
55import copy
56if sys.version_info.major >= 3:
57 from typing import Iterable
58
59Z3_DEBUG = __debug__
60
61
63 global Z3_DEBUG
64 return Z3_DEBUG
65
66
67if sys.version_info.major < 3:
68 def _is_int(v):
69 return isinstance(v, (int, long))
70else:
71 def _is_int(v):
72 return isinstance(v, int)
73
74
75def enable_trace(msg):
77
78
81
82
84 major = ctypes.c_uint(0)
85 minor = ctypes.c_uint(0)
86 build = ctypes.c_uint(0)
87 rev = ctypes.c_uint(0)
88 Z3_get_version(major, minor, build, rev)
89 return "%s.%s.%s" % (major.value, minor.value, build.value)
90
91
93 major = ctypes.c_uint(0)
94 minor = ctypes.c_uint(0)
95 build = ctypes.c_uint(0)
96 rev = ctypes.c_uint(0)
97 Z3_get_version(major, minor, build, rev)
98 return (major.value, minor.value, build.value, rev.value)
99
100
102 return Z3_get_full_version()
103
104
105def _z3_assert(cond, msg):
106 if not cond:
107 raise Z3Exception(msg)
108
109
111 _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
112
113
114def open_log(fname):
115 """Log interaction to a file. This function must be invoked immediately after init(). """
116 Z3_open_log(fname)
117
118
120 """Append user-defined string to interaction log. """
122
123
124def to_symbol(s, ctx=None):
125 """Convert an integer or string into a Z3 symbol."""
126 if _is_int(s):
127 return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
128 else:
129 return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
130
131
132def _symbol2py(ctx, s):
133 """Convert a Z3 symbol back into a Python object. """
134 if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
135 return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
136 else:
137 return Z3_get_symbol_string(ctx.ref(), s)
138
139# Hack for having nary functions that can receive one argument that is the
140# list of arguments.
141# Use this when function takes a single list of arguments
142
143
144def _get_args(args):
145 try:
146 if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
147 return args[0]
148 elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
149 return [arg for arg in args[0]]
150 else:
151 return args
152 except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?)
153 return args
154
155# Use this when function takes multiple arguments
156
157
159 try:
160 if isinstance(args, (set, AstVector, tuple)):
161 return [arg for arg in args]
162 else:
163 return args
164 except Exception:
165 return args
166
167
169 if isinstance(val, bool):
170 return "true" if val else "false"
171 return str(val)
172
173
175 # Do nothing error handler, just avoid exit(0)
176 # The wrappers in z3core.py will raise a Z3Exception if an error is detected
177 return
178
179
180class Context:
181 """A Context manages all other Z3 objects, global configuration options, etc.
182
183 Z3Py uses a default global context. For most applications this is sufficient.
184 An application may use multiple Z3 contexts. Objects created in one context
185 cannot be used in another one. However, several objects may be "translated" from
186 one context to another. It is not safe to access Z3 objects from multiple threads.
187 The only exception is the method `interrupt()` that can be used to interrupt() a long
188 computation.
189 The initialization method receives global configuration options for the new context.
190 """
191
192 def __init__(self, *args, **kws):
193 if z3_debug():
194 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
195 conf = Z3_mk_config()
196 for key in kws:
197 value = kws[key]
198 Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
199 prev = None
200 for a in args:
201 if prev is None:
202 prev = a
203 else:
204 Z3_set_param_value(conf, str(prev), _to_param_value(a))
205 prev = None
207 self.owner = True
208 self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
209 Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
210 Z3_del_config(conf)
211
212 def __del__(self):
213 if Z3_del_context is not None and self.owner:
214 Z3_del_context(self.ctx)
215 self.ctx = None
216 self.eh = None
217
218 def ref(self):
219 """Return a reference to the actual C pointer to the Z3 context."""
220 return self.ctx
221
222 def interrupt(self):
223 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
224
225 This method can be invoked from a thread different from the one executing the
226 interruptible procedure.
227 """
228 Z3_interrupt(self.ref())
229
230 def param_descrs(self):
231 """Return the global parameter description set."""
232 return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self)
233
234
235# Global Z3 context
236_main_ctx = None
237
238
240 """Return a reference to the global Z3 context.
241
242 >>> x = Real('x')
243 >>> x.ctx == main_ctx()
244 True
245 >>> c = Context()
246 >>> c == main_ctx()
247 False
248 >>> x2 = Real('x', c)
249 >>> x2.ctx == c
250 True
251 >>> eq(x, x2)
252 False
253 """
254 global _main_ctx
255 if _main_ctx is None:
256 _main_ctx = Context()
257 return _main_ctx
258
259
260def _get_ctx(ctx):
261 if ctx is None:
262 return main_ctx()
263 else:
264 return ctx
265
266
267def get_ctx(ctx):
268 return _get_ctx(ctx)
269
270
271def set_param(*args, **kws):
272 """Set Z3 global (or module) parameters.
273
274 >>> set_param(precision=10)
275 """
276 if z3_debug():
277 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
278 new_kws = {}
279 for k in kws:
280 v = kws[k]
281 if not set_pp_option(k, v):
282 new_kws[k] = v
283 for key in new_kws:
284 value = new_kws[key]
285 Z3_global_param_set(str(key).upper(), _to_param_value(value))
286 prev = None
287 for a in args:
288 if prev is None:
289 prev = a
290 else:
292 prev = None
293
294
296 """Reset all global (or module) parameters.
297 """
299
300
301def set_option(*args, **kws):
302 """Alias for 'set_param' for backward compatibility.
303 """
304 return set_param(*args, **kws)
305
306
307def get_param(name):
308 """Return the value of a Z3 global (or module) parameter
309
310 >>> get_param('nlsat.reorder')
311 'true'
312 """
313 ptr = (ctypes.c_char_p * 1)()
314 if Z3_global_param_get(str(name), ptr):
315 r = z3core._to_pystr(ptr[0])
316 return r
317 raise Z3Exception("failed to retrieve value for '%s'" % name)
318
319
324
325# Mark objects that use pretty printer
326
327
329 """Superclass for all Z3 objects that have support for pretty printing."""
330
331 def use_pp(self):
332 return True
333
334 def _repr_html_(self):
335 in_html = in_html_mode()
336 set_html_mode(True)
337 res = repr(self)
338 set_html_mode(in_html)
339 return res
340
341
343 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
344
345 def __init__(self, ast, ctx=None):
346 self.ast = ast
347 self.ctx = _get_ctx(ctx)
348 Z3_inc_ref(self.ctx.ref(), self.as_ast())
349
350 def __del__(self):
351 if self.ctx.ref() is not None and self.ast is not None and Z3_dec_ref is not None:
352 Z3_dec_ref(self.ctx.ref(), self.as_ast())
353 self.ast = None
354
355 def __deepcopy__(self, memo={}):
356 return _to_ast_ref(self.ast, self.ctx)
357
358 def __str__(self):
359 return obj_to_string(self)
360
361 def __repr__(self):
362 return obj_to_string(self)
363
364 def __eq__(self, other):
365 return self.eq(other)
366
367 def __hash__(self):
368 return self.hash()
369
370 def __nonzero__(self):
371 return self.__bool__()
372
373 def __bool__(self):
374 if is_true(self):
375 return True
376 elif is_false(self):
377 return False
378 elif is_eq(self) and self.num_args() == 2:
379 return self.arg(0).eq(self.arg(1))
380 else:
381 raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
382
383 def sexpr(self):
384 """Return a string representing the AST node in s-expression notation.
385
386 >>> x = Int('x')
387 >>> ((x + 1)*x).sexpr()
388 '(* (+ x 1) x)'
389 """
390 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
391
392 def as_ast(self):
393 """Return a pointer to the corresponding C Z3_ast object."""
394 return self.ast
395
396 def get_id(self):
397 """Return unique identifier for object. It can be used for hash-tables and maps."""
398 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
399
400 def ctx_ref(self):
401 """Return a reference to the C context where this AST node is stored."""
402 return self.ctx.ref()
403
404 def eq(self, other):
405 """Return `True` if `self` and `other` are structurally identical.
406
407 >>> x = Int('x')
408 >>> n1 = x + 1
409 >>> n2 = 1 + x
410 >>> n1.eq(n2)
411 False
412 >>> n1 = simplify(n1)
413 >>> n2 = simplify(n2)
414 >>> n1.eq(n2)
415 True
416 """
417 if z3_debug():
418 _z3_assert(is_ast(other), "Z3 AST expected")
419 return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
420
421 def translate(self, target):
422 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
423
424 >>> c1 = Context()
425 >>> c2 = Context()
426 >>> x = Int('x', c1)
427 >>> y = Int('y', c2)
428 >>> # Nodes in different contexts can't be mixed.
429 >>> # However, we can translate nodes from one context to another.
430 >>> x.translate(c2) + y
431 x + y
432 """
433 if z3_debug():
434 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
435 return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
436
437 def __copy__(self):
438 return self.translate(self.ctx)
439
440 def hash(self):
441 """Return a hashcode for the `self`.
442
443 >>> n1 = simplify(Int('x') + 1)
444 >>> n2 = simplify(2 + Int('x') - 1)
445 >>> n1.hash() == n2.hash()
446 True
447 """
448 return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
449
450
451def is_ast(a):
452 """Return `True` if `a` is an AST node.
453
454 >>> is_ast(10)
455 False
456 >>> is_ast(IntVal(10))
457 True
458 >>> is_ast(Int('x'))
459 True
460 >>> is_ast(BoolSort())
461 True
462 >>> is_ast(Function('f', IntSort(), IntSort()))
463 True
464 >>> is_ast("x")
465 False
466 >>> is_ast(Solver())
467 False
468 """
469 return isinstance(a, AstRef)
470
471
472def eq(a, b):
473 """Return `True` if `a` and `b` are structurally identical AST nodes.
474
475 >>> x = Int('x')
476 >>> y = Int('y')
477 >>> eq(x, y)
478 False
479 >>> eq(x + 1, x + 1)
480 True
481 >>> eq(x + 1, 1 + x)
482 False
483 >>> eq(simplify(x + 1), simplify(1 + x))
484 True
485 """
486 if z3_debug():
487 _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
488 return a.eq(b)
489
490
491def _ast_kind(ctx, a):
492 if is_ast(a):
493 a = a.as_ast()
494 return Z3_get_ast_kind(ctx.ref(), a)
495
496
497def _ctx_from_ast_arg_list(args, default_ctx=None):
498 ctx = None
499 for a in args:
500 if is_ast(a) or is_probe(a):
501 if ctx is None:
502 ctx = a.ctx
503 else:
504 if z3_debug():
505 _z3_assert(ctx == a.ctx, "Context mismatch")
506 if ctx is None:
507 ctx = default_ctx
508 return ctx
509
510
512 return _ctx_from_ast_arg_list(args)
513
514
516 sz = len(args)
517 _args = (FuncDecl * sz)()
518 for i in range(sz):
519 _args[i] = args[i].as_func_decl()
520 return _args, sz
521
522
524 sz = len(args)
525 _args = (Ast * sz)()
526 for i in range(sz):
527 _args[i] = args[i].as_ast()
528 return _args, sz
529
530
531def _to_ref_array(ref, args):
532 sz = len(args)
533 _args = (ref * sz)()
534 for i in range(sz):
535 _args[i] = args[i].as_ast()
536 return _args, sz
537
538
539def _to_ast_ref(a, ctx):
540 k = _ast_kind(ctx, a)
541 if k == Z3_SORT_AST:
542 return _to_sort_ref(a, ctx)
543 elif k == Z3_FUNC_DECL_AST:
544 return _to_func_decl_ref(a, ctx)
545 else:
546 return _to_expr_ref(a, ctx)
547
548
549
554
555def _sort_kind(ctx, s):
556 return Z3_get_sort_kind(ctx.ref(), s)
557
558
560 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
561
562 def as_ast(self):
563 return Z3_sort_to_ast(self.ctx_ref(), self.ast)
564
565 def get_id(self):
566 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
567
568 def kind(self):
569 """Return the Z3 internal kind of a sort.
570 This method can be used to test if `self` is one of the Z3 builtin sorts.
571
572 >>> b = BoolSort()
573 >>> b.kind() == Z3_BOOL_SORT
574 True
575 >>> b.kind() == Z3_INT_SORT
576 False
577 >>> A = ArraySort(IntSort(), IntSort())
578 >>> A.kind() == Z3_ARRAY_SORT
579 True
580 >>> A.kind() == Z3_INT_SORT
581 False
582 """
583 return _sort_kind(self.ctx, self.ast)
584
585 def subsort(self, other):
586 """Return `True` if `self` is a subsort of `other`.
587
588 >>> IntSort().subsort(RealSort())
589 True
590 """
591 return False
592
593 def cast(self, val):
594 """Try to cast `val` as an element of sort `self`.
595
596 This method is used in Z3Py to convert Python objects such as integers,
597 floats, longs and strings into Z3 expressions.
598
599 >>> x = Int('x')
600 >>> RealSort().cast(x)
601 ToReal(x)
602 """
603 if z3_debug():
604 _z3_assert(is_expr(val), "Z3 expression expected")
605 _z3_assert(self.eq(val.sort()), "Sort mismatch")
606 return val
607
608 def name(self):
609 """Return the name (string) of sort `self`.
610
611 >>> BoolSort().name()
612 'Bool'
613 >>> ArraySort(IntSort(), IntSort()).name()
614 'Array'
615 """
616 return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
617
618 def __eq__(self, other):
619 """Return `True` if `self` and `other` are the same Z3 sort.
620
621 >>> p = Bool('p')
622 >>> p.sort() == BoolSort()
623 True
624 >>> p.sort() == IntSort()
625 False
626 """
627 if other is None:
628 return False
629 return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
630
631 def __ne__(self, other):
632 """Return `True` if `self` and `other` are not the same Z3 sort.
633
634 >>> p = Bool('p')
635 >>> p.sort() != BoolSort()
636 False
637 >>> p.sort() != IntSort()
638 True
639 """
640 return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
641
642 def __hash__(self):
643 """ Hash code. """
644 return AstRef.__hash__(self)
645
646
647def is_sort(s):
648 """Return `True` if `s` is a Z3 sort.
649
650 >>> is_sort(IntSort())
651 True
652 >>> is_sort(Int('x'))
653 False
654 >>> is_expr(Int('x'))
655 True
656 """
657 return isinstance(s, SortRef)
658
659
660def _to_sort_ref(s, ctx):
661 if z3_debug():
662 _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
663 k = _sort_kind(ctx, s)
664 if k == Z3_BOOL_SORT:
665 return BoolSortRef(s, ctx)
666 elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
667 return ArithSortRef(s, ctx)
668 elif k == Z3_BV_SORT:
669 return BitVecSortRef(s, ctx)
670 elif k == Z3_ARRAY_SORT:
671 return ArraySortRef(s, ctx)
672 elif k == Z3_DATATYPE_SORT:
673 return DatatypeSortRef(s, ctx)
674 elif k == Z3_FINITE_DOMAIN_SORT:
675 return FiniteDomainSortRef(s, ctx)
676 elif k == Z3_FLOATING_POINT_SORT:
677 return FPSortRef(s, ctx)
678 elif k == Z3_ROUNDING_MODE_SORT:
679 return FPRMSortRef(s, ctx)
680 elif k == Z3_RE_SORT:
681 return ReSortRef(s, ctx)
682 elif k == Z3_SEQ_SORT:
683 return SeqSortRef(s, ctx)
684 elif k == Z3_CHAR_SORT:
685 return CharSortRef(s, ctx)
686 return SortRef(s, ctx)
687
688
689def _sort(ctx, a):
690 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
691
692
693def DeclareSort(name, ctx=None):
694 """Create a new uninterpreted sort named `name`.
695
696 If `ctx=None`, then the new sort is declared in the global Z3Py context.
697
698 >>> A = DeclareSort('A')
699 >>> a = Const('a', A)
700 >>> b = Const('b', A)
701 >>> a.sort() == A
702 True
703 >>> b.sort() == A
704 True
705 >>> a == b
706 a == b
707 """
708 ctx = _get_ctx(ctx)
709 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
710
711
716
717
719 """Function declaration. Every constant and function have an associated declaration.
720
721 The declaration assigns a name, a sort (i.e., type), and for function
722 the sort (i.e., type) of each of its arguments. Note that, in Z3,
723 a constant is a function with 0 arguments.
724 """
725
726 def as_ast(self):
727 return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
728
729 def get_id(self):
730 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
731
732 def as_func_decl(self):
733 return self.ast
734
735 def name(self):
736 """Return the name of the function declaration `self`.
737
738 >>> f = Function('f', IntSort(), IntSort())
739 >>> f.name()
740 'f'
741 >>> isinstance(f.name(), str)
742 True
743 """
744 return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
745
746 def arity(self):
747 """Return the number of arguments of a function declaration.
748 If `self` is a constant, then `self.arity()` is 0.
749
750 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
751 >>> f.arity()
752 2
753 """
754 return int(Z3_get_arity(self.ctx_ref(), self.ast))
755
756 def domain(self, i):
757 """Return the sort of the argument `i` of a function declaration.
758 This method assumes that `0 <= i < self.arity()`.
759
760 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
761 >>> f.domain(0)
762 Int
763 >>> f.domain(1)
764 Real
765 """
766 if z3_debug():
767 _z3_assert(i < self.arity(), "Index out of bounds")
768 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
769
770 def range(self):
771 """Return the sort of the range of a function declaration.
772 For constants, this is the sort of the constant.
773
774 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
775 >>> f.range()
776 Bool
777 """
778 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
779
780 def kind(self):
781 """Return the internal kind of a function declaration.
782 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
783
784 >>> x = Int('x')
785 >>> d = (x + 1).decl()
786 >>> d.kind() == Z3_OP_ADD
787 True
788 >>> d.kind() == Z3_OP_MUL
789 False
790 """
791 return Z3_get_decl_kind(self.ctx_ref(), self.ast)
792
793 def params(self):
794 ctx = self.ctx
795 n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
796 result = [None for i in range(n)]
797 for i in range(n):
798 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
799 if k == Z3_PARAMETER_INT:
800 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
801 elif k == Z3_PARAMETER_DOUBLE:
802 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
803 elif k == Z3_PARAMETER_RATIONAL:
804 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
805 elif k == Z3_PARAMETER_SYMBOL:
806 result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
807 elif k == Z3_PARAMETER_SORT:
808 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
809 elif k == Z3_PARAMETER_AST:
810 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
811 elif k == Z3_PARAMETER_FUNC_DECL:
812 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
813 else:
814 assert(False)
815 return result
816
817 def __call__(self, *args):
818 """Create a Z3 application expression using the function `self`, and the given arguments.
819
820 The arguments must be Z3 expressions. This method assumes that
821 the sorts of the elements in `args` match the sorts of the
822 domain. Limited coercion is supported. For example, if
823 args[0] is a Python integer, and the function expects a Z3
824 integer, then the argument is automatically converted into a
825 Z3 integer.
826
827 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
828 >>> x = Int('x')
829 >>> y = Real('y')
830 >>> f(x, y)
831 f(x, y)
832 >>> f(x, x)
833 f(x, ToReal(x))
834 """
835 args = _get_args(args)
836 num = len(args)
837 if z3_debug():
838 _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
839 _args = (Ast * num)()
840 saved = []
841 for i in range(num):
842 # self.domain(i).cast(args[i]) may create a new Z3 expression,
843 # then we must save in 'saved' to prevent it from being garbage collected.
844 tmp = self.domain(i).cast(args[i])
845 saved.append(tmp)
846 _args[i] = tmp.as_ast()
847 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
848
849
851 """Return `True` if `a` is a Z3 function declaration.
852
853 >>> f = Function('f', IntSort(), IntSort())
854 >>> is_func_decl(f)
855 True
856 >>> x = Real('x')
857 >>> is_func_decl(x)
858 False
859 """
860 return isinstance(a, FuncDeclRef)
861
862
863def Function(name, *sig):
864 """Create a new Z3 uninterpreted function with the given sorts.
865
866 >>> f = Function('f', IntSort(), IntSort())
867 >>> f(f(0))
868 f(f(0))
869 """
870 sig = _get_args(sig)
871 if z3_debug():
872 _z3_assert(len(sig) > 0, "At least two arguments expected")
873 arity = len(sig) - 1
874 rng = sig[arity]
875 if z3_debug():
876 _z3_assert(is_sort(rng), "Z3 sort expected")
877 dom = (Sort * arity)()
878 for i in range(arity):
879 if z3_debug():
880 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
881 dom[i] = sig[i].ast
882 ctx = rng.ctx
883 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
884
885
887 """Create a new fresh Z3 uninterpreted function with the given sorts.
888 """
889 sig = _get_args(sig)
890 if z3_debug():
891 _z3_assert(len(sig) > 0, "At least two arguments expected")
892 arity = len(sig) - 1
893 rng = sig[arity]
894 if z3_debug():
895 _z3_assert(is_sort(rng), "Z3 sort expected")
896 dom = (z3.Sort * arity)()
897 for i in range(arity):
898 if z3_debug():
899 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
900 dom[i] = sig[i].ast
901 ctx = rng.ctx
902 return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
903
904
906 return FuncDeclRef(a, ctx)
907
908
909def RecFunction(name, *sig):
910 """Create a new Z3 recursive with the given sorts."""
911 sig = _get_args(sig)
912 if z3_debug():
913 _z3_assert(len(sig) > 0, "At least two arguments expected")
914 arity = len(sig) - 1
915 rng = sig[arity]
916 if z3_debug():
917 _z3_assert(is_sort(rng), "Z3 sort expected")
918 dom = (Sort * arity)()
919 for i in range(arity):
920 if z3_debug():
921 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
922 dom[i] = sig[i].ast
923 ctx = rng.ctx
924 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
925
926
927def RecAddDefinition(f, args, body):
928 """Set the body of a recursive function.
929 Recursive definitions can be simplified if they are applied to ground
930 arguments.
931 >>> ctx = Context()
932 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
933 >>> n = Int('n', ctx)
934 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
935 >>> simplify(fac(5))
936 120
937 >>> s = Solver(ctx=ctx)
938 >>> s.add(fac(n) < 3)
939 >>> s.check()
940 sat
941 >>> s.model().eval(fac(5))
942 120
943 """
944 if is_app(args):
945 args = [args]
946 ctx = body.ctx
947 args = _get_args(args)
948 n = len(args)
949 _args = (Ast * n)()
950 for i in range(n):
951 _args[i] = args[i].ast
952 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
953
954
959
960
962 """Constraints, formulas and terms are expressions in Z3.
963
964 Expressions are ASTs. Every expression has a sort.
965 There are three main kinds of expressions:
966 function applications, quantifiers and bounded variables.
967 A constant is a function application with 0 arguments.
968 For quantifier free problems, all expressions are
969 function applications.
970 """
971
972 def as_ast(self):
973 return self.ast
974
975 def get_id(self):
976 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
977
978 def sort(self):
979 """Return the sort of expression `self`.
980
981 >>> x = Int('x')
982 >>> (x + 1).sort()
983 Int
984 >>> y = Real('y')
985 >>> (x + y).sort()
986 Real
987 """
988 return _sort(self.ctx, self.as_astas_ast())
989
990 def sort_kind(self):
991 """Shorthand for `self.sort().kind()`.
992
993 >>> a = Array('a', IntSort(), IntSort())
994 >>> a.sort_kind() == Z3_ARRAY_SORT
995 True
996 >>> a.sort_kind() == Z3_INT_SORT
997 False
998 """
999 return self.sort().kind()
1000
1001 def __eq__(self, other):
1002 """Return a Z3 expression that represents the constraint `self == other`.
1003
1004 If `other` is `None`, then this method simply returns `False`.
1005
1006 >>> a = Int('a')
1007 >>> b = Int('b')
1008 >>> a == b
1009 a == b
1010 >>> a is None
1011 False
1012 """
1013 if other is None:
1014 return False
1015 a, b = _coerce_exprs(self, other)
1016 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
1017
1018 def __hash__(self):
1019 """ Hash code. """
1020 return AstRef.__hash__(self)
1021
1022 def __ne__(self, other):
1023 """Return a Z3 expression that represents the constraint `self != other`.
1024
1025 If `other` is `None`, then this method simply returns `True`.
1026
1027 >>> a = Int('a')
1028 >>> b = Int('b')
1029 >>> a != b
1030 a != b
1031 >>> a is not None
1032 True
1033 """
1034 if other is None:
1035 return True
1036 a, b = _coerce_exprs(self, other)
1037 _args, sz = _to_ast_array((a, b))
1038 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
1039
1040 def params(self):
1041 return self.decl().params()
1042
1043 def decl(self):
1044 """Return the Z3 function declaration associated with a Z3 application.
1045
1046 >>> f = Function('f', IntSort(), IntSort())
1047 >>> a = Int('a')
1048 >>> t = f(a)
1049 >>> eq(t.decl(), f)
1050 True
1051 >>> (a + 1).decl()
1052 +
1053 """
1054 if z3_debug():
1055 _z3_assert(is_app(self), "Z3 application expected")
1056 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1057
1058 def num_args(self):
1059 """Return the number of arguments of a Z3 application.
1060
1061 >>> a = Int('a')
1062 >>> b = Int('b')
1063 >>> (a + b).num_args()
1064 2
1065 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1066 >>> t = f(a, b, 0)
1067 >>> t.num_args()
1068 3
1069 """
1070 if z3_debug():
1071 _z3_assert(is_app(self), "Z3 application expected")
1072 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_astas_ast()))
1073
1074 def arg(self, idx):
1075 """Return argument `idx` of the application `self`.
1076
1077 This method assumes that `self` is a function application with at least `idx+1` arguments.
1078
1079 >>> a = Int('a')
1080 >>> b = Int('b')
1081 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1082 >>> t = f(a, b, 0)
1083 >>> t.arg(0)
1084 a
1085 >>> t.arg(1)
1086 b
1087 >>> t.arg(2)
1088 0
1089 """
1090 if z3_debug():
1091 _z3_assert(is_app(self), "Z3 application expected")
1092 _z3_assert(idx < self.num_args(), "Invalid argument index")
1093 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_astas_ast(), idx), self.ctx)
1094
1095 def children(self):
1096 """Return a list containing the children of the given expression
1097
1098 >>> a = Int('a')
1099 >>> b = Int('b')
1100 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1101 >>> t = f(a, b, 0)
1102 >>> t.children()
1103 [a, b, 0]
1104 """
1105 if is_app(self):
1106 return [self.arg(i) for i in range(self.num_args())]
1107 else:
1108 return []
1109
1110 def from_string(self, s):
1111 pass
1112
1113 def serialize(self):
1114 s = Solver()
1115 f = Function('F', self.sort(), BoolSort(self.ctx))
1116 s.add(f(self))
1117 return s.sexpr()
1118
1120 """inverse function to the serialize method on ExprRef.
1121 It is made available to make it easier for users to serialize expressions back and forth between
1122 strings. Solvers can be serialized using the 'sexpr()' method.
1123 """
1124 s = Solver()
1125 s.from_string(st)
1126 if len(s.assertions()) != 1:
1127 raise Z3Exception("single assertion expected")
1128 fml = s.assertions()[0]
1129 if fml.num_args() != 1:
1130 raise Z3Exception("dummy function 'F' expected")
1131 return fml.arg(0)
1132
1133def _to_expr_ref(a, ctx):
1134 if isinstance(a, Pattern):
1135 return PatternRef(a, ctx)
1136 ctx_ref = ctx.ref()
1137 k = Z3_get_ast_kind(ctx_ref, a)
1138 if k == Z3_QUANTIFIER_AST:
1139 return QuantifierRef(a, ctx)
1140 sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1141 if sk == Z3_BOOL_SORT:
1142 return BoolRef(a, ctx)
1143 if sk == Z3_INT_SORT:
1144 if k == Z3_NUMERAL_AST:
1145 return IntNumRef(a, ctx)
1146 return ArithRef(a, ctx)
1147 if sk == Z3_REAL_SORT:
1148 if k == Z3_NUMERAL_AST:
1149 return RatNumRef(a, ctx)
1150 if _is_algebraic(ctx, a):
1151 return AlgebraicNumRef(a, ctx)
1152 return ArithRef(a, ctx)
1153 if sk == Z3_BV_SORT:
1154 if k == Z3_NUMERAL_AST:
1155 return BitVecNumRef(a, ctx)
1156 else:
1157 return BitVecRef(a, ctx)
1158 if sk == Z3_ARRAY_SORT:
1159 return ArrayRef(a, ctx)
1160 if sk == Z3_DATATYPE_SORT:
1161 return DatatypeRef(a, ctx)
1162 if sk == Z3_FLOATING_POINT_SORT:
1163 if k == Z3_APP_AST and _is_numeral(ctx, a):
1164 return FPNumRef(a, ctx)
1165 else:
1166 return FPRef(a, ctx)
1167 if sk == Z3_FINITE_DOMAIN_SORT:
1168 if k == Z3_NUMERAL_AST:
1169 return FiniteDomainNumRef(a, ctx)
1170 else:
1171 return FiniteDomainRef(a, ctx)
1172 if sk == Z3_ROUNDING_MODE_SORT:
1173 return FPRMRef(a, ctx)
1174 if sk == Z3_SEQ_SORT:
1175 return SeqRef(a, ctx)
1176 if sk == Z3_CHAR_SORT:
1177 return CharRef(a, ctx)
1178 if sk == Z3_RE_SORT:
1179 return ReRef(a, ctx)
1180 return ExprRef(a, ctx)
1181
1182
1184 if is_expr(a):
1185 s1 = a.sort()
1186 if s is None:
1187 return s1
1188 if s1.eq(s):
1189 return s
1190 elif s.subsort(s1):
1191 return s1
1192 elif s1.subsort(s):
1193 return s
1194 else:
1195 if z3_debug():
1196 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1197 _z3_assert(False, "sort mismatch")
1198 else:
1199 return s
1200
1201
1202def _coerce_exprs(a, b, ctx=None):
1203 if not is_expr(a) and not is_expr(b):
1204 a = _py2expr(a, ctx)
1205 b = _py2expr(b, ctx)
1206 if isinstance(a, str) and isinstance(b, SeqRef):
1207 a = StringVal(a, b.ctx)
1208 if isinstance(b, str) and isinstance(a, SeqRef):
1209 b = StringVal(b, a.ctx)
1210 if isinstance(a, float) and isinstance(b, ArithRef):
1211 a = RealVal(a, b.ctx)
1212 if isinstance(b, float) and isinstance(a, ArithRef):
1213 b = RealVal(b, a.ctx)
1214
1215 s = None
1216 s = _coerce_expr_merge(s, a)
1217 s = _coerce_expr_merge(s, b)
1218 a = s.cast(a)
1219 b = s.cast(b)
1220 return (a, b)
1221
1222
1223def _reduce(func, sequence, initial):
1224 result = initial
1225 for element in sequence:
1226 result = func(result, element)
1227 return result
1228
1229
1230def _coerce_expr_list(alist, ctx=None):
1231 has_expr = False
1232 for a in alist:
1233 if is_expr(a):
1234 has_expr = True
1235 break
1236 if not has_expr:
1237 alist = [_py2expr(a, ctx) for a in alist]
1238 s = _reduce(_coerce_expr_merge, alist, None)
1239 return [s.cast(a) for a in alist]
1240
1241
1242def is_expr(a):
1243 """Return `True` if `a` is a Z3 expression.
1244
1245 >>> a = Int('a')
1246 >>> is_expr(a)
1247 True
1248 >>> is_expr(a + 1)
1249 True
1250 >>> is_expr(IntSort())
1251 False
1252 >>> is_expr(1)
1253 False
1254 >>> is_expr(IntVal(1))
1255 True
1256 >>> x = Int('x')
1257 >>> is_expr(ForAll(x, x >= 0))
1258 True
1259 >>> is_expr(FPVal(1.0))
1260 True
1261 """
1262 return isinstance(a, ExprRef)
1263
1264
1265def is_app(a):
1266 """Return `True` if `a` is a Z3 function application.
1267
1268 Note that, constants are function applications with 0 arguments.
1269
1270 >>> a = Int('a')
1271 >>> is_app(a)
1272 True
1273 >>> is_app(a + 1)
1274 True
1275 >>> is_app(IntSort())
1276 False
1277 >>> is_app(1)
1278 False
1279 >>> is_app(IntVal(1))
1280 True
1281 >>> x = Int('x')
1282 >>> is_app(ForAll(x, x >= 0))
1283 False
1284 """
1285 if not isinstance(a, ExprRef):
1286 return False
1287 k = _ast_kind(a.ctx, a)
1288 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1289
1290
1292 """Return `True` if `a` is Z3 constant/variable expression.
1293
1294 >>> a = Int('a')
1295 >>> is_const(a)
1296 True
1297 >>> is_const(a + 1)
1298 False
1299 >>> is_const(1)
1300 False
1301 >>> is_const(IntVal(1))
1302 True
1303 >>> x = Int('x')
1304 >>> is_const(ForAll(x, x >= 0))
1305 False
1306 """
1307 return is_app(a) and a.num_args() == 0
1308
1309
1310def is_var(a):
1311 """Return `True` if `a` is variable.
1312
1313 Z3 uses de-Bruijn indices for representing bound variables in
1314 quantifiers.
1315
1316 >>> x = Int('x')
1317 >>> is_var(x)
1318 False
1319 >>> is_const(x)
1320 True
1321 >>> f = Function('f', IntSort(), IntSort())
1322 >>> # Z3 replaces x with bound variables when ForAll is executed.
1323 >>> q = ForAll(x, f(x) == x)
1324 >>> b = q.body()
1325 >>> b
1326 f(Var(0)) == Var(0)
1327 >>> b.arg(1)
1328 Var(0)
1329 >>> is_var(b.arg(1))
1330 True
1331 """
1332 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1333
1334
1336 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1337
1338 >>> x = Int('x')
1339 >>> y = Int('y')
1340 >>> is_var(x)
1341 False
1342 >>> is_const(x)
1343 True
1344 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1345 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1346 >>> q = ForAll([x, y], f(x, y) == x + y)
1347 >>> q.body()
1348 f(Var(1), Var(0)) == Var(1) + Var(0)
1349 >>> b = q.body()
1350 >>> b.arg(0)
1351 f(Var(1), Var(0))
1352 >>> v1 = b.arg(0).arg(0)
1353 >>> v2 = b.arg(0).arg(1)
1354 >>> v1
1355 Var(1)
1356 >>> v2
1357 Var(0)
1358 >>> get_var_index(v1)
1359 1
1360 >>> get_var_index(v2)
1361 0
1362 """
1363 if z3_debug():
1364 _z3_assert(is_var(a), "Z3 bound variable expected")
1365 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1366
1367
1368def is_app_of(a, k):
1369 """Return `True` if `a` is an application of the given kind `k`.
1370
1371 >>> x = Int('x')
1372 >>> n = x + 1
1373 >>> is_app_of(n, Z3_OP_ADD)
1374 True
1375 >>> is_app_of(n, Z3_OP_MUL)
1376 False
1377 """
1378 return is_app(a) and a.decl().kind() == k
1379
1380
1381def If(a, b, c, ctx=None):
1382 """Create a Z3 if-then-else expression.
1383
1384 >>> x = Int('x')
1385 >>> y = Int('y')
1386 >>> max = If(x > y, x, y)
1387 >>> max
1388 If(x > y, x, y)
1389 >>> simplify(max)
1390 If(x <= y, y, x)
1391 """
1392 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1393 return Cond(a, b, c, ctx)
1394 else:
1395 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1396 s = BoolSort(ctx)
1397 a = s.cast(a)
1398 b, c = _coerce_exprs(b, c, ctx)
1399 if z3_debug():
1400 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1401 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1402
1403
1404def Distinct(*args):
1405 """Create a Z3 distinct expression.
1406
1407 >>> x = Int('x')
1408 >>> y = Int('y')
1409 >>> Distinct(x, y)
1410 x != y
1411 >>> z = Int('z')
1412 >>> Distinct(x, y, z)
1413 Distinct(x, y, z)
1414 >>> simplify(Distinct(x, y, z))
1415 Distinct(x, y, z)
1416 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1417 And(Not(x == y), Not(x == z), Not(y == z))
1418 """
1419 args = _get_args(args)
1420 ctx = _ctx_from_ast_arg_list(args)
1421 if z3_debug():
1422 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1423 args = _coerce_expr_list(args, ctx)
1424 _args, sz = _to_ast_array(args)
1425 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1426
1427
1428def _mk_bin(f, a, b):
1429 args = (Ast * 2)()
1430 if z3_debug():
1431 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1432 args[0] = a.as_ast()
1433 args[1] = b.as_ast()
1434 return f(a.ctx.ref(), 2, args)
1435
1436
1437def Const(name, sort):
1438 """Create a constant of the given sort.
1439
1440 >>> Const('x', IntSort())
1441 x
1442 """
1443 if z3_debug():
1444 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1445 ctx = sort.ctx
1446 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1447
1448
1449def Consts(names, sort):
1450 """Create several constants of the given sort.
1451
1452 `names` is a string containing the names of all constants to be created.
1453 Blank spaces separate the names of different constants.
1454
1455 >>> x, y, z = Consts('x y z', IntSort())
1456 >>> x + y + z
1457 x + y + z
1458 """
1459 if isinstance(names, str):
1460 names = names.split(" ")
1461 return [Const(name, sort) for name in names]
1462
1463
1464def FreshConst(sort, prefix="c"):
1465 """Create a fresh constant of a specified sort"""
1466 ctx = _get_ctx(sort.ctx)
1467 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1468
1469
1470def Var(idx, s):
1471 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1472 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1473 declarations.
1474
1475 >>> Var(0, IntSort())
1476 Var(0)
1477 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1478 False
1479 """
1480 if z3_debug():
1481 _z3_assert(is_sort(s), "Z3 sort expected")
1482 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1483
1484
1485def RealVar(idx, ctx=None):
1486 """
1487 Create a real free variable. Free variables are used to create quantified formulas.
1488 They are also used to create polynomials.
1489
1490 >>> RealVar(0)
1491 Var(0)
1492 """
1493 return Var(idx, RealSort(ctx))
1494
1495
1496def RealVarVector(n, ctx=None):
1497 """
1498 Create a list of Real free variables.
1499 The variables have ids: 0, 1, ..., n-1
1500
1501 >>> x0, x1, x2, x3 = RealVarVector(4)
1502 >>> x2
1503 Var(2)
1504 """
1505 return [RealVar(i, ctx) for i in range(n)]
1506
1507
1512
1513
1515 """Boolean sort."""
1516
1517 def cast(self, val):
1518 """Try to cast `val` as a Boolean.
1519
1520 >>> x = BoolSort().cast(True)
1521 >>> x
1522 True
1523 >>> is_expr(x)
1524 True
1525 >>> is_expr(True)
1526 False
1527 >>> x.sort()
1528 Bool
1529 """
1530 if isinstance(val, bool):
1531 return BoolVal(val, self.ctx)
1532 if z3_debug():
1533 if not is_expr(val):
1534 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1535 _z3_assert(is_expr(val), msg % (val, type(val)))
1536 if not self.eq(val.sort()):
1537 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1538 return val
1539
1540 def subsort(self, other):
1541 return isinstance(other, ArithSortRef)
1542
1543 def is_int(self):
1544 return True
1545
1546 def is_bool(self):
1547 return True
1548
1549
1551 """All Boolean expressions are instances of this class."""
1552
1553 def sort(self):
1554 return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1555
1556 def __rmul__(self, other):
1557 return self * other
1558
1559 def __mul__(self, other):
1560 """Create the Z3 expression `self * other`.
1561 """
1562 if isinstance(other, int) and other == 1:
1563 return If(self, 1, 0)
1564 if isinstance(other, int) and other == 0:
1565 return IntVal(0, self.ctx)
1566 if isinstance(other, BoolRef):
1567 other = If(other, 1, 0)
1568 return If(self, other, 0)
1569
1570
1571def is_bool(a):
1572 """Return `True` if `a` is a Z3 Boolean expression.
1573
1574 >>> p = Bool('p')
1575 >>> is_bool(p)
1576 True
1577 >>> q = Bool('q')
1578 >>> is_bool(And(p, q))
1579 True
1580 >>> x = Real('x')
1581 >>> is_bool(x)
1582 False
1583 >>> is_bool(x == 0)
1584 True
1585 """
1586 return isinstance(a, BoolRef)
1587
1588
1589def is_true(a):
1590 """Return `True` if `a` is the Z3 true expression.
1591
1592 >>> p = Bool('p')
1593 >>> is_true(p)
1594 False
1595 >>> is_true(simplify(p == p))
1596 True
1597 >>> x = Real('x')
1598 >>> is_true(x == 0)
1599 False
1600 >>> # True is a Python Boolean expression
1601 >>> is_true(True)
1602 False
1603 """
1604 return is_app_of(a, Z3_OP_TRUE)
1605
1606
1608 """Return `True` if `a` is the Z3 false expression.
1609
1610 >>> p = Bool('p')
1611 >>> is_false(p)
1612 False
1613 >>> is_false(False)
1614 False
1615 >>> is_false(BoolVal(False))
1616 True
1617 """
1618 return is_app_of(a, Z3_OP_FALSE)
1619
1620
1621def is_and(a):
1622 """Return `True` if `a` is a Z3 and expression.
1623
1624 >>> p, q = Bools('p q')
1625 >>> is_and(And(p, q))
1626 True
1627 >>> is_and(Or(p, q))
1628 False
1629 """
1630 return is_app_of(a, Z3_OP_AND)
1631
1632
1633def is_or(a):
1634 """Return `True` if `a` is a Z3 or expression.
1635
1636 >>> p, q = Bools('p q')
1637 >>> is_or(Or(p, q))
1638 True
1639 >>> is_or(And(p, q))
1640 False
1641 """
1642 return is_app_of(a, Z3_OP_OR)
1643
1644
1646 """Return `True` if `a` is a Z3 implication expression.
1647
1648 >>> p, q = Bools('p q')
1649 >>> is_implies(Implies(p, q))
1650 True
1651 >>> is_implies(And(p, q))
1652 False
1653 """
1654 return is_app_of(a, Z3_OP_IMPLIES)
1655
1656
1657def is_not(a):
1658 """Return `True` if `a` is a Z3 not expression.
1659
1660 >>> p = Bool('p')
1661 >>> is_not(p)
1662 False
1663 >>> is_not(Not(p))
1664 True
1665 """
1666 return is_app_of(a, Z3_OP_NOT)
1667
1668
1669def is_eq(a):
1670 """Return `True` if `a` is a Z3 equality expression.
1671
1672 >>> x, y = Ints('x y')
1673 >>> is_eq(x == y)
1674 True
1675 """
1676 return is_app_of(a, Z3_OP_EQ)
1677
1678
1680 """Return `True` if `a` is a Z3 distinct expression.
1681
1682 >>> x, y, z = Ints('x y z')
1683 >>> is_distinct(x == y)
1684 False
1685 >>> is_distinct(Distinct(x, y, z))
1686 True
1687 """
1688 return is_app_of(a, Z3_OP_DISTINCT)
1689
1690
1691def BoolSort(ctx=None):
1692 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1693
1694 >>> BoolSort()
1695 Bool
1696 >>> p = Const('p', BoolSort())
1697 >>> is_bool(p)
1698 True
1699 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1700 >>> r(0, 1)
1701 r(0, 1)
1702 >>> is_bool(r(0, 1))
1703 True
1704 """
1705 ctx = _get_ctx(ctx)
1706 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1707
1708
1709def BoolVal(val, ctx=None):
1710 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1711
1712 >>> BoolVal(True)
1713 True
1714 >>> is_true(BoolVal(True))
1715 True
1716 >>> is_true(True)
1717 False
1718 >>> is_false(BoolVal(False))
1719 True
1720 """
1721 ctx = _get_ctx(ctx)
1722 if val:
1723 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1724 else:
1725 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1726
1727
1728def Bool(name, ctx=None):
1729 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1730
1731 >>> p = Bool('p')
1732 >>> q = Bool('q')
1733 >>> And(p, q)
1734 And(p, q)
1735 """
1736 ctx = _get_ctx(ctx)
1737 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1738
1739
1740def Bools(names, ctx=None):
1741 """Return a tuple of Boolean constants.
1742
1743 `names` is a single string containing all names separated by blank spaces.
1744 If `ctx=None`, then the global context is used.
1745
1746 >>> p, q, r = Bools('p q r')
1747 >>> And(p, Or(q, r))
1748 And(p, Or(q, r))
1749 """
1750 ctx = _get_ctx(ctx)
1751 if isinstance(names, str):
1752 names = names.split(" ")
1753 return [Bool(name, ctx) for name in names]
1754
1755
1756def BoolVector(prefix, sz, ctx=None):
1757 """Return a list of Boolean constants of size `sz`.
1758
1759 The constants are named using the given prefix.
1760 If `ctx=None`, then the global context is used.
1761
1762 >>> P = BoolVector('p', 3)
1763 >>> P
1764 [p__0, p__1, p__2]
1765 >>> And(P)
1766 And(p__0, p__1, p__2)
1767 """
1768 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1769
1770
1771def FreshBool(prefix="b", ctx=None):
1772 """Return a fresh Boolean constant in the given context using the given prefix.
1773
1774 If `ctx=None`, then the global context is used.
1775
1776 >>> b1 = FreshBool()
1777 >>> b2 = FreshBool()
1778 >>> eq(b1, b2)
1779 False
1780 """
1781 ctx = _get_ctx(ctx)
1782 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1783
1784
1785def Implies(a, b, ctx=None):
1786 """Create a Z3 implies expression.
1787
1788 >>> p, q = Bools('p q')
1789 >>> Implies(p, q)
1790 Implies(p, q)
1791 """
1792 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1793 s = BoolSort(ctx)
1794 a = s.cast(a)
1795 b = s.cast(b)
1796 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1797
1798
1799def Xor(a, b, ctx=None):
1800 """Create a Z3 Xor expression.
1801
1802 >>> p, q = Bools('p q')
1803 >>> Xor(p, q)
1804 Xor(p, q)
1805 >>> simplify(Xor(p, q))
1806 Not(p == q)
1807 """
1808 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1809 s = BoolSort(ctx)
1810 a = s.cast(a)
1811 b = s.cast(b)
1812 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1813
1814
1815def Not(a, ctx=None):
1816 """Create a Z3 not expression or probe.
1817
1818 >>> p = Bool('p')
1819 >>> Not(Not(p))
1820 Not(Not(p))
1821 >>> simplify(Not(Not(p)))
1822 p
1823 """
1824 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1825 if is_probe(a):
1826 # Not is also used to build probes
1827 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1828 else:
1829 s = BoolSort(ctx)
1830 a = s.cast(a)
1831 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1832
1833
1834def mk_not(a):
1835 if is_not(a):
1836 return a.arg(0)
1837 else:
1838 return Not(a)
1839
1840
1841def _has_probe(args):
1842 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1843 for arg in args:
1844 if is_probe(arg):
1845 return True
1846 return False
1847
1848
1849def And(*args):
1850 """Create a Z3 and-expression or and-probe.
1851
1852 >>> p, q, r = Bools('p q r')
1853 >>> And(p, q, r)
1854 And(p, q, r)
1855 >>> P = BoolVector('p', 5)
1856 >>> And(P)
1857 And(p__0, p__1, p__2, p__3, p__4)
1858 """
1859 last_arg = None
1860 if len(args) > 0:
1861 last_arg = args[len(args) - 1]
1862 if isinstance(last_arg, Context):
1863 ctx = args[len(args) - 1]
1864 args = args[:len(args) - 1]
1865 elif len(args) == 1 and isinstance(args[0], AstVector):
1866 ctx = args[0].ctx
1867 args = [a for a in args[0]]
1868 else:
1869 ctx = None
1870 args = _get_args(args)
1871 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1872 if z3_debug():
1873 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1874 if _has_probe(args):
1875 return _probe_and(args, ctx)
1876 else:
1877 args = _coerce_expr_list(args, ctx)
1878 _args, sz = _to_ast_array(args)
1879 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1880
1881
1882def Or(*args):
1883 """Create a Z3 or-expression or or-probe.
1884
1885 >>> p, q, r = Bools('p q r')
1886 >>> Or(p, q, r)
1887 Or(p, q, r)
1888 >>> P = BoolVector('p', 5)
1889 >>> Or(P)
1890 Or(p__0, p__1, p__2, p__3, p__4)
1891 """
1892 last_arg = None
1893 if len(args) > 0:
1894 last_arg = args[len(args) - 1]
1895 if isinstance(last_arg, Context):
1896 ctx = args[len(args) - 1]
1897 args = args[:len(args) - 1]
1898 elif len(args) == 1 and isinstance(args[0], AstVector):
1899 ctx = args[0].ctx
1900 args = [a for a in args[0]]
1901 else:
1902 ctx = None
1903 args = _get_args(args)
1904 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1905 if z3_debug():
1906 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1907 if _has_probe(args):
1908 return _probe_or(args, ctx)
1909 else:
1910 args = _coerce_expr_list(args, ctx)
1911 _args, sz = _to_ast_array(args)
1912 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1913
1914
1919
1920
1922 """Patterns are hints for quantifier instantiation.
1923
1924 """
1925
1926 def as_ast(self):
1927 return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1928
1929 def get_id(self):
1930 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1931
1932
1934 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1935
1936 >>> f = Function('f', IntSort(), IntSort())
1937 >>> x = Int('x')
1938 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1939 >>> q
1940 ForAll(x, f(x) == 0)
1941 >>> q.num_patterns()
1942 1
1943 >>> is_pattern(q.pattern(0))
1944 True
1945 >>> q.pattern(0)
1946 f(Var(0))
1947 """
1948 return isinstance(a, PatternRef)
1949
1950
1951def MultiPattern(*args):
1952 """Create a Z3 multi-pattern using the given expressions `*args`
1953
1954 >>> f = Function('f', IntSort(), IntSort())
1955 >>> g = Function('g', IntSort(), IntSort())
1956 >>> x = Int('x')
1957 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1958 >>> q
1959 ForAll(x, f(x) != g(x))
1960 >>> q.num_patterns()
1961 1
1962 >>> is_pattern(q.pattern(0))
1963 True
1964 >>> q.pattern(0)
1965 MultiPattern(f(Var(0)), g(Var(0)))
1966 """
1967 if z3_debug():
1968 _z3_assert(len(args) > 0, "At least one argument expected")
1969 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1970 ctx = args[0].ctx
1971 args, sz = _to_ast_array(args)
1972 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1973
1974
1976 if is_pattern(arg):
1977 return arg
1978 else:
1979 return MultiPattern(arg)
1980
1981
1986
1987
1989 """Universally and Existentially quantified formulas."""
1990
1991 def as_ast(self):
1992 return self.ast
1993
1994 def get_id(self):
1995 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1996
1997 def sort(self):
1998 """Return the Boolean sort or sort of Lambda."""
1999 if self.is_lambda():
2000 return _sort(self.ctx, self.as_astas_astas_ast())
2001 return BoolSort(self.ctx)
2002
2003 def is_forall(self):
2004 """Return `True` if `self` is a universal quantifier.
2005
2006 >>> f = Function('f', IntSort(), IntSort())
2007 >>> x = Int('x')
2008 >>> q = ForAll(x, f(x) == 0)
2009 >>> q.is_forall()
2010 True
2011 >>> q = Exists(x, f(x) != 0)
2012 >>> q.is_forall()
2013 False
2014 """
2015 return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
2016
2017 def is_exists(self):
2018 """Return `True` if `self` is an existential quantifier.
2019
2020 >>> f = Function('f', IntSort(), IntSort())
2021 >>> x = Int('x')
2022 >>> q = ForAll(x, f(x) == 0)
2023 >>> q.is_exists()
2024 False
2025 >>> q = Exists(x, f(x) != 0)
2026 >>> q.is_exists()
2027 True
2028 """
2029 return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
2030
2031 def is_lambda(self):
2032 """Return `True` if `self` is a lambda expression.
2033
2034 >>> f = Function('f', IntSort(), IntSort())
2035 >>> x = Int('x')
2036 >>> q = Lambda(x, f(x))
2037 >>> q.is_lambda()
2038 True
2039 >>> q = Exists(x, f(x) != 0)
2040 >>> q.is_lambda()
2041 False
2042 """
2043 return Z3_is_lambda(self.ctx_ref(), self.ast)
2044
2045 def __getitem__(self, arg):
2046 """Return the Z3 expression `self[arg]`.
2047 """
2048 if z3_debug():
2049 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2050 return _array_select(self, arg)
2051
2052 def weight(self):
2053 """Return the weight annotation of `self`.
2054
2055 >>> f = Function('f', IntSort(), IntSort())
2056 >>> x = Int('x')
2057 >>> q = ForAll(x, f(x) == 0)
2058 >>> q.weight()
2059 1
2060 >>> q = ForAll(x, f(x) == 0, weight=10)
2061 >>> q.weight()
2062 10
2063 """
2064 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
2065
2066 def num_patterns(self):
2067 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2068
2069 >>> f = Function('f', IntSort(), IntSort())
2070 >>> g = Function('g', IntSort(), IntSort())
2071 >>> x = Int('x')
2072 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2073 >>> q.num_patterns()
2074 2
2075 """
2076 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
2077
2078 def pattern(self, idx):
2079 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2080
2081 >>> f = Function('f', IntSort(), IntSort())
2082 >>> g = Function('g', IntSort(), IntSort())
2083 >>> x = Int('x')
2084 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2085 >>> q.num_patterns()
2086 2
2087 >>> q.pattern(0)
2088 f(Var(0))
2089 >>> q.pattern(1)
2090 g(Var(0))
2091 """
2092 if z3_debug():
2093 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2094 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2095
2097 """Return the number of no-patterns."""
2098 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
2099
2100 def no_pattern(self, idx):
2101 """Return a no-pattern."""
2102 if z3_debug():
2103 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2104 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2105
2106 def body(self):
2107 """Return the expression being quantified.
2108
2109 >>> f = Function('f', IntSort(), IntSort())
2110 >>> x = Int('x')
2111 >>> q = ForAll(x, f(x) == 0)
2112 >>> q.body()
2113 f(Var(0)) == 0
2114 """
2115 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
2116
2117 def num_vars(self):
2118 """Return the number of variables bounded by this quantifier.
2119
2120 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2121 >>> x = Int('x')
2122 >>> y = Int('y')
2123 >>> q = ForAll([x, y], f(x, y) >= x)
2124 >>> q.num_vars()
2125 2
2126 """
2127 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
2128
2129 def var_name(self, idx):
2130 """Return a string representing a name used when displaying the quantifier.
2131
2132 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2133 >>> x = Int('x')
2134 >>> y = Int('y')
2135 >>> q = ForAll([x, y], f(x, y) >= x)
2136 >>> q.var_name(0)
2137 'x'
2138 >>> q.var_name(1)
2139 'y'
2140 """
2141 if z3_debug():
2142 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2143 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
2144
2145 def var_sort(self, idx):
2146 """Return the sort of a bound variable.
2147
2148 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2149 >>> x = Int('x')
2150 >>> y = Real('y')
2151 >>> q = ForAll([x, y], f(x, y) >= x)
2152 >>> q.var_sort(0)
2153 Int
2154 >>> q.var_sort(1)
2155 Real
2156 """
2157 if z3_debug():
2158 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2159 return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
2160
2161 def children(self):
2162 """Return a list containing a single element self.body()
2163
2164 >>> f = Function('f', IntSort(), IntSort())
2165 >>> x = Int('x')
2166 >>> q = ForAll(x, f(x) == 0)
2167 >>> q.children()
2168 [f(Var(0)) == 0]
2169 """
2170 return [self.body()]
2171
2172
2174 """Return `True` if `a` is a Z3 quantifier.
2175
2176 >>> f = Function('f', IntSort(), IntSort())
2177 >>> x = Int('x')
2178 >>> q = ForAll(x, f(x) == 0)
2179 >>> is_quantifier(q)
2180 True
2181 >>> is_quantifier(f(x))
2182 False
2183 """
2184 return isinstance(a, QuantifierRef)
2185
2186
2187def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2188 if z3_debug():
2189 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2190 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2191 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2192 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2193 if is_app(vs):
2194 ctx = vs.ctx
2195 vs = [vs]
2196 else:
2197 ctx = vs[0].ctx
2198 if not is_expr(body):
2199 body = BoolVal(body, ctx)
2200 num_vars = len(vs)
2201 if num_vars == 0:
2202 return body
2203 _vs = (Ast * num_vars)()
2204 for i in range(num_vars):
2205 # TODO: Check if is constant
2206 _vs[i] = vs[i].as_ast()
2207 patterns = [_to_pattern(p) for p in patterns]
2208 num_pats = len(patterns)
2209 _pats = (Pattern * num_pats)()
2210 for i in range(num_pats):
2211 _pats[i] = patterns[i].ast
2212 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2213 qid = to_symbol(qid, ctx)
2214 skid = to_symbol(skid, ctx)
2215 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2216 num_vars, _vs,
2217 num_pats, _pats,
2218 num_no_pats, _no_pats,
2219 body.as_ast()), ctx)
2220
2221
2222def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2223 """Create a Z3 forall formula.
2224
2225 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2226
2227 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2228 >>> x = Int('x')
2229 >>> y = Int('y')
2230 >>> ForAll([x, y], f(x, y) >= x)
2231 ForAll([x, y], f(x, y) >= x)
2232 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2233 ForAll([x, y], f(x, y) >= x)
2234 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2235 ForAll([x, y], f(x, y) >= x)
2236 """
2237 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2238
2239
2240def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2241 """Create a Z3 exists formula.
2242
2243 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2244
2245
2246 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2247 >>> x = Int('x')
2248 >>> y = Int('y')
2249 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2250 >>> q
2251 Exists([x, y], f(x, y) >= x)
2252 >>> is_quantifier(q)
2253 True
2254 >>> r = Tactic('nnf')(q).as_expr()
2255 >>> is_quantifier(r)
2256 False
2257 """
2258 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2259
2260
2261def Lambda(vs, body):
2262 """Create a Z3 lambda expression.
2263
2264 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2265 >>> mem0 = Array('mem0', IntSort(), IntSort())
2266 >>> lo, hi, e, i = Ints('lo hi e i')
2267 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2268 >>> mem1
2269 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2270 """
2271 ctx = body.ctx
2272 if is_app(vs):
2273 vs = [vs]
2274 num_vars = len(vs)
2275 _vs = (Ast * num_vars)()
2276 for i in range(num_vars):
2277 # TODO: Check if is constant
2278 _vs[i] = vs[i].as_ast()
2279 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2280
2281
2286
2287
2289 """Real and Integer sorts."""
2290
2291 def is_real(self):
2292 """Return `True` if `self` is of the sort Real.
2293
2294 >>> x = Real('x')
2295 >>> x.is_real()
2296 True
2297 >>> (x + 1).is_real()
2298 True
2299 >>> x = Int('x')
2300 >>> x.is_real()
2301 False
2302 """
2303 return self.kind() == Z3_REAL_SORT
2304
2305 def is_int(self):
2306 """Return `True` if `self` is of the sort Integer.
2307
2308 >>> x = Int('x')
2309 >>> x.is_int()
2310 True
2311 >>> (x + 1).is_int()
2312 True
2313 >>> x = Real('x')
2314 >>> x.is_int()
2315 False
2316 """
2317 return self.kind() == Z3_INT_SORT
2318
2319 def is_bool(self):
2320 return False
2321
2322 def subsort(self, other):
2323 """Return `True` if `self` is a subsort of `other`."""
2324 return self.is_int() and is_arith_sort(other) and other.is_real()
2325
2326 def cast(self, val):
2327 """Try to cast `val` as an Integer or Real.
2328
2329 >>> IntSort().cast(10)
2330 10
2331 >>> is_int(IntSort().cast(10))
2332 True
2333 >>> is_int(10)
2334 False
2335 >>> RealSort().cast(10)
2336 10
2337 >>> is_real(RealSort().cast(10))
2338 True
2339 """
2340 if is_expr(val):
2341 if z3_debug():
2342 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
2343 val_s = val.sort()
2344 if self.eq(val_s):
2345 return val
2346 if val_s.is_int() and self.is_real():
2347 return ToReal(val)
2348 if val_s.is_bool() and self.is_int():
2349 return If(val, 1, 0)
2350 if val_s.is_bool() and self.is_real():
2351 return ToReal(If(val, 1, 0))
2352 if z3_debug():
2353 _z3_assert(False, "Z3 Integer/Real expression expected")
2354 else:
2355 if self.is_int():
2356 return IntVal(val, self.ctxctx)
2357 if self.is_real():
2358 return RealVal(val, self.ctxctx)
2359 if z3_debug():
2360 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2361 _z3_assert(False, msg % self)
2362
2363
2365 """Return `True` if s is an arithmetical sort (type).
2366
2367 >>> is_arith_sort(IntSort())
2368 True
2369 >>> is_arith_sort(RealSort())
2370 True
2371 >>> is_arith_sort(BoolSort())
2372 False
2373 >>> n = Int('x') + 1
2374 >>> is_arith_sort(n.sort())
2375 True
2376 """
2377 return isinstance(s, ArithSortRef)
2378
2379
2381 """Integer and Real expressions."""
2382
2383 def sort(self):
2384 """Return the sort (type) of the arithmetical expression `self`.
2385
2386 >>> Int('x').sort()
2387 Int
2388 >>> (Real('x') + 1).sort()
2389 Real
2390 """
2391 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2392
2393 def is_int(self):
2394 """Return `True` if `self` is an integer expression.
2395
2396 >>> x = Int('x')
2397 >>> x.is_int()
2398 True
2399 >>> (x + 1).is_int()
2400 True
2401 >>> y = Real('y')
2402 >>> (x + y).is_int()
2403 False
2404 """
2405 return self.sortsort().is_int()
2406
2407 def is_real(self):
2408 """Return `True` if `self` is an real expression.
2409
2410 >>> x = Real('x')
2411 >>> x.is_real()
2412 True
2413 >>> (x + 1).is_real()
2414 True
2415 """
2416 return self.sortsort().is_real()
2417
2418 def __add__(self, other):
2419 """Create the Z3 expression `self + other`.
2420
2421 >>> x = Int('x')
2422 >>> y = Int('y')
2423 >>> x + y
2424 x + y
2425 >>> (x + y).sort()
2426 Int
2427 """
2428 a, b = _coerce_exprs(self, other)
2429 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2430
2431 def __radd__(self, other):
2432 """Create the Z3 expression `other + self`.
2433
2434 >>> x = Int('x')
2435 >>> 10 + x
2436 10 + x
2437 """
2438 a, b = _coerce_exprs(self, other)
2439 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2440
2441 def __mul__(self, other):
2442 """Create the Z3 expression `self * other`.
2443
2444 >>> x = Real('x')
2445 >>> y = Real('y')
2446 >>> x * y
2447 x*y
2448 >>> (x * y).sort()
2449 Real
2450 """
2451 if isinstance(other, BoolRef):
2452 return If(other, self, 0)
2453 a, b = _coerce_exprs(self, other)
2454 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2455
2456 def __rmul__(self, other):
2457 """Create the Z3 expression `other * self`.
2458
2459 >>> x = Real('x')
2460 >>> 10 * x
2461 10*x
2462 """
2463 a, b = _coerce_exprs(self, other)
2464 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2465
2466 def __sub__(self, other):
2467 """Create the Z3 expression `self - other`.
2468
2469 >>> x = Int('x')
2470 >>> y = Int('y')
2471 >>> x - y
2472 x - y
2473 >>> (x - y).sort()
2474 Int
2475 """
2476 a, b = _coerce_exprs(self, other)
2477 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2478
2479 def __rsub__(self, other):
2480 """Create the Z3 expression `other - self`.
2481
2482 >>> x = Int('x')
2483 >>> 10 - x
2484 10 - x
2485 """
2486 a, b = _coerce_exprs(self, other)
2487 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2488
2489 def __pow__(self, other):
2490 """Create the Z3 expression `self**other` (** is the power operator).
2491
2492 >>> x = Real('x')
2493 >>> x**3
2494 x**3
2495 >>> (x**3).sort()
2496 Real
2497 >>> simplify(IntVal(2)**8)
2498 256
2499 """
2500 a, b = _coerce_exprs(self, other)
2501 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2502
2503 def __rpow__(self, other):
2504 """Create the Z3 expression `other**self` (** is the power operator).
2505
2506 >>> x = Real('x')
2507 >>> 2**x
2508 2**x
2509 >>> (2**x).sort()
2510 Real
2511 >>> simplify(2**IntVal(8))
2512 256
2513 """
2514 a, b = _coerce_exprs(self, other)
2515 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2516
2517 def __div__(self, other):
2518 """Create the Z3 expression `other/self`.
2519
2520 >>> x = Int('x')
2521 >>> y = Int('y')
2522 >>> x/y
2523 x/y
2524 >>> (x/y).sort()
2525 Int
2526 >>> (x/y).sexpr()
2527 '(div x y)'
2528 >>> x = Real('x')
2529 >>> y = Real('y')
2530 >>> x/y
2531 x/y
2532 >>> (x/y).sort()
2533 Real
2534 >>> (x/y).sexpr()
2535 '(/ x y)'
2536 """
2537 a, b = _coerce_exprs(self, other)
2538 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2539
2540 def __truediv__(self, other):
2541 """Create the Z3 expression `other/self`."""
2542 return self.__div__(other)
2543
2544 def __rdiv__(self, other):
2545 """Create the Z3 expression `other/self`.
2546
2547 >>> x = Int('x')
2548 >>> 10/x
2549 10/x
2550 >>> (10/x).sexpr()
2551 '(div 10 x)'
2552 >>> x = Real('x')
2553 >>> 10/x
2554 10/x
2555 >>> (10/x).sexpr()
2556 '(/ 10.0 x)'
2557 """
2558 a, b = _coerce_exprs(self, other)
2559 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2560
2561 def __rtruediv__(self, other):
2562 """Create the Z3 expression `other/self`."""
2563 return self.__rdiv__(other)
2564
2565 def __mod__(self, other):
2566 """Create the Z3 expression `other%self`.
2567
2568 >>> x = Int('x')
2569 >>> y = Int('y')
2570 >>> x % y
2571 x%y
2572 >>> simplify(IntVal(10) % IntVal(3))
2573 1
2574 """
2575 a, b = _coerce_exprs(self, other)
2576 if z3_debug():
2577 _z3_assert(a.is_int(), "Z3 integer expression expected")
2578 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2579
2580 def __rmod__(self, other):
2581 """Create the Z3 expression `other%self`.
2582
2583 >>> x = Int('x')
2584 >>> 10 % x
2585 10%x
2586 """
2587 a, b = _coerce_exprs(self, other)
2588 if z3_debug():
2589 _z3_assert(a.is_int(), "Z3 integer expression expected")
2590 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2591
2592 def __neg__(self):
2593 """Return an expression representing `-self`.
2594
2595 >>> x = Int('x')
2596 >>> -x
2597 -x
2598 >>> simplify(-(-x))
2599 x
2600 """
2601 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2602
2603 def __pos__(self):
2604 """Return `self`.
2605
2606 >>> x = Int('x')
2607 >>> +x
2608 x
2609 """
2610 return self
2611
2612 def __le__(self, other):
2613 """Create the Z3 expression `other <= self`.
2614
2615 >>> x, y = Ints('x y')
2616 >>> x <= y
2617 x <= y
2618 >>> y = Real('y')
2619 >>> x <= y
2620 ToReal(x) <= y
2621 """
2622 a, b = _coerce_exprs(self, other)
2623 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2624
2625 def __lt__(self, other):
2626 """Create the Z3 expression `other < self`.
2627
2628 >>> x, y = Ints('x y')
2629 >>> x < y
2630 x < y
2631 >>> y = Real('y')
2632 >>> x < y
2633 ToReal(x) < y
2634 """
2635 a, b = _coerce_exprs(self, other)
2636 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2637
2638 def __gt__(self, other):
2639 """Create the Z3 expression `other > self`.
2640
2641 >>> x, y = Ints('x y')
2642 >>> x > y
2643 x > y
2644 >>> y = Real('y')
2645 >>> x > y
2646 ToReal(x) > y
2647 """
2648 a, b = _coerce_exprs(self, other)
2649 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2650
2651 def __ge__(self, other):
2652 """Create the Z3 expression `other >= self`.
2653
2654 >>> x, y = Ints('x y')
2655 >>> x >= y
2656 x >= y
2657 >>> y = Real('y')
2658 >>> x >= y
2659 ToReal(x) >= y
2660 """
2661 a, b = _coerce_exprs(self, other)
2662 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2663
2664
2666 """Return `True` if `a` is an arithmetical expression.
2667
2668 >>> x = Int('x')
2669 >>> is_arith(x)
2670 True
2671 >>> is_arith(x + 1)
2672 True
2673 >>> is_arith(1)
2674 False
2675 >>> is_arith(IntVal(1))
2676 True
2677 >>> y = Real('y')
2678 >>> is_arith(y)
2679 True
2680 >>> is_arith(y + 1)
2681 True
2682 """
2683 return isinstance(a, ArithRef)
2684
2685
2686def is_int(a):
2687 """Return `True` if `a` is an integer expression.
2688
2689 >>> x = Int('x')
2690 >>> is_int(x + 1)
2691 True
2692 >>> is_int(1)
2693 False
2694 >>> is_int(IntVal(1))
2695 True
2696 >>> y = Real('y')
2697 >>> is_int(y)
2698 False
2699 >>> is_int(y + 1)
2700 False
2701 """
2702 return is_arith(a) and a.is_int()
2703
2704
2705def is_real(a):
2706 """Return `True` if `a` is a real expression.
2707
2708 >>> x = Int('x')
2709 >>> is_real(x + 1)
2710 False
2711 >>> y = Real('y')
2712 >>> is_real(y)
2713 True
2714 >>> is_real(y + 1)
2715 True
2716 >>> is_real(1)
2717 False
2718 >>> is_real(RealVal(1))
2719 True
2720 """
2721 return is_arith(a) and a.is_real()
2722
2723
2724def _is_numeral(ctx, a):
2725 return Z3_is_numeral_ast(ctx.ref(), a)
2726
2727
2728def _is_algebraic(ctx, a):
2729 return Z3_is_algebraic_number(ctx.ref(), a)
2730
2731
2733 """Return `True` if `a` is an integer value of sort Int.
2734
2735 >>> is_int_value(IntVal(1))
2736 True
2737 >>> is_int_value(1)
2738 False
2739 >>> is_int_value(Int('x'))
2740 False
2741 >>> n = Int('x') + 1
2742 >>> n
2743 x + 1
2744 >>> n.arg(1)
2745 1
2746 >>> is_int_value(n.arg(1))
2747 True
2748 >>> is_int_value(RealVal("1/3"))
2749 False
2750 >>> is_int_value(RealVal(1))
2751 False
2752 """
2753 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2754
2755
2757 """Return `True` if `a` is rational value of sort Real.
2758
2760 True
2761 >>> is_rational_value(RealVal("3/5"))
2762 True
2764 False
2765 >>> is_rational_value(1)
2766 False
2767 >>> n = Real('x') + 1
2768 >>> n.arg(1)
2769 1
2770 >>> is_rational_value(n.arg(1))
2771 True
2772 >>> is_rational_value(Real('x'))
2773 False
2774 """
2775 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2776
2777
2779 """Return `True` if `a` is an algebraic value of sort Real.
2780
2781 >>> is_algebraic_value(RealVal("3/5"))
2782 False
2783 >>> n = simplify(Sqrt(2))
2784 >>> n
2785 1.4142135623?
2786 >>> is_algebraic_value(n)
2787 True
2788 """
2789 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2790
2791
2792def is_add(a):
2793 """Return `True` if `a` is an expression of the form b + c.
2794
2795 >>> x, y = Ints('x y')
2796 >>> is_add(x + y)
2797 True
2798 >>> is_add(x - y)
2799 False
2800 """
2801 return is_app_of(a, Z3_OP_ADD)
2802
2803
2804def is_mul(a):
2805 """Return `True` if `a` is an expression of the form b * c.
2806
2807 >>> x, y = Ints('x y')
2808 >>> is_mul(x * y)
2809 True
2810 >>> is_mul(x - y)
2811 False
2812 """
2813 return is_app_of(a, Z3_OP_MUL)
2814
2815
2816def is_sub(a):
2817 """Return `True` if `a` is an expression of the form b - c.
2818
2819 >>> x, y = Ints('x y')
2820 >>> is_sub(x - y)
2821 True
2822 >>> is_sub(x + y)
2823 False
2824 """
2825 return is_app_of(a, Z3_OP_SUB)
2826
2827
2828def is_div(a):
2829 """Return `True` if `a` is an expression of the form b / c.
2830
2831 >>> x, y = Reals('x y')
2832 >>> is_div(x / y)
2833 True
2834 >>> is_div(x + y)
2835 False
2836 >>> x, y = Ints('x y')
2837 >>> is_div(x / y)
2838 False
2839 >>> is_idiv(x / y)
2840 True
2841 """
2842 return is_app_of(a, Z3_OP_DIV)
2843
2844
2845def is_idiv(a):
2846 """Return `True` if `a` is an expression of the form b div c.
2847
2848 >>> x, y = Ints('x y')
2849 >>> is_idiv(x / y)
2850 True
2851 >>> is_idiv(x + y)
2852 False
2853 """
2854 return is_app_of(a, Z3_OP_IDIV)
2855
2856
2857def is_mod(a):
2858 """Return `True` if `a` is an expression of the form b % c.
2859
2860 >>> x, y = Ints('x y')
2861 >>> is_mod(x % y)
2862 True
2863 >>> is_mod(x + y)
2864 False
2865 """
2866 return is_app_of(a, Z3_OP_MOD)
2867
2868
2869def is_le(a):
2870 """Return `True` if `a` is an expression of the form b <= c.
2871
2872 >>> x, y = Ints('x y')
2873 >>> is_le(x <= y)
2874 True
2875 >>> is_le(x < y)
2876 False
2877 """
2878 return is_app_of(a, Z3_OP_LE)
2879
2880
2881def is_lt(a):
2882 """Return `True` if `a` is an expression of the form b < c.
2883
2884 >>> x, y = Ints('x y')
2885 >>> is_lt(x < y)
2886 True
2887 >>> is_lt(x == y)
2888 False
2889 """
2890 return is_app_of(a, Z3_OP_LT)
2891
2892
2893def is_ge(a):
2894 """Return `True` if `a` is an expression of the form b >= c.
2895
2896 >>> x, y = Ints('x y')
2897 >>> is_ge(x >= y)
2898 True
2899 >>> is_ge(x == y)
2900 False
2901 """
2902 return is_app_of(a, Z3_OP_GE)
2903
2904
2905def is_gt(a):
2906 """Return `True` if `a` is an expression of the form b > c.
2907
2908 >>> x, y = Ints('x y')
2909 >>> is_gt(x > y)
2910 True
2911 >>> is_gt(x == y)
2912 False
2913 """
2914 return is_app_of(a, Z3_OP_GT)
2915
2916
2918 """Return `True` if `a` is an expression of the form IsInt(b).
2919
2920 >>> x = Real('x')
2921 >>> is_is_int(IsInt(x))
2922 True
2923 >>> is_is_int(x)
2924 False
2925 """
2926 return is_app_of(a, Z3_OP_IS_INT)
2927
2928
2930 """Return `True` if `a` is an expression of the form ToReal(b).
2931
2932 >>> x = Int('x')
2933 >>> n = ToReal(x)
2934 >>> n
2935 ToReal(x)
2936 >>> is_to_real(n)
2937 True
2938 >>> is_to_real(x)
2939 False
2940 """
2941 return is_app_of(a, Z3_OP_TO_REAL)
2942
2943
2945 """Return `True` if `a` is an expression of the form ToInt(b).
2946
2947 >>> x = Real('x')
2948 >>> n = ToInt(x)
2949 >>> n
2950 ToInt(x)
2951 >>> is_to_int(n)
2952 True
2953 >>> is_to_int(x)
2954 False
2955 """
2956 return is_app_of(a, Z3_OP_TO_INT)
2957
2958
2960 """Integer values."""
2961
2962 def as_long(self):
2963 """Return a Z3 integer numeral as a Python long (bignum) numeral.
2964
2965 >>> v = IntVal(1)
2966 >>> v + 1
2967 1 + 1
2968 >>> v.as_long() + 1
2969 2
2970 """
2971 if z3_debug():
2972 _z3_assert(self.is_int(), "Integer value expected")
2973 return int(self.as_string())
2974
2975 def as_string(self):
2976 """Return a Z3 integer numeral as a Python string.
2977 >>> v = IntVal(100)
2978 >>> v.as_string()
2979 '100'
2980 """
2981 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
2982
2984 """Return a Z3 integer numeral as a Python binary string.
2985 >>> v = IntVal(10)
2986 >>> v.as_binary_string()
2987 '1010'
2988 """
2990
2991
2993 """Rational values."""
2994
2995 def numerator(self):
2996 """ Return the numerator of a Z3 rational numeral.
2997
2998 >>> is_rational_value(RealVal("3/5"))
2999 True
3000 >>> n = RealVal("3/5")
3001 >>> n.numerator()
3002 3
3003 >>> is_rational_value(Q(3,5))
3004 True
3005 >>> Q(3,5).numerator()
3006 3
3007 """
3008 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3009
3010 def denominator(self):
3011 """ Return the denominator of a Z3 rational numeral.
3012
3013 >>> is_rational_value(Q(3,5))
3014 True
3015 >>> n = Q(3,5)
3016 >>> n.denominator()
3017 5
3018 """
3019 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3020
3022 """ Return the numerator as a Python long.
3023
3024 >>> v = RealVal(10000000000)
3025 >>> v
3026 10000000000
3027 >>> v + 1
3028 10000000000 + 1
3029 >>> v.numerator_as_long() + 1 == 10000000001
3030 True
3031 """
3032 return self.numerator().as_long()
3033
3035 """ Return the denominator as a Python long.
3036
3037 >>> v = RealVal("1/3")
3038 >>> v
3039 1/3
3040 >>> v.denominator_as_long()
3041 3
3042 """
3043 return self.denominator().as_long()
3044
3045 def is_int(self):
3046 return False
3047
3048 def is_real(self):
3049 return True
3050
3051 def is_int_value(self):
3052 return self.denominator().is_int() and self.denominator_as_long() == 1
3053
3054 def as_long(self):
3055 _z3_assert(self.is_int_value(), "Expected integer fraction")
3056 return self.numerator_as_long()
3057
3058 def as_decimal(self, prec):
3059 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3060
3061 >>> v = RealVal("1/5")
3062 >>> v.as_decimal(3)
3063 '0.2'
3064 >>> v = RealVal("1/3")
3065 >>> v.as_decimal(3)
3066 '0.333?'
3067 """
3068 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3069
3070 def as_string(self):
3071 """Return a Z3 rational numeral as a Python string.
3072
3073 >>> v = Q(3,6)
3074 >>> v.as_string()
3075 '1/2'
3076 """
3077 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3078
3079 def as_fraction(self):
3080 """Return a Z3 rational as a Python Fraction object.
3081
3082 >>> v = RealVal("1/5")
3083 >>> v.as_fraction()
3084 Fraction(1, 5)
3085 """
3086 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3087
3088
3090 """Algebraic irrational values."""
3091
3092 def approx(self, precision=10):
3093 """Return a Z3 rational number that approximates the algebraic number `self`.
3094 The result `r` is such that |r - self| <= 1/10^precision
3095
3096 >>> x = simplify(Sqrt(2))
3097 >>> x.approx(20)
3098 6838717160008073720548335/4835703278458516698824704
3099 >>> x.approx(5)
3100 2965821/2097152
3101 """
3102 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_astas_ast(), precision), self.ctx)
3103
3104 def as_decimal(self, prec):
3105 """Return a string representation of the algebraic number `self` in decimal notation
3106 using `prec` decimal places.
3107
3108 >>> x = simplify(Sqrt(2))
3109 >>> x.as_decimal(10)
3110 '1.4142135623?'
3111 >>> x.as_decimal(20)
3112 '1.41421356237309504880?'
3113 """
3114 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3115
3116 def poly(self):
3117 return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3118
3119 def index(self):
3120 return Z3_algebraic_get_i(self.ctx_ref(), self.as_astas_ast())
3121
3122
3123def _py2expr(a, ctx=None):
3124 if isinstance(a, bool):
3125 return BoolVal(a, ctx)
3126 if _is_int(a):
3127 return IntVal(a, ctx)
3128 if isinstance(a, float):
3129 return RealVal(a, ctx)
3130 if isinstance(a, str):
3131 return StringVal(a, ctx)
3132 if is_expr(a):
3133 return a
3134 if z3_debug():
3135 _z3_assert(False, "Python bool, int, long or float expected")
3136
3137
3138def IntSort(ctx=None):
3139 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3140
3141 >>> IntSort()
3142 Int
3143 >>> x = Const('x', IntSort())
3144 >>> is_int(x)
3145 True
3146 >>> x.sort() == IntSort()
3147 True
3148 >>> x.sort() == BoolSort()
3149 False
3150 """
3151 ctx = _get_ctx(ctx)
3152 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3153
3154
3155def RealSort(ctx=None):
3156 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3157
3158 >>> RealSort()
3159 Real
3160 >>> x = Const('x', RealSort())
3161 >>> is_real(x)
3162 True
3163 >>> is_int(x)
3164 False
3165 >>> x.sort() == RealSort()
3166 True
3167 """
3168 ctx = _get_ctx(ctx)
3169 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3170
3171
3173 if isinstance(val, float):
3174 return str(int(val))
3175 elif isinstance(val, bool):
3176 if val:
3177 return "1"
3178 else:
3179 return "0"
3180 elif _is_int(val):
3181 return str(val)
3182 elif isinstance(val, str):
3183 return val
3184 if z3_debug():
3185 _z3_assert(False, "Python value cannot be used as a Z3 integer")
3186
3187
3188def IntVal(val, ctx=None):
3189 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3190
3191 >>> IntVal(1)
3192 1
3193 >>> IntVal("100")
3194 100
3195 """
3196 ctx = _get_ctx(ctx)
3197 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3198
3199
3200def RealVal(val, ctx=None):
3201 """Return a Z3 real value.
3202
3203 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3204 If `ctx=None`, then the global context is used.
3205
3206 >>> RealVal(1)
3207 1
3208 >>> RealVal(1).sort()
3209 Real
3210 >>> RealVal("3/5")
3211 3/5
3212 >>> RealVal("1.5")
3213 3/2
3214 """
3215 ctx = _get_ctx(ctx)
3216 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3217
3218
3219def RatVal(a, b, ctx=None):
3220 """Return a Z3 rational a/b.
3221
3222 If `ctx=None`, then the global context is used.
3223
3224 >>> RatVal(3,5)
3225 3/5
3226 >>> RatVal(3,5).sort()
3227 Real
3228 """
3229 if z3_debug():
3230 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3231 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3232 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3233
3234
3235def Q(a, b, ctx=None):
3236 """Return a Z3 rational a/b.
3237
3238 If `ctx=None`, then the global context is used.
3239
3240 >>> Q(3,5)
3241 3/5
3242 >>> Q(3,5).sort()
3243 Real
3244 """
3245 return simplify(RatVal(a, b, ctx=ctx))
3246
3247
3248def Int(name, ctx=None):
3249 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3250
3251 >>> x = Int('x')
3252 >>> is_int(x)
3253 True
3254 >>> is_int(x + 1)
3255 True
3256 """
3257 ctx = _get_ctx(ctx)
3258 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3259
3260
3261def Ints(names, ctx=None):
3262 """Return a tuple of Integer constants.
3263
3264 >>> x, y, z = Ints('x y z')
3265 >>> Sum(x, y, z)
3266 x + y + z
3267 """
3268 ctx = _get_ctx(ctx)
3269 if isinstance(names, str):
3270 names = names.split(" ")
3271 return [Int(name, ctx) for name in names]
3272
3273
3274def IntVector(prefix, sz, ctx=None):
3275 """Return a list of integer constants of size `sz`.
3276
3277 >>> X = IntVector('x', 3)
3278 >>> X
3279 [x__0, x__1, x__2]
3280 >>> Sum(X)
3281 x__0 + x__1 + x__2
3282 """
3283 ctx = _get_ctx(ctx)
3284 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3285
3286
3287def FreshInt(prefix="x", ctx=None):
3288 """Return a fresh integer constant in the given context using the given prefix.
3289
3290 >>> x = FreshInt()
3291 >>> y = FreshInt()
3292 >>> eq(x, y)
3293 False
3294 >>> x.sort()
3295 Int
3296 """
3297 ctx = _get_ctx(ctx)
3298 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3299
3300
3301def Real(name, ctx=None):
3302 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3303
3304 >>> x = Real('x')
3305 >>> is_real(x)
3306 True
3307 >>> is_real(x + 1)
3308 True
3309 """
3310 ctx = _get_ctx(ctx)
3311 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3312
3313
3314def Reals(names, ctx=None):
3315 """Return a tuple of real constants.
3316
3317 >>> x, y, z = Reals('x y z')
3318 >>> Sum(x, y, z)
3319 x + y + z
3320 >>> Sum(x, y, z).sort()
3321 Real
3322 """
3323 ctx = _get_ctx(ctx)
3324 if isinstance(names, str):
3325 names = names.split(" ")
3326 return [Real(name, ctx) for name in names]
3327
3328
3329def RealVector(prefix, sz, ctx=None):
3330 """Return a list of real constants of size `sz`.
3331
3332 >>> X = RealVector('x', 3)
3333 >>> X
3334 [x__0, x__1, x__2]
3335 >>> Sum(X)
3336 x__0 + x__1 + x__2
3337 >>> Sum(X).sort()
3338 Real
3339 """
3340 ctx = _get_ctx(ctx)
3341 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3342
3343
3344def FreshReal(prefix="b", ctx=None):
3345 """Return a fresh real constant in the given context using the given prefix.
3346
3347 >>> x = FreshReal()
3348 >>> y = FreshReal()
3349 >>> eq(x, y)
3350 False
3351 >>> x.sort()
3352 Real
3353 """
3354 ctx = _get_ctx(ctx)
3355 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3356
3357
3358def ToReal(a):
3359 """ Return the Z3 expression ToReal(a).
3360
3361 >>> x = Int('x')
3362 >>> x.sort()
3363 Int
3364 >>> n = ToReal(x)
3365 >>> n
3366 ToReal(x)
3367 >>> n.sort()
3368 Real
3369 """
3370 if z3_debug():
3371 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3372 ctx = a.ctx
3373 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3374
3375
3376def ToInt(a):
3377 """ Return the Z3 expression ToInt(a).
3378
3379 >>> x = Real('x')
3380 >>> x.sort()
3381 Real
3382 >>> n = ToInt(x)
3383 >>> n
3384 ToInt(x)
3385 >>> n.sort()
3386 Int
3387 """
3388 if z3_debug():
3389 _z3_assert(a.is_real(), "Z3 real expression expected.")
3390 ctx = a.ctx
3391 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3392
3393
3394def IsInt(a):
3395 """ Return the Z3 predicate IsInt(a).
3396
3397 >>> x = Real('x')
3398 >>> IsInt(x + "1/2")
3399 IsInt(x + 1/2)
3400 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3401 [x = 1/2]
3402 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3403 no solution
3404 """
3405 if z3_debug():
3406 _z3_assert(a.is_real(), "Z3 real expression expected.")
3407 ctx = a.ctx
3408 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3409
3410
3411def Sqrt(a, ctx=None):
3412 """ Return a Z3 expression which represents the square root of a.
3413
3414 >>> x = Real('x')
3415 >>> Sqrt(x)
3416 x**(1/2)
3417 """
3418 if not is_expr(a):
3419 ctx = _get_ctx(ctx)
3420 a = RealVal(a, ctx)
3421 return a ** "1/2"
3422
3423
3424def Cbrt(a, ctx=None):
3425 """ Return a Z3 expression which represents the cubic root of a.
3426
3427 >>> x = Real('x')
3428 >>> Cbrt(x)
3429 x**(1/3)
3430 """
3431 if not is_expr(a):
3432 ctx = _get_ctx(ctx)
3433 a = RealVal(a, ctx)
3434 return a ** "1/3"
3435
3436
3441
3442
3444 """Bit-vector sort."""
3445
3446 def size(self):
3447 """Return the size (number of bits) of the bit-vector sort `self`.
3448
3449 >>> b = BitVecSort(32)
3450 >>> b.size()
3451 32
3452 """
3453 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3454
3455 def subsort(self, other):
3456 return is_bv_sort(other) and self.size() < other.size()
3457
3458 def cast(self, val):
3459 """Try to cast `val` as a Bit-Vector.
3460
3461 >>> b = BitVecSort(32)
3462 >>> b.cast(10)
3463 10
3464 >>> b.cast(10).sexpr()
3465 '#x0000000a'
3466 """
3467 if is_expr(val):
3468 if z3_debug():
3469 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
3470 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3471 return val
3472 else:
3473 return BitVecVal(val, self)
3474
3475
3477 """Return True if `s` is a Z3 bit-vector sort.
3478
3479 >>> is_bv_sort(BitVecSort(32))
3480 True
3481 >>> is_bv_sort(IntSort())
3482 False
3483 """
3484 return isinstance(s, BitVecSortRef)
3485
3486
3488 """Bit-vector expressions."""
3489
3490 def sort(self):
3491 """Return the sort of the bit-vector expression `self`.
3492
3493 >>> x = BitVec('x', 32)
3494 >>> x.sort()
3495 BitVec(32)
3496 >>> x.sort() == BitVecSort(32)
3497 True
3498 """
3499 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3500
3501 def size(self):
3502 """Return the number of bits of the bit-vector expression `self`.
3503
3504 >>> x = BitVec('x', 32)
3505 >>> (x + 1).size()
3506 32
3507 >>> Concat(x, x).size()
3508 64
3509 """
3510 return self.sortsort().size()
3511
3512 def __add__(self, other):
3513 """Create the Z3 expression `self + other`.
3514
3515 >>> x = BitVec('x', 32)
3516 >>> y = BitVec('y', 32)
3517 >>> x + y
3518 x + y
3519 >>> (x + y).sort()
3520 BitVec(32)
3521 """
3522 a, b = _coerce_exprs(self, other)
3523 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3524
3525 def __radd__(self, other):
3526 """Create the Z3 expression `other + self`.
3527
3528 >>> x = BitVec('x', 32)
3529 >>> 10 + x
3530 10 + x
3531 """
3532 a, b = _coerce_exprs(self, other)
3533 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3534
3535 def __mul__(self, other):
3536 """Create the Z3 expression `self * other`.
3537
3538 >>> x = BitVec('x', 32)
3539 >>> y = BitVec('y', 32)
3540 >>> x * y
3541 x*y
3542 >>> (x * y).sort()
3543 BitVec(32)
3544 """
3545 a, b = _coerce_exprs(self, other)
3546 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3547
3548 def __rmul__(self, other):
3549 """Create the Z3 expression `other * self`.
3550
3551 >>> x = BitVec('x', 32)
3552 >>> 10 * x
3553 10*x
3554 """
3555 a, b = _coerce_exprs(self, other)
3556 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3557
3558 def __sub__(self, other):
3559 """Create the Z3 expression `self - other`.
3560
3561 >>> x = BitVec('x', 32)
3562 >>> y = BitVec('y', 32)
3563 >>> x - y
3564 x - y
3565 >>> (x - y).sort()
3566 BitVec(32)
3567 """
3568 a, b = _coerce_exprs(self, other)
3569 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3570
3571 def __rsub__(self, other):
3572 """Create the Z3 expression `other - self`.
3573
3574 >>> x = BitVec('x', 32)
3575 >>> 10 - x
3576 10 - x
3577 """
3578 a, b = _coerce_exprs(self, other)
3579 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3580
3581 def __or__(self, other):
3582 """Create the Z3 expression bitwise-or `self | other`.
3583
3584 >>> x = BitVec('x', 32)
3585 >>> y = BitVec('y', 32)
3586 >>> x | y
3587 x | y
3588 >>> (x | y).sort()
3589 BitVec(32)
3590 """
3591 a, b = _coerce_exprs(self, other)
3592 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3593
3594 def __ror__(self, other):
3595 """Create the Z3 expression bitwise-or `other | self`.
3596
3597 >>> x = BitVec('x', 32)
3598 >>> 10 | x
3599 10 | x
3600 """
3601 a, b = _coerce_exprs(self, other)
3602 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3603
3604 def __and__(self, other):
3605 """Create the Z3 expression bitwise-and `self & other`.
3606
3607 >>> x = BitVec('x', 32)
3608 >>> y = BitVec('y', 32)
3609 >>> x & y
3610 x & y
3611 >>> (x & y).sort()
3612 BitVec(32)
3613 """
3614 a, b = _coerce_exprs(self, other)
3615 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3616
3617 def __rand__(self, other):
3618 """Create the Z3 expression bitwise-or `other & self`.
3619
3620 >>> x = BitVec('x', 32)
3621 >>> 10 & x
3622 10 & x
3623 """
3624 a, b = _coerce_exprs(self, other)
3625 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3626
3627 def __xor__(self, other):
3628 """Create the Z3 expression bitwise-xor `self ^ other`.
3629
3630 >>> x = BitVec('x', 32)
3631 >>> y = BitVec('y', 32)
3632 >>> x ^ y
3633 x ^ y
3634 >>> (x ^ y).sort()
3635 BitVec(32)
3636 """
3637 a, b = _coerce_exprs(self, other)
3638 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3639
3640 def __rxor__(self, other):
3641 """Create the Z3 expression bitwise-xor `other ^ self`.
3642
3643 >>> x = BitVec('x', 32)
3644 >>> 10 ^ x
3645 10 ^ x
3646 """
3647 a, b = _coerce_exprs(self, other)
3648 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3649
3650 def __pos__(self):
3651 """Return `self`.
3652
3653 >>> x = BitVec('x', 32)
3654 >>> +x
3655 x
3656 """
3657 return self
3658
3659 def __neg__(self):
3660 """Return an expression representing `-self`.
3661
3662 >>> x = BitVec('x', 32)
3663 >>> -x
3664 -x
3665 >>> simplify(-(-x))
3666 x
3667 """
3668 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3669
3670 def __invert__(self):
3671 """Create the Z3 expression bitwise-not `~self`.
3672
3673 >>> x = BitVec('x', 32)
3674 >>> ~x
3675 ~x
3676 >>> simplify(~(~x))
3677 x
3678 """
3679 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3680
3681 def __div__(self, other):
3682 """Create the Z3 expression (signed) division `self / other`.
3683
3684 Use the function UDiv() for unsigned division.
3685
3686 >>> x = BitVec('x', 32)
3687 >>> y = BitVec('y', 32)
3688 >>> x / y
3689 x/y
3690 >>> (x / y).sort()
3691 BitVec(32)
3692 >>> (x / y).sexpr()
3693 '(bvsdiv x y)'
3694 >>> UDiv(x, y).sexpr()
3695 '(bvudiv x y)'
3696 """
3697 a, b = _coerce_exprs(self, other)
3698 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3699
3700 def __truediv__(self, other):
3701 """Create the Z3 expression (signed) division `self / other`."""
3702 return self.__div__(other)
3703
3704 def __rdiv__(self, other):
3705 """Create the Z3 expression (signed) division `other / self`.
3706
3707 Use the function UDiv() for unsigned division.
3708
3709 >>> x = BitVec('x', 32)
3710 >>> 10 / x
3711 10/x
3712 >>> (10 / x).sexpr()
3713 '(bvsdiv #x0000000a x)'
3714 >>> UDiv(10, x).sexpr()
3715 '(bvudiv #x0000000a x)'
3716 """
3717 a, b = _coerce_exprs(self, other)
3718 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3719
3720 def __rtruediv__(self, other):
3721 """Create the Z3 expression (signed) division `other / self`."""
3722 return self.__rdiv__(other)
3723
3724 def __mod__(self, other):
3725 """Create the Z3 expression (signed) mod `self % other`.
3726
3727 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3728
3729 >>> x = BitVec('x', 32)
3730 >>> y = BitVec('y', 32)
3731 >>> x % y
3732 x%y
3733 >>> (x % y).sort()
3734 BitVec(32)
3735 >>> (x % y).sexpr()
3736 '(bvsmod x y)'
3737 >>> URem(x, y).sexpr()
3738 '(bvurem x y)'
3739 >>> SRem(x, y).sexpr()
3740 '(bvsrem x y)'
3741 """
3742 a, b = _coerce_exprs(self, other)
3743 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3744
3745 def __rmod__(self, other):
3746 """Create the Z3 expression (signed) mod `other % self`.
3747
3748 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3749
3750 >>> x = BitVec('x', 32)
3751 >>> 10 % x
3752 10%x
3753 >>> (10 % x).sexpr()
3754 '(bvsmod #x0000000a x)'
3755 >>> URem(10, x).sexpr()
3756 '(bvurem #x0000000a x)'
3757 >>> SRem(10, x).sexpr()
3758 '(bvsrem #x0000000a x)'
3759 """
3760 a, b = _coerce_exprs(self, other)
3761 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3762
3763 def __le__(self, other):
3764 """Create the Z3 expression (signed) `other <= self`.
3765
3766 Use the function ULE() for unsigned less than or equal to.
3767
3768 >>> x, y = BitVecs('x y', 32)
3769 >>> x <= y
3770 x <= y
3771 >>> (x <= y).sexpr()
3772 '(bvsle x y)'
3773 >>> ULE(x, y).sexpr()
3774 '(bvule x y)'
3775 """
3776 a, b = _coerce_exprs(self, other)
3777 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3778
3779 def __lt__(self, other):
3780 """Create the Z3 expression (signed) `other < self`.
3781
3782 Use the function ULT() for unsigned less than.
3783
3784 >>> x, y = BitVecs('x y', 32)
3785 >>> x < y
3786 x < y
3787 >>> (x < y).sexpr()
3788 '(bvslt x y)'
3789 >>> ULT(x, y).sexpr()
3790 '(bvult x y)'
3791 """
3792 a, b = _coerce_exprs(self, other)
3793 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3794
3795 def __gt__(self, other):
3796 """Create the Z3 expression (signed) `other > self`.
3797
3798 Use the function UGT() for unsigned greater than.
3799
3800 >>> x, y = BitVecs('x y', 32)
3801 >>> x > y
3802 x > y
3803 >>> (x > y).sexpr()
3804 '(bvsgt x y)'
3805 >>> UGT(x, y).sexpr()
3806 '(bvugt x y)'
3807 """
3808 a, b = _coerce_exprs(self, other)
3809 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3810
3811 def __ge__(self, other):
3812 """Create the Z3 expression (signed) `other >= self`.
3813
3814 Use the function UGE() for unsigned greater than or equal to.
3815
3816 >>> x, y = BitVecs('x y', 32)
3817 >>> x >= y
3818 x >= y
3819 >>> (x >= y).sexpr()
3820 '(bvsge x y)'
3821 >>> UGE(x, y).sexpr()
3822 '(bvuge x y)'
3823 """
3824 a, b = _coerce_exprs(self, other)
3825 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3826
3827 def __rshift__(self, other):
3828 """Create the Z3 expression (arithmetical) right shift `self >> other`
3829
3830 Use the function LShR() for the right logical shift
3831
3832 >>> x, y = BitVecs('x y', 32)
3833 >>> x >> y
3834 x >> y
3835 >>> (x >> y).sexpr()
3836 '(bvashr x y)'
3837 >>> LShR(x, y).sexpr()
3838 '(bvlshr x y)'
3839 >>> BitVecVal(4, 3)
3840 4
3841 >>> BitVecVal(4, 3).as_signed_long()
3842 -4
3843 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3844 -2
3845 >>> simplify(BitVecVal(4, 3) >> 1)
3846 6
3847 >>> simplify(LShR(BitVecVal(4, 3), 1))
3848 2
3849 >>> simplify(BitVecVal(2, 3) >> 1)
3850 1
3851 >>> simplify(LShR(BitVecVal(2, 3), 1))
3852 1
3853 """
3854 a, b = _coerce_exprs(self, other)
3855 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3856
3857 def __lshift__(self, other):
3858 """Create the Z3 expression left shift `self << other`
3859
3860 >>> x, y = BitVecs('x y', 32)
3861 >>> x << y
3862 x << y
3863 >>> (x << y).sexpr()
3864 '(bvshl x y)'
3865 >>> simplify(BitVecVal(2, 3) << 1)
3866 4
3867 """
3868 a, b = _coerce_exprs(self, other)
3869 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3870
3871 def __rrshift__(self, other):
3872 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3873
3874 Use the function LShR() for the right logical shift
3875
3876 >>> x = BitVec('x', 32)
3877 >>> 10 >> x
3878 10 >> x
3879 >>> (10 >> x).sexpr()
3880 '(bvashr #x0000000a x)'
3881 """
3882 a, b = _coerce_exprs(self, other)
3883 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3884
3885 def __rlshift__(self, other):
3886 """Create the Z3 expression left shift `other << self`.
3887
3888 Use the function LShR() for the right logical shift
3889
3890 >>> x = BitVec('x', 32)
3891 >>> 10 << x
3892 10 << x
3893 >>> (10 << x).sexpr()
3894 '(bvshl #x0000000a x)'
3895 """
3896 a, b = _coerce_exprs(self, other)
3897 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3898
3899
3901 """Bit-vector values."""
3902
3903 def as_long(self):
3904 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3905
3906 >>> v = BitVecVal(0xbadc0de, 32)
3907 >>> v
3908 195936478
3909 >>> print("0x%.8x" % v.as_long())
3910 0x0badc0de
3911 """
3912 return int(self.as_string())
3913
3915 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3916 The most significant bit is assumed to be the sign.
3917
3918 >>> BitVecVal(4, 3).as_signed_long()
3919 -4
3920 >>> BitVecVal(7, 3).as_signed_long()
3921 -1
3922 >>> BitVecVal(3, 3).as_signed_long()
3923 3
3924 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3925 -1
3926 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3927 -1
3928 """
3929 sz = self.size()
3930 val = self.as_long()
3931 if val >= 2**(sz - 1):
3932 val = val - 2**sz
3933 if val < -2**(sz - 1):
3934 val = val + 2**sz
3935 return int(val)
3936
3937 def as_string(self):
3938 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3939
3942
3943
3944def is_bv(a):
3945 """Return `True` if `a` is a Z3 bit-vector expression.
3946
3947 >>> b = BitVec('b', 32)
3948 >>> is_bv(b)
3949 True
3950 >>> is_bv(b + 10)
3951 True
3952 >>> is_bv(Int('x'))
3953 False
3954 """
3955 return isinstance(a, BitVecRef)
3956
3957
3959 """Return `True` if `a` is a Z3 bit-vector numeral value.
3960
3961 >>> b = BitVec('b', 32)
3962 >>> is_bv_value(b)
3963 False
3964 >>> b = BitVecVal(10, 32)
3965 >>> b
3966 10
3967 >>> is_bv_value(b)
3968 True
3969 """
3970 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3971
3972
3973def BV2Int(a, is_signed=False):
3974 """Return the Z3 expression BV2Int(a).
3975
3976 >>> b = BitVec('b', 3)
3977 >>> BV2Int(b).sort()
3978 Int
3979 >>> x = Int('x')
3980 >>> x > BV2Int(b)
3981 x > BV2Int(b)
3982 >>> x > BV2Int(b, is_signed=False)
3983 x > BV2Int(b)
3984 >>> x > BV2Int(b, is_signed=True)
3985 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3986 >>> solve(x > BV2Int(b), b == 1, x < 3)
3987 [x = 2, b = 1]
3988 """
3989 if z3_debug():
3990 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3991 ctx = a.ctx
3992 # investigate problem with bv2int
3993 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3994
3995
3996def Int2BV(a, num_bits):
3997 """Return the z3 expression Int2BV(a, num_bits).
3998 It is a bit-vector of width num_bits and represents the
3999 modulo of a by 2^num_bits
4000 """
4001 ctx = a.ctx
4002 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
4003
4004
4005def BitVecSort(sz, ctx=None):
4006 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4007
4008 >>> Byte = BitVecSort(8)
4009 >>> Word = BitVecSort(16)
4010 >>> Byte
4011 BitVec(8)
4012 >>> x = Const('x', Byte)
4013 >>> eq(x, BitVec('x', 8))
4014 True
4015 """
4016 ctx = _get_ctx(ctx)
4017 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4018
4019
4020def BitVecVal(val, bv, ctx=None):
4021 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4022
4023 >>> v = BitVecVal(10, 32)
4024 >>> v
4025 10
4026 >>> print("0x%.8x" % v.as_long())
4027 0x0000000a
4028 """
4029 if is_bv_sort(bv):
4030 ctx = bv.ctx
4031 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4032 else:
4033 ctx = _get_ctx(ctx)
4034 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4035
4036
4037def BitVec(name, bv, ctx=None):
4038 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4039 If `ctx=None`, then the global context is used.
4040
4041 >>> x = BitVec('x', 16)
4042 >>> is_bv(x)
4043 True
4044 >>> x.size()
4045 16
4046 >>> x.sort()
4047 BitVec(16)
4048 >>> word = BitVecSort(16)
4049 >>> x2 = BitVec('x', word)
4050 >>> eq(x, x2)
4051 True
4052 """
4053 if isinstance(bv, BitVecSortRef):
4054 ctx = bv.ctx
4055 else:
4056 ctx = _get_ctx(ctx)
4057 bv = BitVecSort(bv, ctx)
4058 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4059
4060
4061def BitVecs(names, bv, ctx=None):
4062 """Return a tuple of bit-vector constants of size bv.
4063
4064 >>> x, y, z = BitVecs('x y z', 16)
4065 >>> x.size()
4066 16
4067 >>> x.sort()
4068 BitVec(16)
4069 >>> Sum(x, y, z)
4070 0 + x + y + z
4071 >>> Product(x, y, z)
4072 1*x*y*z
4073 >>> simplify(Product(x, y, z))
4074 x*y*z
4075 """
4076 ctx = _get_ctx(ctx)
4077 if isinstance(names, str):
4078 names = names.split(" ")
4079 return [BitVec(name, bv, ctx) for name in names]
4080
4081
4082def Concat(*args):
4083 """Create a Z3 bit-vector concatenation expression.
4084
4085 >>> v = BitVecVal(1, 4)
4086 >>> Concat(v, v+1, v)
4087 Concat(Concat(1, 1 + 1), 1)
4088 >>> simplify(Concat(v, v+1, v))
4089 289
4090 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4091 121
4092 """
4093 args = _get_args(args)
4094 sz = len(args)
4095 if z3_debug():
4096 _z3_assert(sz >= 2, "At least two arguments expected.")
4097
4098 ctx = None
4099 for a in args:
4100 if is_expr(a):
4101 ctx = a.ctx
4102 break
4103 if is_seq(args[0]) or isinstance(args[0], str):
4104 args = [_coerce_seq(s, ctx) for s in args]
4105 if z3_debug():
4106 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4107 v = (Ast * sz)()
4108 for i in range(sz):
4109 v[i] = args[i].as_ast()
4110 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4111
4112 if is_re(args[0]):
4113 if z3_debug():
4114 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4115 v = (Ast * sz)()
4116 for i in range(sz):
4117 v[i] = args[i].as_ast()
4118 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4119
4120 if z3_debug():
4121 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4122 r = args[0]
4123 for i in range(sz - 1):
4124 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4125 return r
4126
4127
4128def Extract(high, low, a):
4129 """Create a Z3 bit-vector extraction expression.
4130 Extract is overloaded to also work on sequence extraction.
4131 The functions SubString and SubSeq are redirected to Extract.
4132 For this case, the arguments are reinterpreted as:
4133 high - is a sequence (string)
4134 low - is an offset
4135 a - is the length to be extracted
4136
4137 >>> x = BitVec('x', 8)
4138 >>> Extract(6, 2, x)
4139 Extract(6, 2, x)
4140 >>> Extract(6, 2, x).sort()
4141 BitVec(5)
4142 >>> simplify(Extract(StringVal("abcd"),2,1))
4143 "c"
4144 """
4145 if isinstance(high, str):
4146 high = StringVal(high)
4147 if is_seq(high):
4148 s = high
4149 offset, length = _coerce_exprs(low, a, s.ctx)
4150 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4151 if z3_debug():
4152 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4153 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4154 "First and second arguments must be non negative integers")
4155 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4156 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4157
4158
4160 if z3_debug():
4161 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4162
4163
4164def ULE(a, b):
4165 """Create the Z3 expression (unsigned) `other <= self`.
4166
4167 Use the operator <= for signed less than or equal to.
4168
4169 >>> x, y = BitVecs('x y', 32)
4170 >>> ULE(x, y)
4171 ULE(x, y)
4172 >>> (x <= y).sexpr()
4173 '(bvsle x y)'
4174 >>> ULE(x, y).sexpr()
4175 '(bvule x y)'
4176 """
4177 _check_bv_args(a, b)
4178 a, b = _coerce_exprs(a, b)
4179 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4180
4181
4182def ULT(a, b):
4183 """Create the Z3 expression (unsigned) `other < self`.
4184
4185 Use the operator < for signed less than.
4186
4187 >>> x, y = BitVecs('x y', 32)
4188 >>> ULT(x, y)
4189 ULT(x, y)
4190 >>> (x < y).sexpr()
4191 '(bvslt x y)'
4192 >>> ULT(x, y).sexpr()
4193 '(bvult x y)'
4194 """
4195 _check_bv_args(a, b)
4196 a, b = _coerce_exprs(a, b)
4197 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4198
4199
4200def UGE(a, b):
4201 """Create the Z3 expression (unsigned) `other >= self`.
4202
4203 Use the operator >= for signed greater than or equal to.
4204
4205 >>> x, y = BitVecs('x y', 32)
4206 >>> UGE(x, y)
4207 UGE(x, y)
4208 >>> (x >= y).sexpr()
4209 '(bvsge x y)'
4210 >>> UGE(x, y).sexpr()
4211 '(bvuge x y)'
4212 """
4213 _check_bv_args(a, b)
4214 a, b = _coerce_exprs(a, b)
4215 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4216
4217
4218def UGT(a, b):
4219 """Create the Z3 expression (unsigned) `other > self`.
4220
4221 Use the operator > for signed greater than.
4222
4223 >>> x, y = BitVecs('x y', 32)
4224 >>> UGT(x, y)
4225 UGT(x, y)
4226 >>> (x > y).sexpr()
4227 '(bvsgt x y)'
4228 >>> UGT(x, y).sexpr()
4229 '(bvugt x y)'
4230 """
4231 _check_bv_args(a, b)
4232 a, b = _coerce_exprs(a, b)
4233 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4234
4235
4236def UDiv(a, b):
4237 """Create the Z3 expression (unsigned) division `self / other`.
4238
4239 Use the operator / for signed division.
4240
4241 >>> x = BitVec('x', 32)
4242 >>> y = BitVec('y', 32)
4243 >>> UDiv(x, y)
4244 UDiv(x, y)
4245 >>> UDiv(x, y).sort()
4246 BitVec(32)
4247 >>> (x / y).sexpr()
4248 '(bvsdiv x y)'
4249 >>> UDiv(x, y).sexpr()
4250 '(bvudiv x y)'
4251 """
4252 _check_bv_args(a, b)
4253 a, b = _coerce_exprs(a, b)
4254 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4255
4256
4257def URem(a, b):
4258 """Create the Z3 expression (unsigned) remainder `self % other`.
4259
4260 Use the operator % for signed modulus, and SRem() for signed remainder.
4261
4262 >>> x = BitVec('x', 32)
4263 >>> y = BitVec('y', 32)
4264 >>> URem(x, y)
4265 URem(x, y)
4266 >>> URem(x, y).sort()
4267 BitVec(32)
4268 >>> (x % y).sexpr()
4269 '(bvsmod x y)'
4270 >>> URem(x, y).sexpr()
4271 '(bvurem x y)'
4272 """
4273 _check_bv_args(a, b)
4274 a, b = _coerce_exprs(a, b)
4275 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4276
4277
4278def SRem(a, b):
4279 """Create the Z3 expression signed remainder.
4280
4281 Use the operator % for signed modulus, and URem() for unsigned remainder.
4282
4283 >>> x = BitVec('x', 32)
4284 >>> y = BitVec('y', 32)
4285 >>> SRem(x, y)
4286 SRem(x, y)
4287 >>> SRem(x, y).sort()
4288 BitVec(32)
4289 >>> (x % y).sexpr()
4290 '(bvsmod x y)'
4291 >>> SRem(x, y).sexpr()
4292 '(bvsrem x y)'
4293 """
4294 _check_bv_args(a, b)
4295 a, b = _coerce_exprs(a, b)
4296 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4297
4298
4299def LShR(a, b):
4300 """Create the Z3 expression logical right shift.
4301
4302 Use the operator >> for the arithmetical right shift.
4303
4304 >>> x, y = BitVecs('x y', 32)
4305 >>> LShR(x, y)
4306 LShR(x, y)
4307 >>> (x >> y).sexpr()
4308 '(bvashr x y)'
4309 >>> LShR(x, y).sexpr()
4310 '(bvlshr x y)'
4311 >>> BitVecVal(4, 3)
4312 4
4313 >>> BitVecVal(4, 3).as_signed_long()
4314 -4
4315 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4316 -2
4317 >>> simplify(BitVecVal(4, 3) >> 1)
4318 6
4319 >>> simplify(LShR(BitVecVal(4, 3), 1))
4320 2
4321 >>> simplify(BitVecVal(2, 3) >> 1)
4322 1
4323 >>> simplify(LShR(BitVecVal(2, 3), 1))
4324 1
4325 """
4326 _check_bv_args(a, b)
4327 a, b = _coerce_exprs(a, b)
4328 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4329
4330
4331def RotateLeft(a, b):
4332 """Return an expression representing `a` rotated to the left `b` times.
4333
4334 >>> a, b = BitVecs('a b', 16)
4335 >>> RotateLeft(a, b)
4336 RotateLeft(a, b)
4337 >>> simplify(RotateLeft(a, 0))
4338 a
4339 >>> simplify(RotateLeft(a, 16))
4340 a
4341 """
4342 _check_bv_args(a, b)
4343 a, b = _coerce_exprs(a, b)
4344 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4345
4346
4347def RotateRight(a, b):
4348 """Return an expression representing `a` rotated to the right `b` times.
4349
4350 >>> a, b = BitVecs('a b', 16)
4351 >>> RotateRight(a, b)
4352 RotateRight(a, b)
4353 >>> simplify(RotateRight(a, 0))
4354 a
4355 >>> simplify(RotateRight(a, 16))
4356 a
4357 """
4358 _check_bv_args(a, b)
4359 a, b = _coerce_exprs(a, b)
4360 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4361
4362
4363def SignExt(n, a):
4364 """Return a bit-vector expression with `n` extra sign-bits.
4365
4366 >>> x = BitVec('x', 16)
4367 >>> n = SignExt(8, x)
4368 >>> n.size()
4369 24
4370 >>> n
4371 SignExt(8, x)
4372 >>> n.sort()
4373 BitVec(24)
4374 >>> v0 = BitVecVal(2, 2)
4375 >>> v0
4376 2
4377 >>> v0.size()
4378 2
4379 >>> v = simplify(SignExt(6, v0))
4380 >>> v
4381 254
4382 >>> v.size()
4383 8
4384 >>> print("%.x" % v.as_long())
4385 fe
4386 """
4387 if z3_debug():
4388 _z3_assert(_is_int(n), "First argument must be an integer")
4389 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4390 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4391
4392
4393def ZeroExt(n, a):
4394 """Return a bit-vector expression with `n` extra zero-bits.
4395
4396 >>> x = BitVec('x', 16)
4397 >>> n = ZeroExt(8, x)
4398 >>> n.size()
4399 24
4400 >>> n
4401 ZeroExt(8, x)
4402 >>> n.sort()
4403 BitVec(24)
4404 >>> v0 = BitVecVal(2, 2)
4405 >>> v0
4406 2
4407 >>> v0.size()
4408 2
4409 >>> v = simplify(ZeroExt(6, v0))
4410 >>> v
4411 2
4412 >>> v.size()
4413 8
4414 """
4415 if z3_debug():
4416 _z3_assert(_is_int(n), "First argument must be an integer")
4417 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4418 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4419
4420
4422 """Return an expression representing `n` copies of `a`.
4423
4424 >>> x = BitVec('x', 8)
4425 >>> n = RepeatBitVec(4, x)
4426 >>> n
4427 RepeatBitVec(4, x)
4428 >>> n.size()
4429 32
4430 >>> v0 = BitVecVal(10, 4)
4431 >>> print("%.x" % v0.as_long())
4432 a
4433 >>> v = simplify(RepeatBitVec(4, v0))
4434 >>> v.size()
4435 16
4436 >>> print("%.x" % v.as_long())
4437 aaaa
4438 """
4439 if z3_debug():
4440 _z3_assert(_is_int(n), "First argument must be an integer")
4441 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4442 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4443
4444
4446 """Return the reduction-and expression of `a`."""
4447 if z3_debug():
4448 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4449 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4450
4451
4452def BVRedOr(a):
4453 """Return the reduction-or expression of `a`."""
4454 if z3_debug():
4455 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4456 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4457
4458
4459def BVAddNoOverflow(a, b, signed):
4460 """A predicate the determines that bit-vector addition does not overflow"""
4461 _check_bv_args(a, b)
4462 a, b = _coerce_exprs(a, b)
4463 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4464
4465
4467 """A predicate the determines that signed bit-vector addition does not underflow"""
4468 _check_bv_args(a, b)
4469 a, b = _coerce_exprs(a, b)
4470 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4471
4472
4474 """A predicate the determines that bit-vector subtraction does not overflow"""
4475 _check_bv_args(a, b)
4476 a, b = _coerce_exprs(a, b)
4477 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4478
4479
4480def BVSubNoUnderflow(a, b, signed):
4481 """A predicate the determines that bit-vector subtraction does not underflow"""
4482 _check_bv_args(a, b)
4483 a, b = _coerce_exprs(a, b)
4484 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4485
4486
4488 """A predicate the determines that bit-vector signed division does not overflow"""
4489 _check_bv_args(a, b)
4490 a, b = _coerce_exprs(a, b)
4491 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4492
4493
4495 """A predicate the determines that bit-vector unary negation does not overflow"""
4496 if z3_debug():
4497 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4498 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4499
4500
4501def BVMulNoOverflow(a, b, signed):
4502 """A predicate the determines that bit-vector multiplication does not overflow"""
4503 _check_bv_args(a, b)
4504 a, b = _coerce_exprs(a, b)
4505 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4506
4507
4509 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4510 _check_bv_args(a, b)
4511 a, b = _coerce_exprs(a, b)
4512 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4513
4514
4515
4520
4522 """Array sorts."""
4523
4524 def domain(self):
4525 """Return the domain of the array sort `self`.
4526
4527 >>> A = ArraySort(IntSort(), BoolSort())
4528 >>> A.domain()
4529 Int
4530 """
4531 return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4532
4533 def domain_n(self, i):
4534 """Return the domain of the array sort `self`.
4535 """
4536 return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx)
4537
4538 def range(self):
4539 """Return the range of the array sort `self`.
4540
4541 >>> A = ArraySort(IntSort(), BoolSort())
4542 >>> A.range()
4543 Bool
4544 """
4545 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4546
4547
4549 """Array expressions. """
4550
4551 def sort(self):
4552 """Return the array sort of the array expression `self`.
4553
4554 >>> a = Array('a', IntSort(), BoolSort())
4555 >>> a.sort()
4556 Array(Int, Bool)
4557 """
4558 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4559
4560 def domain(self):
4561 """Shorthand for `self.sort().domain()`.
4562
4563 >>> a = Array('a', IntSort(), BoolSort())
4564 >>> a.domain()
4565 Int
4566 """
4567 return self.sortsort().domain()
4568
4569 def domain_n(self, i):
4570 """Shorthand for self.sort().domain_n(i)`."""
4571 return self.sortsort().domain_n(i)
4572
4573 def range(self):
4574 """Shorthand for `self.sort().range()`.
4575
4576 >>> a = Array('a', IntSort(), BoolSort())
4577 >>> a.range()
4578 Bool
4579 """
4580 return self.sortsort().range()
4581
4582 def __getitem__(self, arg):
4583 """Return the Z3 expression `self[arg]`.
4584
4585 >>> a = Array('a', IntSort(), BoolSort())
4586 >>> i = Int('i')
4587 >>> a[i]
4588 a[i]
4589 >>> a[i].sexpr()
4590 '(select a i)'
4591 """
4592 return _array_select(self, arg)
4593
4594 def default(self):
4595 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4596
4597
4598def _array_select(ar, arg):
4599 if isinstance(arg, tuple):
4600 args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))]
4601 _args, sz = _to_ast_array(args)
4602 return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4603 arg = ar.sort().domain().cast(arg)
4604 return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4605
4606
4608 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4609
4610
4612 """Return `True` if `a` is a Z3 array expression.
4613
4614 >>> a = Array('a', IntSort(), IntSort())
4615 >>> is_array(a)
4616 True
4617 >>> is_array(Store(a, 0, 1))
4618 True
4619 >>> is_array(a[0])
4620 False
4621 """
4622 return isinstance(a, ArrayRef)
4623
4624
4626 """Return `True` if `a` is a Z3 constant array.
4627
4628 >>> a = K(IntSort(), 10)
4629 >>> is_const_array(a)
4630 True
4631 >>> a = Array('a', IntSort(), IntSort())
4632 >>> is_const_array(a)
4633 False
4634 """
4635 return is_app_of(a, Z3_OP_CONST_ARRAY)
4636
4637
4638def is_K(a):
4639 """Return `True` if `a` is a Z3 constant array.
4640
4641 >>> a = K(IntSort(), 10)
4642 >>> is_K(a)
4643 True
4644 >>> a = Array('a', IntSort(), IntSort())
4645 >>> is_K(a)
4646 False
4647 """
4648 return is_app_of(a, Z3_OP_CONST_ARRAY)
4649
4650
4651def is_map(a):
4652 """Return `True` if `a` is a Z3 map array expression.
4653
4654 >>> f = Function('f', IntSort(), IntSort())
4655 >>> b = Array('b', IntSort(), IntSort())
4656 >>> a = Map(f, b)
4657 >>> a
4658 Map(f, b)
4659 >>> is_map(a)
4660 True
4661 >>> is_map(b)
4662 False
4663 """
4664 return is_app_of(a, Z3_OP_ARRAY_MAP)
4665
4666
4668 """Return `True` if `a` is a Z3 default array expression.
4669 >>> d = Default(K(IntSort(), 10))
4670 >>> is_default(d)
4671 True
4672 """
4673 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4674
4675
4677 """Return the function declaration associated with a Z3 map array expression.
4678
4679 >>> f = Function('f', IntSort(), IntSort())
4680 >>> b = Array('b', IntSort(), IntSort())
4681 >>> a = Map(f, b)
4682 >>> eq(f, get_map_func(a))
4683 True
4684 >>> get_map_func(a)
4685 f
4686 >>> get_map_func(a)(0)
4687 f(0)
4688 """
4689 if z3_debug():
4690 _z3_assert(is_map(a), "Z3 array map expression expected.")
4691 return FuncDeclRef(
4693 a.ctx_ref(),
4694 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4695 ),
4696 ctx=a.ctx,
4697 )
4698
4699
4700def ArraySort(*sig):
4701 """Return the Z3 array sort with the given domain and range sorts.
4702
4703 >>> A = ArraySort(IntSort(), BoolSort())
4704 >>> A
4705 Array(Int, Bool)
4706 >>> A.domain()
4707 Int
4708 >>> A.range()
4709 Bool
4710 >>> AA = ArraySort(IntSort(), A)
4711 >>> AA
4712 Array(Int, Array(Int, Bool))
4713 """
4714 sig = _get_args(sig)
4715 if z3_debug():
4716 _z3_assert(len(sig) > 1, "At least two arguments expected")
4717 arity = len(sig) - 1
4718 r = sig[arity]
4719 d = sig[0]
4720 if z3_debug():
4721 for s in sig:
4722 _z3_assert(is_sort(s), "Z3 sort expected")
4723 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4724 ctx = d.ctx
4725 if len(sig) == 2:
4726 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4727 dom = (Sort * arity)()
4728 for i in range(arity):
4729 dom[i] = sig[i].ast
4730 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4731
4732
4733def Array(name, *sorts):
4734 """Return an array constant named `name` with the given domain and range sorts.
4735
4736 >>> a = Array('a', IntSort(), IntSort())
4737 >>> a.sort()
4738 Array(Int, Int)
4739 >>> a[0]
4740 a[0]
4741 """
4742 s = ArraySort(sorts)
4743 ctx = s.ctx
4744 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4745
4746
4747def Update(a, *args):
4748 """Return a Z3 store array expression.
4749
4750 >>> a = Array('a', IntSort(), IntSort())
4751 >>> i, v = Ints('i v')
4752 >>> s = Update(a, i, v)
4753 >>> s.sort()
4754 Array(Int, Int)
4755 >>> prove(s[i] == v)
4756 proved
4757 >>> j = Int('j')
4758 >>> prove(Implies(i != j, s[j] == a[j]))
4759 proved
4760 """
4761 if z3_debug():
4762 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4763 args = _get_args(args)
4764 ctx = a.ctx
4765 if len(args) <= 1:
4766 raise Z3Exception("array update requires index and value arguments")
4767 if len(args) == 2:
4768 i = args[0]
4769 v = args[1]
4770 i = a.sort().domain().cast(i)
4771 v = a.sort().range().cast(v)
4772 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4773 v = a.sort().range().cast(args[-1])
4774 idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
4775 _args, sz = _to_ast_array(idxs)
4776 return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
4777
4778
4779def Default(a):
4780 """ Return a default value for array expression.
4781 >>> b = K(IntSort(), 1)
4782 >>> prove(Default(b) == 1)
4783 proved
4784 """
4785 if z3_debug():
4786 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4787 return a.default()
4788
4789
4790def Store(a, *args):
4791 """Return a Z3 store array expression.
4792
4793 >>> a = Array('a', IntSort(), IntSort())
4794 >>> i, v = Ints('i v')
4795 >>> s = Store(a, i, v)
4796 >>> s.sort()
4797 Array(Int, Int)
4798 >>> prove(s[i] == v)
4799 proved
4800 >>> j = Int('j')
4801 >>> prove(Implies(i != j, s[j] == a[j]))
4802 proved
4803 """
4804 return Update(a, args)
4805
4806
4807def Select(a, *args):
4808 """Return a Z3 select array expression.
4809
4810 >>> a = Array('a', IntSort(), IntSort())
4811 >>> i = Int('i')
4812 >>> Select(a, i)
4813 a[i]
4814 >>> eq(Select(a, i), a[i])
4815 True
4816 """
4817 args = _get_args(args)
4818 if z3_debug():
4819 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4820 return a[args]
4821
4822
4823def Map(f, *args):
4824 """Return a Z3 map array expression.
4825
4826 >>> f = Function('f', IntSort(), IntSort(), IntSort())
4827 >>> a1 = Array('a1', IntSort(), IntSort())
4828 >>> a2 = Array('a2', IntSort(), IntSort())
4829 >>> b = Map(f, a1, a2)
4830 >>> b
4831 Map(f, a1, a2)
4832 >>> prove(b[0] == f(a1[0], a2[0]))
4833 proved
4834 """
4835 args = _get_args(args)
4836 if z3_debug():
4837 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4838 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4839 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4840 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4841 _args, sz = _to_ast_array(args)
4842 ctx = f.ctx
4843 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4844
4845
4846def K(dom, v):
4847 """Return a Z3 constant array expression.
4848
4849 >>> a = K(IntSort(), 10)
4850 >>> a
4851 K(Int, 10)
4852 >>> a.sort()
4853 Array(Int, Int)
4854 >>> i = Int('i')
4855 >>> a[i]
4856 K(Int, 10)[i]
4857 >>> simplify(a[i])
4858 10
4859 """
4860 if z3_debug():
4861 _z3_assert(is_sort(dom), "Z3 sort expected")
4862 ctx = dom.ctx
4863 if not is_expr(v):
4864 v = _py2expr(v, ctx)
4865 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4866
4867
4868def Ext(a, b):
4869 """Return extensionality index for one-dimensional arrays.
4870 >> a, b = Consts('a b', SetSort(IntSort()))
4871 >> Ext(a, b)
4872 Ext(a, b)
4873 """
4874 ctx = a.ctx
4875 if z3_debug():
4876 _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
4877 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4878
4879
4880def SetHasSize(a, k):
4881 ctx = a.ctx
4882 k = _py2expr(k, ctx)
4883 return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4884
4885
4887 """Return `True` if `a` is a Z3 array select application.
4888
4889 >>> a = Array('a', IntSort(), IntSort())
4890 >>> is_select(a)
4891 False
4892 >>> i = Int('i')
4893 >>> is_select(a[i])
4894 True
4895 """
4896 return is_app_of(a, Z3_OP_SELECT)
4897
4898
4900 """Return `True` if `a` is a Z3 array store application.
4901
4902 >>> a = Array('a', IntSort(), IntSort())
4903 >>> is_store(a)
4904 False
4905 >>> is_store(Store(a, 0, 1))
4906 True
4907 """
4908 return is_app_of(a, Z3_OP_STORE)
4909
4910
4915
4916
4917def SetSort(s):
4918 """ Create a set sort over element sort s"""
4919 return ArraySort(s, BoolSort())
4920
4921
4923 """Create the empty set
4924 >>> EmptySet(IntSort())
4925 K(Int, False)
4926 """
4927 ctx = s.ctx
4928 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4929
4930
4931def FullSet(s):
4932 """Create the full set
4933 >>> FullSet(IntSort())
4934 K(Int, True)
4935 """
4936 ctx = s.ctx
4937 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4938
4939
4940def SetUnion(*args):
4941 """ Take the union of sets
4942 >>> a = Const('a', SetSort(IntSort()))
4943 >>> b = Const('b', SetSort(IntSort()))
4944 >>> SetUnion(a, b)
4945 union(a, b)
4946 """
4947 args = _get_args(args)
4948 ctx = _ctx_from_ast_arg_list(args)
4949 _args, sz = _to_ast_array(args)
4950 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4951
4952
4953def SetIntersect(*args):
4954 """ Take the union of sets
4955 >>> a = Const('a', SetSort(IntSort()))
4956 >>> b = Const('b', SetSort(IntSort()))
4957 >>> SetIntersect(a, b)
4958 intersection(a, b)
4959 """
4960 args = _get_args(args)
4961 ctx = _ctx_from_ast_arg_list(args)
4962 _args, sz = _to_ast_array(args)
4963 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4964
4965
4966def SetAdd(s, e):
4967 """ Add element e to set s
4968 >>> a = Const('a', SetSort(IntSort()))
4969 >>> SetAdd(a, 1)
4970 Store(a, 1, True)
4971 """
4972 ctx = _ctx_from_ast_arg_list([s, e])
4973 e = _py2expr(e, ctx)
4974 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4975
4976
4977def SetDel(s, e):
4978 """ Remove element e to set s
4979 >>> a = Const('a', SetSort(IntSort()))
4980 >>> SetDel(a, 1)
4981 Store(a, 1, False)
4982 """
4983 ctx = _ctx_from_ast_arg_list([s, e])
4984 e = _py2expr(e, ctx)
4985 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4986
4987
4989 """ The complement of set s
4990 >>> a = Const('a', SetSort(IntSort()))
4991 >>> SetComplement(a)
4992 complement(a)
4993 """
4994 ctx = s.ctx
4995 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4996
4997
4999 """ The set difference of a and b
5000 >>> a = Const('a', SetSort(IntSort()))
5001 >>> b = Const('b', SetSort(IntSort()))
5002 >>> SetDifference(a, b)
5003 setminus(a, b)
5004 """
5005 ctx = _ctx_from_ast_arg_list([a, b])
5006 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5007
5008
5009def IsMember(e, s):
5010 """ Check if e is a member of set s
5011 >>> a = Const('a', SetSort(IntSort()))
5012 >>> IsMember(1, a)
5013 a[1]
5014 """
5015 ctx = _ctx_from_ast_arg_list([s, e])
5016 e = _py2expr(e, ctx)
5017 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5018
5019
5020def IsSubset(a, b):
5021 """ Check if a is a subset of b
5022 >>> a = Const('a', SetSort(IntSort()))
5023 >>> b = Const('b', SetSort(IntSort()))
5024 >>> IsSubset(a, b)
5025 subset(a, b)
5026 """
5027 ctx = _ctx_from_ast_arg_list([a, b])
5028 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5029
5030
5031
5036
5038 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5039 if not isinstance(acc, tuple):
5040 return False
5041 if len(acc) != 2:
5042 return False
5043 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5044
5045
5047 """Helper class for declaring Z3 datatypes.
5048
5049 >>> List = Datatype('List')
5050 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5051 >>> List.declare('nil')
5052 >>> List = List.create()
5053 >>> # List is now a Z3 declaration
5054 >>> List.nil
5055 nil
5056 >>> List.cons(10, List.nil)
5057 cons(10, nil)
5058 >>> List.cons(10, List.nil).sort()
5059 List
5060 >>> cons = List.cons
5061 >>> nil = List.nil
5062 >>> car = List.car
5063 >>> cdr = List.cdr
5064 >>> n = cons(1, cons(0, nil))
5065 >>> n
5066 cons(1, cons(0, nil))
5067 >>> simplify(cdr(n))
5068 cons(0, nil)
5069 >>> simplify(car(n))
5070 1
5071 """
5072
5073 def __init__(self, name, ctx=None):
5074 self.ctx = _get_ctx(ctx)
5075 self.name = name
5077
5078 def __deepcopy__(self, memo={}):
5079 r = Datatype(self.name, self.ctx)
5080 r.constructors = copy.deepcopy(self.constructors)
5081 return r
5082
5083 def declare_core(self, name, rec_name, *args):
5084 if z3_debug():
5085 _z3_assert(isinstance(name, str), "String expected")
5086 _z3_assert(isinstance(rec_name, str), "String expected")
5087 _z3_assert(
5088 all([_valid_accessor(a) for a in args]),
5089 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5090 )
5091 self.constructors.append((name, rec_name, args))
5092
5093 def declare(self, name, *args):
5094 """Declare constructor named `name` with the given accessors `args`.
5095 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5096 or a reference to the datatypes being declared.
5097
5098 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5099 declares the constructor named `cons` that builds a new List using an integer and a List.
5100 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5101 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5102 we use the method create() to create the actual datatype in Z3.
5103
5104 >>> List = Datatype('List')
5105 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5106 >>> List.declare('nil')
5107 >>> List = List.create()
5108 """
5109 if z3_debug():
5110 _z3_assert(isinstance(name, str), "String expected")
5111 _z3_assert(name != "", "Constructor name cannot be empty")
5112 return self.declare_core(name, "is-" + name, *args)
5113
5114 def __repr__(self):
5115 return "Datatype(%s, %s)" % (self.name, self.constructors)
5116
5117 def create(self):
5118 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5119
5120 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5121
5122 >>> List = Datatype('List')
5123 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5124 >>> List.declare('nil')
5125 >>> List = List.create()
5126 >>> List.nil
5127 nil
5128 >>> List.cons(10, List.nil)
5129 cons(10, nil)
5130 """
5131 return CreateDatatypes([self])[0]
5132
5133
5135 """Auxiliary object used to create Z3 datatypes."""
5136
5137 def __init__(self, c, ctx):
5138 self.c = c
5139 self.ctx = ctx
5140
5141 def __del__(self):
5142 if self.ctx.ref() is not None and Z3_del_constructor is not None:
5143 Z3_del_constructor(self.ctx.ref(), self.c)
5144
5145
5147 """Auxiliary object used to create Z3 datatypes."""
5148
5149 def __init__(self, c, ctx):
5150 self.c = c
5151 self.ctx = ctx
5152
5153 def __del__(self):
5154 if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5155 Z3_del_constructor_list(self.ctx.ref(), self.c)
5156
5157
5159 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5160
5161 In the following example we define a Tree-List using two mutually recursive datatypes.
5162
5163 >>> TreeList = Datatype('TreeList')
5164 >>> Tree = Datatype('Tree')
5165 >>> # Tree has two constructors: leaf and node
5166 >>> Tree.declare('leaf', ('val', IntSort()))
5167 >>> # a node contains a list of trees
5168 >>> Tree.declare('node', ('children', TreeList))
5169 >>> TreeList.declare('nil')
5170 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5171 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5172 >>> Tree.val(Tree.leaf(10))
5173 val(leaf(10))
5174 >>> simplify(Tree.val(Tree.leaf(10)))
5175 10
5176 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5177 >>> n1
5178 node(cons(leaf(10), cons(leaf(20), nil)))
5179 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5180 >>> simplify(n2 == n1)
5181 False
5182 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5183 True
5184 """
5185 ds = _get_args(ds)
5186 if z3_debug():
5187 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5188 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5189 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5190 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5191 ctx = ds[0].ctx
5192 num = len(ds)
5193 names = (Symbol * num)()
5194 out = (Sort * num)()
5195 clists = (ConstructorList * num)()
5196 to_delete = []
5197 for i in range(num):
5198 d = ds[i]
5199 names[i] = to_symbol(d.name, ctx)
5200 num_cs = len(d.constructors)
5201 cs = (Constructor * num_cs)()
5202 for j in range(num_cs):
5203 c = d.constructors[j]
5204 cname = to_symbol(c[0], ctx)
5205 rname = to_symbol(c[1], ctx)
5206 fs = c[2]
5207 num_fs = len(fs)
5208 fnames = (Symbol * num_fs)()
5209 sorts = (Sort * num_fs)()
5210 refs = (ctypes.c_uint * num_fs)()
5211 for k in range(num_fs):
5212 fname = fs[k][0]
5213 ftype = fs[k][1]
5214 fnames[k] = to_symbol(fname, ctx)
5215 if isinstance(ftype, Datatype):
5216 if z3_debug():
5217 _z3_assert(
5218 ds.count(ftype) == 1,
5219 "One and only one occurrence of each datatype is expected",
5220 )
5221 sorts[k] = None
5222 refs[k] = ds.index(ftype)
5223 else:
5224 if z3_debug():
5225 _z3_assert(is_sort(ftype), "Z3 sort expected")
5226 sorts[k] = ftype.ast
5227 refs[k] = 0
5228 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5229 to_delete.append(ScopedConstructor(cs[j], ctx))
5230 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5231 to_delete.append(ScopedConstructorList(clists[i], ctx))
5232 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5233 result = []
5234 # Create a field for every constructor, recognizer and accessor
5235 for i in range(num):
5236 dref = DatatypeSortRef(out[i], ctx)
5237 num_cs = dref.num_constructors()
5238 for j in range(num_cs):
5239 cref = dref.constructor(j)
5240 cref_name = cref.name()
5241 cref_arity = cref.arity()
5242 if cref.arity() == 0:
5243 cref = cref()
5244 setattr(dref, cref_name, cref)
5245 rref = dref.recognizer(j)
5246 setattr(dref, "is_" + cref_name, rref)
5247 for k in range(cref_arity):
5248 aref = dref.accessor(j, k)
5249 setattr(dref, aref.name(), aref)
5250 result.append(dref)
5251 return tuple(result)
5252
5253
5255 """Datatype sorts."""
5256
5258 """Return the number of constructors in the given Z3 datatype.
5259
5260 >>> List = Datatype('List')
5261 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5262 >>> List.declare('nil')
5263 >>> List = List.create()
5264 >>> # List is now a Z3 declaration
5265 >>> List.num_constructors()
5266 2
5267 """
5268 return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
5269
5270 def constructor(self, idx):
5271 """Return a constructor of the datatype `self`.
5272
5273 >>> List = Datatype('List')
5274 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5275 >>> List.declare('nil')
5276 >>> List = List.create()
5277 >>> # List is now a Z3 declaration
5278 >>> List.num_constructors()
5279 2
5280 >>> List.constructor(0)
5281 cons
5282 >>> List.constructor(1)
5283 nil
5284 """
5285 if z3_debug():
5286 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5287 return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
5288
5289 def recognizer(self, idx):
5290 """In Z3, each constructor has an associated recognizer predicate.
5291
5292 If the constructor is named `name`, then the recognizer `is_name`.
5293
5294 >>> List = Datatype('List')
5295 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5296 >>> List.declare('nil')
5297 >>> List = List.create()
5298 >>> # List is now a Z3 declaration
5299 >>> List.num_constructors()
5300 2
5301 >>> List.recognizer(0)
5302 is(cons)
5303 >>> List.recognizer(1)
5304 is(nil)
5305 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5306 False
5307 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5308 True
5309 >>> l = Const('l', List)
5310 >>> simplify(List.is_cons(l))
5311 is(cons, l)
5312 """
5313 if z3_debug():
5314 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5315 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
5316
5317 def accessor(self, i, j):
5318 """In Z3, each constructor has 0 or more accessor.
5319 The number of accessors is equal to the arity of the constructor.
5320
5321 >>> List = Datatype('List')
5322 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5323 >>> List.declare('nil')
5324 >>> List = List.create()
5325 >>> List.num_constructors()
5326 2
5327 >>> List.constructor(0)
5328 cons
5329 >>> num_accs = List.constructor(0).arity()
5330 >>> num_accs
5331 2
5332 >>> List.accessor(0, 0)
5333 car
5334 >>> List.accessor(0, 1)
5335 cdr
5336 >>> List.constructor(1)
5337 nil
5338 >>> num_accs = List.constructor(1).arity()
5339 >>> num_accs
5340 0
5341 """
5342 if z3_debug():
5343 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5344 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5345 return FuncDeclRef(
5347 ctx=self.ctx,
5348 )
5349
5350
5352 """Datatype expressions."""
5353
5354 def sort(self):
5355 """Return the datatype sort of the datatype expression `self`."""
5356 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
5357
5358def DatatypeSort(name, ctx = None):
5359 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype"""
5360 ctx = _get_ctx(ctx)
5361 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
5362
5363def TupleSort(name, sorts, ctx=None):
5364 """Create a named tuple sort base on a set of underlying sorts
5365 Example:
5366 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5367 """
5368 tuple = Datatype(name, ctx)
5369 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5370 tuple.declare(name, *projects)
5371 tuple = tuple.create()
5372 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5373
5374
5375def DisjointSum(name, sorts, ctx=None):
5376 """Create a named tagged union sort base on a set of underlying sorts
5377 Example:
5378 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5379 """
5380 sum = Datatype(name, ctx)
5381 for i in range(len(sorts)):
5382 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5383 sum = sum.create()
5384 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5385
5386
5387def EnumSort(name, values, ctx=None):
5388 """Return a new enumeration sort named `name` containing the given values.
5389
5390 The result is a pair (sort, list of constants).
5391 Example:
5392 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5393 """
5394 if z3_debug():
5395 _z3_assert(isinstance(name, str), "Name must be a string")
5396 _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5397 _z3_assert(len(values) > 0, "At least one value expected")
5398 ctx = _get_ctx(ctx)
5399 num = len(values)
5400 _val_names = (Symbol * num)()
5401 for i in range(num):
5402 _val_names[i] = to_symbol(values[i])
5403 _values = (FuncDecl * num)()
5404 _testers = (FuncDecl * num)()
5405 name = to_symbol(name)
5406 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5407 V = []
5408 for i in range(num):
5409 V.append(FuncDeclRef(_values[i], ctx))
5410 V = [a() for a in V]
5411 return S, V
5412
5413
5418
5419
5421 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5422
5423 Consider using the function `args2params` to create instances of this object.
5424 """
5425
5426 def __init__(self, ctx=None, params=None):
5427 self.ctx = _get_ctx(ctx)
5428 if params is None:
5429 self.params = Z3_mk_params(self.ctx.ref())
5430 else:
5431 self.params = params
5432 Z3_params_inc_ref(self.ctx.ref(), self.params)
5433
5434 def __deepcopy__(self, memo={}):
5435 return ParamsRef(self.ctx, self.params)
5436
5437 def __del__(self):
5438 if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
5439 Z3_params_dec_ref(self.ctx.ref(), self.params)
5440
5441 def set(self, name, val):
5442 """Set parameter name with value val."""
5443 if z3_debug():
5444 _z3_assert(isinstance(name, str), "parameter name must be a string")
5445 name_sym = to_symbol(name, self.ctx)
5446 if isinstance(val, bool):
5447 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5448 elif _is_int(val):
5449 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5450 elif isinstance(val, float):
5451 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5452 elif isinstance(val, str):
5453 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5454 else:
5455 if z3_debug():
5456 _z3_assert(False, "invalid parameter value")
5457
5458 def __repr__(self):
5459 return Z3_params_to_string(self.ctx.ref(), self.params)
5460
5461 def validate(self, ds):
5462 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5463 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5464
5465
5466def args2params(arguments, keywords, ctx=None):
5467 """Convert python arguments into a Z3_params object.
5468 A ':' is added to the keywords, and '_' is replaced with '-'
5469
5470 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5471 (params model true relevancy 2 elim_and true)
5472 """
5473 if z3_debug():
5474 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5475 prev = None
5476 r = ParamsRef(ctx)
5477 for a in arguments:
5478 if prev is None:
5479 prev = a
5480 else:
5481 r.set(prev, a)
5482 prev = None
5483 for k in keywords:
5484 v = keywords[k]
5485 r.set(k, v)
5486 return r
5487
5488
5490 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5491 """
5492
5493 def __init__(self, descr, ctx=None):
5494 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5495 self.ctx = _get_ctx(ctx)
5496 self.descr = descr
5497 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5498
5499 def __deepcopy__(self, memo={}):
5500 return ParamsDescrsRef(self.descr, self.ctx)
5501
5502 def __del__(self):
5503 if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
5504 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5505
5506 def size(self):
5507 """Return the size of in the parameter description `self`.
5508 """
5509 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5510
5511 def __len__(self):
5512 """Return the size of in the parameter description `self`.
5513 """
5514 return self.size()
5515
5516 def get_name(self, i):
5517 """Return the i-th parameter name in the parameter description `self`.
5518 """
5519 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5520
5521 def get_kind(self, n):
5522 """Return the kind of the parameter named `n`.
5523 """
5524 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5525
5526 def get_documentation(self, n):
5527 """Return the documentation string of the parameter named `n`.
5528 """
5529 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5530
5531 def __getitem__(self, arg):
5532 if _is_int(arg):
5533 return self.get_name(arg)
5534 else:
5535 return self.get_kind(arg)
5536
5537 def __repr__(self):
5538 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5539
5540
5545
5546
5548 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5549
5550 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5551 A goal has a solution if one of its subgoals has a solution.
5552 A goal is unsatisfiable if all subgoals are unsatisfiable.
5553 """
5554
5555 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5556 if z3_debug():
5557 _z3_assert(goal is None or ctx is not None,
5558 "If goal is different from None, then ctx must be also different from None")
5559 self.ctx = _get_ctx(ctx)
5560 self.goal = goal
5561 if self.goal is None:
5562 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5563 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5564
5565 def __del__(self):
5566 if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
5567 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5568
5569 def depth(self):
5570 """Return the depth of the goal `self`.
5571 The depth corresponds to the number of tactics applied to `self`.
5572
5573 >>> x, y = Ints('x y')
5574 >>> g = Goal()
5575 >>> g.add(x == 0, y >= x + 1)
5576 >>> g.depth()
5577 0
5578 >>> r = Then('simplify', 'solve-eqs')(g)
5579 >>> # r has 1 subgoal
5580 >>> len(r)
5581 1
5582 >>> r[0].depth()
5583 2
5584 """
5585 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5586
5587 def inconsistent(self):
5588 """Return `True` if `self` contains the `False` constraints.
5589
5590 >>> x, y = Ints('x y')
5591 >>> g = Goal()
5592 >>> g.inconsistent()
5593 False
5594 >>> g.add(x == 0, x == 1)
5595 >>> g
5596 [x == 0, x == 1]
5597 >>> g.inconsistent()
5598 False
5599 >>> g2 = Tactic('propagate-values')(g)[0]
5600 >>> g2.inconsistent()
5601 True
5602 """
5603 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5604
5605 def prec(self):
5606 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5607
5608 >>> g = Goal()
5609 >>> g.prec() == Z3_GOAL_PRECISE
5610 True
5611 >>> x, y = Ints('x y')
5612 >>> g.add(x == y + 1)
5613 >>> g.prec() == Z3_GOAL_PRECISE
5614 True
5615 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5616 >>> g2 = t(g)[0]
5617 >>> g2
5618 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5619 >>> g2.prec() == Z3_GOAL_PRECISE
5620 False
5621 >>> g2.prec() == Z3_GOAL_UNDER
5622 True
5623 """
5624 return Z3_goal_precision(self.ctx.ref(), self.goal)
5625
5626 def precision(self):
5627 """Alias for `prec()`.
5628
5629 >>> g = Goal()
5630 >>> g.precision() == Z3_GOAL_PRECISE
5631 True
5632 """
5633 return self.prec()
5634
5635 def size(self):
5636 """Return the number of constraints in the goal `self`.
5637
5638 >>> g = Goal()
5639 >>> g.size()
5640 0
5641 >>> x, y = Ints('x y')
5642 >>> g.add(x == 0, y > x)
5643 >>> g.size()
5644 2
5645 """
5646 return int(Z3_goal_size(self.ctx.ref(), self.goal))
5647
5648 def __len__(self):
5649 """Return the number of constraints in the goal `self`.
5650
5651 >>> g = Goal()
5652 >>> len(g)
5653 0
5654 >>> x, y = Ints('x y')
5655 >>> g.add(x == 0, y > x)
5656 >>> len(g)
5657 2
5658 """
5659 return self.size()
5660
5661 def get(self, i):
5662 """Return a constraint in the goal `self`.
5663
5664 >>> g = Goal()
5665 >>> x, y = Ints('x y')
5666 >>> g.add(x == 0, y > x)
5667 >>> g.get(0)
5668 x == 0
5669 >>> g.get(1)
5670 y > x
5671 """
5672 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5673
5674 def __getitem__(self, arg):
5675 """Return a constraint in the goal `self`.
5676
5677 >>> g = Goal()
5678 >>> x, y = Ints('x y')
5679 >>> g.add(x == 0, y > x)
5680 >>> g[0]
5681 x == 0
5682 >>> g[1]
5683 y > x
5684 """
5685 if arg >= len(self):
5686 raise IndexError
5687 return self.get(arg)
5688
5689 def assert_exprs(self, *args):
5690 """Assert constraints into the goal.
5691
5692 >>> x = Int('x')
5693 >>> g = Goal()
5694 >>> g.assert_exprs(x > 0, x < 2)
5695 >>> g
5696 [x > 0, x < 2]
5697 """
5698 args = _get_args(args)
5699 s = BoolSort(self.ctx)
5700 for arg in args:
5701 arg = s.cast(arg)
5702 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5703
5704 def append(self, *args):
5705 """Add constraints.
5706
5707 >>> x = Int('x')
5708 >>> g = Goal()
5709 >>> g.append(x > 0, x < 2)
5710 >>> g
5711 [x > 0, x < 2]
5712 """
5713 self.assert_exprs(*args)
5714
5715 def insert(self, *args):
5716 """Add constraints.
5717
5718 >>> x = Int('x')
5719 >>> g = Goal()
5720 >>> g.insert(x > 0, x < 2)
5721 >>> g
5722 [x > 0, x < 2]
5723 """
5724 self.assert_exprs(*args)
5725
5726 def add(self, *args):
5727 """Add constraints.
5728
5729 >>> x = Int('x')
5730 >>> g = Goal()
5731 >>> g.add(x > 0, x < 2)
5732 >>> g
5733 [x > 0, x < 2]
5734 """
5735 self.assert_exprs(*args)
5736
5737 def convert_model(self, model):
5738 """Retrieve model from a satisfiable goal
5739 >>> a, b = Ints('a b')
5740 >>> g = Goal()
5741 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5742 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5743 >>> r = t(g)
5744 >>> r[0]
5745 [Or(b == 0, b == 1), Not(0 <= b)]
5746 >>> r[1]
5747 [Or(b == 0, b == 1), Not(1 <= b)]
5748 >>> # Remark: the subgoal r[0] is unsatisfiable
5749 >>> # Creating a solver for solving the second subgoal
5750 >>> s = Solver()
5751 >>> s.add(r[1])
5752 >>> s.check()
5753 sat
5754 >>> s.model()
5755 [b = 0]
5756 >>> # Model s.model() does not assign a value to `a`
5757 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5758 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5759 >>> r[1].convert_model(s.model())
5760 [b = 0, a = 1]
5761 """
5762 if z3_debug():
5763 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5764 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5765
5766 def __repr__(self):
5767 return obj_to_string(self)
5768
5769 def sexpr(self):
5770 """Return a textual representation of the s-expression representing the goal."""
5771 return Z3_goal_to_string(self.ctx.ref(), self.goal)
5772
5773 def dimacs(self, include_names=True):
5774 """Return a textual representation of the goal in DIMACS format."""
5775 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
5776
5777 def translate(self, target):
5778 """Copy goal `self` to context `target`.
5779
5780 >>> x = Int('x')
5781 >>> g = Goal()
5782 >>> g.add(x > 10)
5783 >>> g
5784 [x > 10]
5785 >>> c2 = Context()
5786 >>> g2 = g.translate(c2)
5787 >>> g2
5788 [x > 10]
5789 >>> g.ctx == main_ctx()
5790 True
5791 >>> g2.ctx == c2
5792 True
5793 >>> g2.ctx == main_ctx()
5794 False
5795 """
5796 if z3_debug():
5797 _z3_assert(isinstance(target, Context), "target must be a context")
5798 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5799
5800 def __copy__(self):
5801 return self.translate(self.ctx)
5802
5803 def __deepcopy__(self, memo={}):
5804 return self.translate(self.ctx)
5805
5806 def simplify(self, *arguments, **keywords):
5807 """Return a new simplified goal.
5808
5809 This method is essentially invoking the simplify tactic.
5810
5811 >>> g = Goal()
5812 >>> x = Int('x')
5813 >>> g.add(x + 1 >= 2)
5814 >>> g
5815 [x + 1 >= 2]
5816 >>> g2 = g.simplify()
5817 >>> g2
5818 [x >= 1]
5819 >>> # g was not modified
5820 >>> g
5821 [x + 1 >= 2]
5822 """
5823 t = Tactic("simplify")
5824 return t.apply(self, *arguments, **keywords)[0]
5825
5826 def as_expr(self):
5827 """Return goal `self` as a single Z3 expression.
5828
5829 >>> x = Int('x')
5830 >>> g = Goal()
5831 >>> g.as_expr()
5832 True
5833 >>> g.add(x > 1)
5834 >>> g.as_expr()
5835 x > 1
5836 >>> g.add(x < 10)
5837 >>> g.as_expr()
5838 And(x > 1, x < 10)
5839 """
5840 sz = len(self)
5841 if sz == 0:
5842 return BoolVal(True, self.ctx)
5843 elif sz == 1:
5844 return self.get(0)
5845 else:
5846 return And([self.get(i) for i in range(len(self))], self.ctx)
5847
5848
5853
5854
5856 """A collection (vector) of ASTs."""
5857
5858 def __init__(self, v=None, ctx=None):
5859 self.vector = None
5860 if v is None:
5861 self.ctx = _get_ctx(ctx)
5862 self.vector = Z3_mk_ast_vector(self.ctx.ref())
5863 else:
5864 self.vector = v
5865 assert ctx is not None
5866 self.ctx = ctx
5867 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5868
5869 def __del__(self):
5870 if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
5871 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5872
5873 def __len__(self):
5874 """Return the size of the vector `self`.
5875
5876 >>> A = AstVector()
5877 >>> len(A)
5878 0
5879 >>> A.push(Int('x'))
5880 >>> A.push(Int('x'))
5881 >>> len(A)
5882 2
5883 """
5884 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5885
5886 def __getitem__(self, i):
5887 """Return the AST at position `i`.
5888
5889 >>> A = AstVector()
5890 >>> A.push(Int('x') + 1)
5891 >>> A.push(Int('y'))
5892 >>> A[0]
5893 x + 1
5894 >>> A[1]
5895 y
5896 """
5897
5898 if isinstance(i, int):
5899 if i < 0:
5900 i += self.__len__()
5901
5902 if i >= self.__len__():
5903 raise IndexError
5904 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5905
5906 elif isinstance(i, slice):
5907 result = []
5908 for ii in range(*i.indices(self.__len__())):
5909 result.append(_to_ast_ref(
5910 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
5911 self.ctx,
5912 ))
5913 return result
5914
5915 def __setitem__(self, i, v):
5916 """Update AST at position `i`.
5917
5918 >>> A = AstVector()
5919 >>> A.push(Int('x') + 1)
5920 >>> A.push(Int('y'))
5921 >>> A[0]
5922 x + 1
5923 >>> A[0] = Int('x')
5924 >>> A[0]
5925 x
5926 """
5927 if i >= self.__len__():
5928 raise IndexError
5929 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5930
5931 def push(self, v):
5932 """Add `v` in the end of the vector.
5933
5934 >>> A = AstVector()
5935 >>> len(A)
5936 0
5937 >>> A.push(Int('x'))
5938 >>> len(A)
5939 1
5940 """
5941 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5942
5943 def resize(self, sz):
5944 """Resize the vector to `sz` elements.
5945
5946 >>> A = AstVector()
5947 >>> A.resize(10)
5948 >>> len(A)
5949 10
5950 >>> for i in range(10): A[i] = Int('x')
5951 >>> A[5]
5952 x
5953 """
5954 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5955
5956 def __contains__(self, item):
5957 """Return `True` if the vector contains `item`.
5958
5959 >>> x = Int('x')
5960 >>> A = AstVector()
5961 >>> x in A
5962 False
5963 >>> A.push(x)
5964 >>> x in A
5965 True
5966 >>> (x+1) in A
5967 False
5968 >>> A.push(x+1)
5969 >>> (x+1) in A
5970 True
5971 >>> A
5972 [x, x + 1]
5973 """
5974 for elem in self:
5975 if elem.eq(item):
5976 return True
5977 return False
5978
5979 def translate(self, other_ctx):
5980 """Copy vector `self` to context `other_ctx`.
5981
5982 >>> x = Int('x')
5983 >>> A = AstVector()
5984 >>> A.push(x)
5985 >>> c2 = Context()
5986 >>> B = A.translate(c2)
5987 >>> B
5988 [x]
5989 """
5990 return AstVector(
5991 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
5992 ctx=other_ctx,
5993 )
5994
5995 def __copy__(self):
5996 return self.translate(self.ctx)
5997
5998 def __deepcopy__(self, memo={}):
5999 return self.translate(self.ctx)
6000
6001 def __repr__(self):
6002 return obj_to_string(self)
6003
6004 def sexpr(self):
6005 """Return a textual representation of the s-expression representing the vector."""
6006 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
6007
6008
6013
6014
6016 """A mapping from ASTs to ASTs."""
6017
6018 def __init__(self, m=None, ctx=None):
6019 self.map = None
6020 if m is None:
6021 self.ctx = _get_ctx(ctx)
6022 self.map = Z3_mk_ast_map(self.ctx.ref())
6023 else:
6024 self.map = m
6025 assert ctx is not None
6026 self.ctx = ctx
6027 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6028
6029 def __deepcopy__(self, memo={}):
6030 return AstMap(self.map, self.ctx)
6031
6032 def __del__(self):
6033 if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6034 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6035
6036 def __len__(self):
6037 """Return the size of the map.
6038
6039 >>> M = AstMap()
6040 >>> len(M)
6041 0
6042 >>> x = Int('x')
6043 >>> M[x] = IntVal(1)
6044 >>> len(M)
6045 1
6046 """
6047 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6048
6049 def __contains__(self, key):
6050 """Return `True` if the map contains key `key`.
6051
6052 >>> M = AstMap()
6053 >>> x = Int('x')
6054 >>> M[x] = x + 1
6055 >>> x in M
6056 True
6057 >>> x+1 in M
6058 False
6059 """
6060 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6061
6062 def __getitem__(self, key):
6063 """Retrieve the value associated with key `key`.
6064
6065 >>> M = AstMap()
6066 >>> x = Int('x')
6067 >>> M[x] = x + 1
6068 >>> M[x]
6069 x + 1
6070 """
6071 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6072
6073 def __setitem__(self, k, v):
6074 """Add/Update key `k` with value `v`.
6075
6076 >>> M = AstMap()
6077 >>> x = Int('x')
6078 >>> M[x] = x + 1
6079 >>> len(M)
6080 1
6081 >>> M[x]
6082 x + 1
6083 >>> M[x] = IntVal(1)
6084 >>> M[x]
6085 1
6086 """
6087 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6088
6089 def __repr__(self):
6090 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6091
6092 def erase(self, k):
6093 """Remove the entry associated with key `k`.
6094
6095 >>> M = AstMap()
6096 >>> x = Int('x')
6097 >>> M[x] = x + 1
6098 >>> len(M)
6099 1
6100 >>> M.erase(x)
6101 >>> len(M)
6102 0
6103 """
6104 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6105
6106 def reset(self):
6107 """Remove all entries from the map.
6108
6109 >>> M = AstMap()
6110 >>> x = Int('x')
6111 >>> M[x] = x + 1
6112 >>> M[x+x] = IntVal(1)
6113 >>> len(M)
6114 2
6115 >>> M.reset()
6116 >>> len(M)
6117 0
6118 """
6119 Z3_ast_map_reset(self.ctx.ref(), self.map)
6120
6121 def keys(self):
6122 """Return an AstVector containing all keys in the map.
6123
6124 >>> M = AstMap()
6125 >>> x = Int('x')
6126 >>> M[x] = x + 1
6127 >>> M[x+x] = IntVal(1)
6128 >>> M.keys()
6129 [x, x + x]
6130 """
6131 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6132
6133
6138
6139
6141 """Store the value of the interpretation of a function in a particular point."""
6142
6143 def __init__(self, entry, ctx):
6144 self.entry = entry
6145 self.ctx = ctx
6146 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6147
6148 def __deepcopy__(self, memo={}):
6149 return FuncEntry(self.entry, self.ctx)
6150
6151 def __del__(self):
6152 if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6153 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6154
6155 def num_args(self):
6156 """Return the number of arguments in the given entry.
6157
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.num_args()
6169 2
6170 """
6171 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6172
6173 def arg_value(self, idx):
6174 """Return the value of argument `idx`.
6175
6176 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6177 >>> s = Solver()
6178 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6179 >>> s.check()
6180 sat
6181 >>> m = s.model()
6182 >>> f_i = m[f]
6183 >>> f_i.num_entries()
6184 1
6185 >>> e = f_i.entry(0)
6186 >>> e
6187 [1, 2, 20]
6188 >>> e.num_args()
6189 2
6190 >>> e.arg_value(0)
6191 1
6192 >>> e.arg_value(1)
6193 2
6194 >>> try:
6195 ... e.arg_value(2)
6196 ... except IndexError:
6197 ... print("index error")
6198 index error
6199 """
6200 if idx >= self.num_args():
6201 raise IndexError
6202 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6203
6204 def value(self):
6205 """Return the value of the function at point `self`.
6206
6207 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6208 >>> s = Solver()
6209 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6210 >>> s.check()
6211 sat
6212 >>> m = s.model()
6213 >>> f_i = m[f]
6214 >>> f_i.num_entries()
6215 1
6216 >>> e = f_i.entry(0)
6217 >>> e
6218 [1, 2, 20]
6219 >>> e.num_args()
6220 2
6221 >>> e.value()
6222 20
6223 """
6224 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6225
6226 def as_list(self):
6227 """Return entry `self` as a Python list.
6228 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6229 >>> s = Solver()
6230 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6231 >>> s.check()
6232 sat
6233 >>> m = s.model()
6234 >>> f_i = m[f]
6235 >>> f_i.num_entries()
6236 1
6237 >>> e = f_i.entry(0)
6238 >>> e.as_list()
6239 [1, 2, 20]
6240 """
6241 args = [self.arg_value(i) for i in range(self.num_args())]
6242 args.append(self.value())
6243 return args
6244
6245 def __repr__(self):
6246 return repr(self.as_list())
6247
6248
6250 """Stores the interpretation of a function in a Z3 model."""
6251
6252 def __init__(self, f, ctx):
6253 self.f = f
6254 self.ctx = ctx
6255 if self.f is not None:
6256 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6257
6258 def __del__(self):
6259 if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6260 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6261
6262 def else_value(self):
6263 """
6264 Return the `else` value for a function interpretation.
6265 Return None if Z3 did not specify the `else` value for
6266 this object.
6267
6268 >>> f = Function('f', IntSort(), IntSort())
6269 >>> s = Solver()
6270 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6271 >>> s.check()
6272 sat
6273 >>> m = s.model()
6274 >>> m[f]
6275 [2 -> 0, else -> 1]
6276 >>> m[f].else_value()
6277 1
6278 """
6279 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6280 if r:
6281 return _to_expr_ref(r, self.ctx)
6282 else:
6283 return None
6284
6285 def num_entries(self):
6286 """Return the number of entries/points in the function interpretation `self`.
6287
6288 >>> f = Function('f', IntSort(), IntSort())
6289 >>> s = Solver()
6290 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6291 >>> s.check()
6292 sat
6293 >>> m = s.model()
6294 >>> m[f]
6295 [2 -> 0, else -> 1]
6296 >>> m[f].num_entries()
6297 1
6298 """
6299 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6300
6301 def arity(self):
6302 """Return the number of arguments for each entry in the function interpretation `self`.
6303
6304 >>> f = Function('f', IntSort(), IntSort())
6305 >>> s = Solver()
6306 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6307 >>> s.check()
6308 sat
6309 >>> m = s.model()
6310 >>> m[f].arity()
6311 1
6312 """
6313 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6314
6315 def entry(self, idx):
6316 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6317
6318 >>> f = Function('f', IntSort(), IntSort())
6319 >>> s = Solver()
6320 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6321 >>> s.check()
6322 sat
6323 >>> m = s.model()
6324 >>> m[f]
6325 [2 -> 0, else -> 1]
6326 >>> m[f].num_entries()
6327 1
6328 >>> m[f].entry(0)
6329 [2, 0]
6330 """
6331 if idx >= self.num_entries():
6332 raise IndexError
6333 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6334
6335 def translate(self, other_ctx):
6336 """Copy model 'self' to context 'other_ctx'.
6337 """
6338 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6339
6340 def __copy__(self):
6341 return self.translate(self.ctx)
6342
6343 def __deepcopy__(self, memo={}):
6344 return self.translate(self.ctx)
6345
6346 def as_list(self):
6347 """Return the function interpretation as a Python list.
6348 >>> f = Function('f', IntSort(), IntSort())
6349 >>> s = Solver()
6350 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6351 >>> s.check()
6352 sat
6353 >>> m = s.model()
6354 >>> m[f]
6355 [2 -> 0, else -> 1]
6356 >>> m[f].as_list()
6357 [[2, 0], 1]
6358 """
6359 r = [self.entry(i).as_list() for i in range(self.num_entries())]
6360 r.append(self.else_value())
6361 return r
6362
6363 def __repr__(self):
6364 return obj_to_string(self)
6365
6366
6368 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6369
6370 def __init__(self, m, ctx):
6371 assert ctx is not None
6372 self.model = m
6373 self.ctx = ctx
6374 Z3_model_inc_ref(self.ctx.ref(), self.model)
6375
6376 def __del__(self):
6377 if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
6378 Z3_model_dec_ref(self.ctx.ref(), self.model)
6379
6380 def __repr__(self):
6381 return obj_to_string(self)
6382
6383 def sexpr(self):
6384 """Return a textual representation of the s-expression representing the model."""
6385 return Z3_model_to_string(self.ctx.ref(), self.model)
6386
6387 def eval(self, t, model_completion=False):
6388 """Evaluate the expression `t` in the model `self`.
6389 If `model_completion` is enabled, then a default interpretation is automatically added
6390 for symbols that do not have an interpretation in the model `self`.
6391
6392 >>> x = Int('x')
6393 >>> s = Solver()
6394 >>> s.add(x > 0, x < 2)
6395 >>> s.check()
6396 sat
6397 >>> m = s.model()
6398 >>> m.eval(x + 1)
6399 2
6400 >>> m.eval(x == 1)
6401 True
6402 >>> y = Int('y')
6403 >>> m.eval(y + x)
6404 1 + y
6405 >>> m.eval(y)
6406 y
6407 >>> m.eval(y, model_completion=True)
6408 0
6409 >>> # Now, m contains an interpretation for y
6410 >>> m.eval(y + x)
6411 1
6412 """
6413 r = (Ast * 1)()
6414 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6415 return _to_expr_ref(r[0], self.ctx)
6416 raise Z3Exception("failed to evaluate expression in the model")
6417
6418 def evaluate(self, t, model_completion=False):
6419 """Alias for `eval`.
6420
6421 >>> x = Int('x')
6422 >>> s = Solver()
6423 >>> s.add(x > 0, x < 2)
6424 >>> s.check()
6425 sat
6426 >>> m = s.model()
6427 >>> m.evaluate(x + 1)
6428 2
6429 >>> m.evaluate(x == 1)
6430 True
6431 >>> y = Int('y')
6432 >>> m.evaluate(y + x)
6433 1 + y
6434 >>> m.evaluate(y)
6435 y
6436 >>> m.evaluate(y, model_completion=True)
6437 0
6438 >>> # Now, m contains an interpretation for y
6439 >>> m.evaluate(y + x)
6440 1
6441 """
6442 return self.eval(t, model_completion)
6443
6444 def __len__(self):
6445 """Return the number of constant and function declarations in the model `self`.
6446
6447 >>> f = Function('f', IntSort(), IntSort())
6448 >>> x = Int('x')
6449 >>> s = Solver()
6450 >>> s.add(x > 0, f(x) != x)
6451 >>> s.check()
6452 sat
6453 >>> m = s.model()
6454 >>> len(m)
6455 2
6456 """
6457 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
6458 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6459 return num_consts + num_funcs
6460
6461 def get_interp(self, decl):
6462 """Return the interpretation for a given declaration or constant.
6463
6464 >>> f = Function('f', IntSort(), IntSort())
6465 >>> x = Int('x')
6466 >>> s = Solver()
6467 >>> s.add(x > 0, x < 2, f(x) == 0)
6468 >>> s.check()
6469 sat
6470 >>> m = s.model()
6471 >>> m[x]
6472 1
6473 >>> m[f]
6474 [else -> 0]
6475 """
6476 if z3_debug():
6477 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6478 if is_const(decl):
6479 decl = decl.decl()
6480 try:
6481 if decl.arity() == 0:
6482 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6483 if _r.value is None:
6484 return None
6485 r = _to_expr_ref(_r, self.ctx)
6486 if is_as_array(r):
6487 fi = self.get_interp(get_as_array_func(r))
6488 if fi is None:
6489 return fi
6490 e = fi.else_value()
6491 if e is None:
6492 return fi
6493 if fi.arity() != 1:
6494 return fi
6495 srt = decl.range()
6496 dom = srt.domain()
6497 e = K(dom, e)
6498 i = 0
6499 sz = fi.num_entries()
6500 n = fi.arity()
6501 while i < sz:
6502 fe = fi.entry(i)
6503 e = Store(e, fe.arg_value(0), fe.value())
6504 i += 1
6505 return e
6506 else:
6507 return r
6508 else:
6509 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6510 except Z3Exception:
6511 return None
6512
6513 def num_sorts(self):
6514 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6515
6516 >>> A = DeclareSort('A')
6517 >>> a, b = Consts('a b', A)
6518 >>> s = Solver()
6519 >>> s.add(a != b)
6520 >>> s.check()
6521 sat
6522 >>> m = s.model()
6523 >>> m.num_sorts()
6524 1
6525 """
6526 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6527
6528 def get_sort(self, idx):
6529 """Return the uninterpreted sort at position `idx` < self.num_sorts().
6530
6531 >>> A = DeclareSort('A')
6532 >>> B = DeclareSort('B')
6533 >>> a1, a2 = Consts('a1 a2', A)
6534 >>> b1, b2 = Consts('b1 b2', B)
6535 >>> s = Solver()
6536 >>> s.add(a1 != a2, b1 != b2)
6537 >>> s.check()
6538 sat
6539 >>> m = s.model()
6540 >>> m.num_sorts()
6541 2
6542 >>> m.get_sort(0)
6543 A
6544 >>> m.get_sort(1)
6545 B
6546 """
6547 if idx >= self.num_sorts():
6548 raise IndexError
6549 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6550
6551 def sorts(self):
6552 """Return all uninterpreted sorts that have an interpretation in the model `self`.
6553
6554 >>> A = DeclareSort('A')
6555 >>> B = DeclareSort('B')
6556 >>> a1, a2 = Consts('a1 a2', A)
6557 >>> b1, b2 = Consts('b1 b2', B)
6558 >>> s = Solver()
6559 >>> s.add(a1 != a2, b1 != b2)
6560 >>> s.check()
6561 sat
6562 >>> m = s.model()
6563 >>> m.sorts()
6564 [A, B]
6565 """
6566 return [self.get_sort(i) for i in range(self.num_sorts())]
6567
6568 def get_universe(self, s):
6569 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6570
6571 >>> A = DeclareSort('A')
6572 >>> a, b = Consts('a b', A)
6573 >>> s = Solver()
6574 >>> s.add(a != b)
6575 >>> s.check()
6576 sat
6577 >>> m = s.model()
6578 >>> m.get_universe(A)
6579 [A!val!1, A!val!0]
6580 """
6581 if z3_debug():
6582 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6583 try:
6584 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6585 except Z3Exception:
6586 return None
6587
6588 def __getitem__(self, idx):
6589 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6590 If `idx` is a declaration, then the actual interpretation is returned.
6591
6592 The elements can be retrieved using position or the actual declaration.
6593
6594 >>> f = Function('f', IntSort(), IntSort())
6595 >>> x = Int('x')
6596 >>> s = Solver()
6597 >>> s.add(x > 0, x < 2, f(x) == 0)
6598 >>> s.check()
6599 sat
6600 >>> m = s.model()
6601 >>> len(m)
6602 2
6603 >>> m[0]
6604 x
6605 >>> m[1]
6606 f
6607 >>> m[x]
6608 1
6609 >>> m[f]
6610 [else -> 0]
6611 >>> for d in m: print("%s -> %s" % (d, m[d]))
6612 x -> 1
6613 f -> [else -> 0]
6614 """
6615 if _is_int(idx):
6616 if idx >= len(self):
6617 raise IndexError
6618 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6619 if (idx < num_consts):
6620 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6621 else:
6622 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6623 if isinstance(idx, FuncDeclRef):
6624 return self.get_interp(idx)
6625 if is_const(idx):
6626 return self.get_interp(idx.decl())
6627 if isinstance(idx, SortRef):
6628 return self.get_universe(idx)
6629 if z3_debug():
6630 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6631 return None
6632
6633 def decls(self):
6634 """Return a list with all symbols that have an interpretation in the model `self`.
6635 >>> f = Function('f', IntSort(), IntSort())
6636 >>> x = Int('x')
6637 >>> s = Solver()
6638 >>> s.add(x > 0, x < 2, f(x) == 0)
6639 >>> s.check()
6640 sat
6641 >>> m = s.model()
6642 >>> m.decls()
6643 [x, f]
6644 """
6645 r = []
6646 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6647 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6648 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6649 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6650 return r
6651
6652 def update_value(self, x, value):
6653 """Update the interpretation of a constant"""
6654 if is_expr(x):
6655 x = x.decl()
6656 if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
6657 fi1 = value.f
6658 fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
6659 fi2 = FuncInterp(fi2, x.ctx)
6660 for i in range(value.num_entries()):
6661 e = value.entry(i)
6662 n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
6663 v = AstVector()
6664 for j in range(n):
6665 v.push(e.arg_value(j))
6666 val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
6667 Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
6668 return
6669 if not is_func_decl(x) or x.arity() != 0:
6670 raise Z3Exception("Expecting 0-ary function or constant expression")
6671 value = _py2expr(value)
6672 Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
6673
6674 def translate(self, target):
6675 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6676 """
6677 if z3_debug():
6678 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6679 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6680 return ModelRef(model, target)
6681
6682 def __copy__(self):
6683 return self.translate(self.ctx)
6684
6685 def __deepcopy__(self, memo={}):
6686 return self.translate(self.ctx)
6687
6688
6689def Model(ctx=None):
6690 ctx = _get_ctx(ctx)
6691 return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6692
6693
6695 """Return true if n is a Z3 expression of the form (_ as-array f)."""
6696 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6697
6698
6700 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6701 if z3_debug():
6702 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6703 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6704
6705
6710
6711
6713 """Statistics for `Solver.check()`."""
6714
6715 def __init__(self, stats, ctx):
6716 self.stats = stats
6717 self.ctx = ctx
6718 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6719
6720 def __deepcopy__(self, memo={}):
6721 return Statistics(self.stats, self.ctx)
6722
6723 def __del__(self):
6724 if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
6725 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6726
6727 def __repr__(self):
6728 if in_html_mode():
6729 out = io.StringIO()
6730 even = True
6731 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6732 for k, v in self:
6733 if even:
6734 out.write(u('<tr style="background-color:#CFCFCF">'))
6735 even = False
6736 else:
6737 out.write(u("<tr>"))
6738 even = True
6739 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6740 out.write(u("</table>"))
6741 return out.getvalue()
6742 else:
6743 return Z3_stats_to_string(self.ctx.ref(), self.stats)
6744
6745 def __len__(self):
6746 """Return the number of statistical counters.
6747
6748 >>> x = Int('x')
6749 >>> s = Then('simplify', 'nlsat').solver()
6750 >>> s.add(x > 0)
6751 >>> s.check()
6752 sat
6753 >>> st = s.statistics()
6754 >>> len(st)
6755 6
6756 """
6757 return int(Z3_stats_size(self.ctx.ref(), self.stats))
6758
6759 def __getitem__(self, idx):
6760 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6761
6762 >>> x = Int('x')
6763 >>> s = Then('simplify', 'nlsat').solver()
6764 >>> s.add(x > 0)
6765 >>> s.check()
6766 sat
6767 >>> st = s.statistics()
6768 >>> len(st)
6769 6
6770 >>> st[0]
6771 ('nlsat propagations', 2)
6772 >>> st[1]
6773 ('nlsat stages', 2)
6774 """
6775 if idx >= len(self):
6776 raise IndexError
6777 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6778 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6779 else:
6780 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6781 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6782
6783 def keys(self):
6784 """Return the list of statistical counters.
6785
6786 >>> x = Int('x')
6787 >>> s = Then('simplify', 'nlsat').solver()
6788 >>> s.add(x > 0)
6789 >>> s.check()
6790 sat
6791 >>> st = s.statistics()
6792 """
6793 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6794
6795 def get_key_value(self, key):
6796 """Return the value of a particular statistical counter.
6797
6798 >>> x = Int('x')
6799 >>> s = Then('simplify', 'nlsat').solver()
6800 >>> s.add(x > 0)
6801 >>> s.check()
6802 sat
6803 >>> st = s.statistics()
6804 >>> st.get_key_value('nlsat propagations')
6805 2
6806 """
6807 for idx in range(len(self)):
6808 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6809 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6810 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6811 else:
6812 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6813 raise Z3Exception("unknown key")
6814
6815 def __getattr__(self, name):
6816 """Access the value of statistical using attributes.
6817
6818 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6819 we should use '_' (e.g., 'nlsat_propagations').
6820
6821 >>> x = Int('x')
6822 >>> s = Then('simplify', 'nlsat').solver()
6823 >>> s.add(x > 0)
6824 >>> s.check()
6825 sat
6826 >>> st = s.statistics()
6827 >>> st.nlsat_propagations
6828 2
6829 >>> st.nlsat_stages
6830 2
6831 """
6832 key = name.replace("_", " ")
6833 try:
6834 return self.get_key_value(key)
6835 except Z3Exception:
6836 raise AttributeError
6837
6838
6843
6844
6846 """Represents the result of a satisfiability check: sat, unsat, unknown.
6847
6848 >>> s = Solver()
6849 >>> s.check()
6850 sat
6851 >>> r = s.check()
6852 >>> isinstance(r, CheckSatResult)
6853 True
6854 """
6855
6856 def __init__(self, r):
6857 self.r = r
6858
6859 def __deepcopy__(self, memo={}):
6860 return CheckSatResult(self.r)
6861
6862 def __eq__(self, other):
6863 return isinstance(other, CheckSatResult) and self.r == other.r
6864
6865 def __ne__(self, other):
6866 return not self.__eq__(other)
6867
6868 def __repr__(self):
6869 if in_html_mode():
6870 if self.r == Z3_L_TRUE:
6871 return "<b>sat</b>"
6872 elif self.r == Z3_L_FALSE:
6873 return "<b>unsat</b>"
6874 else:
6875 return "<b>unknown</b>"
6876 else:
6877 if self.r == Z3_L_TRUE:
6878 return "sat"
6879 elif self.r == Z3_L_FALSE:
6880 return "unsat"
6881 else:
6882 return "unknown"
6883
6884 def _repr_html_(self):
6885 in_html = in_html_mode()
6886 set_html_mode(True)
6887 res = repr(self)
6888 set_html_mode(in_html)
6889 return res
6890
6891
6892sat = CheckSatResult(Z3_L_TRUE)
6893unsat = CheckSatResult(Z3_L_FALSE)
6894unknown = CheckSatResult(Z3_L_UNDEF)
6895
6896
6898 """
6899 Solver API provides methods for implementing the main SMT 2.0 commands:
6900 push, pop, check, get-model, etc.
6901 """
6902
6903 def __init__(self, solver=None, ctx=None, logFile=None):
6904 assert solver is None or ctx is not None
6905 self.ctx = _get_ctx(ctx)
6906 self.backtrack_level = 4000000000
6907 self.solver = None
6908 if solver is None:
6909 self.solver = Z3_mk_solver(self.ctx.ref())
6910 else:
6911 self.solver = solver
6912 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6913 if logFile is not None:
6914 self.set("smtlib2_log", logFile)
6915
6916 def __del__(self):
6917 if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
6918 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6919
6920 def set(self, *args, **keys):
6921 """Set a configuration option.
6922 The method `help()` return a string containing all available options.
6923
6924 >>> s = Solver()
6925 >>> # The option MBQI can be set using three different approaches.
6926 >>> s.set(mbqi=True)
6927 >>> s.set('MBQI', True)
6928 >>> s.set(':mbqi', True)
6929 """
6930 p = args2params(args, keys, self.ctx)
6931 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6932
6933 def push(self):
6934 """Create a backtracking point.
6935
6936 >>> x = Int('x')
6937 >>> s = Solver()
6938 >>> s.add(x > 0)
6939 >>> s
6940 [x > 0]
6941 >>> s.push()
6942 >>> s.add(x < 1)
6943 >>> s
6944 [x > 0, x < 1]
6945 >>> s.check()
6946 unsat
6947 >>> s.pop()
6948 >>> s.check()
6949 sat
6950 >>> s
6951 [x > 0]
6952 """
6953 Z3_solver_push(self.ctx.ref(), self.solver)
6954
6955 def pop(self, num=1):
6956 """Backtrack \\c num backtracking points.
6957
6958 >>> x = Int('x')
6959 >>> s = Solver()
6960 >>> s.add(x > 0)
6961 >>> s
6962 [x > 0]
6963 >>> s.push()
6964 >>> s.add(x < 1)
6965 >>> s
6966 [x > 0, x < 1]
6967 >>> s.check()
6968 unsat
6969 >>> s.pop()
6970 >>> s.check()
6971 sat
6972 >>> s
6973 [x > 0]
6974 """
6975 Z3_solver_pop(self.ctx.ref(), self.solver, num)
6976
6977 def num_scopes(self):
6978 """Return the current number of backtracking points.
6979
6980 >>> s = Solver()
6981 >>> s.num_scopes()
6982 0
6983 >>> s.push()
6984 >>> s.num_scopes()
6985 1
6986 >>> s.push()
6987 >>> s.num_scopes()
6988 2
6989 >>> s.pop()
6990 >>> s.num_scopes()
6991 1
6992 """
6993 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6994
6995 def reset(self):
6996 """Remove all asserted constraints and backtracking points created using `push()`.
6997
6998 >>> x = Int('x')
6999 >>> s = Solver()
7000 >>> s.add(x > 0)
7001 >>> s
7002 [x > 0]
7003 >>> s.reset()
7004 >>> s
7005 []
7006 """
7007 Z3_solver_reset(self.ctx.ref(), self.solver)
7008
7009 def assert_exprs(self, *args):
7010 """Assert constraints into the solver.
7011
7012 >>> x = Int('x')
7013 >>> s = Solver()
7014 >>> s.assert_exprs(x > 0, x < 2)
7015 >>> s
7016 [x > 0, x < 2]
7017 """
7018 args = _get_args(args)
7019 s = BoolSort(self.ctx)
7020 for arg in args:
7021 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7022 for f in arg:
7023 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7024 else:
7025 arg = s.cast(arg)
7026 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7027
7028 def add(self, *args):
7029 """Assert constraints into the solver.
7030
7031 >>> x = Int('x')
7032 >>> s = Solver()
7033 >>> s.add(x > 0, x < 2)
7034 >>> s
7035 [x > 0, x < 2]
7036 """
7037 self.assert_exprs(*args)
7038
7039 def __iadd__(self, fml):
7040 self.add(fml)
7041 return self
7042
7043 def append(self, *args):
7044 """Assert constraints into the solver.
7045
7046 >>> x = Int('x')
7047 >>> s = Solver()
7048 >>> s.append(x > 0, x < 2)
7049 >>> s
7050 [x > 0, x < 2]
7051 """
7052 self.assert_exprs(*args)
7053
7054 def insert(self, *args):
7055 """Assert constraints into the solver.
7056
7057 >>> x = Int('x')
7058 >>> s = Solver()
7059 >>> s.insert(x > 0, x < 2)
7060 >>> s
7061 [x > 0, x < 2]
7062 """
7063 self.assert_exprs(*args)
7064
7065 def assert_and_track(self, a, p):
7066 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7067
7068 If `p` is a string, it will be automatically converted into a Boolean constant.
7069
7070 >>> x = Int('x')
7071 >>> p3 = Bool('p3')
7072 >>> s = Solver()
7073 >>> s.set(unsat_core=True)
7074 >>> s.assert_and_track(x > 0, 'p1')
7075 >>> s.assert_and_track(x != 1, 'p2')
7076 >>> s.assert_and_track(x < 0, p3)
7077 >>> print(s.check())
7078 unsat
7079 >>> c = s.unsat_core()
7080 >>> len(c)
7081 2
7082 >>> Bool('p1') in c
7083 True
7084 >>> Bool('p2') in c
7085 False
7086 >>> p3 in c
7087 True
7088 """
7089 if isinstance(p, str):
7090 p = Bool(p, self.ctx)
7091 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7092 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7093 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7094
7095 def check(self, *assumptions):
7096 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7097
7098 >>> x = Int('x')
7099 >>> s = Solver()
7100 >>> s.check()
7101 sat
7102 >>> s.add(x > 0, x < 2)
7103 >>> s.check()
7104 sat
7105 >>> s.model().eval(x)
7106 1
7107 >>> s.add(x < 1)
7108 >>> s.check()
7109 unsat
7110 >>> s.reset()
7111 >>> s.add(2**x == 4)
7112 >>> s.check()
7113 unknown
7114 """
7115 s = BoolSort(self.ctx)
7116 assumptions = _get_args(assumptions)
7117 num = len(assumptions)
7118 _assumptions = (Ast * num)()
7119 for i in range(num):
7120 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7121 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7122 return CheckSatResult(r)
7123
7124 def model(self):
7125 """Return a model for the last `check()`.
7126
7127 This function raises an exception if
7128 a model is not available (e.g., last `check()` returned unsat).
7129
7130 >>> s = Solver()
7131 >>> a = Int('a')
7132 >>> s.add(a + 2 == 0)
7133 >>> s.check()
7134 sat
7135 >>> s.model()
7136 [a = -2]
7137 """
7138 try:
7139 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7140 except Z3Exception:
7141 raise Z3Exception("model is not available")
7142
7143 def import_model_converter(self, other):
7144 """Import model converter from other into the current solver"""
7145 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7146
7147 def unsat_core(self):
7148 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7149
7150 These are the assumptions Z3 used in the unsatisfiability proof.
7151 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7152 They may be also used to "retract" assumptions. Note that, assumptions are not really
7153 "soft constraints", but they can be used to implement them.
7154
7155 >>> p1, p2, p3 = Bools('p1 p2 p3')
7156 >>> x, y = Ints('x y')
7157 >>> s = Solver()
7158 >>> s.add(Implies(p1, x > 0))
7159 >>> s.add(Implies(p2, y > x))
7160 >>> s.add(Implies(p2, y < 1))
7161 >>> s.add(Implies(p3, y > -3))
7162 >>> s.check(p1, p2, p3)
7163 unsat
7164 >>> core = s.unsat_core()
7165 >>> len(core)
7166 2
7167 >>> p1 in core
7168 True
7169 >>> p2 in core
7170 True
7171 >>> p3 in core
7172 False
7173 >>> # "Retracting" p2
7174 >>> s.check(p1, p3)
7175 sat
7176 """
7177 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7178
7179 def consequences(self, assumptions, variables):
7180 """Determine fixed values for the variables based on the solver state and assumptions.
7181 >>> s = Solver()
7182 >>> a, b, c, d = Bools('a b c d')
7183 >>> s.add(Implies(a,b), Implies(b, c))
7184 >>> s.consequences([a],[b,c,d])
7185 (sat, [Implies(a, b), Implies(a, c)])
7186 >>> s.consequences([Not(c),d],[a,b,c,d])
7187 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7188 """
7189 if isinstance(assumptions, list):
7190 _asms = AstVector(None, self.ctx)
7191 for a in assumptions:
7192 _asms.push(a)
7193 assumptions = _asms
7194 if isinstance(variables, list):
7195 _vars = AstVector(None, self.ctx)
7196 for a in variables:
7197 _vars.push(a)
7198 variables = _vars
7199 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7200 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7201 consequences = AstVector(None, self.ctx)
7202 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7203 variables.vector, consequences.vector)
7204 sz = len(consequences)
7205 consequences = [consequences[i] for i in range(sz)]
7206 return CheckSatResult(r), consequences
7207
7208 def from_file(self, filename):
7209 """Parse assertions from a file"""
7210 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7211
7212 def from_string(self, s):
7213 """Parse assertions from a string"""
7214 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7215
7216 def cube(self, vars=None):
7217 """Get set of cubes
7218 The method takes an optional set of variables that restrict which
7219 variables may be used as a starting point for cubing.
7220 If vars is not None, then the first case split is based on a variable in
7221 this set.
7222 """
7223 self.cube_vs = AstVector(None, self.ctx)
7224 if vars is not None:
7225 for v in vars:
7226 self.cube_vs.push(v)
7227 while True:
7228 lvl = self.backtrack_level
7229 self.backtrack_level = 4000000000
7230 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7231 if (len(r) == 1 and is_false(r[0])):
7232 return
7233 yield r
7234 if (len(r) == 0):
7235 return
7236
7237 def cube_vars(self):
7238 """Access the set of variables that were touched by the most recently generated cube.
7239 This set of variables can be used as a starting point for additional cubes.
7240 The idea is that variables that appear in clauses that are reduced by the most recent
7241 cube are likely more useful to cube on."""
7242 return self.cube_vs
7243
7244 def root(self, t):
7245 t = _py2expr(t, self.ctx)
7246 """Retrieve congruence closure root of the term t relative to the current search state
7247 The function primarily works for SimpleSolver. Terms and variables that are
7248 eliminated during pre-processing are not visible to the congruence closure.
7249 """
7250 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
7251
7252 def next(self, t):
7253 t = _py2expr(t, self.ctx)
7254 """Retrieve congruence closure sibling of the term t relative to the current search state
7255 The function primarily works for SimpleSolver. Terms and variables that are
7256 eliminated during pre-processing are not visible to the congruence closure.
7257 """
7258 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
7259
7260 def proof(self):
7261 """Return a proof for the last `check()`. Proof construction must be enabled."""
7262 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7263
7264 def assertions(self):
7265 """Return an AST vector containing all added constraints.
7266
7267 >>> s = Solver()
7268 >>> s.assertions()
7269 []
7270 >>> a = Int('a')
7271 >>> s.add(a > 0)
7272 >>> s.add(a < 10)
7273 >>> s.assertions()
7274 [a > 0, a < 10]
7275 """
7276 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7277
7278 def units(self):
7279 """Return an AST vector containing all currently inferred units.
7280 """
7281 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7282
7283 def non_units(self):
7284 """Return an AST vector containing all atomic formulas in solver state that are not units.
7285 """
7286 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7287
7288 def trail_levels(self):
7289 """Return trail and decision levels of the solver state after a check() call.
7290 """
7291 trail = self.trail()
7292 levels = (ctypes.c_uint * len(trail))()
7293 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7294 return trail, levels
7295
7296 def trail(self):
7297 """Return trail of the solver state after a check() call.
7298 """
7299 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7300
7301 def statistics(self):
7302 """Return statistics for the last `check()`.
7303
7304 >>> s = SimpleSolver()
7305 >>> x = Int('x')
7306 >>> s.add(x > 0)
7307 >>> s.check()
7308 sat
7309 >>> st = s.statistics()
7310 >>> st.get_key_value('final checks')
7311 1
7312 >>> len(st) > 0
7313 True
7314 >>> st[0] != 0
7315 True
7316 """
7317 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
7318
7320 """Return a string describing why the last `check()` returned `unknown`.
7321
7322 >>> x = Int('x')
7323 >>> s = SimpleSolver()
7324 >>> s.add(2**x == 4)
7325 >>> s.check()
7326 unknown
7327 >>> s.reason_unknown()
7328 '(incomplete (theory arithmetic))'
7329 """
7330 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
7331
7332 def help(self):
7333 """Display a string describing all available options."""
7334 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
7335
7336 def param_descrs(self):
7337 """Return the parameter description set."""
7338 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
7339
7340 def __repr__(self):
7341 """Return a formatted string with all added constraints."""
7342 return obj_to_string(self)
7343
7344 def translate(self, target):
7345 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7346
7347 >>> c1 = Context()
7348 >>> c2 = Context()
7349 >>> s1 = Solver(ctx=c1)
7350 >>> s2 = s1.translate(c2)
7351 """
7352 if z3_debug():
7353 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7354 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
7355 return Solver(solver, target)
7356
7357 def __copy__(self):
7358 return self.translate(self.ctx)
7359
7360 def __deepcopy__(self, memo={}):
7361 return self.translate(self.ctx)
7362
7363 def sexpr(self):
7364 """Return a formatted string (in Lisp-like format) with all added constraints.
7365 We say the string is in s-expression format.
7366
7367 >>> x = Int('x')
7368 >>> s = Solver()
7369 >>> s.add(x > 0)
7370 >>> s.add(x < 2)
7371 >>> r = s.sexpr()
7372 """
7373 return Z3_solver_to_string(self.ctx.ref(), self.solver)
7374
7375 def dimacs(self, include_names=True):
7376 """Return a textual representation of the solver in DIMACS format."""
7377 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
7378
7379 def to_smt2(self):
7380 """return SMTLIB2 formatted benchmark for solver's assertions"""
7381 es = self.assertions()
7382 sz = len(es)
7383 sz1 = sz
7384 if sz1 > 0:
7385 sz1 -= 1
7386 v = (Ast * sz1)()
7387 for i in range(sz1):
7388 v[i] = es[i].as_ast()
7389 if sz > 0:
7390 e = es[sz1].as_ast()
7391 else:
7392 e = BoolVal(True, self.ctx).as_ast()
7394 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7395 )
7396
7397
7398def SolverFor(logic, ctx=None, logFile=None):
7399 """Create a solver customized for the given logic.
7400
7401 The parameter `logic` is a string. It should be contains
7402 the name of a SMT-LIB logic.
7403 See http://www.smtlib.org/ for the name of all available logics.
7404
7405 >>> s = SolverFor("QF_LIA")
7406 >>> x = Int('x')
7407 >>> s.add(x > 0)
7408 >>> s.add(x < 2)
7409 >>> s.check()
7410 sat
7411 >>> s.model()
7412 [x = 1]
7413 """
7414 ctx = _get_ctx(ctx)
7415 logic = to_symbol(logic)
7416 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7417
7418
7419def SimpleSolver(ctx=None, logFile=None):
7420 """Return a simple general purpose solver with limited amount of preprocessing.
7421
7422 >>> s = SimpleSolver()
7423 >>> x = Int('x')
7424 >>> s.add(x > 0)
7425 >>> s.check()
7426 sat
7427 """
7428 ctx = _get_ctx(ctx)
7429 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7430
7431
7436
7437
7439 """Fixedpoint API provides methods for solving with recursive predicates"""
7440
7441 def __init__(self, fixedpoint=None, ctx=None):
7442 assert fixedpoint is None or ctx is not None
7443 self.ctx = _get_ctx(ctx)
7444 self.fixedpoint = None
7445 if fixedpoint is None:
7446 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
7447 else:
7448 self.fixedpoint = fixedpoint
7449 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
7450 self.vars = []
7451
7452 def __deepcopy__(self, memo={}):
7453 return FixedPoint(self.fixedpoint, self.ctx)
7454
7455 def __del__(self):
7456 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
7457 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
7458
7459 def set(self, *args, **keys):
7460 """Set a configuration option. The method `help()` return a string containing all available options.
7461 """
7462 p = args2params(args, keys, self.ctx)
7463 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
7464
7465 def help(self):
7466 """Display a string describing all available options."""
7467 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
7468
7469 def param_descrs(self):
7470 """Return the parameter description set."""
7471 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
7472
7473 def assert_exprs(self, *args):
7474 """Assert constraints as background axioms for the fixedpoint solver."""
7475 args = _get_args(args)
7476 s = BoolSort(self.ctx)
7477 for arg in args:
7478 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7479 for f in arg:
7480 f = self.abstract(f)
7481 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
7482 else:
7483 arg = s.cast(arg)
7484 arg = self.abstract(arg)
7485 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
7486
7487 def add(self, *args):
7488 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7489 self.assert_exprs(*args)
7490
7491 def __iadd__(self, fml):
7492 self.add(fml)
7493 return self
7494
7495 def append(self, *args):
7496 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7497 self.assert_exprs(*args)
7498
7499 def insert(self, *args):
7500 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7501 self.assert_exprs(*args)
7502
7503 def add_rule(self, head, body=None, name=None):
7504 """Assert rules defining recursive predicates to the fixedpoint solver.
7505 >>> a = Bool('a')
7506 >>> b = Bool('b')
7507 >>> s = Fixedpoint()
7508 >>> s.register_relation(a.decl())
7509 >>> s.register_relation(b.decl())
7510 >>> s.fact(a)
7511 >>> s.rule(b, a)
7512 >>> s.query(b)
7513 sat
7514 """
7515 if name is None:
7516 name = ""
7517 name = to_symbol(name, self.ctx)
7518 if body is None:
7519 head = self.abstract(head)
7520 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7521 else:
7522 body = _get_args(body)
7523 f = self.abstract(Implies(And(body, self.ctx), head))
7524 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7525
7526 def rule(self, head, body=None, name=None):
7527 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7528 self.add_rule(head, body, name)
7529
7530 def fact(self, head, name=None):
7531 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7532 self.add_rule(head, None, name)
7533
7534 def query(self, *query):
7535 """Query the fixedpoint engine whether formula is derivable.
7536 You can also pass an tuple or list of recursive predicates.
7537 """
7538 query = _get_args(query)
7539 sz = len(query)
7540 if sz >= 1 and isinstance(query[0], FuncDeclRef):
7541 _decls = (FuncDecl * sz)()
7542 i = 0
7543 for q in query:
7544 _decls[i] = q.ast
7545 i = i + 1
7546 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7547 else:
7548 if sz == 1:
7549 query = query[0]
7550 else:
7551 query = And(query, self.ctx)
7552 query = self.abstract(query, False)
7553 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7554 return CheckSatResult(r)
7555
7556 def query_from_lvl(self, lvl, *query):
7557 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7558 """
7559 query = _get_args(query)
7560 sz = len(query)
7561 if sz >= 1 and isinstance(query[0], FuncDecl):
7562 _z3_assert(False, "unsupported")
7563 else:
7564 if sz == 1:
7565 query = query[0]
7566 else:
7567 query = And(query)
7568 query = self.abstract(query, False)
7569 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7570 return CheckSatResult(r)
7571
7572 def update_rule(self, head, body, name):
7573 """update rule"""
7574 if name is None:
7575 name = ""
7576 name = to_symbol(name, self.ctx)
7577 body = _get_args(body)
7578 f = self.abstract(Implies(And(body, self.ctx), head))
7579 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7580
7581 def get_answer(self):
7582 """Retrieve answer from last query call."""
7583 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7584 return _to_expr_ref(r, self.ctx)
7585
7587 """Retrieve a ground cex from last query call."""
7588 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7589 return _to_expr_ref(r, self.ctx)
7590
7592 """retrieve rules along the counterexample trace"""
7593 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7594
7596 """retrieve rule names along the counterexample trace"""
7597 # this is a hack as I don't know how to return a list of symbols from C++;
7598 # obtain names as a single string separated by semicolons
7599 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7600 # split into individual names
7601 return names.split(";")
7602
7603 def get_num_levels(self, predicate):
7604 """Retrieve number of levels used for predicate in PDR engine"""
7605 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7606
7607 def get_cover_delta(self, level, predicate):
7608 """Retrieve properties known about predicate for the level'th unfolding.
7609 -1 is treated as the limit (infinity)
7610 """
7611 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7612 return _to_expr_ref(r, self.ctx)
7613
7614 def add_cover(self, level, predicate, property):
7615 """Add property to predicate for the level'th unfolding.
7616 -1 is treated as infinity (infinity)
7617 """
7618 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7619
7620 def register_relation(self, *relations):
7621 """Register relation as recursive"""
7622 relations = _get_args(relations)
7623 for f in relations:
7624 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7625
7626 def set_predicate_representation(self, f, *representations):
7627 """Control how relation is represented"""
7628 representations = _get_args(representations)
7629 representations = [to_symbol(s) for s in representations]
7630 sz = len(representations)
7631 args = (Symbol * sz)()
7632 for i in range(sz):
7633 args[i] = representations[i]
7634 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7635
7636 def parse_string(self, s):
7637 """Parse rules and queries from a string"""
7638 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7639
7640 def parse_file(self, f):
7641 """Parse rules and queries from a file"""
7642 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7643
7644 def get_rules(self):
7645 """retrieve rules that have been added to fixedpoint context"""
7646 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7647
7649 """retrieve assertions that have been added to fixedpoint context"""
7650 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7651
7652 def __repr__(self):
7653 """Return a formatted string with all added rules and constraints."""
7654 return self.sexpr()
7655
7656 def sexpr(self):
7657 """Return a formatted string (in Lisp-like format) with all added constraints.
7658 We say the string is in s-expression format.
7659 """
7660 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7661
7662 def to_string(self, queries):
7663 """Return a formatted string (in Lisp-like format) with all added constraints.
7664 We say the string is in s-expression format.
7665 Include also queries.
7666 """
7667 args, len = _to_ast_array(queries)
7668 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7669
7670 def statistics(self):
7671 """Return statistics for the last `query()`.
7672 """
7673 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7674
7676 """Return a string describing why the last `query()` returned `unknown`.
7677 """
7678 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7679
7680 def declare_var(self, *vars):
7681 """Add variable or several variables.
7682 The added variable or variables will be bound in the rules
7683 and queries
7684 """
7685 vars = _get_args(vars)
7686 for v in vars:
7687 self.vars += [v]
7688
7689 def abstract(self, fml, is_forall=True):
7690 if self.vars == []:
7691 return fml
7692 if is_forall:
7693 return ForAll(self.vars, fml)
7694 else:
7695 return Exists(self.vars, fml)
7696
7697
7698
7703
7705 """Finite domain sort."""
7706
7707 def size(self):
7708 """Return the size of the finite domain sort"""
7709 r = (ctypes.c_ulonglong * 1)()
7710 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7711 return r[0]
7712 else:
7713 raise Z3Exception("Failed to retrieve finite domain sort size")
7714
7715
7716def FiniteDomainSort(name, sz, ctx=None):
7717 """Create a named finite domain sort of a given size sz"""
7718 if not isinstance(name, Symbol):
7719 name = to_symbol(name)
7720 ctx = _get_ctx(ctx)
7721 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7722
7723
7725 """Return True if `s` is a Z3 finite-domain sort.
7726
7728 True
7730 False
7731 """
7732 return isinstance(s, FiniteDomainSortRef)
7733
7734
7736 """Finite-domain expressions."""
7737
7738 def sort(self):
7739 """Return the sort of the finite-domain expression `self`."""
7740 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
7741
7742 def as_string(self):
7743 """Return a Z3 floating point expression as a Python string."""
7744 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
7745
7746
7748 """Return `True` if `a` is a Z3 finite-domain expression.
7749
7750 >>> s = FiniteDomainSort('S', 100)
7751 >>> b = Const('b', s)
7752 >>> is_finite_domain(b)
7753 True
7754 >>> is_finite_domain(Int('x'))
7755 False
7756 """
7757 return isinstance(a, FiniteDomainRef)
7758
7759
7761 """Integer values."""
7762
7763 def as_long(self):
7764 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7765
7766 >>> s = FiniteDomainSort('S', 100)
7767 >>> v = FiniteDomainVal(3, s)
7768 >>> v
7769 3
7770 >>> v.as_long() + 1
7771 4
7772 """
7773 return int(self.as_stringas_string())
7774
7775 def as_string(self):
7776 """Return a Z3 finite-domain numeral as a Python string.
7777
7778 >>> s = FiniteDomainSort('S', 100)
7779 >>> v = FiniteDomainVal(42, s)
7780 >>> v.as_string()
7781 '42'
7782 """
7783 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
7784
7785
7786def FiniteDomainVal(val, sort, ctx=None):
7787 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7788
7789 >>> s = FiniteDomainSort('S', 256)
7790 >>> FiniteDomainVal(255, s)
7791 255
7792 >>> FiniteDomainVal('100', s)
7793 100
7794 """
7795 if z3_debug():
7796 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7797 ctx = sort.ctx
7798 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7799
7800
7802 """Return `True` if `a` is a Z3 finite-domain value.
7803
7804 >>> s = FiniteDomainSort('S', 100)
7805 >>> b = Const('b', s)
7807 False
7808 >>> b = FiniteDomainVal(10, s)
7809 >>> b
7810 10
7812 True
7813 """
7814 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7815
7816
7817
7822
7824 def __init__(self, opt, value, is_max):
7825 self._opt = opt
7826 self._value = value
7827 self._is_max = is_max
7828
7829 def lower(self):
7830 opt = self._opt
7831 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7832
7833 def upper(self):
7834 opt = self._opt
7835 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7836
7837 def lower_values(self):
7838 opt = self._opt
7839 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7840
7841 def upper_values(self):
7842 opt = self._opt
7843 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7844
7845 def value(self):
7846 if self._is_max:
7847 return self.upper()
7848 else:
7849 return self.lower()
7850
7851 def __str__(self):
7852 return "%s:%s" % (self._value, self._is_max)
7853
7854
7855_on_models = {}
7856
7857
7859 (fn, mdl) = _on_models[ctx]
7860 fn(mdl)
7861
7862
7863_on_model_eh = on_model_eh_type(_global_on_model)
7864
7865
7867 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7868
7869 def __init__(self, ctx=None):
7870 self.ctx = _get_ctx(ctx)
7871 self.optimize = Z3_mk_optimize(self.ctx.ref())
7872 self._on_models_id = None
7873 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7874
7875 def __deepcopy__(self, memo={}):
7876 return Optimize(self.optimize, self.ctx)
7877
7878 def __del__(self):
7879 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
7880 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7881 if self._on_models_id is not None:
7882 del _on_models[self._on_models_id]
7883
7884 def set(self, *args, **keys):
7885 """Set a configuration option.
7886 The method `help()` return a string containing all available options.
7887 """
7888 p = args2params(args, keys, self.ctx)
7889 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7890
7891 def help(self):
7892 """Display a string describing all available options."""
7893 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7894
7895 def param_descrs(self):
7896 """Return the parameter description set."""
7897 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7898
7899 def assert_exprs(self, *args):
7900 """Assert constraints as background axioms for the optimize solver."""
7901 args = _get_args(args)
7902 s = BoolSort(self.ctx)
7903 for arg in args:
7904 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7905 for f in arg:
7906 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7907 else:
7908 arg = s.cast(arg)
7909 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7910
7911 def add(self, *args):
7912 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7913 self.assert_exprs(*args)
7914
7915 def __iadd__(self, fml):
7916 self.add(fml)
7917 return self
7918
7919 def assert_and_track(self, a, p):
7920 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7921
7922 If `p` is a string, it will be automatically converted into a Boolean constant.
7923
7924 >>> x = Int('x')
7925 >>> p3 = Bool('p3')
7926 >>> s = Optimize()
7927 >>> s.assert_and_track(x > 0, 'p1')
7928 >>> s.assert_and_track(x != 1, 'p2')
7929 >>> s.assert_and_track(x < 0, p3)
7930 >>> print(s.check())
7931 unsat
7932 >>> c = s.unsat_core()
7933 >>> len(c)
7934 2
7935 >>> Bool('p1') in c
7936 True
7937 >>> Bool('p2') in c
7938 False
7939 >>> p3 in c
7940 True
7941 """
7942 if isinstance(p, str):
7943 p = Bool(p, self.ctx)
7944 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7945 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7946 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7947
7948 def add_soft(self, arg, weight="1", id=None):
7949 """Add soft constraint with optional weight and optional identifier.
7950 If no weight is supplied, then the penalty for violating the soft constraint
7951 is 1.
7952 Soft constraints are grouped by identifiers. Soft constraints that are
7953 added without identifiers are grouped by default.
7954 """
7955 if _is_int(weight):
7956 weight = "%d" % weight
7957 elif isinstance(weight, float):
7958 weight = "%f" % weight
7959 if not isinstance(weight, str):
7960 raise Z3Exception("weight should be a string or an integer")
7961 if id is None:
7962 id = ""
7963 id = to_symbol(id, self.ctx)
7964
7965 def asoft(a):
7966 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
7967 return OptimizeObjective(self, v, False)
7968 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7969 return [asoft(a) for a in arg]
7970 return asoft(arg)
7971
7972 def maximize(self, arg):
7973 """Add objective function to maximize."""
7974 return OptimizeObjective(
7975 self,
7976 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
7977 is_max=True,
7978 )
7979
7980 def minimize(self, arg):
7981 """Add objective function to minimize."""
7982 return OptimizeObjective(
7983 self,
7984 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
7985 is_max=False,
7986 )
7987
7988 def push(self):
7989 """create a backtracking point for added rules, facts and assertions"""
7990 Z3_optimize_push(self.ctx.ref(), self.optimize)
7991
7992 def pop(self):
7993 """restore to previously created backtracking point"""
7994 Z3_optimize_pop(self.ctx.ref(), self.optimize)
7995
7996 def check(self, *assumptions):
7997 """Check satisfiability while optimizing objective functions."""
7998 assumptions = _get_args(assumptions)
7999 num = len(assumptions)
8000 _assumptions = (Ast * num)()
8001 for i in range(num):
8002 _assumptions[i] = assumptions[i].as_ast()
8003 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8004
8006 """Return a string that describes why the last `check()` returned `unknown`."""
8007 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8008
8009 def model(self):
8010 """Return a model for the last check()."""
8011 try:
8012 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8013 except Z3Exception:
8014 raise Z3Exception("model is not available")
8015
8016 def unsat_core(self):
8017 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8018
8019 def lower(self, obj):
8020 if not isinstance(obj, OptimizeObjective):
8021 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8022 return obj.lower()
8023
8024 def upper(self, obj):
8025 if not isinstance(obj, OptimizeObjective):
8026 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8027 return obj.upper()
8028
8029 def lower_values(self, obj):
8030 if not isinstance(obj, OptimizeObjective):
8031 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8032 return obj.lower_values()
8033
8034 def upper_values(self, obj):
8035 if not isinstance(obj, OptimizeObjective):
8036 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8037 return obj.upper_values()
8038
8039 def from_file(self, filename):
8040 """Parse assertions and objectives from a file"""
8041 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8042
8043 def from_string(self, s):
8044 """Parse assertions and objectives from a string"""
8045 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8046
8047 def assertions(self):
8048 """Return an AST vector containing all added constraints."""
8049 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8050
8051 def objectives(self):
8052 """returns set of objective functions"""
8053 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8054
8055 def __repr__(self):
8056 """Return a formatted string with all added rules and constraints."""
8057 return self.sexpr()
8058
8059 def sexpr(self):
8060 """Return a formatted string (in Lisp-like format) with all added constraints.
8061 We say the string is in s-expression format.
8062 """
8063 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8064
8065 def statistics(self):
8066 """Return statistics for the last check`.
8067 """
8068 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8069
8070 def set_on_model(self, on_model):
8071 """Register a callback that is invoked with every incremental improvement to
8072 objective values. The callback takes a model as argument.
8073 The life-time of the model is limited to the callback so the
8074 model has to be (deep) copied if it is to be used after the callback
8075 """
8076 id = len(_on_models) + 41
8077 mdl = Model(self.ctx)
8078 _on_models[id] = (on_model, mdl)
8079 self._on_models_id = id
8081 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8082 )
8083
8084
8085
8091 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8092 It also contains model and proof converters.
8093 """
8094
8095 def __init__(self, result, ctx):
8096 self.result = result
8097 self.ctx = ctx
8098 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8099
8100 def __deepcopy__(self, memo={}):
8101 return ApplyResult(self.result, self.ctx)
8102
8103 def __del__(self):
8104 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8105 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8106
8107 def __len__(self):
8108 """Return the number of subgoals in `self`.
8109
8110 >>> a, b = Ints('a b')
8111 >>> g = Goal()
8112 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8113 >>> t = Tactic('split-clause')
8114 >>> r = t(g)
8115 >>> len(r)
8116 2
8117 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8118 >>> len(t(g))
8119 4
8120 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8121 >>> len(t(g))
8122 1
8123 """
8124 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8125
8126 def __getitem__(self, idx):
8127 """Return one of the subgoals stored in ApplyResult object `self`.
8128
8129 >>> a, b = Ints('a b')
8130 >>> g = Goal()
8131 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8132 >>> t = Tactic('split-clause')
8133 >>> r = t(g)
8134 >>> r[0]
8135 [a == 0, Or(b == 0, b == 1), a > b]
8136 >>> r[1]
8137 [a == 1, Or(b == 0, b == 1), a > b]
8138 """
8139 if idx >= len(self):
8140 raise IndexError
8141 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8142
8143 def __repr__(self):
8144 return obj_to_string(self)
8145
8146 def sexpr(self):
8147 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8148 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8149
8150 def as_expr(self):
8151 """Return a Z3 expression consisting of all subgoals.
8152
8153 >>> x = Int('x')
8154 >>> g = Goal()
8155 >>> g.add(x > 1)
8156 >>> g.add(Or(x == 2, x == 3))
8157 >>> r = Tactic('simplify')(g)
8158 >>> r
8159 [[Not(x <= 1), Or(x == 2, x == 3)]]
8160 >>> r.as_expr()
8161 And(Not(x <= 1), Or(x == 2, x == 3))
8162 >>> r = Tactic('split-clause')(g)
8163 >>> r
8164 [[x > 1, x == 2], [x > 1, x == 3]]
8165 >>> r.as_expr()
8166 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8167 """
8168 sz = len(self)
8169 if sz == 0:
8170 return BoolVal(False, self.ctx)
8171 elif sz == 1:
8172 return self[0].as_expr()
8173 else:
8174 return Or([self[i].as_expr() for i in range(len(self))])
8175
8176
8181
8182
8184 """Tactics transform, solver and/or simplify sets of constraints (Goal).
8185 A Tactic can be converted into a Solver using the method solver().
8186
8187 Several combinators are available for creating new tactics using the built-in ones:
8188 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8189 """
8190
8191 def __init__(self, tactic, ctx=None):
8192 self.ctx = _get_ctx(ctx)
8193 self.tactic = None
8194 if isinstance(tactic, TacticObj):
8195 self.tactic = tactic
8196 else:
8197 if z3_debug():
8198 _z3_assert(isinstance(tactic, str), "tactic name expected")
8199 try:
8200 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
8201 except Z3Exception:
8202 raise Z3Exception("unknown tactic '%s'" % tactic)
8203 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
8204
8205 def __deepcopy__(self, memo={}):
8206 return Tactic(self.tactic, self.ctx)
8207
8208 def __del__(self):
8209 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
8210 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
8211
8212 def solver(self, logFile=None):
8213 """Create a solver using the tactic `self`.
8214
8215 The solver supports the methods `push()` and `pop()`, but it
8216 will always solve each `check()` from scratch.
8217
8218 >>> t = Then('simplify', 'nlsat')
8219 >>> s = t.solver()
8220 >>> x = Real('x')
8221 >>> s.add(x**2 == 2, x > 0)
8222 >>> s.check()
8223 sat
8224 >>> s.model()
8225 [x = 1.4142135623?]
8226 """
8227 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
8228
8229 def apply(self, goal, *arguments, **keywords):
8230 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8231
8232 >>> x, y = Ints('x y')
8233 >>> t = Tactic('solve-eqs')
8234 >>> t.apply(And(x == 0, y >= x + 1))
8235 [[y >= 1]]
8236 """
8237 if z3_debug():
8238 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8239 goal = _to_goal(goal)
8240 if len(arguments) > 0 or len(keywords) > 0:
8241 p = args2params(arguments, keywords, self.ctx)
8242 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
8243 else:
8244 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
8245
8246 def __call__(self, goal, *arguments, **keywords):
8247 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8248
8249 >>> x, y = Ints('x y')
8250 >>> t = Tactic('solve-eqs')
8251 >>> t(And(x == 0, y >= x + 1))
8252 [[y >= 1]]
8253 """
8254 return self.apply(goal, *arguments, **keywords)
8255
8256 def help(self):
8257 """Display a string containing a description of the available options for the `self` tactic."""
8258 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
8259
8260 def param_descrs(self):
8261 """Return the parameter description set."""
8262 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
8263
8264
8266 if isinstance(a, BoolRef):
8267 goal = Goal(ctx=a.ctx)
8268 goal.add(a)
8269 return goal
8270 else:
8271 return a
8272
8273
8274def _to_tactic(t, ctx=None):
8275 if isinstance(t, Tactic):
8276 return t
8277 else:
8278 return Tactic(t, ctx)
8279
8280
8281def _and_then(t1, t2, ctx=None):
8282 t1 = _to_tactic(t1, ctx)
8283 t2 = _to_tactic(t2, ctx)
8284 if z3_debug():
8285 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8286 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8287
8288
8289def _or_else(t1, t2, ctx=None):
8290 t1 = _to_tactic(t1, ctx)
8291 t2 = _to_tactic(t2, ctx)
8292 if z3_debug():
8293 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8294 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8295
8296
8297def AndThen(*ts, **ks):
8298 """Return a tactic that applies the tactics in `*ts` in sequence.
8299
8300 >>> x, y = Ints('x y')
8301 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8302 >>> t(And(x == 0, y > x + 1))
8303 [[Not(y <= 1)]]
8304 >>> t(And(x == 0, y > x + 1)).as_expr()
8305 Not(y <= 1)
8306 """
8307 if z3_debug():
8308 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8309 ctx = ks.get("ctx", None)
8310 num = len(ts)
8311 r = ts[0]
8312 for i in range(num - 1):
8313 r = _and_then(r, ts[i + 1], ctx)
8314 return r
8315
8316
8317def Then(*ts, **ks):
8318 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8319
8320 >>> x, y = Ints('x y')
8321 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8322 >>> t(And(x == 0, y > x + 1))
8323 [[Not(y <= 1)]]
8324 >>> t(And(x == 0, y > x + 1)).as_expr()
8325 Not(y <= 1)
8326 """
8327 return AndThen(*ts, **ks)
8328
8329
8330def OrElse(*ts, **ks):
8331 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8332
8333 >>> x = Int('x')
8334 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8335 >>> # Tactic split-clause fails if there is no clause in the given goal.
8336 >>> t(x == 0)
8337 [[x == 0]]
8338 >>> t(Or(x == 0, x == 1))
8339 [[x == 0], [x == 1]]
8340 """
8341 if z3_debug():
8342 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8343 ctx = ks.get("ctx", None)
8344 num = len(ts)
8345 r = ts[0]
8346 for i in range(num - 1):
8347 r = _or_else(r, ts[i + 1], ctx)
8348 return r
8349
8350
8351def ParOr(*ts, **ks):
8352 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8353
8354 >>> x = Int('x')
8355 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8356 >>> t(x + 1 == 2)
8357 [[x == 1]]
8358 """
8359 if z3_debug():
8360 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8361 ctx = _get_ctx(ks.get("ctx", None))
8362 ts = [_to_tactic(t, ctx) for t in ts]
8363 sz = len(ts)
8364 _args = (TacticObj * sz)()
8365 for i in range(sz):
8366 _args[i] = ts[i].tactic
8367 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8368
8369
8370def ParThen(t1, t2, ctx=None):
8371 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8372 The subgoals are processed in parallel.
8373
8374 >>> x, y = Ints('x y')
8375 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8376 >>> t(And(Or(x == 1, x == 2), y == x + 1))
8377 [[x == 1, y == 2], [x == 2, y == 3]]
8378 """
8379 t1 = _to_tactic(t1, ctx)
8380 t2 = _to_tactic(t2, ctx)
8381 if z3_debug():
8382 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8383 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8384
8385
8386def ParAndThen(t1, t2, ctx=None):
8387 """Alias for ParThen(t1, t2, ctx)."""
8388 return ParThen(t1, t2, ctx)
8389
8390
8391def With(t, *args, **keys):
8392 """Return a tactic that applies tactic `t` using the given configuration options.
8393
8394 >>> x, y = Ints('x y')
8395 >>> t = With(Tactic('simplify'), som=True)
8396 >>> t((x + 1)*(y + 2) == 0)
8397 [[2*x + y + x*y == -2]]
8398 """
8399 ctx = keys.pop("ctx", None)
8400 t = _to_tactic(t, ctx)
8401 p = args2params(args, keys, t.ctx)
8402 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8403
8404
8405def WithParams(t, p):
8406 """Return a tactic that applies tactic `t` using the given configuration options.
8407
8408 >>> x, y = Ints('x y')
8409 >>> p = ParamsRef()
8410 >>> p.set("som", True)
8411 >>> t = WithParams(Tactic('simplify'), p)
8412 >>> t((x + 1)*(y + 2) == 0)
8413 [[2*x + y + x*y == -2]]
8414 """
8415 t = _to_tactic(t, None)
8416 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8417
8418
8419def Repeat(t, max=4294967295, ctx=None):
8420 """Return a tactic that keeps applying `t` until the goal is not modified anymore
8421 or the maximum number of iterations `max` is reached.
8422
8423 >>> x, y = Ints('x y')
8424 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8425 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8426 >>> r = t(c)
8427 >>> for subgoal in r: print(subgoal)
8428 [x == 0, y == 0, x > y]
8429 [x == 0, y == 1, x > y]
8430 [x == 1, y == 0, x > y]
8431 [x == 1, y == 1, x > y]
8432 >>> t = Then(t, Tactic('propagate-values'))
8433 >>> t(c)
8434 [[x == 1, y == 0]]
8435 """
8436 t = _to_tactic(t, ctx)
8437 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8438
8439
8440def TryFor(t, ms, ctx=None):
8441 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8442
8443 If `t` does not terminate in `ms` milliseconds, then it fails.
8444 """
8445 t = _to_tactic(t, ctx)
8446 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8447
8448
8449def tactics(ctx=None):
8450 """Return a list of all available tactics in Z3.
8451
8452 >>> l = tactics()
8453 >>> l.count('simplify') == 1
8454 True
8455 """
8456 ctx = _get_ctx(ctx)
8457 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8458
8459
8460def tactic_description(name, ctx=None):
8461 """Return a short description for the tactic named `name`.
8462
8463 >>> d = tactic_description('simplify')
8464 """
8465 ctx = _get_ctx(ctx)
8466 return Z3_tactic_get_descr(ctx.ref(), name)
8467
8468
8470 """Display a (tabular) description of all available tactics in Z3."""
8471 if in_html_mode():
8472 even = True
8473 print('<table border="1" cellpadding="2" cellspacing="0">')
8474 for t in tactics():
8475 if even:
8476 print('<tr style="background-color:#CFCFCF">')
8477 even = False
8478 else:
8479 print("<tr>")
8480 even = True
8481 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8482 print("</table>")
8483 else:
8484 for t in tactics():
8485 print("%s : %s" % (t, tactic_description(t)))
8486
8487
8488class Probe:
8489 """Probes are used to inspect a goal (aka problem) and collect information that may be used
8490 to decide which solver and/or preprocessing step will be used.
8491 """
8492
8493 def __init__(self, probe, ctx=None):
8494 self.ctx = _get_ctx(ctx)
8495 self.probe = None
8496 if isinstance(probe, ProbeObj):
8497 self.probe = probe
8498 elif isinstance(probe, float):
8499 self.probe = Z3_probe_const(self.ctx.ref(), probe)
8500 elif _is_int(probe):
8501 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
8502 elif isinstance(probe, bool):
8503 if probe:
8504 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
8505 else:
8506 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
8507 else:
8508 if z3_debug():
8509 _z3_assert(isinstance(probe, str), "probe name expected")
8510 try:
8511 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
8512 except Z3Exception:
8513 raise Z3Exception("unknown probe '%s'" % probe)
8514 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
8515
8516 def __deepcopy__(self, memo={}):
8517 return Probe(self.probe, self.ctx)
8518
8519 def __del__(self):
8520 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
8521 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
8522
8523 def __lt__(self, other):
8524 """Return a probe that evaluates to "true" when the value returned by `self`
8525 is less than the value returned by `other`.
8526
8527 >>> p = Probe('size') < 10
8528 >>> x = Int('x')
8529 >>> g = Goal()
8530 >>> g.add(x > 0)
8531 >>> g.add(x < 10)
8532 >>> p(g)
8533 1.0
8534 """
8535 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8536
8537 def __gt__(self, other):
8538 """Return a probe that evaluates to "true" when the value returned by `self`
8539 is greater than the value returned by `other`.
8540
8541 >>> p = Probe('size') > 10
8542 >>> x = Int('x')
8543 >>> g = Goal()
8544 >>> g.add(x > 0)
8545 >>> g.add(x < 10)
8546 >>> p(g)
8547 0.0
8548 """
8549 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8550
8551 def __le__(self, other):
8552 """Return a probe that evaluates to "true" when the value returned by `self`
8553 is less than or equal to the value returned by `other`.
8554
8555 >>> p = Probe('size') <= 2
8556 >>> x = Int('x')
8557 >>> g = Goal()
8558 >>> g.add(x > 0)
8559 >>> g.add(x < 10)
8560 >>> p(g)
8561 1.0
8562 """
8563 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8564
8565 def __ge__(self, other):
8566 """Return a probe that evaluates to "true" when the value returned by `self`
8567 is greater than or equal to the value returned by `other`.
8568
8569 >>> p = Probe('size') >= 2
8570 >>> x = Int('x')
8571 >>> g = Goal()
8572 >>> g.add(x > 0)
8573 >>> g.add(x < 10)
8574 >>> p(g)
8575 1.0
8576 """
8577 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8578
8579 def __eq__(self, other):
8580 """Return a probe that evaluates to "true" when the value returned by `self`
8581 is equal to the value returned by `other`.
8582
8583 >>> p = Probe('size') == 2
8584 >>> x = Int('x')
8585 >>> g = Goal()
8586 >>> g.add(x > 0)
8587 >>> g.add(x < 10)
8588 >>> p(g)
8589 1.0
8590 """
8591 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8592
8593 def __ne__(self, other):
8594 """Return a probe that evaluates to "true" when the value returned by `self`
8595 is not equal to the value returned by `other`.
8596
8597 >>> p = Probe('size') != 2
8598 >>> x = Int('x')
8599 >>> g = Goal()
8600 >>> g.add(x > 0)
8601 >>> g.add(x < 10)
8602 >>> p(g)
8603 0.0
8604 """
8605 p = self.__eq__(other)
8606 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8607
8608 def __call__(self, goal):
8609 """Evaluate the probe `self` in the given goal.
8610
8611 >>> p = Probe('size')
8612 >>> x = Int('x')
8613 >>> g = Goal()
8614 >>> g.add(x > 0)
8615 >>> g.add(x < 10)
8616 >>> p(g)
8617 2.0
8618 >>> g.add(x < 20)
8619 >>> p(g)
8620 3.0
8621 >>> p = Probe('num-consts')
8622 >>> p(g)
8623 1.0
8624 >>> p = Probe('is-propositional')
8625 >>> p(g)
8626 0.0
8627 >>> p = Probe('is-qflia')
8628 >>> p(g)
8629 1.0
8630 """
8631 if z3_debug():
8632 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8633 goal = _to_goal(goal)
8634 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8635
8636
8638 """Return `True` if `p` is a Z3 probe.
8639
8640 >>> is_probe(Int('x'))
8641 False
8642 >>> is_probe(Probe('memory'))
8643 True
8644 """
8645 return isinstance(p, Probe)
8646
8647
8648def _to_probe(p, ctx=None):
8649 if is_probe(p):
8650 return p
8651 else:
8652 return Probe(p, ctx)
8653
8654
8655def probes(ctx=None):
8656 """Return a list of all available probes in Z3.
8657
8658 >>> l = probes()
8659 >>> l.count('memory') == 1
8660 True
8661 """
8662 ctx = _get_ctx(ctx)
8663 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8664
8665
8666def probe_description(name, ctx=None):
8667 """Return a short description for the probe named `name`.
8668
8669 >>> d = probe_description('memory')
8670 """
8671 ctx = _get_ctx(ctx)
8672 return Z3_probe_get_descr(ctx.ref(), name)
8673
8674
8676 """Display a (tabular) description of all available probes in Z3."""
8677 if in_html_mode():
8678 even = True
8679 print('<table border="1" cellpadding="2" cellspacing="0">')
8680 for p in probes():
8681 if even:
8682 print('<tr style="background-color:#CFCFCF">')
8683 even = False
8684 else:
8685 print("<tr>")
8686 even = True
8687 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8688 print("</table>")
8689 else:
8690 for p in probes():
8691 print("%s : %s" % (p, probe_description(p)))
8692
8693
8694def _probe_nary(f, args, ctx):
8695 if z3_debug():
8696 _z3_assert(len(args) > 0, "At least one argument expected")
8697 num = len(args)
8698 r = _to_probe(args[0], ctx)
8699 for i in range(num - 1):
8700 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8701 return r
8702
8703
8704def _probe_and(args, ctx):
8705 return _probe_nary(Z3_probe_and, args, ctx)
8706
8707
8708def _probe_or(args, ctx):
8709 return _probe_nary(Z3_probe_or, args, ctx)
8710
8711
8712def FailIf(p, ctx=None):
8713 """Return a tactic that fails if the probe `p` evaluates to true.
8714 Otherwise, it returns the input goal unmodified.
8715
8716 In the following example, the tactic applies 'simplify' if and only if there are
8717 more than 2 constraints in the goal.
8718
8719 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8720 >>> x, y = Ints('x y')
8721 >>> g = Goal()
8722 >>> g.add(x > 0)
8723 >>> g.add(y > 0)
8724 >>> t(g)
8725 [[x > 0, y > 0]]
8726 >>> g.add(x == y + 1)
8727 >>> t(g)
8728 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8729 """
8730 p = _to_probe(p, ctx)
8731 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8732
8733
8734def When(p, t, ctx=None):
8735 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8736 Otherwise, it returns the input goal unmodified.
8737
8738 >>> t = When(Probe('size') > 2, Tactic('simplify'))
8739 >>> x, y = Ints('x y')
8740 >>> g = Goal()
8741 >>> g.add(x > 0)
8742 >>> g.add(y > 0)
8743 >>> t(g)
8744 [[x > 0, y > 0]]
8745 >>> g.add(x == y + 1)
8746 >>> t(g)
8747 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8748 """
8749 p = _to_probe(p, ctx)
8750 t = _to_tactic(t, ctx)
8751 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8752
8753
8754def Cond(p, t1, t2, ctx=None):
8755 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8756
8757 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8758 """
8759 p = _to_probe(p, ctx)
8760 t1 = _to_tactic(t1, ctx)
8761 t2 = _to_tactic(t2, ctx)
8762 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8763
8764
8769
8770
8771def simplify(a, *arguments, **keywords):
8772 """Simplify the expression `a` using the given options.
8773
8774 This function has many options. Use `help_simplify` to obtain the complete list.
8775
8776 >>> x = Int('x')
8777 >>> y = Int('y')
8778 >>> simplify(x + 1 + y + x + 1)
8779 2 + 2*x + y
8780 >>> simplify((x + 1)*(y + 1), som=True)
8781 1 + x + y + x*y
8782 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8783 And(Not(x == y), Not(x == 1), Not(y == 1))
8784 >>> simplify(And(x == 0, y == 1), elim_and=True)
8785 Not(Or(Not(x == 0), Not(y == 1)))
8786 """
8787 if z3_debug():
8788 _z3_assert(is_expr(a), "Z3 expression expected")
8789 if len(arguments) > 0 or len(keywords) > 0:
8790 p = args2params(arguments, keywords, a.ctx)
8791 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8792 else:
8793 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8794
8795
8797 """Return a string describing all options available for Z3 `simplify` procedure."""
8798 print(Z3_simplify_get_help(main_ctx().ref()))
8799
8800
8802 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8804
8805
8806def substitute(t, *m):
8807 """Apply substitution m on t, m is a list of pairs of the form (from, to).
8808 Every occurrence in t of from is replaced with to.
8809
8810 >>> x = Int('x')
8811 >>> y = Int('y')
8812 >>> substitute(x + 1, (x, y + 1))
8813 y + 1 + 1
8814 >>> f = Function('f', IntSort(), IntSort())
8815 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8816 1 + 1
8817 """
8818 if isinstance(m, tuple):
8819 m1 = _get_args(m)
8820 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8821 m = m1
8822 if z3_debug():
8823 _z3_assert(is_expr(t), "Z3 expression expected")
8824 _z3_assert(
8825 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
8826 "Z3 invalid substitution, expression pairs expected.")
8827 _z3_assert(
8828 all([p[0].sort().eq(p[1].sort()) for p in m]),
8829 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
8830 num = len(m)
8831 _from = (Ast * num)()
8832 _to = (Ast * num)()
8833 for i in range(num):
8834 _from[i] = m[i][0].as_ast()
8835 _to[i] = m[i][1].as_ast()
8836 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8837
8838
8840 """Substitute the free variables in t with the expression in m.
8841
8842 >>> v0 = Var(0, IntSort())
8843 >>> v1 = Var(1, IntSort())
8844 >>> x = Int('x')
8845 >>> f = Function('f', IntSort(), IntSort(), IntSort())
8846 >>> # replace v0 with x+1 and v1 with x
8847 >>> substitute_vars(f(v0, v1), x + 1, x)
8848 f(x + 1, x)
8849 """
8850 if z3_debug():
8851 _z3_assert(is_expr(t), "Z3 expression expected")
8852 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8853 num = len(m)
8854 _to = (Ast * num)()
8855 for i in range(num):
8856 _to[i] = m[i].as_ast()
8857 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8858
8860 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
8861 Every occurrence in to of the function from is replaced with the expression to.
8862 The expression to can have free variables, that refer to the arguments of from.
8863 For examples, see
8864 """
8865 if isinstance(m, tuple):
8866 m1 = _get_args(m)
8867 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8868 m = m1
8869 if z3_debug():
8870 _z3_assert(is_expr(t), "Z3 expression expected")
8871 _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, funcion pairs expected.")
8872 num = len(m)
8873 _from = (FuncDecl * num)()
8874 _to = (Ast * num)()
8875 for i in range(num):
8876 _from[i] = m[i][0].as_func_decl()
8877 _to[i] = m[i][1].as_ast()
8878 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8879
8880
8881def Sum(*args):
8882 """Create the sum of the Z3 expressions.
8883
8884 >>> a, b, c = Ints('a b c')
8885 >>> Sum(a, b, c)
8886 a + b + c
8887 >>> Sum([a, b, c])
8888 a + b + c
8889 >>> A = IntVector('a', 5)
8890 >>> Sum(A)
8891 a__0 + a__1 + a__2 + a__3 + a__4
8892 """
8893 args = _get_args(args)
8894 if len(args) == 0:
8895 return 0
8896 ctx = _ctx_from_ast_arg_list(args)
8897 if ctx is None:
8898 return _reduce(lambda a, b: a + b, args, 0)
8899 args = _coerce_expr_list(args, ctx)
8900 if is_bv(args[0]):
8901 return _reduce(lambda a, b: a + b, args, 0)
8902 else:
8903 _args, sz = _to_ast_array(args)
8904 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8905
8906
8907def Product(*args):
8908 """Create the product of the Z3 expressions.
8909
8910 >>> a, b, c = Ints('a b c')
8911 >>> Product(a, b, c)
8912 a*b*c
8913 >>> Product([a, b, c])
8914 a*b*c
8915 >>> A = IntVector('a', 5)
8916 >>> Product(A)
8917 a__0*a__1*a__2*a__3*a__4
8918 """
8919 args = _get_args(args)
8920 if len(args) == 0:
8921 return 1
8922 ctx = _ctx_from_ast_arg_list(args)
8923 if ctx is None:
8924 return _reduce(lambda a, b: a * b, args, 1)
8925 args = _coerce_expr_list(args, ctx)
8926 if is_bv(args[0]):
8927 return _reduce(lambda a, b: a * b, args, 1)
8928 else:
8929 _args, sz = _to_ast_array(args)
8930 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8931
8932def Abs(arg):
8933 """Create the absolute value of an arithmetic expression"""
8934 return If(arg > 0, arg, -arg)
8935
8936
8937def AtMost(*args):
8938 """Create an at-most Pseudo-Boolean k constraint.
8939
8940 >>> a, b, c = Bools('a b c')
8941 >>> f = AtMost(a, b, c, 2)
8942 """
8943 args = _get_args(args)
8944 if z3_debug():
8945 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8946 ctx = _ctx_from_ast_arg_list(args)
8947 if z3_debug():
8948 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8949 args1 = _coerce_expr_list(args[:-1], ctx)
8950 k = args[-1]
8951 _args, sz = _to_ast_array(args1)
8952 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8953
8954
8955def AtLeast(*args):
8956 """Create an at-most Pseudo-Boolean k constraint.
8957
8958 >>> a, b, c = Bools('a b c')
8959 >>> f = AtLeast(a, b, c, 2)
8960 """
8961 args = _get_args(args)
8962 if z3_debug():
8963 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8964 ctx = _ctx_from_ast_arg_list(args)
8965 if z3_debug():
8966 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8967 args1 = _coerce_expr_list(args[:-1], ctx)
8968 k = args[-1]
8969 _args, sz = _to_ast_array(args1)
8970 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8971
8972
8974 a, b = arg
8975 if not _is_int(b) and _is_int(a):
8976 return b, a
8977 return arg
8978
8979
8980def _pb_args_coeffs(args, default_ctx=None):
8981 args = _get_args_ast_list(args)
8982 if len(args) == 0:
8983 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8984 args = [_reorder_pb_arg(arg) for arg in args]
8985 args, coeffs = zip(*args)
8986 if z3_debug():
8987 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8988 ctx = _ctx_from_ast_arg_list(args)
8989 if z3_debug():
8990 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8991 args = _coerce_expr_list(args, ctx)
8992 _args, sz = _to_ast_array(args)
8993 _coeffs = (ctypes.c_int * len(coeffs))()
8994 for i in range(len(coeffs)):
8995 _z3_check_cint_overflow(coeffs[i], "coefficient")
8996 _coeffs[i] = coeffs[i]
8997 return ctx, sz, _args, _coeffs, args
8998
8999
9000def PbLe(args, k):
9001 """Create a Pseudo-Boolean inequality k constraint.
9002
9003 >>> a, b, c = Bools('a b c')
9004 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9005 """
9007 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9008 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9009
9010
9011def PbGe(args, k):
9012 """Create a Pseudo-Boolean inequality k constraint.
9013
9014 >>> a, b, c = Bools('a b c')
9015 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9016 """
9018 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9019 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9020
9021
9022def PbEq(args, k, ctx=None):
9023 """Create a Pseudo-Boolean inequality k constraint.
9024
9025 >>> a, b, c = Bools('a b c')
9026 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9027 """
9029 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9030 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9031
9032
9033def solve(*args, **keywords):
9034 """Solve the constraints `*args`.
9035
9036 This is a simple function for creating demonstrations. It creates a solver,
9037 configure it using the options in `keywords`, adds the constraints
9038 in `args`, and invokes check.
9039
9040 >>> a = Int('a')
9041 >>> solve(a > 0, a < 2)
9042 [a = 1]
9043 """
9044 show = keywords.pop("show", False)
9045 s = Solver()
9046 s.set(**keywords)
9047 s.add(*args)
9048 if show:
9049 print(s)
9050 r = s.check()
9051 if r == unsat:
9052 print("no solution")
9053 elif r == unknown:
9054 print("failed to solve")
9055 try:
9056 print(s.model())
9057 except Z3Exception:
9058 return
9059 else:
9060 print(s.model())
9061
9062
9063def solve_using(s, *args, **keywords):
9064 """Solve the constraints `*args` using solver `s`.
9065
9066 This is a simple function for creating demonstrations. It is similar to `solve`,
9067 but it uses the given solver `s`.
9068 It configures solver `s` using the options in `keywords`, adds the constraints
9069 in `args`, and invokes check.
9070 """
9071 show = keywords.pop("show", False)
9072 if z3_debug():
9073 _z3_assert(isinstance(s, Solver), "Solver object expected")
9074 s.set(**keywords)
9075 s.add(*args)
9076 if show:
9077 print("Problem:")
9078 print(s)
9079 r = s.check()
9080 if r == unsat:
9081 print("no solution")
9082 elif r == unknown:
9083 print("failed to solve")
9084 try:
9085 print(s.model())
9086 except Z3Exception:
9087 return
9088 else:
9089 if show:
9090 print("Solution:")
9091 print(s.model())
9092
9093
9094def prove(claim, show=False, **keywords):
9095 """Try to prove the given claim.
9096
9097 This is a simple function for creating demonstrations. It tries to prove
9098 `claim` by showing the negation is unsatisfiable.
9099
9100 >>> p, q = Bools('p q')
9101 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9102 proved
9103 """
9104 if z3_debug():
9105 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9106 s = Solver()
9107 s.set(**keywords)
9108 s.add(Not(claim))
9109 if show:
9110 print(s)
9111 r = s.check()
9112 if r == unsat:
9113 print("proved")
9114 elif r == unknown:
9115 print("failed to prove")
9116 print(s.model())
9117 else:
9118 print("counterexample")
9119 print(s.model())
9120
9121
9122def _solve_html(*args, **keywords):
9123 """Version of function `solve` that renders HTML output."""
9124 show = keywords.pop("show", False)
9125 s = Solver()
9126 s.set(**keywords)
9127 s.add(*args)
9128 if show:
9129 print("<b>Problem:</b>")
9130 print(s)
9131 r = s.check()
9132 if r == unsat:
9133 print("<b>no solution</b>")
9134 elif r == unknown:
9135 print("<b>failed to solve</b>")
9136 try:
9137 print(s.model())
9138 except Z3Exception:
9139 return
9140 else:
9141 if show:
9142 print("<b>Solution:</b>")
9143 print(s.model())
9144
9145
9146def _solve_using_html(s, *args, **keywords):
9147 """Version of function `solve_using` that renders HTML."""
9148 show = keywords.pop("show", False)
9149 if z3_debug():
9150 _z3_assert(isinstance(s, Solver), "Solver object expected")
9151 s.set(**keywords)
9152 s.add(*args)
9153 if show:
9154 print("<b>Problem:</b>")
9155 print(s)
9156 r = s.check()
9157 if r == unsat:
9158 print("<b>no solution</b>")
9159 elif r == unknown:
9160 print("<b>failed to solve</b>")
9161 try:
9162 print(s.model())
9163 except Z3Exception:
9164 return
9165 else:
9166 if show:
9167 print("<b>Solution:</b>")
9168 print(s.model())
9169
9170
9171def _prove_html(claim, show=False, **keywords):
9172 """Version of function `prove` that renders HTML."""
9173 if z3_debug():
9174 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9175 s = Solver()
9176 s.set(**keywords)
9177 s.add(Not(claim))
9178 if show:
9179 print(s)
9180 r = s.check()
9181 if r == unsat:
9182 print("<b>proved</b>")
9183 elif r == unknown:
9184 print("<b>failed to prove</b>")
9185 print(s.model())
9186 else:
9187 print("<b>counterexample</b>")
9188 print(s.model())
9189
9190
9191def _dict2sarray(sorts, ctx):
9192 sz = len(sorts)
9193 _names = (Symbol * sz)()
9194 _sorts = (Sort * sz)()
9195 i = 0
9196 for k in sorts:
9197 v = sorts[k]
9198 if z3_debug():
9199 _z3_assert(isinstance(k, str), "String expected")
9200 _z3_assert(is_sort(v), "Z3 sort expected")
9201 _names[i] = to_symbol(k, ctx)
9202 _sorts[i] = v.ast
9203 i = i + 1
9204 return sz, _names, _sorts
9205
9206
9207def _dict2darray(decls, ctx):
9208 sz = len(decls)
9209 _names = (Symbol * sz)()
9210 _decls = (FuncDecl * sz)()
9211 i = 0
9212 for k in decls:
9213 v = decls[k]
9214 if z3_debug():
9215 _z3_assert(isinstance(k, str), "String expected")
9216 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9217 _names[i] = to_symbol(k, ctx)
9218 if is_const(v):
9219 _decls[i] = v.decl().ast
9220 else:
9221 _decls[i] = v.ast
9222 i = i + 1
9223 return sz, _names, _decls
9224
9226 def __init__(self, ctx= None):
9227 self.ctx = _get_ctx(ctx)
9228 self.pctx = Z3_mk_parser_context(self.ctx.ref())
9229 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
9230
9231 def __del__(self):
9232 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
9233 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
9234 self.pctx = None
9235
9236 def add_sort(self, sort):
9237 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
9238
9239 def add_decl(self, decl):
9240 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
9241
9242 def from_string(self, s):
9243 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
9244
9245def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9246 """Parse a string in SMT 2.0 format using the given sorts and decls.
9247
9248 The arguments sorts and decls are Python dictionaries used to initialize
9249 the symbol table used for the SMT 2.0 parser.
9250
9251 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9252 [x > 0, x < 10]
9253 >>> x, y = Ints('x y')
9254 >>> f = Function('f', IntSort(), IntSort())
9255 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9256 [x + f(y) > 0]
9257 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9258 [a > 0]
9259 """
9260 ctx = _get_ctx(ctx)
9261 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9262 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9263 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9264
9265
9266def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9267 """Parse a file in SMT 2.0 format using the given sorts and decls.
9268
9269 This function is similar to parse_smt2_string().
9270 """
9271 ctx = _get_ctx(ctx)
9272 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9273 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9274 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9275
9276
9277
9282
9283
9284# Global default rounding mode
9285_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
9286_dflt_fpsort_ebits = 11
9287_dflt_fpsort_sbits = 53
9288
9289
9291 """Retrieves the global default rounding mode."""
9292 global _dflt_rounding_mode
9293 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9294 return RTZ(ctx)
9295 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9296 return RTN(ctx)
9297 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9298 return RTP(ctx)
9299 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9300 return RNE(ctx)
9301 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9302 return RNA(ctx)
9303
9304
9305_ROUNDING_MODES = frozenset({
9306 Z3_OP_FPA_RM_TOWARD_ZERO,
9307 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9308 Z3_OP_FPA_RM_TOWARD_POSITIVE,
9309 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9310 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9311})
9312
9313
9315 global _dflt_rounding_mode
9316 if is_fprm_value(rm):
9317 _dflt_rounding_mode = rm.decl().kind()
9318 else:
9319 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9320 _dflt_rounding_mode = rm
9321
9322
9324 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9325
9326
9327def set_default_fp_sort(ebits, sbits, ctx=None):
9328 global _dflt_fpsort_ebits
9329 global _dflt_fpsort_sbits
9330 _dflt_fpsort_ebits = ebits
9331 _dflt_fpsort_sbits = sbits
9332
9333
9334def _dflt_rm(ctx=None):
9335 return get_default_rounding_mode(ctx)
9336
9337
9338def _dflt_fps(ctx=None):
9339 return get_default_fp_sort(ctx)
9340
9341
9342def _coerce_fp_expr_list(alist, ctx):
9343 first_fp_sort = None
9344 for a in alist:
9345 if is_fp(a):
9346 if first_fp_sort is None:
9347 first_fp_sort = a.sort()
9348 elif first_fp_sort == a.sort():
9349 pass # OK, same as before
9350 else:
9351 # we saw at least 2 different float sorts; something will
9352 # throw a sort mismatch later, for now assume None.
9353 first_fp_sort = None
9354 break
9355
9356 r = []
9357 for i in range(len(alist)):
9358 a = alist[i]
9359 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9360 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9361 r.append(FPVal(a, None, first_fp_sort, ctx))
9362 else:
9363 r.append(a)
9364 return _coerce_expr_list(r, ctx)
9365
9366
9367# FP Sorts
9368
9370 """Floating-point sort."""
9371
9372 def ebits(self):
9373 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9374 >>> b = FPSort(8, 24)
9375 >>> b.ebits()
9376 8
9377 """
9378 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
9379
9380 def sbits(self):
9381 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9382 >>> b = FPSort(8, 24)
9383 >>> b.sbits()
9384 24
9385 """
9386 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
9387
9388 def cast(self, val):
9389 """Try to cast `val` as a floating-point expression.
9390 >>> b = FPSort(8, 24)
9391 >>> b.cast(1.0)
9392 1
9393 >>> b.cast(1.0).sexpr()
9394 '(fp #b0 #x7f #b00000000000000000000000)'
9395 """
9396 if is_expr(val):
9397 if z3_debug():
9398 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
9399 return val
9400 else:
9401 return FPVal(val, None, self, self.ctxctx)
9402
9403
9404def Float16(ctx=None):
9405 """Floating-point 16-bit (half) sort."""
9406 ctx = _get_ctx(ctx)
9407 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9408
9409
9410def FloatHalf(ctx=None):
9411 """Floating-point 16-bit (half) sort."""
9412 ctx = _get_ctx(ctx)
9413 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9414
9415
9416def Float32(ctx=None):
9417 """Floating-point 32-bit (single) sort."""
9418 ctx = _get_ctx(ctx)
9419 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9420
9421
9422def FloatSingle(ctx=None):
9423 """Floating-point 32-bit (single) sort."""
9424 ctx = _get_ctx(ctx)
9425 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9426
9427
9428def Float64(ctx=None):
9429 """Floating-point 64-bit (double) sort."""
9430 ctx = _get_ctx(ctx)
9431 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9432
9433
9434def FloatDouble(ctx=None):
9435 """Floating-point 64-bit (double) sort."""
9436 ctx = _get_ctx(ctx)
9437 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9438
9439
9440def Float128(ctx=None):
9441 """Floating-point 128-bit (quadruple) sort."""
9442 ctx = _get_ctx(ctx)
9443 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9444
9445
9446def FloatQuadruple(ctx=None):
9447 """Floating-point 128-bit (quadruple) sort."""
9448 ctx = _get_ctx(ctx)
9449 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9450
9451
9453 """"Floating-point rounding mode sort."""
9454
9455
9457 """Return True if `s` is a Z3 floating-point sort.
9458
9459 >>> is_fp_sort(FPSort(8, 24))
9460 True
9461 >>> is_fp_sort(IntSort())
9462 False
9463 """
9464 return isinstance(s, FPSortRef)
9465
9466
9468 """Return True if `s` is a Z3 floating-point rounding mode sort.
9469
9470 >>> is_fprm_sort(FPSort(8, 24))
9471 False
9472 >>> is_fprm_sort(RNE().sort())
9473 True
9474 """
9475 return isinstance(s, FPRMSortRef)
9476
9477# FP Expressions
9478
9479
9481 """Floating-point expressions."""
9482
9483 def sort(self):
9484 """Return the sort of the floating-point expression `self`.
9485
9486 >>> x = FP('1.0', FPSort(8, 24))
9487 >>> x.sort()
9488 FPSort(8, 24)
9489 >>> x.sort() == FPSort(8, 24)
9490 True
9491 """
9492 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
9493
9494 def ebits(self):
9495 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9496 >>> b = FPSort(8, 24)
9497 >>> b.ebits()
9498 8
9499 """
9500 return self.sortsort().ebits()
9501
9502 def sbits(self):
9503 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9504 >>> b = FPSort(8, 24)
9505 >>> b.sbits()
9506 24
9507 """
9508 return self.sortsort().sbits()
9509
9510 def as_string(self):
9511 """Return a Z3 floating point expression as a Python string."""
9512 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9513
9514 def __le__(self, other):
9515 return fpLEQ(self, other, self.ctx)
9516
9517 def __lt__(self, other):
9518 return fpLT(self, other, self.ctx)
9519
9520 def __ge__(self, other):
9521 return fpGEQ(self, other, self.ctx)
9522
9523 def __gt__(self, other):
9524 return fpGT(self, other, self.ctx)
9525
9526 def __add__(self, other):
9527 """Create the Z3 expression `self + other`.
9528
9529 >>> x = FP('x', FPSort(8, 24))
9530 >>> y = FP('y', FPSort(8, 24))
9531 >>> x + y
9532 x + y
9533 >>> (x + y).sort()
9534 FPSort(8, 24)
9535 """
9536 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9537 return fpAdd(_dflt_rm(), a, b, self.ctx)
9538
9539 def __radd__(self, other):
9540 """Create the Z3 expression `other + self`.
9541
9542 >>> x = FP('x', FPSort(8, 24))
9543 >>> 10 + x
9544 1.25*(2**3) + x
9545 """
9546 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9547 return fpAdd(_dflt_rm(), a, b, self.ctx)
9548
9549 def __sub__(self, other):
9550 """Create the Z3 expression `self - other`.
9551
9552 >>> x = FP('x', FPSort(8, 24))
9553 >>> y = FP('y', FPSort(8, 24))
9554 >>> x - y
9555 x - y
9556 >>> (x - y).sort()
9557 FPSort(8, 24)
9558 """
9559 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9560 return fpSub(_dflt_rm(), a, b, self.ctx)
9561
9562 def __rsub__(self, other):
9563 """Create the Z3 expression `other - self`.
9564
9565 >>> x = FP('x', FPSort(8, 24))
9566 >>> 10 - x
9567 1.25*(2**3) - x
9568 """
9569 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9570 return fpSub(_dflt_rm(), a, b, self.ctx)
9571
9572 def __mul__(self, other):
9573 """Create the Z3 expression `self * other`.
9574
9575 >>> x = FP('x', FPSort(8, 24))
9576 >>> y = FP('y', FPSort(8, 24))
9577 >>> x * y
9578 x * y
9579 >>> (x * y).sort()
9580 FPSort(8, 24)
9581 >>> 10 * y
9582 1.25*(2**3) * y
9583 """
9584 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9585 return fpMul(_dflt_rm(), a, b, self.ctx)
9586
9587 def __rmul__(self, other):
9588 """Create the Z3 expression `other * self`.
9589
9590 >>> x = FP('x', FPSort(8, 24))
9591 >>> y = FP('y', FPSort(8, 24))
9592 >>> x * y
9593 x * y
9594 >>> x * 10
9595 x * 1.25*(2**3)
9596 """
9597 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9598 return fpMul(_dflt_rm(), a, b, self.ctx)
9599
9600 def __pos__(self):
9601 """Create the Z3 expression `+self`."""
9602 return self
9603
9604 def __neg__(self):
9605 """Create the Z3 expression `-self`.
9606
9607 >>> x = FP('x', Float32())
9608 >>> -x
9609 -x
9610 """
9611 return fpNeg(self)
9612
9613 def __div__(self, other):
9614 """Create the Z3 expression `self / other`.
9615
9616 >>> x = FP('x', FPSort(8, 24))
9617 >>> y = FP('y', FPSort(8, 24))
9618 >>> x / y
9619 x / y
9620 >>> (x / y).sort()
9621 FPSort(8, 24)
9622 >>> 10 / y
9623 1.25*(2**3) / y
9624 """
9625 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9626 return fpDiv(_dflt_rm(), a, b, self.ctx)
9627
9628 def __rdiv__(self, other):
9629 """Create the Z3 expression `other / self`.
9630
9631 >>> x = FP('x', FPSort(8, 24))
9632 >>> y = FP('y', FPSort(8, 24))
9633 >>> x / y
9634 x / y
9635 >>> x / 10
9636 x / 1.25*(2**3)
9637 """
9638 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9639 return fpDiv(_dflt_rm(), a, b, self.ctx)
9640
9641 def __truediv__(self, other):
9642 """Create the Z3 expression division `self / other`."""
9643 return self.__div__(other)
9644
9645 def __rtruediv__(self, other):
9646 """Create the Z3 expression division `other / self`."""
9647 return self.__rdiv__(other)
9648
9649 def __mod__(self, other):
9650 """Create the Z3 expression mod `self % other`."""
9651 return fpRem(self, other)
9652
9653 def __rmod__(self, other):
9654 """Create the Z3 expression mod `other % self`."""
9655 return fpRem(other, self)
9656
9657
9659 """Floating-point rounding mode expressions"""
9660
9661 def as_string(self):
9662 """Return a Z3 floating point expression as a Python string."""
9663 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9664
9665
9667 ctx = _get_ctx(ctx)
9668 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9669
9670
9671def RNE(ctx=None):
9672 ctx = _get_ctx(ctx)
9673 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9674
9675
9677 ctx = _get_ctx(ctx)
9678 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9679
9680
9681def RNA(ctx=None):
9682 ctx = _get_ctx(ctx)
9683 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9684
9685
9687 ctx = _get_ctx(ctx)
9688 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9689
9690
9691def RTP(ctx=None):
9692 ctx = _get_ctx(ctx)
9693 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9694
9695
9697 ctx = _get_ctx(ctx)
9698 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9699
9700
9701def RTN(ctx=None):
9702 ctx = _get_ctx(ctx)
9703 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9704
9705
9706def RoundTowardZero(ctx=None):
9707 ctx = _get_ctx(ctx)
9708 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9709
9710
9711def RTZ(ctx=None):
9712 ctx = _get_ctx(ctx)
9713 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9714
9715
9716def is_fprm(a):
9717 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9718
9719 >>> rm = RNE()
9720 >>> is_fprm(rm)
9721 True
9722 >>> rm = 1.0
9723 >>> is_fprm(rm)
9724 False
9725 """
9726 return isinstance(a, FPRMRef)
9727
9728
9730 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9731 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9732
9733# FP Numerals
9734
9735
9737 """The sign of the numeral.
9738
9739 >>> x = FPVal(+1.0, FPSort(8, 24))
9740 >>> x.sign()
9741 False
9742 >>> x = FPVal(-1.0, FPSort(8, 24))
9743 >>> x.sign()
9744 True
9745 """
9746
9747 def sign(self):
9748 num = (ctypes.c_int)()
9749 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_astas_ast(), byref(num))
9750 if nsign is False:
9751 raise Z3Exception("error retrieving the sign of a numeral.")
9752 return num.value != 0
9753
9754 """The sign of a floating-point numeral as a bit-vector expression.
9755
9756 Remark: NaN's are invalid arguments.
9757 """
9758
9759 def sign_as_bv(self):
9760 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9761
9762 """The significand of the numeral.
9763
9764 >>> x = FPVal(2.5, FPSort(8, 24))
9765 >>> x.significand()
9766 1.25
9767 """
9768
9769 def significand(self):
9770 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_astas_ast())
9771
9772 """The significand of the numeral as a long.
9773
9774 >>> x = FPVal(2.5, FPSort(8, 24))
9775 >>> x.significand_as_long()
9776 1.25
9777 """
9778
9780 ptr = (ctypes.c_ulonglong * 1)()
9781 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_astas_ast(), ptr):
9782 raise Z3Exception("error retrieving the significand of a numeral.")
9783 return ptr[0]
9784
9785 """The significand of the numeral as a bit-vector expression.
9786
9787 Remark: NaN are invalid arguments.
9788 """
9789
9791 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9792
9793 """The exponent of the numeral.
9794
9795 >>> x = FPVal(2.5, FPSort(8, 24))
9796 >>> x.exponent()
9797 1
9798 """
9799
9800 def exponent(self, biased=True):
9801 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_astas_ast(), biased)
9802
9803 """The exponent of the numeral as a long.
9804
9805 >>> x = FPVal(2.5, FPSort(8, 24))
9806 >>> x.exponent_as_long()
9807 1
9808 """
9809
9810 def exponent_as_long(self, biased=True):
9811 ptr = (ctypes.c_longlong * 1)()
9812 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_astas_ast(), ptr, biased):
9813 raise Z3Exception("error retrieving the exponent of a numeral.")
9814 return ptr[0]
9815
9816 """The exponent of the numeral as a bit-vector expression.
9817
9818 Remark: NaNs are invalid arguments.
9819 """
9820
9821 def exponent_as_bv(self, biased=True):
9822 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_astas_ast(), biased), self.ctx)
9823
9824 """Indicates whether the numeral is a NaN."""
9825
9826 def isNaN(self):
9827 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_astas_ast())
9828
9829 """Indicates whether the numeral is +oo or -oo."""
9830
9831 def isInf(self):
9832 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_astas_ast())
9833
9834 """Indicates whether the numeral is +zero or -zero."""
9835
9836 def isZero(self):
9837 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_astas_ast())
9838
9839 """Indicates whether the numeral is normal."""
9840
9841 def isNormal(self):
9842 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_astas_ast())
9843
9844 """Indicates whether the numeral is subnormal."""
9845
9846 def isSubnormal(self):
9847 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_astas_ast())
9848
9849 """Indicates whether the numeral is positive."""
9850
9851 def isPositive(self):
9852 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_astas_ast())
9853
9854 """Indicates whether the numeral is negative."""
9855
9856 def isNegative(self):
9857 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_astas_ast())
9858
9859 """
9860 The string representation of the numeral.
9861
9862 >>> x = FPVal(20, FPSort(8, 24))
9863 >>> x.as_string()
9864 1.25*(2**4)
9865 """
9866
9867 def as_string(self):
9868 s = Z3_get_numeral_string(self.ctx.ref(), self.as_astas_ast())
9869 return ("FPVal(%s, %s)" % (s, self.sortsort()))
9870
9871
9872def is_fp(a):
9873 """Return `True` if `a` is a Z3 floating-point expression.
9874
9875 >>> b = FP('b', FPSort(8, 24))
9876 >>> is_fp(b)
9877 True
9878 >>> is_fp(b + 1.0)
9879 True
9880 >>> is_fp(Int('x'))
9881 False
9882 """
9883 return isinstance(a, FPRef)
9884
9885
9887 """Return `True` if `a` is a Z3 floating-point numeral value.
9888
9889 >>> b = FP('b', FPSort(8, 24))
9890 >>> is_fp_value(b)
9891 False
9892 >>> b = FPVal(1.0, FPSort(8, 24))
9893 >>> b
9894 1
9895 >>> is_fp_value(b)
9896 True
9897 """
9898 return is_fp(a) and _is_numeral(a.ctx, a.ast)
9899
9900
9901def FPSort(ebits, sbits, ctx=None):
9902 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9903
9904 >>> Single = FPSort(8, 24)
9905 >>> Double = FPSort(11, 53)
9906 >>> Single
9907 FPSort(8, 24)
9908 >>> x = Const('x', Single)
9909 >>> eq(x, FP('x', FPSort(8, 24)))
9910 True
9911 """
9912 ctx = _get_ctx(ctx)
9913 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9914
9915
9916def _to_float_str(val, exp=0):
9917 if isinstance(val, float):
9918 if math.isnan(val):
9919 res = "NaN"
9920 elif val == 0.0:
9921 sone = math.copysign(1.0, val)
9922 if sone < 0.0:
9923 return "-0.0"
9924 else:
9925 return "+0.0"
9926 elif val == float("+inf"):
9927 res = "+oo"
9928 elif val == float("-inf"):
9929 res = "-oo"
9930 else:
9931 v = val.as_integer_ratio()
9932 num = v[0]
9933 den = v[1]
9934 rvs = str(num) + "/" + str(den)
9935 res = rvs + "p" + _to_int_str(exp)
9936 elif isinstance(val, bool):
9937 if val:
9938 res = "1.0"
9939 else:
9940 res = "0.0"
9941 elif _is_int(val):
9942 res = str(val)
9943 elif isinstance(val, str):
9944 inx = val.find("*(2**")
9945 if inx == -1:
9946 res = val
9947 elif val[-1] == ")":
9948 res = val[0:inx]
9949 exp = str(int(val[inx + 5:-1]) + int(exp))
9950 else:
9951 _z3_assert(False, "String does not have floating-point numeral form.")
9952 elif z3_debug():
9953 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9954 if exp == 0:
9955 return res
9956 else:
9957 return res + "p" + exp
9958
9959
9960def fpNaN(s):
9961 """Create a Z3 floating-point NaN term.
9962
9963 >>> s = FPSort(8, 24)
9964 >>> set_fpa_pretty(True)
9965 >>> fpNaN(s)
9966 NaN
9967 >>> pb = get_fpa_pretty()
9968 >>> set_fpa_pretty(False)
9969 >>> fpNaN(s)
9970 fpNaN(FPSort(8, 24))
9971 >>> set_fpa_pretty(pb)
9972 """
9973 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9974 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9975
9976
9978 """Create a Z3 floating-point +oo term.
9979
9980 >>> s = FPSort(8, 24)
9981 >>> pb = get_fpa_pretty()
9982 >>> set_fpa_pretty(True)
9983 >>> fpPlusInfinity(s)
9984 +oo
9985 >>> set_fpa_pretty(False)
9986 >>> fpPlusInfinity(s)
9987 fpPlusInfinity(FPSort(8, 24))
9988 >>> set_fpa_pretty(pb)
9989 """
9990 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9991 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9992
9993
9995 """Create a Z3 floating-point -oo term."""
9996 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9997 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9998
9999
10000def fpInfinity(s, negative):
10001 """Create a Z3 floating-point +oo or -oo term."""
10002 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10003 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10004 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10005
10006
10008 """Create a Z3 floating-point +0.0 term."""
10009 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10010 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10011
10012
10014 """Create a Z3 floating-point -0.0 term."""
10015 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10016 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10017
10018
10019def fpZero(s, negative):
10020 """Create a Z3 floating-point +0.0 or -0.0 term."""
10021 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10022 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10023 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10024
10025
10026def FPVal(sig, exp=None, fps=None, ctx=None):
10027 """Return a floating-point value of value `val` and sort `fps`.
10028 If `ctx=None`, then the global context is used.
10029
10030 >>> v = FPVal(20.0, FPSort(8, 24))
10031 >>> v
10032 1.25*(2**4)
10033 >>> print("0x%.8x" % v.exponent_as_long(False))
10034 0x00000004
10035 >>> v = FPVal(2.25, FPSort(8, 24))
10036 >>> v
10037 1.125*(2**1)
10038 >>> v = FPVal(-2.25, FPSort(8, 24))
10039 >>> v
10040 -1.125*(2**1)
10041 >>> FPVal(-0.0, FPSort(8, 24))
10042 -0.0
10043 >>> FPVal(0.0, FPSort(8, 24))
10044 +0.0
10045 >>> FPVal(+0.0, FPSort(8, 24))
10046 +0.0
10047 """
10048 ctx = _get_ctx(ctx)
10049 if is_fp_sort(exp):
10050 fps = exp
10051 exp = None
10052 elif fps is None:
10053 fps = _dflt_fps(ctx)
10054 _z3_assert(is_fp_sort(fps), "sort mismatch")
10055 if exp is None:
10056 exp = 0
10057 val = _to_float_str(sig)
10058 if val == "NaN" or val == "nan":
10059 return fpNaN(fps)
10060 elif val == "-0.0":
10061 return fpMinusZero(fps)
10062 elif val == "0.0" or val == "+0.0":
10063 return fpPlusZero(fps)
10064 elif val == "+oo" or val == "+inf" or val == "+Inf":
10065 return fpPlusInfinity(fps)
10066 elif val == "-oo" or val == "-inf" or val == "-Inf":
10067 return fpMinusInfinity(fps)
10068 else:
10069 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10070
10071
10072def FP(name, fpsort, ctx=None):
10073 """Return a floating-point constant named `name`.
10074 `fpsort` is the floating-point sort.
10075 If `ctx=None`, then the global context is used.
10076
10077 >>> x = FP('x', FPSort(8, 24))
10078 >>> is_fp(x)
10079 True
10080 >>> x.ebits()
10081 8
10082 >>> x.sort()
10083 FPSort(8, 24)
10084 >>> word = FPSort(8, 24)
10085 >>> x2 = FP('x', word)
10086 >>> eq(x, x2)
10087 True
10088 """
10089 if isinstance(fpsort, FPSortRef) and ctx is None:
10090 ctx = fpsort.ctx
10091 else:
10092 ctx = _get_ctx(ctx)
10093 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10094
10095
10096def FPs(names, fpsort, ctx=None):
10097 """Return an array of floating-point constants.
10098
10099 >>> x, y, z = FPs('x y z', FPSort(8, 24))
10100 >>> x.sort()
10101 FPSort(8, 24)
10102 >>> x.sbits()
10103 24
10104 >>> x.ebits()
10105 8
10106 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10107 x + y * z
10108 """
10109 ctx = _get_ctx(ctx)
10110 if isinstance(names, str):
10111 names = names.split(" ")
10112 return [FP(name, fpsort, ctx) for name in names]
10113
10114
10115def fpAbs(a, ctx=None):
10116 """Create a Z3 floating-point absolute value expression.
10117
10118 >>> s = FPSort(8, 24)
10119 >>> rm = RNE()
10120 >>> x = FPVal(1.0, s)
10121 >>> fpAbs(x)
10122 fpAbs(1)
10123 >>> y = FPVal(-20.0, s)
10124 >>> y
10125 -1.25*(2**4)
10126 >>> fpAbs(y)
10127 fpAbs(-1.25*(2**4))
10128 >>> fpAbs(-1.25*(2**4))
10129 fpAbs(-1.25*(2**4))
10130 >>> fpAbs(x).sort()
10131 FPSort(8, 24)
10132 """
10133 ctx = _get_ctx(ctx)
10134 [a] = _coerce_fp_expr_list([a], ctx)
10135 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10136
10137
10138def fpNeg(a, ctx=None):
10139 """Create a Z3 floating-point addition expression.
10140
10141 >>> s = FPSort(8, 24)
10142 >>> rm = RNE()
10143 >>> x = FP('x', s)
10144 >>> fpNeg(x)
10145 -x
10146 >>> fpNeg(x).sort()
10147 FPSort(8, 24)
10148 """
10149 ctx = _get_ctx(ctx)
10150 [a] = _coerce_fp_expr_list([a], ctx)
10151 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10152
10153
10154def _mk_fp_unary(f, rm, a, ctx):
10155 ctx = _get_ctx(ctx)
10156 [a] = _coerce_fp_expr_list([a], ctx)
10157 if z3_debug():
10158 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10159 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10160 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10161
10162
10163def _mk_fp_unary_pred(f, a, ctx):
10164 ctx = _get_ctx(ctx)
10165 [a] = _coerce_fp_expr_list([a], ctx)
10166 if z3_debug():
10167 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10168 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10169
10170
10171def _mk_fp_bin(f, rm, a, b, ctx):
10172 ctx = _get_ctx(ctx)
10173 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10174 if z3_debug():
10175 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10176 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10177 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10178
10179
10180def _mk_fp_bin_norm(f, a, b, ctx):
10181 ctx = _get_ctx(ctx)
10182 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10183 if z3_debug():
10184 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10185 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10186
10187
10188def _mk_fp_bin_pred(f, a, b, ctx):
10189 ctx = _get_ctx(ctx)
10190 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10191 if z3_debug():
10192 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10193 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10194
10195
10196def _mk_fp_tern(f, rm, a, b, c, ctx):
10197 ctx = _get_ctx(ctx)
10198 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
10199 if z3_debug():
10200 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10201 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
10202 c), "Second, third or fourth argument must be a Z3 floating-point expression")
10203 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10204
10205
10206def fpAdd(rm, a, b, ctx=None):
10207 """Create a Z3 floating-point addition expression.
10208
10209 >>> s = FPSort(8, 24)
10210 >>> rm = RNE()
10211 >>> x = FP('x', s)
10212 >>> y = FP('y', s)
10213 >>> fpAdd(rm, x, y)
10214 x + y
10215 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10216 fpAdd(RTZ(), x, y)
10217 >>> fpAdd(rm, x, y).sort()
10218 FPSort(8, 24)
10219 """
10220 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10221
10222
10223def fpSub(rm, a, b, ctx=None):
10224 """Create a Z3 floating-point subtraction expression.
10225
10226 >>> s = FPSort(8, 24)
10227 >>> rm = RNE()
10228 >>> x = FP('x', s)
10229 >>> y = FP('y', s)
10230 >>> fpSub(rm, x, y)
10231 x - y
10232 >>> fpSub(rm, x, y).sort()
10233 FPSort(8, 24)
10234 """
10235 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10236
10237
10238def fpMul(rm, a, b, ctx=None):
10239 """Create a Z3 floating-point multiplication expression.
10240
10241 >>> s = FPSort(8, 24)
10242 >>> rm = RNE()
10243 >>> x = FP('x', s)
10244 >>> y = FP('y', s)
10245 >>> fpMul(rm, x, y)
10246 x * y
10247 >>> fpMul(rm, x, y).sort()
10248 FPSort(8, 24)
10249 """
10250 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10251
10252
10253def fpDiv(rm, a, b, ctx=None):
10254 """Create a Z3 floating-point division expression.
10255
10256 >>> s = FPSort(8, 24)
10257 >>> rm = RNE()
10258 >>> x = FP('x', s)
10259 >>> y = FP('y', s)
10260 >>> fpDiv(rm, x, y)
10261 x / y
10262 >>> fpDiv(rm, x, y).sort()
10263 FPSort(8, 24)
10264 """
10265 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10266
10267
10268def fpRem(a, b, ctx=None):
10269 """Create a Z3 floating-point remainder expression.
10270
10271 >>> s = FPSort(8, 24)
10272 >>> x = FP('x', s)
10273 >>> y = FP('y', s)
10274 >>> fpRem(x, y)
10275 fpRem(x, y)
10276 >>> fpRem(x, y).sort()
10277 FPSort(8, 24)
10278 """
10279 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10280
10281
10282def fpMin(a, b, ctx=None):
10283 """Create a Z3 floating-point minimum expression.
10284
10285 >>> s = FPSort(8, 24)
10286 >>> rm = RNE()
10287 >>> x = FP('x', s)
10288 >>> y = FP('y', s)
10289 >>> fpMin(x, y)
10290 fpMin(x, y)
10291 >>> fpMin(x, y).sort()
10292 FPSort(8, 24)
10293 """
10294 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10295
10296
10297def fpMax(a, b, ctx=None):
10298 """Create a Z3 floating-point maximum expression.
10299
10300 >>> s = FPSort(8, 24)
10301 >>> rm = RNE()
10302 >>> x = FP('x', s)
10303 >>> y = FP('y', s)
10304 >>> fpMax(x, y)
10305 fpMax(x, y)
10306 >>> fpMax(x, y).sort()
10307 FPSort(8, 24)
10308 """
10309 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10310
10311
10312def fpFMA(rm, a, b, c, ctx=None):
10313 """Create a Z3 floating-point fused multiply-add expression.
10314 """
10315 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10316
10317
10318def fpSqrt(rm, a, ctx=None):
10319 """Create a Z3 floating-point square root expression.
10320 """
10321 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10322
10323
10324def fpRoundToIntegral(rm, a, ctx=None):
10325 """Create a Z3 floating-point roundToIntegral expression.
10326 """
10327 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10328
10329
10330def fpIsNaN(a, ctx=None):
10331 """Create a Z3 floating-point isNaN expression.
10332
10333 >>> s = FPSort(8, 24)
10334 >>> x = FP('x', s)
10335 >>> y = FP('y', s)
10336 >>> fpIsNaN(x)
10337 fpIsNaN(x)
10338 """
10339 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10340
10341
10342def fpIsInf(a, ctx=None):
10343 """Create a Z3 floating-point isInfinite expression.
10344
10345 >>> s = FPSort(8, 24)
10346 >>> x = FP('x', s)
10347 >>> fpIsInf(x)
10348 fpIsInf(x)
10349 """
10350 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10351
10352
10353def fpIsZero(a, ctx=None):
10354 """Create a Z3 floating-point isZero expression.
10355 """
10356 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10357
10358
10359def fpIsNormal(a, ctx=None):
10360 """Create a Z3 floating-point isNormal expression.
10361 """
10362 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10363
10364
10365def fpIsSubnormal(a, ctx=None):
10366 """Create a Z3 floating-point isSubnormal expression.
10367 """
10368 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10369
10370
10371def fpIsNegative(a, ctx=None):
10372 """Create a Z3 floating-point isNegative expression.
10373 """
10374 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10375
10376
10377def fpIsPositive(a, ctx=None):
10378 """Create a Z3 floating-point isPositive expression.
10379 """
10380 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10381
10382
10384 if z3_debug():
10385 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10386
10387
10388def fpLT(a, b, ctx=None):
10389 """Create the Z3 floating-point expression `other < self`.
10390
10391 >>> x, y = FPs('x y', FPSort(8, 24))
10392 >>> fpLT(x, y)
10393 x < y
10394 >>> (x < y).sexpr()
10395 '(fp.lt x y)'
10396 """
10397 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10398
10399
10400def fpLEQ(a, b, ctx=None):
10401 """Create the Z3 floating-point expression `other <= self`.
10402
10403 >>> x, y = FPs('x y', FPSort(8, 24))
10404 >>> fpLEQ(x, y)
10405 x <= y
10406 >>> (x <= y).sexpr()
10407 '(fp.leq x y)'
10408 """
10409 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10410
10411
10412def fpGT(a, b, ctx=None):
10413 """Create the Z3 floating-point expression `other > self`.
10414
10415 >>> x, y = FPs('x y', FPSort(8, 24))
10416 >>> fpGT(x, y)
10417 x > y
10418 >>> (x > y).sexpr()
10419 '(fp.gt x y)'
10420 """
10421 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10422
10423
10424def fpGEQ(a, b, ctx=None):
10425 """Create the Z3 floating-point expression `other >= self`.
10426
10427 >>> x, y = FPs('x y', FPSort(8, 24))
10428 >>> fpGEQ(x, y)
10429 x >= y
10430 >>> (x >= y).sexpr()
10431 '(fp.geq x y)'
10432 """
10433 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10434
10435
10436def fpEQ(a, b, ctx=None):
10437 """Create the Z3 floating-point expression `fpEQ(other, self)`.
10438
10439 >>> x, y = FPs('x y', FPSort(8, 24))
10440 >>> fpEQ(x, y)
10441 fpEQ(x, y)
10442 >>> fpEQ(x, y).sexpr()
10443 '(fp.eq x y)'
10444 """
10445 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10446
10447
10448def fpNEQ(a, b, ctx=None):
10449 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10450
10451 >>> x, y = FPs('x y', FPSort(8, 24))
10452 >>> fpNEQ(x, y)
10453 Not(fpEQ(x, y))
10454 >>> (x != y).sexpr()
10455 '(distinct x y)'
10456 """
10457 return Not(fpEQ(a, b, ctx))
10458
10459
10460def fpFP(sgn, exp, sig, ctx=None):
10461 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10462
10463 >>> s = FPSort(8, 24)
10464 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10465 >>> print(x)
10466 fpFP(1, 127, 4194304)
10467 >>> xv = FPVal(-1.5, s)
10468 >>> print(xv)
10469 -1.5
10470 >>> slvr = Solver()
10471 >>> slvr.add(fpEQ(x, xv))
10472 >>> slvr.check()
10473 sat
10474 >>> xv = FPVal(+1.5, s)
10475 >>> print(xv)
10476 1.5
10477 >>> slvr = Solver()
10478 >>> slvr.add(fpEQ(x, xv))
10479 >>> slvr.check()
10480 unsat
10481 """
10482 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10483 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10484 ctx = _get_ctx(ctx)
10485 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10486 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10487
10488
10489def fpToFP(a1, a2=None, a3=None, ctx=None):
10490 """Create a Z3 floating-point conversion expression from other term sorts
10491 to floating-point.
10492
10493 From a bit-vector term in IEEE 754-2008 format:
10494 >>> x = FPVal(1.0, Float32())
10495 >>> x_bv = fpToIEEEBV(x)
10496 >>> simplify(fpToFP(x_bv, Float32()))
10497 1
10498
10499 From a floating-point term with different precision:
10500 >>> x = FPVal(1.0, Float32())
10501 >>> x_db = fpToFP(RNE(), x, Float64())
10502 >>> x_db.sort()
10503 FPSort(11, 53)
10504
10505 From a real term:
10506 >>> x_r = RealVal(1.5)
10507 >>> simplify(fpToFP(RNE(), x_r, Float32()))
10508 1.5
10509
10510 From a signed bit-vector term:
10511 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10512 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10513 -1.25*(2**2)
10514 """
10515 ctx = _get_ctx(ctx)
10516 if is_bv(a1) and is_fp_sort(a2):
10517 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10518 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10519 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10520 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10521 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10522 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10523 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10524 else:
10525 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10526
10527
10528def fpBVToFP(v, sort, ctx=None):
10529 """Create a Z3 floating-point conversion expression that represents the
10530 conversion from a bit-vector term to a floating-point term.
10531
10532 >>> x_bv = BitVecVal(0x3F800000, 32)
10533 >>> x_fp = fpBVToFP(x_bv, Float32())
10534 >>> x_fp
10535 fpToFP(1065353216)
10536 >>> simplify(x_fp)
10537 1
10538 """
10539 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10540 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10541 ctx = _get_ctx(ctx)
10542 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10543
10544
10545def fpFPToFP(rm, v, sort, ctx=None):
10546 """Create a Z3 floating-point conversion expression that represents the
10547 conversion from a floating-point term to a floating-point term of different precision.
10548
10549 >>> x_sgl = FPVal(1.0, Float32())
10550 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10551 >>> x_dbl
10552 fpToFP(RNE(), 1)
10553 >>> simplify(x_dbl)
10554 1
10555 >>> x_dbl.sort()
10556 FPSort(11, 53)
10557 """
10558 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10559 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10560 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10561 ctx = _get_ctx(ctx)
10562 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10563
10564
10565def fpRealToFP(rm, v, sort, ctx=None):
10566 """Create a Z3 floating-point conversion expression that represents the
10567 conversion from a real term to a floating-point term.
10568
10569 >>> x_r = RealVal(1.5)
10570 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10571 >>> x_fp
10572 fpToFP(RNE(), 3/2)
10573 >>> simplify(x_fp)
10574 1.5
10575 """
10576 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10577 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10578 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10579 ctx = _get_ctx(ctx)
10580 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10581
10582
10583def fpSignedToFP(rm, v, sort, ctx=None):
10584 """Create a Z3 floating-point conversion expression that represents the
10585 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10586
10587 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10588 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10589 >>> x_fp
10590 fpToFP(RNE(), 4294967291)
10591 >>> simplify(x_fp)
10592 -1.25*(2**2)
10593 """
10594 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10595 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10596 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10597 ctx = _get_ctx(ctx)
10598 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10599
10600
10601def fpUnsignedToFP(rm, v, sort, ctx=None):
10602 """Create a Z3 floating-point conversion expression that represents the
10603 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10604
10605 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10606 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10607 >>> x_fp
10608 fpToFPUnsigned(RNE(), 4294967291)
10609 >>> simplify(x_fp)
10610 1*(2**32)
10611 """
10612 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10613 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10614 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10615 ctx = _get_ctx(ctx)
10616 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10617
10618
10619def fpToFPUnsigned(rm, x, s, ctx=None):
10620 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10621 if z3_debug():
10622 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10623 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10624 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10625 ctx = _get_ctx(ctx)
10626 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10627
10628
10629def fpToSBV(rm, x, s, ctx=None):
10630 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10631
10632 >>> x = FP('x', FPSort(8, 24))
10633 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10634 >>> print(is_fp(x))
10635 True
10636 >>> print(is_bv(y))
10637 True
10638 >>> print(is_fp(y))
10639 False
10640 >>> print(is_bv(x))
10641 False
10642 """
10643 if z3_debug():
10644 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10645 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10646 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10647 ctx = _get_ctx(ctx)
10648 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10649
10650
10651def fpToUBV(rm, x, s, ctx=None):
10652 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10653
10654 >>> x = FP('x', FPSort(8, 24))
10655 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10656 >>> print(is_fp(x))
10657 True
10658 >>> print(is_bv(y))
10659 True
10660 >>> print(is_fp(y))
10661 False
10662 >>> print(is_bv(x))
10663 False
10664 """
10665 if z3_debug():
10666 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10667 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10668 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10669 ctx = _get_ctx(ctx)
10670 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10671
10672
10673def fpToReal(x, ctx=None):
10674 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10675
10676 >>> x = FP('x', FPSort(8, 24))
10677 >>> y = fpToReal(x)
10678 >>> print(is_fp(x))
10679 True
10680 >>> print(is_real(y))
10681 True
10682 >>> print(is_fp(y))
10683 False
10684 >>> print(is_real(x))
10685 False
10686 """
10687 if z3_debug():
10688 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10689 ctx = _get_ctx(ctx)
10690 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10691
10692
10693def fpToIEEEBV(x, ctx=None):
10694 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10695
10696 The size of the resulting bit-vector is automatically determined.
10697
10698 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10699 knows only one NaN and it will always produce the same bit-vector representation of
10700 that NaN.
10701
10702 >>> x = FP('x', FPSort(8, 24))
10703 >>> y = fpToIEEEBV(x)
10704 >>> print(is_fp(x))
10705 True
10706 >>> print(is_bv(y))
10707 True
10708 >>> print(is_fp(y))
10709 False
10710 >>> print(is_bv(x))
10711 False
10712 """
10713 if z3_debug():
10714 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10715 ctx = _get_ctx(ctx)
10716 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10717
10718
10719
10724
10726 """Sequence sort."""
10727
10728 def is_string(self):
10729 """Determine if sort is a string
10730 >>> s = StringSort()
10731 >>> s.is_string()
10732 True
10733 >>> s = SeqSort(IntSort())
10734 >>> s.is_string()
10735 False
10736 """
10737 return Z3_is_string_sort(self.ctx_ref(), self.ast)
10738
10739 def basis(self):
10740 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10741
10743 """Character sort."""
10744
10745
10746def StringSort(ctx=None):
10747 """Create a string sort
10748 >>> s = StringSort()
10749 >>> print(s)
10750 String
10751 """
10752 ctx = _get_ctx(ctx)
10753 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10754
10755def CharSort(ctx=None):
10756 """Create a character sort
10757 >>> ch = CharSort()
10758 >>> print(ch)
10759 Char
10760 """
10761 ctx = _get_ctx(ctx)
10762 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
10763
10764
10765def SeqSort(s):
10766 """Create a sequence sort over elements provided in the argument
10767 >>> s = SeqSort(IntSort())
10768 >>> s == Unit(IntVal(1)).sort()
10769 True
10770 """
10771 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10772
10773
10775 """Sequence expression."""
10776
10777 def sort(self):
10778 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10779
10780 def __add__(self, other):
10781 return Concat(self, other)
10782
10783 def __radd__(self, other):
10784 return Concat(other, self)
10785
10786 def __getitem__(self, i):
10787 if _is_int(i):
10788 i = IntVal(i, self.ctx)
10789 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10790
10791 def at(self, i):
10792 if _is_int(i):
10793 i = IntVal(i, self.ctx)
10794 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10795
10796 def is_string(self):
10797 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_astas_ast()))
10798
10800 return Z3_is_string(self.ctx_ref(), self.as_astas_ast())
10801
10802 def as_string(self):
10803 """Return a string representation of sequence expression."""
10804 if self.is_string_value():
10805 string_length = ctypes.c_uint()
10806 chars = Z3_get_lstring(self.ctx_ref(), self.as_astas_ast(), byref(string_length))
10807 return string_at(chars, size=string_length.value).decode("latin-1")
10808 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
10809
10810 def __le__(self, other):
10811 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10812
10813 def __lt__(self, other):
10814 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10815
10816 def __ge__(self, other):
10817 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10818
10819 def __gt__(self, other):
10820 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10821
10822
10823def _coerce_char(ch, ctx=None):
10824 if isinstance(ch, str):
10825 ctx = _get_ctx(ctx)
10826 ch = CharVal(ch, ctx)
10827 if not is_expr(ch):
10828 raise Z3Exception("Character expression expected")
10829 return ch
10830
10832 """Character expression."""
10833
10834 def __le__(self, other):
10835 other = _coerce_char(other, self.ctx)
10836 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10837
10838 def to_int(self):
10839 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10840
10841 def to_bv(self):
10842 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10843
10844 def is_digit(self):
10845 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10846
10847
10848def CharVal(ch, ctx=None):
10849 ctx = _get_ctx(ctx)
10850 if isinstance(ch, str):
10851 ch = ord(ch)
10852 if not isinstance(ch, int):
10853 raise Z3Exception("character value should be an ordinal")
10854 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
10855
10856def CharFromBv(ch, ctx=None):
10857 if not is_expr(ch):
10858 raise Z3Expression("Bit-vector expression needed")
10859 return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
10860
10861def CharToBv(ch, ctx=None):
10862 ch = _coerce_char(ch, ctx)
10863 return ch.to_bv()
10864
10865def CharToInt(ch, ctx=None):
10866 ch = _coerce_char(ch, ctx)
10867 return ch.to_int()
10868
10869def CharIsDigit(ch, ctx=None):
10870 ch = _coerce_char(ch, ctx)
10871 return ch.is_digit()
10872
10873def _coerce_seq(s, ctx=None):
10874 if isinstance(s, str):
10875 ctx = _get_ctx(ctx)
10876 s = StringVal(s, ctx)
10877 if not is_expr(s):
10878 raise Z3Exception("Non-expression passed as a sequence")
10879 if not is_seq(s):
10880 raise Z3Exception("Non-sequence passed as a sequence")
10881 return s
10882
10883
10884def _get_ctx2(a, b, ctx=None):
10885 if is_expr(a):
10886 return a.ctx
10887 if is_expr(b):
10888 return b.ctx
10889 if ctx is None:
10890 ctx = main_ctx()
10891 return ctx
10892
10893
10894def is_seq(a):
10895 """Return `True` if `a` is a Z3 sequence expression.
10896 >>> print (is_seq(Unit(IntVal(0))))
10897 True
10898 >>> print (is_seq(StringVal("abc")))
10899 True
10900 """
10901 return isinstance(a, SeqRef)
10902
10903
10905 """Return `True` if `a` is a Z3 string expression.
10906 >>> print (is_string(StringVal("ab")))
10907 True
10908 """
10909 return isinstance(a, SeqRef) and a.is_string()
10910
10911
10913 """return 'True' if 'a' is a Z3 string constant expression.
10914 >>> print (is_string_value(StringVal("a")))
10915 True
10916 >>> print (is_string_value(StringVal("a") + StringVal("b")))
10917 False
10918 """
10919 return isinstance(a, SeqRef) and a.is_string_value()
10920
10921def StringVal(s, ctx=None):
10922 """create a string expression"""
10923 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
10924 ctx = _get_ctx(ctx)
10925 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
10926
10927
10928def String(name, ctx=None):
10929 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10930
10931 >>> x = String('x')
10932 """
10933 ctx = _get_ctx(ctx)
10934 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10935
10936
10937def Strings(names, ctx=None):
10938 """Return a tuple of String constants. """
10939 ctx = _get_ctx(ctx)
10940 if isinstance(names, str):
10941 names = names.split(" ")
10942 return [String(name, ctx) for name in names]
10943
10944
10945def SubString(s, offset, length):
10946 """Extract substring or subsequence starting at offset"""
10947 return Extract(s, offset, length)
10948
10949
10950def SubSeq(s, offset, length):
10951 """Extract substring or subsequence starting at offset"""
10952 return Extract(s, offset, length)
10953
10954
10955def Empty(s):
10956 """Create the empty sequence of the given sort
10957 >>> e = Empty(StringSort())
10958 >>> e2 = StringVal("")
10959 >>> print(e.eq(e2))
10960 True
10961 >>> e3 = Empty(SeqSort(IntSort()))
10962 >>> print(e3)
10963 Empty(Seq(Int))
10964 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10965 >>> print(e4)
10966 Empty(ReSort(Seq(Int)))
10967 """
10968 if isinstance(s, SeqSortRef):
10969 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10970 if isinstance(s, ReSortRef):
10971 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10972 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10973
10974
10975def Full(s):
10976 """Create the regular expression that accepts the universal language
10977 >>> e = Full(ReSort(SeqSort(IntSort())))
10978 >>> print(e)
10979 Full(ReSort(Seq(Int)))
10980 >>> e1 = Full(ReSort(StringSort()))
10981 >>> print(e1)
10982 Full(ReSort(String))
10983 """
10984 if isinstance(s, ReSortRef):
10985 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10986 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10987
10988
10989
10990def Unit(a):
10991 """Create a singleton sequence"""
10992 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10993
10994
10995def PrefixOf(a, b):
10996 """Check if 'a' is a prefix of 'b'
10997 >>> s1 = PrefixOf("ab", "abc")
10998 >>> simplify(s1)
10999 True
11000 >>> s2 = PrefixOf("bc", "abc")
11001 >>> simplify(s2)
11002 False
11003 """
11004 ctx = _get_ctx2(a, b)
11005 a = _coerce_seq(a, ctx)
11006 b = _coerce_seq(b, ctx)
11007 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11008
11009
11010def SuffixOf(a, b):
11011 """Check if 'a' is a suffix of 'b'
11012 >>> s1 = SuffixOf("ab", "abc")
11013 >>> simplify(s1)
11014 False
11015 >>> s2 = SuffixOf("bc", "abc")
11016 >>> simplify(s2)
11017 True
11018 """
11019 ctx = _get_ctx2(a, b)
11020 a = _coerce_seq(a, ctx)
11021 b = _coerce_seq(b, ctx)
11022 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11023
11024
11025def Contains(a, b):
11026 """Check if 'a' contains 'b'
11027 >>> s1 = Contains("abc", "ab")
11028 >>> simplify(s1)
11029 True
11030 >>> s2 = Contains("abc", "bc")
11031 >>> simplify(s2)
11032 True
11033 >>> x, y, z = Strings('x y z')
11034 >>> s3 = Contains(Concat(x,y,z), y)
11035 >>> simplify(s3)
11036 True
11037 """
11038 ctx = _get_ctx2(a, b)
11039 a = _coerce_seq(a, ctx)
11040 b = _coerce_seq(b, ctx)
11041 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11042
11043
11044def Replace(s, src, dst):
11045 """Replace the first occurrence of 'src' by 'dst' in 's'
11046 >>> r = Replace("aaa", "a", "b")
11047 >>> simplify(r)
11048 "baa"
11049 """
11050 ctx = _get_ctx2(dst, s)
11051 if ctx is None and is_expr(src):
11052 ctx = src.ctx
11053 src = _coerce_seq(src, ctx)
11054 dst = _coerce_seq(dst, ctx)
11055 s = _coerce_seq(s, ctx)
11056 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11057
11058
11059def IndexOf(s, substr, offset=None):
11060 """Retrieve the index of substring within a string starting at a specified offset.
11061 >>> simplify(IndexOf("abcabc", "bc", 0))
11062 1
11063 >>> simplify(IndexOf("abcabc", "bc", 2))
11064 4
11065 """
11066 if offset is None:
11067 offset = IntVal(0)
11068 ctx = None
11069 if is_expr(offset):
11070 ctx = offset.ctx
11071 ctx = _get_ctx2(s, substr, ctx)
11072 s = _coerce_seq(s, ctx)
11073 substr = _coerce_seq(substr, ctx)
11074 if _is_int(offset):
11075 offset = IntVal(offset, ctx)
11076 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11077
11078
11079def LastIndexOf(s, substr):
11080 """Retrieve the last index of substring within a string"""
11081 ctx = None
11082 ctx = _get_ctx2(s, substr, ctx)
11083 s = _coerce_seq(s, ctx)
11084 substr = _coerce_seq(substr, ctx)
11085 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11086
11087
11088def Length(s):
11089 """Obtain the length of a sequence 's'
11090 >>> l = Length(StringVal("abc"))
11091 >>> simplify(l)
11092 3
11093 """
11094 s = _coerce_seq(s)
11095 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11096
11097
11099 """Convert string expression to integer
11100 >>> a = StrToInt("1")
11101 >>> simplify(1 == a)
11102 True
11103 >>> b = StrToInt("2")
11104 >>> simplify(1 == b)
11105 False
11106 >>> c = StrToInt(IntToStr(2))
11107 >>> simplify(1 == c)
11108 False
11109 """
11110 s = _coerce_seq(s)
11111 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11112
11113
11115 """Convert integer expression to string"""
11116 if not is_expr(s):
11117 s = _py2expr(s)
11118 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11119
11120
11122 """Convert a unit length string to integer code"""
11123 if not is_expr(s):
11124 s = _py2expr(s)
11125 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
11126
11128 """Convert code to a string"""
11129 if not is_expr(c):
11130 c = _py2expr(c)
11131 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
11132
11133def Re(s, ctx=None):
11134 """The regular expression that accepts sequence 's'
11135 >>> s1 = Re("ab")
11136 >>> s2 = Re(StringVal("ab"))
11137 >>> s3 = Re(Unit(BoolVal(True)))
11138 """
11139 s = _coerce_seq(s, ctx)
11140 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
11141
11142
11143# Regular expressions
11144
11146 """Regular expression sort."""
11147
11148 def basis(self):
11149 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11150
11151
11152def ReSort(s):
11153 if is_ast(s):
11154 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
11155 if s is None or isinstance(s, Context):
11156 ctx = _get_ctx(s)
11157 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
11158 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
11159
11160
11162 """Regular expressions."""
11163
11164 def __add__(self, other):
11165 return Union(self, other)
11166
11167
11168def is_re(s):
11169 return isinstance(s, ReRef)
11170
11171
11172def InRe(s, re):
11173 """Create regular expression membership test
11174 >>> re = Union(Re("a"),Re("b"))
11175 >>> print (simplify(InRe("a", re)))
11176 True
11177 >>> print (simplify(InRe("b", re)))
11178 True
11179 >>> print (simplify(InRe("c", re)))
11180 False
11181 """
11182 s = _coerce_seq(s, re.ctx)
11183 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
11184
11185
11186def Union(*args):
11187 """Create union of regular expressions.
11188 >>> re = Union(Re("a"), Re("b"), Re("c"))
11189 >>> print (simplify(InRe("d", re)))
11190 False
11191 """
11192 args = _get_args(args)
11193 sz = len(args)
11194 if z3_debug():
11195 _z3_assert(sz > 0, "At least one argument expected.")
11196 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11197 if sz == 1:
11198 return args[0]
11199 ctx = args[0].ctx
11200 v = (Ast * sz)()
11201 for i in range(sz):
11202 v[i] = args[i].as_ast()
11203 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
11204
11205
11206def Intersect(*args):
11207 """Create intersection of regular expressions.
11208 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
11209 """
11210 args = _get_args(args)
11211 sz = len(args)
11212 if z3_debug():
11213 _z3_assert(sz > 0, "At least one argument expected.")
11214 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11215 if sz == 1:
11216 return args[0]
11217 ctx = args[0].ctx
11218 v = (Ast * sz)()
11219 for i in range(sz):
11220 v[i] = args[i].as_ast()
11221 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
11222
11223
11224def Plus(re):
11225 """Create the regular expression accepting one or more repetitions of argument.
11226 >>> re = Plus(Re("a"))
11227 >>> print(simplify(InRe("aa", re)))
11228 True
11229 >>> print(simplify(InRe("ab", re)))
11230 False
11231 >>> print(simplify(InRe("", re)))
11232 False
11233 """
11234 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
11235
11236
11237def Option(re):
11238 """Create the regular expression that optionally accepts the argument.
11239 >>> re = Option(Re("a"))
11240 >>> print(simplify(InRe("a", re)))
11241 True
11242 >>> print(simplify(InRe("", re)))
11243 True
11244 >>> print(simplify(InRe("aa", re)))
11245 False
11246 """
11247 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11248
11249
11251 """Create the complement regular expression."""
11252 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11253
11254
11255def Star(re):
11256 """Create the regular expression accepting zero or more repetitions of argument.
11257 >>> re = Star(Re("a"))
11258 >>> print(simplify(InRe("aa", re)))
11259 True
11260 >>> print(simplify(InRe("ab", re)))
11261 False
11262 >>> print(simplify(InRe("", re)))
11263 True
11264 """
11265 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11266
11267
11268def Loop(re, lo, hi=0):
11269 """Create the regular expression accepting between a lower and upper bound repetitions
11270 >>> re = Loop(Re("a"), 1, 3)
11271 >>> print(simplify(InRe("aa", re)))
11272 True
11273 >>> print(simplify(InRe("aaaa", re)))
11274 False
11275 >>> print(simplify(InRe("", re)))
11276 False
11277 """
11278 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11279
11280
11281def Range(lo, hi, ctx=None):
11282 """Create the range regular expression over two sequences of length 1
11283 >>> range = Range("a","z")
11284 >>> print(simplify(InRe("b", range)))
11285 True
11286 >>> print(simplify(InRe("bb", range)))
11287 False
11288 """
11289 lo = _coerce_seq(lo, ctx)
11290 hi = _coerce_seq(hi, ctx)
11291 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11292
11293def Diff(a, b, ctx=None):
11294 """Create the difference regular epression
11295 """
11296 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
11297
11298def AllChar(regex_sort, ctx=None):
11299 """Create a regular expression that accepts all single character strings
11300 """
11301 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
11302
11303# Special Relations
11304
11305
11306def PartialOrder(a, index):
11307 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11308
11309
11310def LinearOrder(a, index):
11311 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11312
11313
11314def TreeOrder(a, index):
11315 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11316
11317
11319 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11320
11321
11323 """Given a binary relation R, such that the two arguments have the same sort
11324 create the transitive closure relation R+.
11325 The transitive closure R+ is a new relation.
11326 """
11327 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11328
11329def to_Ast(ptr,):
11330 ast = Ast(ptr)
11331 super(ctypes.c_void_p, ast).__init__(ptr)
11332 return ast
11333
11335 ctx = ContextObj(ptr)
11336 super(ctypes.c_void_p, ctx).__init__(ptr)
11337 return ctx
11338
11340 v = AstVectorObj(ptr)
11341 super(ctypes.c_void_p, v).__init__(ptr)
11342 return v
11343
11344# NB. my-hacky-class only works for a single instance of OnClause
11345# it should be replaced with a proper correlation between OnClause
11346# and object references that can be passed over the FFI.
11347# for UserPropagator we use a global dictionary, which isn't great code.
11348
11349_my_hacky_class = None
11350def on_clause_eh(ctx, p, clause):
11351 onc = _my_hacky_class
11352 p = _to_expr_ref(to_Ast(p), onc.ctx)
11353 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
11354 onc.on_clause(p, clause)
11355
11356_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
11357
11359 def __init__(self, s, on_clause):
11360 self.s = s
11361 self.ctx = s.ctx
11362 self.on_clause = on_clause
11363 self.idx = 22
11364 global _my_hacky_class
11365 _my_hacky_class = self
11366 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
11367
11368
11370 def __init__(self):
11371 self.bases = {}
11372 self.lock = None
11373
11374 def set_threaded(self):
11375 if self.lock is None:
11376 import threading
11377 self.lock = threading.Lock()
11378
11379 def get(self, ctx):
11380 if self.lock:
11381 with self.lock:
11382 r = self.bases[ctx]
11383 else:
11384 r = self.bases[ctx]
11385 return r
11386
11387 def set(self, ctx, r):
11388 if self.lock:
11389 with self.lock:
11390 self.bases[ctx] = r
11391 else:
11392 self.bases[ctx] = r
11393
11394 def insert(self, r):
11395 if self.lock:
11396 with self.lock:
11397 id = len(self.bases) + 3
11398 self.bases[id] = r
11399 else:
11400 id = len(self.bases) + 3
11401 self.bases[id] = r
11402 return id
11403
11404
11405_prop_closures = None
11406
11407
11409 global _prop_closures
11410 if _prop_closures is None:
11411 _prop_closures = PropClosures()
11412
11413
11414def user_prop_push(ctx, cb):
11415 prop = _prop_closures.get(ctx)
11416 prop.cb = cb
11417 prop.push()
11418
11419
11420def user_prop_pop(ctx, cb, num_scopes):
11421 prop = _prop_closures.get(ctx)
11422 prop.cb = cb
11423 prop.pop(num_scopes)
11424
11425
11426def user_prop_fresh(ctx, _new_ctx):
11427 _prop_closures.set_threaded()
11428 prop = _prop_closures.get(ctx)
11429 nctx = Context()
11430 Z3_del_context(nctx.ctx)
11431 new_ctx = to_ContextObj(_new_ctx)
11432 nctx.ctx = new_ctx
11433 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
11434 nctx.owner = False
11435 new_prop = prop.fresh(nctx)
11436 _prop_closures.set(new_prop.id, new_prop)
11437 return new_prop.id
11438
11439
11440def user_prop_fixed(ctx, cb, id, value):
11441 prop = _prop_closures.get(ctx)
11442 prop.cb = cb
11443 id = _to_expr_ref(to_Ast(id), prop.ctx())
11444 value = _to_expr_ref(to_Ast(value), prop.ctx())
11445 prop.fixed(id, value)
11446 prop.cb = None
11447
11448def user_prop_created(ctx, cb, id):
11449 prop = _prop_closures.get(ctx)
11450 prop.cb = cb
11451 id = _to_expr_ref(to_Ast(id), prop.ctx())
11452 prop.created(id)
11453 prop.cb = None
11454
11455def user_prop_final(ctx, cb):
11456 prop = _prop_closures.get(ctx)
11457 prop.cb = cb
11458 prop.final()
11459 prop.cb = None
11460
11461def user_prop_eq(ctx, cb, x, y):
11462 prop = _prop_closures.get(ctx)
11463 prop.cb = cb
11464 x = _to_expr_ref(to_Ast(x), prop.ctx())
11465 y = _to_expr_ref(to_Ast(y), prop.ctx())
11466 prop.eq(x, y)
11467 prop.cb = None
11468
11469def user_prop_diseq(ctx, cb, x, y):
11470 prop = _prop_closures.get(ctx)
11471 prop.cb = cb
11472 x = _to_expr_ref(to_Ast(x), prop.ctx())
11473 y = _to_expr_ref(to_Ast(y), prop.ctx())
11474 prop.diseq(x, y)
11475 prop.cb = None
11476
11477# TODO The decision callback is not fully implemented.
11478# It needs to handle the ast*, unsigned* idx, and Z3_lbool*
11479def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref):
11480 prop = _prop_closures.get(ctx)
11481 prop.cb = cb
11482 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
11483 t, idx, phase = prop.decide(t, idx, phase)
11484 t_ref = t
11485 idx_ref = idx
11486 phase_ref = phase
11487 prop.cb = None
11488
11489
11490_user_prop_push = Z3_push_eh(user_prop_push)
11491_user_prop_pop = Z3_pop_eh(user_prop_pop)
11492_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
11493_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
11494_user_prop_created = Z3_created_eh(user_prop_created)
11495_user_prop_final = Z3_final_eh(user_prop_final)
11496_user_prop_eq = Z3_eq_eh(user_prop_eq)
11497_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
11498_user_prop_decide = Z3_decide_eh(user_prop_decide)
11499
11500
11501def PropagateFunction(name, *sig):
11502 """Create a function that gets tracked by user propagator.
11503 Every term headed by this function symbol is tracked.
11504 If a term is fixed and the fixed callback is registered a
11505 callback is invoked that the term headed by this function is fixed.
11506 """
11507 sig = _get_args(sig)
11508 if z3_debug():
11509 _z3_assert(len(sig) > 0, "At least two arguments expected")
11510 arity = len(sig) - 1
11511 rng = sig[arity]
11512 if z3_debug():
11513 _z3_assert(is_sort(rng), "Z3 sort expected")
11514 dom = (Sort * arity)()
11515 for i in range(arity):
11516 if z3_debug():
11517 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
11518 dom[i] = sig[i].ast
11519 ctx = rng.ctx
11520 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
11521
11522
11523
11525
11526 #
11527 # Either solver is set or ctx is set.
11528 # Propagators that are created throuh callbacks
11529 # to "fresh" inherit the context of that is supplied
11530 # as argument to the callback.
11531 # This context should not be deleted. It is owned by the solver.
11532 #
11533 def __init__(self, s, ctx=None):
11534 assert s is None or ctx is None
11536 self.solver = s
11537 self._ctx = None
11538 self.fresh_ctx = None
11539 self.cb = None
11540 self.id = _prop_closures.insert(self)
11541 self.fixed = None
11542 self.final = None
11543 self.eq = None
11544 self.diseq = None
11545 self.created = None
11546 if ctx:
11547 self.fresh_ctx = ctx
11548 if s:
11550 s.solver,
11551 ctypes.c_void_p(self.id),
11552 _user_prop_push,
11553 _user_prop_pop,
11554 _user_prop_fresh)
11555
11556 def __del__(self):
11557 if self._ctx:
11558 self._ctx.ctx = None
11559
11560 def ctx(self):
11561 if self.fresh_ctx:
11562 return self.fresh_ctx
11563 else:
11564 return self.solver.ctx
11565
11566 def ctx_ref(self):
11567 return self.ctx().ref()
11568
11569 def add_fixed(self, fixed):
11570 assert not self.fixed
11571 assert not self._ctx
11572 if self.solver:
11573 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
11574 self.fixed = fixed
11575
11576 def add_created(self, created):
11577 assert not self.created
11578 assert not self._ctx
11579 if self.solver:
11580 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
11581 self.created = created
11582
11583 def add_final(self, final):
11584 assert not self.final
11585 assert not self._ctx
11586 if self.solver:
11587 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
11588 self.final = final
11589
11590 def add_eq(self, eq):
11591 assert not self.eq
11592 assert not self._ctx
11593 if self.solver:
11594 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
11595 self.eq = eq
11596
11597 def add_diseq(self, diseq):
11598 assert not self.diseq
11599 assert not self._ctx
11600 if self.solver:
11601 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
11602 self.diseq = diseq
11603
11604 def add_decide(self, decide):
11605 assert not self.decide
11606 assert not self._ctx
11607 if self.solver:
11608 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
11609 self.decide = decide
11610
11611 def push(self):
11612 raise Z3Exception("push needs to be overwritten")
11613
11614 def pop(self, num_scopes):
11615 raise Z3Exception("pop needs to be overwritten")
11616
11617 def fresh(self, new_ctx):
11618 raise Z3Exception("fresh needs to be overwritten")
11619
11620 def add(self, e):
11621 assert not self._ctx
11622 if self.solver:
11623 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
11624 else:
11625 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
11626
11627 #
11628 # Tell the solver to perform the next split on a given term
11629 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
11630 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
11631 #
11632 def next_split(self, t, idx, phase):
11633 Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
11634
11635 #
11636 # Propagation can only be invoked as during a fixed or final callback.
11637 #
11638 def propagate(self, e, ids, eqs=[]):
11639 _ids, num_fixed = _to_ast_array(ids)
11640 num_eqs = len(eqs)
11641 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
11642 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
11643 Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11644 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11645
11646 def conflict(self, deps = [], eqs = []):
11647 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
def poly(self)
Definition: z3py.py:3116
def as_decimal(self, prec)
Definition: z3py.py:3104
def index(self)
Definition: z3py.py:3119
def approx(self, precision=10)
Definition: z3py.py:3092
def __del__(self)
Definition: z3py.py:8103
def __getitem__(self, idx)
Definition: z3py.py:8126
def __init__(self, result, ctx)
Definition: z3py.py:8095
def __len__(self)
Definition: z3py.py:8107
def as_expr(self)
Definition: z3py.py:8150
def __repr__(self)
Definition: z3py.py:8143
def sexpr(self)
Definition: z3py.py:8146
def __deepcopy__(self, memo={})
Definition: z3py.py:8100
def is_real(self)
Definition: z3py.py:2407
def __pos__(self)
Definition: z3py.py:2603
def sort(self)
Definition: z3py.py:2383
def __radd__(self, other)
Definition: z3py.py:2431
def __pow__(self, other)
Definition: z3py.py:2489
def __add__(self, other)
Definition: z3py.py:2418
def __lt__(self, other)
Definition: z3py.py:2625
def __neg__(self)
Definition: z3py.py:2592
def __rmul__(self, other)
Definition: z3py.py:2456
def __le__(self, other)
Definition: z3py.py:2612
def __mul__(self, other)
Definition: z3py.py:2441
def __mod__(self, other)
Definition: z3py.py:2565
def __rsub__(self, other)
Definition: z3py.py:2479
def __rtruediv__(self, other)
Definition: z3py.py:2561
def __rdiv__(self, other)
Definition: z3py.py:2544
def __ge__(self, other)
Definition: z3py.py:2651
def is_int(self)
Definition: z3py.py:2393
def __truediv__(self, other)
Definition: z3py.py:2540
def __gt__(self, other)
Definition: z3py.py:2638
def __sub__(self, other)
Definition: z3py.py:2466
def __rpow__(self, other)
Definition: z3py.py:2503
def __rmod__(self, other)
Definition: z3py.py:2580
def __div__(self, other)
Definition: z3py.py:2517
Arithmetic.
Definition: z3py.py:2288
def is_real(self)
Definition: z3py.py:2291
def subsort(self, other)
Definition: z3py.py:2322
def cast(self, val)
Definition: z3py.py:2326
def is_int(self)
Definition: z3py.py:2305
def is_bool(self)
Definition: z3py.py:2319
def sort(self)
Definition: z3py.py:4551
def domain_n(self, i)
Definition: z3py.py:4569
def default(self)
Definition: z3py.py:4594
def __getitem__(self, arg)
Definition: z3py.py:4582
def domain(self)
Definition: z3py.py:4560
def range(self)
Definition: z3py.py:4573
def domain_n(self, i)
Definition: z3py.py:4533
def domain(self)
Definition: z3py.py:4524
def range(self)
Definition: z3py.py:4538
def erase(self, k)
Definition: z3py.py:6092
def __del__(self)
Definition: z3py.py:6032
def reset(self)
Definition: z3py.py:6106
def __init__(self, m=None, ctx=None)
Definition: z3py.py:6018
def __len__(self)
Definition: z3py.py:6036
def keys(self)
Definition: z3py.py:6121
def __repr__(self)
Definition: z3py.py:6089
def __getitem__(self, key)
Definition: z3py.py:6062
def __deepcopy__(self, memo={})
Definition: z3py.py:6029
def __setitem__(self, k, v)
Definition: z3py.py:6073
def __contains__(self, key)
Definition: z3py.py:6049
def ctx_ref(self)
Definition: z3py.py:400
def __str__(self)
Definition: z3py.py:358
def __hash__(self)
Definition: z3py.py:367
def __nonzero__(self)
Definition: z3py.py:370
def __bool__(self)
Definition: z3py.py:373
def __del__(self)
Definition: z3py.py:350
def hash(self)
Definition: z3py.py:440
def get_id(self)
Definition: z3py.py:396
def as_ast(self)
Definition: z3py.py:392
def __repr__(self)
Definition: z3py.py:361
def __init__(self, ast, ctx=None)
Definition: z3py.py:345
def sexpr(self)
Definition: z3py.py:383
def translate(self, target)
Definition: z3py.py:421
def __deepcopy__(self, memo={})
Definition: z3py.py:355
def __copy__(self)
Definition: z3py.py:437
def __eq__(self, other)
Definition: z3py.py:364
def eq(self, other)
Definition: z3py.py:404
def __contains__(self, item)
Definition: z3py.py:5956
def resize(self, sz)
Definition: z3py.py:5943
def __del__(self)
Definition: z3py.py:5869
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5858
def __setitem__(self, i, v)
Definition: z3py.py:5915
def push(self, v)
Definition: z3py.py:5931
def __len__(self)
Definition: z3py.py:5873
def translate(self, other_ctx)
Definition: z3py.py:5979
def __repr__(self)
Definition: z3py.py:6001
def sexpr(self)
Definition: z3py.py:6004
def __deepcopy__(self, memo={})
Definition: z3py.py:5998
def __copy__(self)
Definition: z3py.py:5995
def __getitem__(self, i)
Definition: z3py.py:5886
def as_signed_long(self)
Definition: z3py.py:3914
def as_long(self)
Definition: z3py.py:3903
def as_binary_string(self)
Definition: z3py.py:3940
def as_string(self)
Definition: z3py.py:3937
def __rlshift__(self, other)
Definition: z3py.py:3885
def __pos__(self)
Definition: z3py.py:3650
def sort(self)
Definition: z3py.py:3490
def __radd__(self, other)
Definition: z3py.py:3525
def __rxor__(self, other)
Definition: z3py.py:3640
def __xor__(self, other)
Definition: z3py.py:3627
def __ror__(self, other)
Definition: z3py.py:3594
def __add__(self, other)
Definition: z3py.py:3512
def __rshift__(self, other)
Definition: z3py.py:3827
def __lt__(self, other)
Definition: z3py.py:3779
def __or__(self, other)
Definition: z3py.py:3581
def size(self)
Definition: z3py.py:3501
def __neg__(self)
Definition: z3py.py:3659
def __rand__(self, other)
Definition: z3py.py:3617
def __rmul__(self, other)
Definition: z3py.py:3548
def __le__(self, other)
Definition: z3py.py:3763
def __mul__(self, other)
Definition: z3py.py:3535
def __mod__(self, other)
Definition: z3py.py:3724
def __rsub__(self, other)
Definition: z3py.py:3571
def __invert__(self)
Definition: z3py.py:3670
def __rtruediv__(self, other)
Definition: z3py.py:3720
def __rdiv__(self, other)
Definition: z3py.py:3704
def __lshift__(self, other)
Definition: z3py.py:3857
def __ge__(self, other)
Definition: z3py.py:3811
def __and__(self, other)
Definition: z3py.py:3604
def __rrshift__(self, other)
Definition: z3py.py:3871
def __truediv__(self, other)
Definition: z3py.py:3700
def __gt__(self, other)
Definition: z3py.py:3795
def __sub__(self, other)
Definition: z3py.py:3558
def __rmod__(self, other)
Definition: z3py.py:3745
def __div__(self, other)
Definition: z3py.py:3681
Bit-Vectors.
Definition: z3py.py:3443
def subsort(self, other)
Definition: z3py.py:3455
def size(self)
Definition: z3py.py:3446
def cast(self, val)
Definition: z3py.py:3458
def sort(self)
Definition: z3py.py:1553
def __rmul__(self, other)
Definition: z3py.py:1556
def __mul__(self, other)
Definition: z3py.py:1559
Booleans.
Definition: z3py.py:1514
def subsort(self, other)
Definition: z3py.py:1540
def cast(self, val)
Definition: z3py.py:1517
def is_int(self)
Definition: z3py.py:1543
def is_bool(self)
Definition: z3py.py:1546
def to_int(self)
Definition: z3py.py:10838
def is_digit(self)
Definition: z3py.py:10844
def __le__(self, other)
Definition: z3py.py:10834
def to_bv(self)
Definition: z3py.py:10841
def _repr_html_(self)
Definition: z3py.py:6884
def __repr__(self)
Definition: z3py.py:6868
def __ne__(self, other)
Definition: z3py.py:6865
def __init__(self, r)
Definition: z3py.py:6856
def __deepcopy__(self, memo={})
Definition: z3py.py:6859
def __eq__(self, other)
Definition: z3py.py:6862
def interrupt(self)
Definition: z3py.py:222
def __init__(self, *args, **kws)
Definition: z3py.py:192
def __del__(self)
Definition: z3py.py:212
def param_descrs(self)
Definition: z3py.py:230
def ref(self)
Definition: z3py.py:218
def create(self)
Definition: z3py.py:5117
def __init__(self, name, ctx=None)
Definition: z3py.py:5073
def declare(self, name, *args)
Definition: z3py.py:5093
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:5083
def __repr__(self)
Definition: z3py.py:5114
def __deepcopy__(self, memo={})
Definition: z3py.py:5078
def sort(self)
Definition: z3py.py:5354
def recognizer(self, idx)
Definition: z3py.py:5289
def num_constructors(self)
Definition: z3py.py:5257
def constructor(self, idx)
Definition: z3py.py:5270
def accessor(self, i, j)
Definition: z3py.py:5317
Expressions.
Definition: z3py.py:961
def params(self)
Definition: z3py.py:1040
def sort(self)
Definition: z3py.py:978
def __hash__(self)
Definition: z3py.py:1018
def from_string(self, s)
Definition: z3py.py:1110
def get_id(self)
Definition: z3py.py:975
def children(self)
Definition: z3py.py:1095
def as_ast(self)
Definition: z3py.py:972
def decl(self)
Definition: z3py.py:1043
def __ne__(self, other)
Definition: z3py.py:1022
def serialize(self)
Definition: z3py.py:1113
def num_args(self)
Definition: z3py.py:1058
def arg(self, idx)
Definition: z3py.py:1074
def sort_kind(self)
Definition: z3py.py:990
def __eq__(self, other)
Definition: z3py.py:1001
def isNormal(self)
Definition: z3py.py:9841
def exponent(self, biased=True)
Definition: z3py.py:9800
def significand(self)
Definition: z3py.py:9769
def sign_as_bv(self)
Definition: z3py.py:9759
def isNegative(self)
Definition: z3py.py:9856
def significand_as_bv(self)
Definition: z3py.py:9790
def exponent_as_long(self, biased=True)
Definition: z3py.py:9810
def isInf(self)
Definition: z3py.py:9831
def isNaN(self)
Definition: z3py.py:9826
def sign(self)
Definition: z3py.py:9747
def isZero(self)
Definition: z3py.py:9836
def significand_as_long(self)
Definition: z3py.py:9779
def isSubnormal(self)
Definition: z3py.py:9846
def isPositive(self)
Definition: z3py.py:9851
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9821
def as_string(self)
Definition: z3py.py:9867
def as_string(self)
Definition: z3py.py:9661
def __pos__(self)
Definition: z3py.py:9600
def sort(self)
Definition: z3py.py:9483
def __radd__(self, other)
Definition: z3py.py:9539
def __add__(self, other)
Definition: z3py.py:9526
def sbits(self)
Definition: z3py.py:9502
def __lt__(self, other)
Definition: z3py.py:9517
def __neg__(self)
Definition: z3py.py:9604
def ebits(self)
Definition: z3py.py:9494
def __rmul__(self, other)
Definition: z3py.py:9587
def __le__(self, other)
Definition: z3py.py:9514
def __mul__(self, other)
Definition: z3py.py:9572
def __mod__(self, other)
Definition: z3py.py:9649
def __rsub__(self, other)
Definition: z3py.py:9562
def __rtruediv__(self, other)
Definition: z3py.py:9645
def __rdiv__(self, other)
Definition: z3py.py:9628
def __ge__(self, other)
Definition: z3py.py:9520
def __truediv__(self, other)
Definition: z3py.py:9641
def __gt__(self, other)
Definition: z3py.py:9523
def __sub__(self, other)
Definition: z3py.py:9549
def as_string(self)
Definition: z3py.py:9510
def __rmod__(self, other)
Definition: z3py.py:9653
def __div__(self, other)
Definition: z3py.py:9613
def sbits(self)
Definition: z3py.py:9380
def ebits(self)
Definition: z3py.py:9372
def cast(self, val)
Definition: z3py.py:9388
def as_long(self)
Definition: z3py.py:7763
def as_string(self)
Definition: z3py.py:7775
def sort(self)
Definition: z3py.py:7738
def as_string(self)
Definition: z3py.py:7742
Fixedpoint.
Definition: z3py.py:7438
def insert(self, *args)
Definition: z3py.py:7499
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7689
def fact(self, head, name=None)
Definition: z3py.py:7530
def reason_unknown(self)
Definition: z3py.py:7675
def rule(self, head, body=None, name=None)
Definition: z3py.py:7526
def to_string(self, queries)
Definition: z3py.py:7662
def add_cover(self, level, predicate, property)
Definition: z3py.py:7614
def add(self, *args)
Definition: z3py.py:7487
def __del__(self)
Definition: z3py.py:7455
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7503
def param_descrs(self)
Definition: z3py.py:7469
def assert_exprs(self, *args)
Definition: z3py.py:7473
def get_answer(self)
Definition: z3py.py:7581
def statistics(self)
Definition: z3py.py:7670
def update_rule(self, head, body, name)
Definition: z3py.py:7572
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7556
def append(self, *args)
Definition: z3py.py:7495
def query(self, *query)
Definition: z3py.py:7534
def parse_string(self, s)
Definition: z3py.py:7636
def help(self)
Definition: z3py.py:7465
def get_rules_along_trace(self)
Definition: z3py.py:7591
def get_ground_sat_answer(self)
Definition: z3py.py:7586
def __repr__(self)
Definition: z3py.py:7652
def get_rules(self)
Definition: z3py.py:7644
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7626
def sexpr(self)
Definition: z3py.py:7656
def get_assertions(self)
Definition: z3py.py:7648
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7607
def __deepcopy__(self, memo={})
Definition: z3py.py:7452
def get_num_levels(self, predicate)
Definition: z3py.py:7603
def declare_var(self, *vars)
Definition: z3py.py:7680
def parse_file(self, f)
Definition: z3py.py:7640
def set(self, *args, **keys)
Definition: z3py.py:7459
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:7441
def register_relation(self, *relations)
Definition: z3py.py:7620
def get_rule_names_along_trace(self)
Definition: z3py.py:7595
def __iadd__(self, fml)
Definition: z3py.py:7491
Function Declarations.
Definition: z3py.py:718
def params(self)
Definition: z3py.py:793
def get_id(self)
Definition: z3py.py:729
def name(self)
Definition: z3py.py:735
def __call__(self, *args)
Definition: z3py.py:817
def arity(self)
Definition: z3py.py:746
def kind(self)
Definition: z3py.py:780
def as_ast(self)
Definition: z3py.py:726
def as_func_decl(self)
Definition: z3py.py:732
def domain(self, i)
Definition: z3py.py:756
def range(self)
Definition: z3py.py:770
Definition: z3py.py:6140
def __del__(self)
Definition: z3py.py:6151
ctx
Definition: z3py.py:6145
def value(self)
Definition: z3py.py:6204
def __init__(self, entry, ctx)
Definition: z3py.py:6143
def arg_value(self, idx)
Definition: z3py.py:6173
entry
Definition: z3py.py:6144
def __repr__(self)
Definition: z3py.py:6245
def num_args(self)
Definition: z3py.py:6155
def __deepcopy__(self, memo={})
Definition: z3py.py:6148
def as_list(self)
Definition: z3py.py:6226
def __del__(self)
Definition: z3py.py:6258
def arity(self)
Definition: z3py.py:6301
def __init__(self, f, ctx)
Definition: z3py.py:6252
def translate(self, other_ctx)
Definition: z3py.py:6335
def __repr__(self)
Definition: z3py.py:6363
def num_entries(self)
Definition: z3py.py:6285
def __deepcopy__(self, memo={})
Definition: z3py.py:6343
def else_value(self)
Definition: z3py.py:6262
def __copy__(self)
Definition: z3py.py:6340
def as_list(self)
Definition: z3py.py:6346
def entry(self, idx)
Definition: z3py.py:6315
def insert(self, *args)
Definition: z3py.py:5715
def dimacs(self, include_names=True)
Definition: z3py.py:5773
def get(self, i)
Definition: z3py.py:5661
def depth(self)
Definition: z3py.py:5569
def convert_model(self, model)
Definition: z3py.py:5737
def add(self, *args)
Definition: z3py.py:5726
def __del__(self)
Definition: z3py.py:5565
def assert_exprs(self, *args)
Definition: z3py.py:5689
def __getitem__(self, arg)
Definition: z3py.py:5674
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5555
def size(self)
Definition: z3py.py:5635
def append(self, *args)
Definition: z3py.py:5704
def __len__(self)
Definition: z3py.py:5648
def as_expr(self)
Definition: z3py.py:5826
def __repr__(self)
Definition: z3py.py:5766
def sexpr(self)
Definition: z3py.py:5769
def precision(self)
Definition: z3py.py:5626
def translate(self, target)
Definition: z3py.py:5777
def __deepcopy__(self, memo={})
Definition: z3py.py:5803
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5806
def __copy__(self)
Definition: z3py.py:5800
def inconsistent(self)
Definition: z3py.py:5587
def prec(self)
Definition: z3py.py:5605
def as_long(self)
Definition: z3py.py:2962
def as_binary_string(self)
Definition: z3py.py:2983
def as_string(self)
Definition: z3py.py:2975
def decls(self)
Definition: z3py.py:6633
def get_universe(self, s)
Definition: z3py.py:6568
def __del__(self)
Definition: z3py.py:6376
def eval(self, t, model_completion=False)
Definition: z3py.py:6387
def __init__(self, m, ctx)
Definition: z3py.py:6370
def sorts(self)
Definition: z3py.py:6551
def __getitem__(self, idx)
Definition: z3py.py:6588
def __len__(self)
Definition: z3py.py:6444
def update_value(self, x, value)
Definition: z3py.py:6652
def num_sorts(self)
Definition: z3py.py:6513
def __repr__(self)
Definition: z3py.py:6380
def sexpr(self)
Definition: z3py.py:6383
def translate(self, target)
Definition: z3py.py:6674
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6418
def __deepcopy__(self, memo={})
Definition: z3py.py:6685
def __copy__(self)
Definition: z3py.py:6682
def get_interp(self, decl)
Definition: z3py.py:6461
def get_sort(self, idx)
Definition: z3py.py:6528
def __init__(self, s, on_clause)
Definition: z3py.py:11359
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7948
def reason_unknown(self)
Definition: z3py.py:8005
def objectives(self)
Definition: z3py.py:8051
def pop(self)
Definition: z3py.py:7992
def maximize(self, arg)
Definition: z3py.py:7972
def unsat_core(self)
Definition: z3py.py:8016
def from_string(self, s)
Definition: z3py.py:8043
def add(self, *args)
Definition: z3py.py:7911
def __del__(self)
Definition: z3py.py:7878
def param_descrs(self)
Definition: z3py.py:7895
def assert_exprs(self, *args)
Definition: z3py.py:7899
def model(self)
Definition: z3py.py:8009
def statistics(self)
Definition: z3py.py:8065
def help(self)
Definition: z3py.py:7891
def upper_values(self, obj)
Definition: z3py.py:8034
def __repr__(self)
Definition: z3py.py:8055
def from_file(self, filename)
Definition: z3py.py:8039
def set_on_model(self, on_model)
Definition: z3py.py:8070
def sexpr(self)
Definition: z3py.py:8059
def check(self, *assumptions)
Definition: z3py.py:7996
def push(self)
Definition: z3py.py:7988
def __deepcopy__(self, memo={})
Definition: z3py.py:7875
def minimize(self, arg)
Definition: z3py.py:7980
def lower(self, obj)
Definition: z3py.py:8019
def assert_and_track(self, a, p)
Definition: z3py.py:7919
def set(self, *args, **keys)
Definition: z3py.py:7884
def upper(self, obj)
Definition: z3py.py:8024
def lower_values(self, obj)
Definition: z3py.py:8029
def __init__(self, ctx=None)
Definition: z3py.py:7869
def assertions(self)
Definition: z3py.py:8047
def __iadd__(self, fml)
Definition: z3py.py:7915
def __str__(self)
Definition: z3py.py:7851
def upper(self)
Definition: z3py.py:7833
def value(self)
Definition: z3py.py:7845
def lower_values(self)
Definition: z3py.py:7837
def __init__(self, opt, value, is_max)
Definition: z3py.py:7824
def lower(self)
Definition: z3py.py:7829
def upper_values(self)
Definition: z3py.py:7841
def get_name(self, i)
Definition: z3py.py:5516
def get_kind(self, n)
Definition: z3py.py:5521
def __del__(self)
Definition: z3py.py:5502
def __getitem__(self, arg)
Definition: z3py.py:5531
def size(self)
Definition: z3py.py:5506
def __init__(self, descr, ctx=None)
Definition: z3py.py:5493
def __len__(self)
Definition: z3py.py:5511
def __repr__(self)
Definition: z3py.py:5537
def get_documentation(self, n)
Definition: z3py.py:5526
def __deepcopy__(self, memo={})
Definition: z3py.py:5499
Parameter Sets.
Definition: z3py.py:5420
def validate(self, ds)
Definition: z3py.py:5461
def __del__(self)
Definition: z3py.py:5437
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5426
def __repr__(self)
Definition: z3py.py:5458
def __deepcopy__(self, memo={})
Definition: z3py.py:5434
def set(self, name, val)
Definition: z3py.py:5441
def from_string(self, s)
Definition: z3py.py:9242
def __del__(self)
Definition: z3py.py:9231
def add_sort(self, sort)
Definition: z3py.py:9236
def add_decl(self, decl)
Definition: z3py.py:9239
def __init__(self, ctx=None)
Definition: z3py.py:9226
Patterns.
Definition: z3py.py:1921
def get_id(self)
Definition: z3py.py:1929
def as_ast(self)
Definition: z3py.py:1926
def __del__(self)
Definition: z3py.py:8519
def __call__(self, goal)
Definition: z3py.py:8608
def __lt__(self, other)
Definition: z3py.py:8523
def __le__(self, other)
Definition: z3py.py:8551
def __init__(self, probe, ctx=None)
Definition: z3py.py:8493
def __ne__(self, other)
Definition: z3py.py:8593
def __ge__(self, other)
Definition: z3py.py:8565
def __deepcopy__(self, memo={})
Definition: z3py.py:8516
def __eq__(self, other)
Definition: z3py.py:8579
def __gt__(self, other)
Definition: z3py.py:8537
def set(self, ctx, r)
Definition: z3py.py:11387
def insert(self, r)
Definition: z3py.py:11394
def set_threaded(self)
Definition: z3py.py:11374
def get(self, ctx)
Definition: z3py.py:11379
def __init__(self)
Definition: z3py.py:11370
Quantifiers.
Definition: z3py.py:1988
def pattern(self, idx)
Definition: z3py.py:2078
def sort(self)
Definition: z3py.py:1997
def var_name(self, idx)
Definition: z3py.py:2129
def no_pattern(self, idx)
Definition: z3py.py:2100
def is_forall(self)
Definition: z3py.py:2003
def num_no_patterns(self)
Definition: z3py.py:2096
def body(self)
Definition: z3py.py:2106
def num_vars(self)
Definition: z3py.py:2117
def get_id(self)
Definition: z3py.py:1994
def __getitem__(self, arg)
Definition: z3py.py:2045
def children(self)
Definition: z3py.py:2161
def weight(self)
Definition: z3py.py:2052
def is_lambda(self)
Definition: z3py.py:2031
def as_ast(self)
Definition: z3py.py:1991
def var_sort(self, idx)
Definition: z3py.py:2145
def num_patterns(self)
Definition: z3py.py:2066
def is_exists(self)
Definition: z3py.py:2017
def is_real(self)
Definition: z3py.py:3048
def as_decimal(self, prec)
Definition: z3py.py:3058
def as_fraction(self)
Definition: z3py.py:3079
def is_int_value(self)
Definition: z3py.py:3051
def numerator_as_long(self)
Definition: z3py.py:3021
def as_long(self)
Definition: z3py.py:3054
def denominator(self)
Definition: z3py.py:3010
def denominator_as_long(self)
Definition: z3py.py:3034
def is_int(self)
Definition: z3py.py:3045
def numerator(self)
Definition: z3py.py:2995
def as_string(self)
Definition: z3py.py:3070
def __add__(self, other)
Definition: z3py.py:11164
def basis(self)
Definition: z3py.py:11148
def __del__(self)
Definition: z3py.py:5141
def __init__(self, c, ctx)
Definition: z3py.py:5137
def __init__(self, c, ctx)
Definition: z3py.py:5149
def sort(self)
Definition: z3py.py:10777
def __radd__(self, other)
Definition: z3py.py:10783
def at(self, i)
Definition: z3py.py:10791
def __add__(self, other)
Definition: z3py.py:10780
def __lt__(self, other)
Definition: z3py.py:10813
def is_string_value(self)
Definition: z3py.py:10799
def __le__(self, other)
Definition: z3py.py:10810
def __ge__(self, other)
Definition: z3py.py:10816
def __gt__(self, other)
Definition: z3py.py:10819
def is_string(self)
Definition: z3py.py:10796
def as_string(self)
Definition: z3py.py:10802
def __getitem__(self, i)
Definition: z3py.py:10786
Strings, Sequences and Regular expressions.
Definition: z3py.py:10725
def basis(self)
Definition: z3py.py:10739
def is_string(self)
Definition: z3py.py:10728
def insert(self, *args)
Definition: z3py.py:7054
def dimacs(self, include_names=True)
Definition: z3py.py:7375
def non_units(self)
Definition: z3py.py:7283
def reason_unknown(self)
Definition: z3py.py:7319
backtrack_level
Definition: z3py.py:6906
def num_scopes(self)
Definition: z3py.py:6977
def unsat_core(self)
Definition: z3py.py:7147
def trail_levels(self)
Definition: z3py.py:7288
def trail(self)
Definition: z3py.py:7296
def from_string(self, s)
Definition: z3py.py:7212
def add(self, *args)
Definition: z3py.py:7028
def __del__(self)
Definition: z3py.py:6916
def import_model_converter(self, other)
Definition: z3py.py:7143
def param_descrs(self)
Definition: z3py.py:7336
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6903
def reset(self)
Definition: z3py.py:6995
def assert_exprs(self, *args)
Definition: z3py.py:7009
def pop(self, num=1)
Definition: z3py.py:6955
def units(self)
Definition: z3py.py:7278
def cube(self, vars=None)
Definition: z3py.py:7216
def cube_vars(self)
Definition: z3py.py:7237
def model(self)
Definition: z3py.py:7124
def statistics(self)
Definition: z3py.py:7301
def append(self, *args)
Definition: z3py.py:7043
def to_smt2(self)
Definition: z3py.py:7379
def help(self)
Definition: z3py.py:7332
def __repr__(self)
Definition: z3py.py:7340
def from_file(self, filename)
Definition: z3py.py:7208
def proof(self)
Definition: z3py.py:7260
def root(self, t)
Definition: z3py.py:7244
def sexpr(self)
Definition: z3py.py:7363
def next(self, t)
Definition: z3py.py:7252
def check(self, *assumptions)
Definition: z3py.py:7095
def translate(self, target)
Definition: z3py.py:7344
def push(self)
Definition: z3py.py:6933
def __deepcopy__(self, memo={})
Definition: z3py.py:7360
def consequences(self, assumptions, variables)
Definition: z3py.py:7179
def assert_and_track(self, a, p)
Definition: z3py.py:7065
def set(self, *args, **keys)
Definition: z3py.py:6920
def __copy__(self)
Definition: z3py.py:7357
def assertions(self)
Definition: z3py.py:7264
def __iadd__(self, fml)
Definition: z3py.py:7039
def __hash__(self)
Definition: z3py.py:642
def subsort(self, other)
Definition: z3py.py:585
def get_id(self)
Definition: z3py.py:565
def name(self)
Definition: z3py.py:608
def kind(self)
Definition: z3py.py:568
def as_ast(self)
Definition: z3py.py:562
def __ne__(self, other)
Definition: z3py.py:631
def cast(self, val)
Definition: z3py.py:593
def __eq__(self, other)
Definition: z3py.py:618
Statistics.
Definition: z3py.py:6712
def __getattr__(self, name)
Definition: z3py.py:6815
def __del__(self)
Definition: z3py.py:6723
def __getitem__(self, idx)
Definition: z3py.py:6759
def __len__(self)
Definition: z3py.py:6745
def keys(self)
Definition: z3py.py:6783
def __init__(self, stats, ctx)
Definition: z3py.py:6715
def __repr__(self)
Definition: z3py.py:6727
def get_key_value(self, key)
Definition: z3py.py:6795
def __deepcopy__(self, memo={})
Definition: z3py.py:6720
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:8246
def __del__(self)
Definition: z3py.py:8208
def param_descrs(self)
Definition: z3py.py:8260
def solver(self, logFile=None)
Definition: z3py.py:8212
def __init__(self, tactic, ctx=None)
Definition: z3py.py:8191
def help(self)
Definition: z3py.py:8256
def __deepcopy__(self, memo={})
Definition: z3py.py:8205
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:8229
def ctx_ref(self)
Definition: z3py.py:11566
def add_fixed(self, fixed)
Definition: z3py.py:11569
def __del__(self)
Definition: z3py.py:11556
def add_diseq(self, diseq)
Definition: z3py.py:11597
def pop(self, num_scopes)
Definition: z3py.py:11614
def next_split(self, t, idx, phase)
Definition: z3py.py:11632
def add_eq(self, eq)
Definition: z3py.py:11590
def add(self, e)
Definition: z3py.py:11620
def __init__(self, s, ctx=None)
Definition: z3py.py:11533
def propagate(self, e, ids, eqs=[])
Definition: z3py.py:11638
def add_decide(self, decide)
Definition: z3py.py:11604
def add_created(self, created)
Definition: z3py.py:11576
def conflict(self, deps=[], eqs=[])
Definition: z3py.py:11646
def add_final(self, final)
Definition: z3py.py:11583
def fresh(self, new_ctx)
Definition: z3py.py:11617
ASTs base class.
Definition: z3py.py:328
def _repr_html_(self)
Definition: z3py.py:334
def use_pp(self)
Definition: z3py.py:331
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
Z3_ast Z3_API Z3_mk_char_to_bv(Z3_context c, Z3_ast ch)
Create a bit-vector (code point) from character.
void Z3_API Z3_solver_propagate_diseq(Z3_context c, Z3_solver s, Z3_eq_eh eq_eh)
register a callback on expression dis-equalities.
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form:
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
Z3_sort Z3_API Z3_mk_char_sort(Z3_context c)
Create a sort for unicode characters.
Z3_ast Z3_API Z3_mk_re_option(Z3_context c, Z3_ast re)
Create the regular language [re].
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs....
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_mk_fpa_to_fp_bv(Z3_context c, Z3_ast bv, Z3_sort s)
Conversion of a single IEEE 754-2008 bit-vector into a floating-point number.
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_ast Z3_API Z3_mk_seq_replace(Z3_context c, Z3_ast s, Z3_ast src, Z3_ast dst)
Replace the first occurrence of src with dst in s.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_ast Z3_API Z3_mk_str_le(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is equal or lexicographically strictly less than s2.
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_ast Z3_API Z3_mk_fpa_to_ieee_bv(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
Z3_lbool Z3_API Z3_solver_get_consequences(Z3_context c, Z3_solver s, Z3_ast_vector assumptions, Z3_ast_vector variables, Z3_ast_vector consequences)
retrieve consequences from solver that determine values of the supplied function symbols.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context....
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
Z3_ast Z3_API Z3_mk_char_le(Z3_context c, Z3_ast ch1, Z3_ast ch2)
Create less than or equal to between two characters.
Z3_ast Z3_API Z3_mk_fpa_to_fp_signed(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort.
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
Z3_param_descrs Z3_API Z3_solver_get_param_descrs(Z3_context c, Z3_solver s)
Return the parameter description set for the given solver object.
void Z3_API Z3_solver_next_split(Z3_context c, Z3_solver_callback cb, Z3_ast t, unsigned idx, Z3_lbool phase)
Z3_ast Z3_API Z3_mk_fpa_to_sbv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into a signed bit-vector.
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
void Z3_API Z3_parser_context_add_decl(Z3_context c, Z3_parser_context pc, Z3_func_decl f)
Add a function declaration.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_string_from_code(Z3_context c, Z3_ast a)
Code to string conversion.
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives....
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1....
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created.
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
Z3_ast Z3_API Z3_mk_seq_length(Z3_context c, Z3_ast s)
Return the length of the sequence s.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
Z3_sort Z3_API Z3_get_seq_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for sequence sort.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
bool Z3_API Z3_fpa_get_numeral_sign(Z3_context c, Z3_ast t, int *sgn)
Retrieves the sign of a floating-point literal.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
Z3_ast Z3_API Z3_mk_str_to_int(Z3_context c, Z3_ast s)
Convert string to integer.
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_ast Z3_API Z3_mk_re_allchar(Z3_context c, Z3_sort regex_sort)
Create a regular expression that accepts all singleton sequences of the regular expression sort.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context....
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
Z3_ast Z3_API Z3_mk_fpa_to_ubv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into an unsigned bit-vector.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_ast Z3_API Z3_mk_seq_at(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the unit sequence positioned at position index. The sequence is empty if the index is...
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_ast Z3_API Z3_mk_re_complement(Z3_context c, Z3_ast re)
Create the complement of the regular language re.
Z3_sort Z3_API Z3_mk_fpa_sort_half(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context....
unsigned Z3_API Z3_fpa_get_ebits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the exponent in a FloatingPoint sort.
Z3_ast_vector Z3_API Z3_solver_get_assertions(Z3_context c, Z3_solver s)
Return the set of asserted formulas on the solver.
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
bool Z3_API Z3_fpa_is_numeral_positive(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is positive.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_char_ptr Z3_API Z3_get_lstring(Z3_context c, Z3_ast s, unsigned *length)
Retrieve the string constant stored in s. The string can contain escape sequences....
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
bool Z3_API Z3_fpa_get_numeral_exponent_int64(Z3_context c, Z3_ast t, int64_t *n, bool biased)
Return the exponent value of a floating-point numeral as a signed 64-bit integer.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
bool Z3_API Z3_fpa_is_numeral_nan(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a NaN.
unsigned Z3_API Z3_fpa_get_sbits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the significand in a FloatingPoint sort.
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective. The returned vector ...
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
void Z3_API Z3_parser_context_dec_ref(Z3_context c, Z3_parser_context pc)
Decrement the reference counter of the given Z3_parser_context object.
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort_opt const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_fpa_round_toward_negative(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardNegative rounding mode.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
void Z3_API Z3_optimize_assert_and_track(Z3_context c, Z3_optimize o, Z3_ast a, Z3_ast t)
Assert tracked hard constraint to the optimization context.
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_ast Z3_API Z3_mk_fpa_to_fp_real(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a term of real sort into a term of FloatingPoint sort.
Z3_ast_vector Z3_API Z3_solver_get_trail(Z3_context c, Z3_solver s)
Return the trail modulo model conversion, in order of decision level The decision level can be retrie...
bool Z3_API Z3_fpa_get_numeral_significand_uint64(Z3_context c, Z3_ast t, uint64_t *n)
Return the significand value of a floating-point numeral as a uint64.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
Z3_func_decl Z3_API Z3_mk_tree_order(Z3_context c, Z3_sort a, unsigned id)
create a tree ordering relation over signature a identified using index id.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
Z3_ast Z3_API Z3_solver_congruence_next(Z3_context c, Z3_solver s, Z3_ast a)
retrieve the next expression in the congruence class. The set of congruent siblings form a cyclic lis...
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.
Z3_func_decl Z3_API Z3_solver_propagate_declare(Z3_context c, Z3_symbol name, unsigned n, Z3_sort *domain, Z3_sort range)
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
bool Z3_API Z3_is_string_sort(Z3_context c, Z3_sort s)
Check if s is a string sort.
Z3_string Z3_API Z3_fpa_get_numeral_exponent_string(Z3_context c, Z3_ast t, bool biased)
Return the exponent value of a floating-point numeral as a string.
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
Z3_sort Z3_API Z3_mk_re_sort(Z3_context c, Z3_sort seq)
Create a regular expression sort out of a sequence sort.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_ast Z3_API Z3_mk_fpa_inf(Z3_context c, Z3_sort s, bool negative)
Create a floating-point infinity of sort s.
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
Z3_func_decl Z3_API Z3_mk_piecewise_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a piecewise linear ordering relation over signature a and index id.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Z3_sort Z3_API Z3_mk_datatype_sort(Z3_context c, Z3_symbol name)
create a forward reference to a recursive datatype being declared. The forward reference can be used ...
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
Z3_ast Z3_API Z3_mk_fpa_nan(Z3_context c, Z3_sort s)
Create a floating-point NaN of sort s.
bool Z3_API Z3_fpa_is_numeral_subnormal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is subnormal.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_sort Z3_API Z3_get_array_sort_domain_n(Z3_context c, Z3_sort t, unsigned idx)
Return the i'th domain sort of an n-dimensional array.
void Z3_API Z3_solver_import_model_converter(Z3_context ctx, Z3_solver src, Z3_solver dst)
Ad-hoc method for importing model conversion from solver.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_re_union(Z3_context c, unsigned n, Z3_ast const args[])
Create the union of the regular languages.
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_ast Z3_API Z3_mk_fpa_round_toward_positive(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardPositive rounding mode.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
Z3_ast Z3_API Z3_mk_seq_empty(Z3_context c, Z3_sort seq)
Create an empty sequence of the sequence sort seq.
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_seq_suffix(Z3_context c, Z3_ast suffix, Z3_ast s)
Check if suffix is a suffix of s.
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
Z3_sort Z3_API Z3_get_re_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for regex sort.
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
Z3_solver Z3_API Z3_solver_translate(Z3_context source, Z3_solver s, Z3_context target)
Copy a solver s from the context source to the context target.
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_string Z3_API Z3_solver_get_help(Z3_context c, Z3_solver s)
Return a string describing all solver available parameters.
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
void Z3_API Z3_solver_propagate_register_cb(Z3_context c, Z3_solver_callback cb, Z3_ast e)
register an expression to propagate on with the solver. Only expressions of type Bool and type Bit-Ve...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
Z3_sort Z3_API Z3_mk_fpa_sort_16(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
void Z3_API Z3_add_const_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast a)
Add a constant interpretation.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a)
Return which root of the polynomial the algebraic number represents.
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
Z3_ast Z3_API Z3_mk_str_lt(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is lexicographically strictly less than s2.
Z3_ast Z3_API Z3_solver_congruence_root(Z3_context c, Z3_solver s, Z3_ast a)
retrieve the congruence closure root of an expression. The root is retrieved relative to the state wh...
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
void Z3_API Z3_solver_propagate_final(Z3_context c, Z3_solver s, Z3_final_eh final_eh)
register a callback on final check. This provides freedom to the propagator to delay actions or imple...
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
Z3_ast_vector Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Parse the given string using the SMT-LIB2 parser.
void Z3_API Z3_solver_register_on_clause(Z3_context c, Z3_solver s, void *user_context, Z3_on_clause_eh on_clause_eh)
register a callback to that retrieves assumed, inferred and deleted clauses during search.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast_vector Z3_API Z3_solver_get_non_units(Z3_context c, Z3_solver s)
Return the set of non units in the solver state.
Z3_ast Z3_API Z3_mk_seq_to_re(Z3_context c, Z3_ast seq)
Create a regular expression that accepts the sequence seq.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
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_seq_index(Z3_context c, Z3_ast s, Z3_ast substr, Z3_ast offset)
Return index of the first occurrence of substr in s starting from offset offset. If s does not contai...
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
Z3_ast Z3_API Z3_mk_re_range(Z3_context c, Z3_ast lo, Z3_ast hi)
Create the range regular expression over two sequences of length 1.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
Z3_ast Z3_API Z3_fpa_get_numeral_significand_bv(Z3_context c, Z3_ast t)
Retrieves the significand of a floating-point literal as a bit-vector expression.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
Z3_sort Z3_API Z3_mk_fpa_sort_quadruple(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_ast Z3_API Z3_mk_seq_prefix(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if prefix is a prefix of s.
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_away(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
Z3_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
void Z3_API Z3_solver_propagate_init(Z3_context c, Z3_solver s, void *user_context, Z3_push_eh push_eh, Z3_pop_eh pop_eh, Z3_fresh_eh fresh_eh)
register a user-properator with the solver.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
Z3_ast Z3_API Z3_mk_re_star(Z3_context c, Z3_ast re)
Create the regular language re*.
Z3_ast Z3_API Z3_mk_char(Z3_context c, unsigned ch)
Create a character literal.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_ast Z3_API Z3_mk_re_full(Z3_context c, Z3_sort re)
Create an universal regular expression of sort re.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_ast Z3_API Z3_mk_re_diff(Z3_context c, Z3_ast re1, Z3_ast re2)
Create the difference of regular expressions.
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate.
Z3_ast Z3_API Z3_mk_fpa_to_real(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a real-numbered term.
Z3_ast Z3_API Z3_mk_re_empty(Z3_context c, Z3_sort re)
Create an empty regular expression of sort re.
void Z3_API Z3_solver_from_string(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a string.
Z3_sort Z3_API Z3_mk_fpa_sort_128(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast_vector Z3_API Z3_parse_smtlib2_file(Z3_context c, Z3_string file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Similar to Z3_parse_smtlib2_string, but reads the benchmark from a file.
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
void Z3_API Z3_solver_get_levels(Z3_context c, Z3_solver s, Z3_ast_vector literals, unsigned sz, unsigned levels[])
retrieve the decision depth of Boolean literals (variables or their negations). Assumes a check-sat c...
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
Z3_ast Z3_API Z3_mk_fpa_to_fp_unsigned(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement unsigned bit-vector term into a term of FloatingPoint sort.
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_ast Z3_API Z3_mk_fpa_abs(Z3_context c, Z3_ast t)
Floating-point absolute value.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_parser_context_add_sort(Z3_context c, Z3_parser_context pc, Z3_sort s)
Add a sort declaration.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
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.
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 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_substitute_funs(Z3_context c, Z3_ast a, unsigned num_funs, Z3_func_decl const from[], Z3_ast const to[])
Substitute funcions in from with new expressions in to.
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.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
void Z3_API Z3_parser_context_inc_ref(Z3_context c, Z3_parser_context pc)
Increment the reference counter of the given Z3_parser_context object.
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast_vector Z3_API Z3_solver_get_unsat_core(Z3_context c, Z3_solver s)
Retrieve the unsat core for the last Z3_solver_check_assumptions The unsat core is a subset of the as...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
void Z3_API Z3_solver_propagate_consequence(Z3_context c, Z3_solver_callback cb, unsigned num_fixed, Z3_ast const *fixed, unsigned num_eqs, Z3_ast const *eq_lhs, Z3_ast const *eq_rhs, Z3_ast conseq)
propagate a consequence based on fixed values. This is a callback a client may invoke during the fixe...
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
Z3_ast Z3_API Z3_mk_fpa_fp(Z3_context c, Z3_ast sgn, Z3_ast exp, Z3_ast sig)
Create an expression of FloatingPoint sort from three bit-vector expressions.
Z3_func_decl Z3_API Z3_mk_partial_order(Z3_context c, Z3_sort a, unsigned id)
create a partial ordering relation over signature a and index id.
Z3_ast Z3_API Z3_fpa_get_numeral_exponent_bv(Z3_context c, Z3_ast t, bool biased)
Retrieves the exponent of a floating-point literal as a bit-vector expression.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_sort Z3_API Z3_mk_fpa_sort_single(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_set_has_size(Z3_context c, Z3_ast set, Z3_ast k)
Create predicate that holds if Boolean array set has k elements set to true.
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
bool Z3_API Z3_is_string(Z3_context c, Z3_ast s)
Determine if s is a string constant.
Z3_ast Z3_API Z3_mk_re_loop(Z3_context c, Z3_ast r, unsigned lo, unsigned hi)
Create a regular expression loop. The supplied regular expression r is repeated between lo and hi tim...
Z3_ast Z3_API Z3_mk_char_to_int(Z3_context c, Z3_ast ch)
Create an integer (code point) from character.
Z3_ast Z3_API Z3_mk_fpa_neg(Z3_context c, Z3_ast t)
Floating-point negation.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
Z3_ast Z3_API Z3_mk_re_plus(Z3_context c, Z3_ast re)
Create the regular language re+.
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural but two different AST objects can m...
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
Z3_sort Z3_API Z3_mk_fpa_sort_32(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
Z3_sort Z3_API Z3_mk_fpa_sort_64(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_solver_get_proof(Z3_context c, Z3_solver s)
Retrieve the proof for the last Z3_solver_check or Z3_solver_check_assumptions.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Z3_parser_context Z3_API Z3_mk_parser_context(Z3_context c)
Create a parser context.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
void Z3_API Z3_solver_from_file(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a file.
Z3_ast Z3_API Z3_mk_seq_last_index(Z3_context c, Z3_ast s, Z3_ast substr)
Return index of the last occurrence of substr in s. If s does not contain substr, then the value is -...
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
void Z3_API Z3_solver_propagate_eq(Z3_context c, Z3_solver s, Z3_eq_eh eq_eh)
register a callback on expression equalities.
Z3_ast Z3_API Z3_mk_string(Z3_context c, Z3_string s)
Create a string constant out of the string that is passed in The string may contain escape encoding f...
Z3_func_decl Z3_API Z3_mk_transitive_closure(Z3_context c, Z3_func_decl f)
create transitive closure of binary relation.
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_sort Z3_API Z3_mk_seq_sort(Z3_context c, Z3_sort s)
Create a sequence sort out of the sort for the elements.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
Z3_ast_vector Z3_API Z3_solver_get_units(Z3_context c, Z3_solver s)
Return the set of units modulo model conversion.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
Z3_ast Z3_API Z3_mk_fpa_to_fp_float(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_even(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
void Z3_API Z3_solver_propagate_created(Z3_context c, Z3_solver s, Z3_created_eh created_eh)
register a callback when a new expression with a registered function is used by the solver The regist...
Z3_ast_vector Z3_API Z3_parser_context_from_string(Z3_context c, Z3_parser_context pc, Z3_string s)
Parse a string of SMTLIB2 commands. Return assertions.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
Z3_stats Z3_API Z3_solver_get_statistics(Z3_context c, Z3_solver s)
Return statistics for the given solver.
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_store_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs, Z3_ast v)
n-ary Array update.
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query.
Z3_func_decl Z3_API Z3_mk_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a linear ordering relation over signature a. The relation is identified by the index id.
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
Z3_ast Z3_API Z3_mk_seq_in_re(Z3_context c, Z3_ast seq, Z3_ast re)
Check if seq is in the language generated by the regular expression re.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
Z3_string Z3_API Z3_solver_to_dimacs_string(Z3_context c, Z3_solver s, bool include_names)
Convert a solver into a DIMACS formatted string.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
void Z3_API Z3_solver_propagate_decide(Z3_context c, Z3_solver s, Z3_decide_eh decide_eh)
register a callback when the solver decides to split on a registered expression. The callback may set...
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0....
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
void Z3_API Z3_solver_propagate_register(Z3_context c, Z3_solver s, Z3_ast e)
register an expression to propagate on with the solver. Only expressions of type Bool and type Bit-Ve...
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the 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_sort Z3_API Z3_mk_fpa_sort(Z3_context c, unsigned ebits, unsigned sbits)
Create a FloatingPoint sort.
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives....
Z3_string Z3_API Z3_fpa_get_numeral_significand_string(Z3_context c, Z3_ast t)
Return the significand value of a floating-point numeral as a string.
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_ast Z3_API Z3_mk_int_to_str(Z3_context c, Z3_ast s)
Integer to string conversion.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
void Z3_API Z3_solver_propagate_fixed(Z3_context c, Z3_solver s, Z3_fixed_eh fixed_eh)
register a callback for when an expression is bound to a fixed value. The supported expression types ...
Z3_ast Z3_API Z3_fpa_get_numeral_sign_bv(Z3_context c, Z3_ast t)
Retrieves the sign of a floating-point literal as a bit-vector expression.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
Z3_ast Z3_API Z3_mk_char_is_digit(Z3_context c, Z3_ast ch)
Create a check if the character is a digit.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value)
add a function entry to a function interpretation.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_solver_to_string(Z3_context c, Z3_solver s)
Convert a solver into a string.
void Z3_API Z3_optimize_register_model_eh(Z3_context c, Z3_optimize o, Z3_model m, void *ctx, Z3_model_eh model_eh)
register a model event handler for new models.
bool Z3_API Z3_fpa_is_numeral_normal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is normal.
Z3_string Z3_API Z3_solver_get_reason_unknown(Z3_context c, Z3_solver s)
Return a brief justification for an "unknown" result (i.e., Z3_L_UNDEF) for the commands Z3_solver_ch...
Z3_string Z3_API Z3_get_numeral_binary_string(Z3_context c, Z3_ast a)
Return numeral value, as a binary string of a numeric constant term.
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
Z3_ast Z3_API Z3_mk_fpa_round_toward_zero(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardZero rounding mode.
Z3_ast Z3_API Z3_mk_char_from_bv(Z3_context c, Z3_ast bv)
Create a character from a bit-vector (code point).
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
Z3_ast Z3_API Z3_mk_fpa_zero(Z3_context c, Z3_sort s, bool negative)
Create a floating-point zero of sort s.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1.
Z3_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
Z3_sort Z3_API Z3_mk_fpa_sort_double(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_string_to_code(Z3_context c, Z3_ast a)
String to code conversion.
Z3_sort Z3_API Z3_mk_string_sort(Z3_context c)
Create a sort for unicode strings.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_seq_nth(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the element positioned at position index. The function is under-specified if the inde...
bool Z3_API Z3_fpa_is_numeral_inf(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a +oo or -oo.
Z3_ast Z3_API Z3_mk_seq_contains(Z3_context c, Z3_ast container, Z3_ast containee)
Check if container contains containee.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
bool Z3_API Z3_fpa_is_numeral_zero(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is +zero or -zero.
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
def is_ge(a)
Definition: z3py.py:2893
def Abs(arg)
Definition: z3py.py:8932
def PbEq(args, k, ctx=None)
Definition: z3py.py:9022
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:10528
def user_prop_created(ctx, cb, id)
Definition: z3py.py:11448
def to_AstVectorObj(ptr)
Definition: z3py.py:11339
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:8419
def PropagateFunction(name, *sig)
Definition: z3py.py:11501
def is_app(a)
Definition: z3py.py:1265
def _prove_html(claim, show=False, **keywords)
Definition: z3py.py:9171
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:10400
def Union(*args)
Definition: z3py.py:11186
def get_map_func(a)
Definition: z3py.py:4676
def RealVar(idx, ctx=None)
Definition: z3py.py:1485
def z3_debug()
Definition: z3py.py:62
def If(a, b, c, ctx=None)
Definition: z3py.py:1381
def _mk_bin(f, a, b)
Definition: z3py.py:1428
def _to_pattern(arg)
Definition: z3py.py:1975
def StringSort(ctx=None)
Definition: z3py.py:10746
def is_string_value(a)
Definition: z3py.py:10912
def Float64(ctx=None)
Definition: z3py.py:9428
def fpIsPositive(a, ctx=None)
Definition: z3py.py:10377
def AndThen(*ts, **ks)
Definition: z3py.py:8297
def substitute_vars(t, *m)
Definition: z3py.py:8839
def ParOr(*ts, **ks)
Definition: z3py.py:8351
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8771
def is_and(a)
Definition: z3py.py:1621
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:10223
def FailIf(p, ctx=None)
Definition: z3py.py:8712
def is_array_sort(a)
Definition: z3py.py:4607
def PrefixOf(a, b)
Definition: z3py.py:10995
def fpPlusInfinity(s)
Definition: z3py.py:9977
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5466
def EnumSort(name, values, ctx=None)
Definition: z3py.py:5387
def prove(claim, show=False, **keywords)
Definition: z3py.py:9094
def RTZ(ctx=None)
Definition: z3py.py:9711
def RTN(ctx=None)
Definition: z3py.py:9701
def _py2expr(a, ctx=None)
Definition: z3py.py:3123
def RecAddDefinition(f, args, body)
Definition: z3py.py:927
def IndexOf(s, substr, offset=None)
Definition: z3py.py:11059
def is_arith(a)
Definition: z3py.py:2665
def on_clause_eh(ctx, p, clause)
Definition: z3py.py:11350
def describe_probes()
Definition: z3py.py:8675
def is_arith_sort(s)
Definition: z3py.py:2364
def SetHasSize(a, k)
Definition: z3py.py:4880
def Distinct(*args)
Definition: z3py.py:1404
def get_version_string()
Definition: z3py.py:83
def is_to_int(a)
Definition: z3py.py:2944
def is_false(a)
Definition: z3py.py:1607
def is_bv(a)
Definition: z3py.py:3944
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:9676
def simplify_param_descrs()
Definition: z3py.py:8801
def Not(a, ctx=None)
Definition: z3py.py:1815
def is_func_decl(a)
Definition: z3py.py:850
def Update(a, *args)
Definition: z3py.py:4747
def _to_probe(p, ctx=None)
Definition: z3py.py:8648
def fpMax(a, b, ctx=None)
Definition: z3py.py:10297
def _to_goal(a)
Definition: z3py.py:8265
def SignExt(n, a)
Definition: z3py.py:4363
def disable_trace(msg)
Definition: z3py.py:79
def RotateLeft(a, b)
Definition: z3py.py:4331
def _get_ctx(ctx)
Definition: z3py.py:260
def is_mul(a)
Definition: z3py.py:2804
def is_re(s)
Definition: z3py.py:11168
def RecFunction(name, *sig)
Definition: z3py.py:909
def EmptySet(s)
Definition: z3py.py:4922
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:11318
def is_K(a)
Definition: z3py.py:4638
def When(p, t, ctx=None)
Definition: z3py.py:8734
def _solve_using_html(s, *args, **keywords)
Definition: z3py.py:9146
def is_not(a)
Definition: z3py.py:1657
def is_bool(a)
Definition: z3py.py:1571
def is_sort(s)
Definition: z3py.py:647
def Float128(ctx=None)
Definition: z3py.py:9440
def _is_algebraic(ctx, a)
Definition: z3py.py:2728
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10565
def _to_int_str(val)
Definition: z3py.py:3172
def fpNaN(s)
Definition: z3py.py:9960
def is_le(a)
Definition: z3py.py:2869
def _check_bv_args(a, b)
Definition: z3py.py:4159
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:7419
def StrFromCode(c)
Definition: z3py.py:11127
def is_ast(a)
Definition: z3py.py:451
def _coerce_seq(s, ctx=None)
Definition: z3py.py:10873
def get_var_index(a)
Definition: z3py.py:1335
def user_prop_fresh(ctx, _new_ctx)
Definition: z3py.py:11426
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:10619
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4508
def is_eq(a)
Definition: z3py.py:1669
def _probe_or(args, ctx)
Definition: z3py.py:8708
def Map(f, *args)
Definition: z3py.py:4823
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:10238
def is_app_of(a, k)
Definition: z3py.py:1368
def is_rational_value(a)
Definition: z3py.py:2756
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:10026
def Complement(re)
Definition: z3py.py:11250
def FreshFunction(*sig)
Definition: z3py.py:886
def RoundTowardPositive(ctx=None)
Definition: z3py.py:9686
def is_fprm(a)
Definition: z3py.py:9716
def fpIsNormal(a, ctx=None)
Definition: z3py.py:10359
def _coerce_exprs(a, b, ctx=None)
Definition: z3py.py:1202
def get_default_fp_sort(ctx=None)
Definition: z3py.py:9323
def _to_expr_ref(a, ctx)
Definition: z3py.py:1133
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:10253
def Implies(a, b, ctx=None)
Definition: z3py.py:1785
def UGE(a, b)
Definition: z3py.py:4200
def probe_description(name, ctx=None)
Definition: z3py.py:8666
def IsSubset(a, b)
Definition: z3py.py:5020
def SRem(a, b)
Definition: z3py.py:4278
def DatatypeSort(name, ctx=None)
Definition: z3py.py:5358
def BVSubNoOverflow(a, b)
Definition: z3py.py:4473
def tactic_description(name, ctx=None)
Definition: z3py.py:8460
def get_as_array_func(n)
Definition: z3py.py:6699
def FloatSingle(ctx=None)
Definition: z3py.py:9422
def is_bv_value(a)
Definition: z3py.py:3958
def Bool(name, ctx=None)
Definition: z3py.py:1728
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9696
def Plus(re)
Definition: z3py.py:11224
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:5363
def fpIsZero(a, ctx=None)
Definition: z3py.py:10353
def RNE(ctx=None)
Definition: z3py.py:9671
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:8386
def RTP(ctx=None)
Definition: z3py.py:9691
def is_is_int(a)
Definition: z3py.py:2917
def reset_params()
Definition: z3py.py:295
def BVRedOr(a)
Definition: z3py.py:4452
def _to_ast_array(args)
Definition: z3py.py:523
def Product(*args)
Definition: z3py.py:8907
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:4020
def is_mod(a)
Definition: z3py.py:2857
def FloatQuadruple(ctx=None)
Definition: z3py.py:9446
def UGT(a, b)
Definition: z3py.py:4218
def RNA(ctx=None)
Definition: z3py.py:9681
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2240
def is_fp_value(a)
Definition: z3py.py:9886
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:10424
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:10206
def IsMember(e, s)
Definition: z3py.py:5009
def Store(a, *args)
Definition: z3py.py:4790
def user_prop_final(ctx, cb)
Definition: z3py.py:11455
def Var(idx, s)
Definition: z3py.py:1470
def Xor(a, b, ctx=None)
Definition: z3py.py:1799
def CharVal(ch, ctx=None)
Definition: z3py.py:10848
def eq(a, b)
Definition: z3py.py:472
def solve_using(s, *args, **keywords)
Definition: z3py.py:9063
def _pb_args_coeffs(args, default_ctx=None)
Definition: z3py.py:8980
def SubString(s, offset, length)
Definition: z3py.py:10945
def user_prop_diseq(ctx, cb, x, y)
Definition: z3py.py:11469
def Empty(s)
Definition: z3py.py:10955
def to_ContextObj(ptr)
Definition: z3py.py:11334
def SetUnion(*args)
Definition: z3py.py:4940
def Float16(ctx=None)
Definition: z3py.py:9404
def With(t, *args, **keys)
Definition: z3py.py:8391
def FullSet(s)
Definition: z3py.py:4931
def Length(s)
Definition: z3py.py:11088
def _to_ast_ref(a, ctx)
Definition: z3py.py:539
def _sort(ctx, a)
Definition: z3py.py:689
def _probe_and(args, ctx)
Definition: z3py.py:8704
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:5375
def is_select(a)
Definition: z3py.py:4886
def is_finite_domain(a)
Definition: z3py.py:7747
def is_const_array(a)
Definition: z3py.py:4625
def ToReal(a)
Definition: z3py.py:3358
def BVSNegNoOverflow(a)
Definition: z3py.py:4494
def Array(name, *sorts)
Definition: z3py.py:4733
def PartialOrder(a, index)
Definition: z3py.py:11306
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:10324
def LShR(a, b)
Definition: z3py.py:4299
def set_option(*args, **kws)
Definition: z3py.py:301
def Const(name, sort)
Definition: z3py.py:1437
def fpAbs(a, ctx=None)
Definition: z3py.py:10115
def is_gt(a)
Definition: z3py.py:2905
def OrElse(*ts, **ks)
Definition: z3py.py:8330
def And(*args)
Definition: z3py.py:1849
def CharSort(ctx=None)
Definition: z3py.py:10755
def TransitiveClosure(f)
Definition: z3py.py:11322
def _probe_nary(f, args, ctx)
Definition: z3py.py:8694
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10601
def RotateRight(a, b)
Definition: z3py.py:4347
def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref)
Definition: z3py.py:11479
def ToInt(a)
Definition: z3py.py:3376
def user_prop_pop(ctx, cb, num_scopes)
Definition: z3py.py:11420
def fpZero(s, negative)
Definition: z3py.py:10019
def solve(*args, **keywords)
Definition: z3py.py:9033
def is_algebraic_value(a)
Definition: z3py.py:2778
def Int(name, ctx=None)
Definition: z3py.py:3248
def FloatHalf(ctx=None)
Definition: z3py.py:9410
def WithParams(t, p)
Definition: z3py.py:8405
def deserialize(st)
Definition: z3py.py:1119
def _coerce_char(ch, ctx=None)
Definition: z3py.py:10823
def is_lt(a)
Definition: z3py.py:2881
def Q(a, b, ctx=None)
Definition: z3py.py:3235
def _reduce(func, sequence, initial)
Definition: z3py.py:1223
def String(name, ctx=None)
Definition: z3py.py:10928
def BVRedAnd(a)
Definition: z3py.py:4445
def user_prop_eq(ctx, cb, x, y)
Definition: z3py.py:11461
def _get_args(args)
Definition: z3py.py:144
def is_expr(a)
Definition: z3py.py:1242
def tactics(ctx=None)
Definition: z3py.py:8449
def Sum(*args)
Definition: z3py.py:8881
def _to_param_value(val)
Definition: z3py.py:168
def SetComplement(s)
Definition: z3py.py:4988
def _to_func_decl_ref(a, ctx)
Definition: z3py.py:905
def fpEQ(a, b, ctx=None)
Definition: z3py.py:10436
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:9290
def _get_args_ast_list(args)
Definition: z3py.py:158
def is_default(a)
Definition: z3py.py:4667
def UDiv(a, b)
Definition: z3py.py:4236
def user_prop_fixed(ctx, cb, id, value)
Definition: z3py.py:11440
def _ast_kind(ctx, a)
Definition: z3py.py:491
def _solve_html(*args, **keywords)
Definition: z3py.py:9122
def Concat(*args)
Definition: z3py.py:4082
def _sort_kind(ctx, s)
Sorts.
Definition: z3py.py:555
def fpIsInf(a, ctx=None)
Definition: z3py.py:10342
def fpMinusZero(s)
Definition: z3py.py:10013
def CharIsDigit(ch, ctx=None)
Definition: z3py.py:10869
def Contains(a, b)
Definition: z3py.py:11025
def AtLeast(*args)
Definition: z3py.py:8955
def URem(a, b)
Definition: z3py.py:4257
def is_to_real(a)
Definition: z3py.py:2929
def fpMin(a, b, ctx=None)
Definition: z3py.py:10282
def is_const(a)
Definition: z3py.py:1291
def SetDel(s, e)
Definition: z3py.py:4977
def describe_tactics()
Definition: z3py.py:8469
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:10460
def RealVal(val, ctx=None)
Definition: z3py.py:3200
def CharToBv(ch, ctx=None)
Definition: z3py.py:10861
def set_param(*args, **kws)
Definition: z3py.py:271
def IntToStr(s)
Definition: z3py.py:11114
def get_full_version()
Definition: z3py.py:101
def _is_numeral(ctx, a)
Definition: z3py.py:2724
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:10365
def BoolVal(val, ctx=None)
Definition: z3py.py:1709
def fpInfinity(s, negative)
Definition: z3py.py:10000
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:7398
def Bools(names, ctx=None)
Definition: z3py.py:1740
def FP(name, fpsort, ctx=None)
Definition: z3py.py:10072
def is_bv_sort(s)
Definition: z3py.py:3476
def Range(lo, hi, ctx=None)
Definition: z3py.py:11281
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4501
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:10318
def StringVal(s, ctx=None)
Definition: z3py.py:10921
def is_idiv(a)
Definition: z3py.py:2845
def _dict2sarray(sorts, ctx)
Definition: z3py.py:9191
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10583
def probes(ctx=None)
Definition: z3py.py:8655
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4459
def TryFor(t, ms, ctx=None)
Definition: z3py.py:8440
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9901
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7786
def _coerce_fp_expr_list(alist, ctx)
Definition: z3py.py:9342
def is_string(a)
Definition: z3py.py:10904
def TreeOrder(a, index)
Definition: z3py.py:11314
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3274
def _ctx_from_ast_args(*args)
Definition: z3py.py:511
def _reorder_pb_arg(arg)
Definition: z3py.py:8973
def Function(name, *sig)
Definition: z3py.py:863
def Real(name, ctx=None)
Definition: z3py.py:3301
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:10629
def _has_probe(args)
Definition: z3py.py:1841
def Full(s)
Definition: z3py.py:10975
def is_fp(a)
Definition: z3py.py:9872
def _mk_fp_unary_pred(f, a, ctx)
Definition: z3py.py:10163
def Diff(a, b, ctx=None)
Definition: z3py.py:11293
def is_array(a)
Definition: z3py.py:4611
def _mk_fp_bin(f, rm, a, b, ctx)
Definition: z3py.py:10171
def IsInt(a)
Definition: z3py.py:3394
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4466
def StrToInt(s)
Definition: z3py.py:11098
def is_add(a)
Definition: z3py.py:2792
def substitute_funs(t, *m)
Definition: z3py.py:8859
def LastIndexOf(s, substr)
Definition: z3py.py:11079
def fpIsNaN(a, ctx=None)
Definition: z3py.py:10330
def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2187
def is_or(a)
Definition: z3py.py:1633
def _z3_check_cint_overflow(n, name)
Definition: z3py.py:110
def is_distinct(a)
Definition: z3py.py:1679
def FloatDouble(ctx=None)
Definition: z3py.py:9434
def _dflt_fps(ctx=None)
Definition: z3py.py:9338
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1756
def BoolSort(ctx=None)
Definition: z3py.py:1691
def is_seq(a)
Definition: z3py.py:10894
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7716
def Strings(names, ctx=None)
Definition: z3py.py:10937
def RealSort(ctx=None)
Definition: z3py.py:3155
def _mk_fp_unary(f, rm, a, ctx)
Definition: z3py.py:10154
def Ext(a, b)
Definition: z3py.py:4868
def IntSort(ctx=None)
Definition: z3py.py:3138
def Re(s, ctx=None)
Definition: z3py.py:11133
def is_int(a)
Definition: z3py.py:2686
def append_log(s)
Definition: z3py.py:119
def is_pattern(a)
Definition: z3py.py:1933
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:10693
def main_ctx()
Definition: z3py.py:239
def _array_select(ar, arg)
Definition: z3py.py:4598
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:4061
def Intersect(*args)
Definition: z3py.py:11206
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8754
def enable_trace(msg)
Definition: z3py.py:75
def is_as_array(n)
Definition: z3py.py:6694
def user_prop_push(ctx, cb)
Definition: z3py.py:11414
def Select(a, *args)
Definition: z3py.py:4807
def _to_func_decl_array(args)
Definition: z3py.py:515
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10545
def is_finite_domain_sort(s)
Definition: z3py.py:7724
def IntVal(val, ctx=None)
Definition: z3py.py:3188
def CharFromBv(ch, ctx=None)
Definition: z3py.py:10856
def RatVal(a, b, ctx=None)
Definition: z3py.py:3219
def DeclareSort(name, ctx=None)
Definition: z3py.py:693
def Loop(re, lo, hi=0)
Definition: z3py.py:11268
def _get_ctx2(a, b, ctx=None)
Definition: z3py.py:10884
def is_probe(p)
Definition: z3py.py:8637
def _or_else(t1, t2, ctx=None)
Definition: z3py.py:8289
def ArraySort(*sig)
Definition: z3py.py:4700
def _coerce_expr_list(alist, ctx=None)
Definition: z3py.py:1230
def Sqrt(a, ctx=None)
Definition: z3py.py:3411
def Replace(s, src, dst)
Definition: z3py.py:11044
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2222
def _symbol2py(ctx, s)
Definition: z3py.py:132
def substitute(t, *m)
Definition: z3py.py:8806
def is_map(a)
Definition: z3py.py:4651
def BV2Int(a, is_signed=False)
Definition: z3py.py:3973
def _global_on_model(ctx)
Definition: z3py.py:7858
def SubSeq(s, offset, length)
Definition: z3py.py:10950
def ReSort(s)
Definition: z3py.py:11152
def fpPlusZero(s)
Definition: z3py.py:10007
def mk_not(a)
Definition: z3py.py:1834
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3329
def Int2BV(a, num_bits)
Definition: z3py.py:3996
def _to_tactic(t, ctx=None)
Definition: z3py.py:8274
def help_simplify()
Definition: z3py.py:8796
def SeqSort(s)
Definition: z3py.py:10765
def get_version()
Definition: z3py.py:92
def StrToCode(s)
Definition: z3py.py:11121
def fpIsNegative(a, ctx=None)
Definition: z3py.py:10371
def PbLe(args, k)
Definition: z3py.py:9000
def K(dom, v)
Definition: z3py.py:4846
def get_ctx(ctx)
Definition: z3py.py:267
def _mk_fp_bin_pred(f, a, b, ctx)
Definition: z3py.py:10188
def fpMinusInfinity(s)
Definition: z3py.py:9994
def _and_then(t1, t2, ctx=None)
Definition: z3py.py:8281
def _to_float_str(val, exp=0)
Definition: z3py.py:9916
def is_true(a)
Definition: z3py.py:1589
def _dict2darray(decls, ctx)
Definition: z3py.py:9207
def is_fprm_sort(s)
Definition: z3py.py:9467
def Reals(names, ctx=None)
Definition: z3py.py:3314
def BitVec(name, bv, ctx=None)
Definition: z3py.py:4037
def is_implies(a)
Definition: z3py.py:1645
def Ints(names, ctx=None)
Definition: z3py.py:3261
def SetDifference(a, b)
Definition: z3py.py:4998
def FreshInt(prefix="x", ctx=None)
Definition: z3py.py:3287
def LinearOrder(a, index)
Definition: z3py.py:11310
def _to_ref_array(ref, args)
Definition: z3py.py:531
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:10096
def fpNeg(a, ctx=None)
Definition: z3py.py:10138
def CreateDatatypes(*ds)
Definition: z3py.py:5158
def fpGT(a, b, ctx=None)
Definition: z3py.py:10412
def _check_fp_args(a, b)
Definition: z3py.py:10383
def Cbrt(a, ctx=None)
Definition: z3py.py:3424
def is_fp_sort(s)
Definition: z3py.py:9456
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4480
def _to_sort_ref(s, ctx)
Definition: z3py.py:660
def _ctx_from_ast_arg_list(args, default_ctx=None)
Definition: z3py.py:497
def fpLT(a, b, ctx=None)
Definition: z3py.py:10388
def get_param(name)
Definition: z3py.py:307
def MultiPattern(*args)
Definition: z3py.py:1951
def AllChar(regex_sort, ctx=None)
Definition: z3py.py:11298
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:8370
def AtMost(*args)
Definition: z3py.py:8937
def RealVarVector(n, ctx=None)
Definition: z3py.py:1496
def FreshReal(prefix="b", ctx=None)
Definition: z3py.py:3344
def _mk_fp_bin_norm(f, a, b, ctx)
Definition: z3py.py:10180
def _is_int(v)
Definition: z3py.py:68
def SetSort(s)
Sets.
Definition: z3py.py:4917
def _z3_assert(cond, msg)
Definition: z3py.py:105
def BitVecSort(sz, ctx=None)
Definition: z3py.py:4005
def _dflt_rm(ctx=None)
Definition: z3py.py:9334
def is_quantifier(a)
Definition: z3py.py:2173
def SetIntersect(*args)
Definition: z3py.py:4953
def fpRem(a, b, ctx=None)
Definition: z3py.py:10268
def Lambda(vs, body)
Definition: z3py.py:2261
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:9314
def Star(re)
Definition: z3py.py:11255
def Model(ctx=None)
Definition: z3py.py:6689
def Default(a)
Definition: z3py.py:4779
def Or(*args)
Definition: z3py.py:1882
def ZeroExt(n, a)
Definition: z3py.py:4393
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9266
def SetAdd(s, e)
Definition: z3py.py:4966
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4487
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9245
def open_log(fname)
Definition: z3py.py:114
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:10312
def is_store(a)
Definition: z3py.py:4899
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:9666
def to_Ast(ptr)
Definition: z3py.py:11329
def Float32(ctx=None)
Definition: z3py.py:9416
def is_fprm_value(a)
Definition: z3py.py:9729
def is_real(a)
Definition: z3py.py:2705
def _mk_fp_tern(f, rm, a, b, c, ctx)
Definition: z3py.py:10196
def Extract(high, low, a)
Definition: z3py.py:4128
def to_symbol(s, ctx=None)
Definition: z3py.py:124
def is_div(a)
Definition: z3py.py:2828
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:9327
def CharToInt(ch, ctx=None)
Definition: z3py.py:10865
def _valid_accessor(acc)
Datatypes.
Definition: z3py.py:5037
def FreshBool(prefix="b", ctx=None)
Definition: z3py.py:1771
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:10651
def is_finite_domain_value(a)
Definition: z3py.py:7801
def ULE(a, b)
Definition: z3py.py:4164
def _coerce_expr_merge(s, a)
Definition: z3py.py:1183
def FreshConst(sort, prefix="c")
Definition: z3py.py:1464
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:10448
def RoundTowardZero(ctx=None)
Definition: z3py.py:9706
def is_sub(a)
Definition: z3py.py:2816
def ULT(a, b)
Definition: z3py.py:4182
def ensure_prop_closures()
Definition: z3py.py:11408
def InRe(s, re)
Definition: z3py.py:11172
def is_int_value(a)
Definition: z3py.py:2732
def is_var(a)
Definition: z3py.py:1310
def SuffixOf(a, b)
Definition: z3py.py:11010
def Then(*ts, **ks)
Definition: z3py.py:8317
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:10489
def Option(re)
Definition: z3py.py:11237
def PbGe(args, k)
Definition: z3py.py:9011
def z3_error_handler(c, e)
Definition: z3py.py:174
def Unit(a)
Definition: z3py.py:10990
def RepeatBitVec(n, a)
Definition: z3py.py:4421
def Consts(names, sort)
Definition: z3py.py:1449
def fpToReal(x, ctx=None)
Definition: z3py.py:10673